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)
- 使用手册 / 常见问题 / 部署指南 / 上线检查清单按实现同步
This commit is contained in:
1 parent
db94d9c119
commit
6841cf49aa
147 files changed
+8141
-423
No files matched your search
@@ -28,9 +28,21 @@ const props = withDefaults(
|
||||
|
||||
const emit = defineEmits<{ confirm: []; cancel: [] }>()
|
||||
|
||||
/**
|
||||
* 关闭弹窗的唯一出口:ESC、遮罩、右上角关闭键都走这里。
|
||||
*
|
||||
* pending 表示不可逆操作(恢复整库 / 彻底删除 / 重算榜单)正在服务端执行,
|
||||
* 这时必须**完全锁死**——只禁用底部按钮不够:ESC 或点遮罩关掉弹窗后,
|
||||
* 操作员会以为「我取消了」,而服务端其实已经做完,且再也没有回执可看。
|
||||
*/
|
||||
function requestCancel(): void {
|
||||
if (props.pending) return
|
||||
emit('cancel')
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (!props.open) return
|
||||
if (event.key === 'Escape') emit('cancel')
|
||||
if (event.key === 'Escape') requestCancel()
|
||||
}
|
||||
|
||||
onMounted(() => window.addEventListener('keydown', onKeydown))
|
||||
@@ -38,11 +50,11 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mx-modal-overlay" :class="{ open }" @click.self="emit('cancel')">
|
||||
<div class="mx-modal-overlay" :class="{ open }" @click.self="requestCancel">
|
||||
<div class="mx-modal" role="dialog" aria-modal="true">
|
||||
<div class="mx-modal-head">
|
||||
<span class="mx-modal-title">{{ title }}</span>
|
||||
<button class="mx-modal-close" type="button" @click="emit('cancel')">
|
||||
<button class="mx-modal-close" type="button" :disabled="pending" @click="requestCancel">
|
||||
<MxIcon name="close" :size="16" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -56,7 +68,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
|
||||
</ul>
|
||||
</div>
|
||||
<div class="mx-modal-foot">
|
||||
<button class="mx-btn mx-btn-secondary" type="button" :disabled="pending" @click="emit('cancel')">
|
||||
<button class="mx-btn mx-btn-secondary" type="button" :disabled="pending" @click="requestCancel">
|
||||
{{ cancelText }}
|
||||
</button>
|
||||
<button
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import type { Athlete, EntryWithResult } from '@/shared'
|
||||
import type { Athlete, EntryWithResult, ImportConflict } from '@/shared'
|
||||
import MxIcon from '../MxIcon.vue'
|
||||
import { adminApi } from '../../api/client'
|
||||
import { useBaseData } from './useBaseData'
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
buildSelectionRows,
|
||||
buildTeamSelectionRows,
|
||||
buildTeamSelections,
|
||||
conflictLabel,
|
||||
emptyTeamPick,
|
||||
registeredAthleteIds,
|
||||
registeredTeamIds,
|
||||
@@ -43,6 +44,8 @@ const entries = ref<EntryWithResult[]>([])
|
||||
const entriesLoading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
/** 上一轮提交里「命中已有人员但字段对不上」的行:服务端既不建报名也不报错,只能等用户逐条决策。 */
|
||||
const conflicts = ref<ImportConflict[]>([])
|
||||
|
||||
// 个人报名
|
||||
const individualTeamId = ref('')
|
||||
@@ -213,11 +216,25 @@ async function loadEntries(id: number): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 转成导入表头一致的 CSV 后复用导入接口;提交后重拉已报名,徽标与计数都是服务端的结果。 */
|
||||
/**
|
||||
* 转成导入表头一致的 CSV 后复用导入接口;提交后重拉已报名,徽标与计数都是服务端的结果。
|
||||
*
|
||||
* 服务端把「命中了库里已有人员、但字段对不上」的行放进 conflicts:这些行**既没建报名也没报错**,
|
||||
* 所以只有 conflicts 为空才算全部加入成功。有冲突时若照旧说「已加入」,界面与事实相反
|
||||
* (勾过的行一条都没进去),用户不会去导入页处理冲突,名单就永远缺这几行。
|
||||
*/
|
||||
async function importSelection(rows: string[][], id: number): Promise<void> {
|
||||
const file = new File([toCsv(rows)], 'selection.csv', { type: 'text/csv' })
|
||||
const result = await data.importEntries(file)
|
||||
toast.success('报名已加入', `新增 ${result.created} · 更新 ${result.updated} · 跳过 ${result.skipped}`)
|
||||
conflicts.value = result.conflicts
|
||||
if (result.conflicts.length === 0) {
|
||||
toast.success('报名已加入', `新增 ${result.created} · 更新 ${result.updated} · 跳过 ${result.skipped}`)
|
||||
} else {
|
||||
toast.error(
|
||||
`有 ${result.conflicts.length} 行没有加入,需要逐条确认`,
|
||||
'这些行命中了库里已有人员、字段却对不上,本轮没有建报名。到本页「报名导入」分区的冲突面板逐条选择保留哪一侧(POST /api/entries/import/resolve),决策后这些行才会写入。',
|
||||
)
|
||||
}
|
||||
if (result.errors.length > 0) error.value = result.errors.join(';')
|
||||
await loadEntries(id)
|
||||
}
|
||||
@@ -240,6 +257,8 @@ async function syncEvent(id: string): Promise<void> {
|
||||
categoryId.value = ''
|
||||
entries.value = []
|
||||
error.value = null
|
||||
// 冲突行属于上一个小项的提交结果,换小项后继续挂在页内会指错行。
|
||||
conflicts.value = []
|
||||
if (id === '') return
|
||||
// loadEventDetail 自带缓存,重复选同一个小项不会二次请求。
|
||||
await data.loadEventDetail(Number(id))
|
||||
@@ -545,6 +564,24 @@ async function submitTeam(): Promise<void> {
|
||||
<p class="bd-note">队员名单只存姓名,不会带动运动员档案;证件号、号码布与种子等字段仍通过下方报名表导入填写。</p>
|
||||
</template>
|
||||
|
||||
<!-- 冲突行既没建报名也没报错,必须在这里说清「哪几行没进、去哪确认」,否则勾了等于白勾。 -->
|
||||
<div v-if="conflicts.length > 0" class="errors">
|
||||
<div class="errors-head">
|
||||
<span class="mx-badge mx-badge-warning">有 {{ conflicts.length }} 行没有加入,需要逐条确认</span>
|
||||
<span class="bd-note">
|
||||
这些行命中了库里已有人员,但姓名 / 证件号 / 性别 / 年龄 / 单位 / 号码布与库里的对不上,
|
||||
本轮既没有建报名也没有报错。到本页「报名导入」分区的冲突面板逐条选择保留哪一侧
|
||||
(POST /api/entries/import/resolve),决策后这些行才会写入。
|
||||
</span>
|
||||
</div>
|
||||
<ul class="error-list">
|
||||
<li v-for="conflict in conflicts" :key="conflictLabel(conflict)">
|
||||
第 {{ conflict.row }} 行 · {{ conflictLabel(conflict) }} · {{ conflict.existing.name }}
|
||||
<template v-if="conflict.duplicate">(本表内重复行:同证件号 + 同小项同组别出现两次)</template>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div v-if="error !== null" class="mx-badge mx-badge-error picker-error">{{ error }}</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -637,4 +674,28 @@ async function submitTeam(): Promise<void> {
|
||||
padding: 10px 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
/* 冲突明细的样式与 ImportSection.vue 的冲突 / 错误块逐条对齐,两处看起来是同一套东西。 */
|
||||
.errors {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.errors-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.error-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
max-height: 260px;
|
||||
overflow-y: auto;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--mx-r-sm);
|
||||
background: var(--mx-s2);
|
||||
font-size: 12px;
|
||||
color: var(--mx-t2);
|
||||
font-family: var(--mx-mono);
|
||||
}
|
||||
</style>
|
||||
@@ -4,6 +4,7 @@ import type { ConflictAction, EntryImportResult, ImportConflict, SameNameNewPers
|
||||
import MxIcon from '../MxIcon.vue'
|
||||
import EntryPicker from './EntryPicker.vue'
|
||||
import { useBaseData } from './useBaseData'
|
||||
import { entryImportSizeError } from './importLimits'
|
||||
import { useToastStore } from '../../stores/toast'
|
||||
import {
|
||||
REQUIRED_COLUMNS,
|
||||
@@ -28,8 +29,6 @@ const TEMPLATE_CSV = [
|
||||
'BB,混合组,F2,,,,,,种子1,,registered,第一分公司代表队',
|
||||
].join('\n')
|
||||
|
||||
const MAX_SIZE = 16 * 1024 * 1024
|
||||
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const picked = ref<File | null>(null)
|
||||
const dragging = ref(false)
|
||||
@@ -68,8 +67,9 @@ function acceptFile(file: File): void {
|
||||
error.value = '只支持 .csv 或 .xlsx 报名表'
|
||||
return
|
||||
}
|
||||
if (file.size > MAX_SIZE) {
|
||||
error.value = '文件超过 16MB,服务端会拒绝解析'
|
||||
const tooBig = entryImportSizeError(file.size)
|
||||
if (tooBig !== null) {
|
||||
error.value = tooBig
|
||||
return
|
||||
}
|
||||
picked.value = file
|
||||
@@ -223,7 +223,7 @@ function downloadTemplate(): void {
|
||||
<MxIcon name="export" :size="26" />
|
||||
<div class="drop-title">点击选择,或把 CSV / XLSX 拖到这里</div>
|
||||
<div class="bd-note">
|
||||
单个文件不超过 16MB;xlsx 由服务端解析第一个工作表;CSV 直接用 Excel「另存为 CSV」即可(UTF-8、带 BOM 的 UTF-8、GBK/GB18030、UTF-16 都能读,不用特意转码)
|
||||
单个文件不超过 32MB;xlsx 由服务端解析第一个工作表;CSV 直接用 Excel「另存为 CSV」即可(UTF-8、带 BOM 的 UTF-8、GBK/GB18030、UTF-16 都能读,不用特意转码)
|
||||
</div>
|
||||
<input ref="fileInput" class="file-input" type="file" accept=".csv,.xlsx" @change="onPick" />
|
||||
</div>
|
||||
|
||||
@@ -484,7 +484,7 @@ const totalTop = computed(() => {
|
||||
<FormField
|
||||
label="分批发布时实时更新榜单"
|
||||
:error="liveError"
|
||||
hint="开(默认):每发布一批成绩就重算名次、各单位总分与奖牌榜。关掉 = 延迟结算:发布只落成绩,等该项目该组所有批次都录完才一起更新名次与榜单;没录完时可在成绩录入页点「立即结算」。"
|
||||
hint="开(默认):每发布一批成绩就重算名次、各单位总分与奖牌榜。关掉 = 延迟结算:发布只落成绩,等该项目该组所有批次都录完才一起更新名次与榜单;没录完时可在成绩录入页点「立即结算」。勾选本身不是即时保存,改完要点「保存结算方式」才写进服务端。"
|
||||
>
|
||||
<div class="settle-row">
|
||||
<label class="bd-check">
|
||||
@@ -495,6 +495,13 @@ const totalTop = computed(() => {
|
||||
/>
|
||||
发布后立即结算
|
||||
</label>
|
||||
<!--
|
||||
勾选不是即时保存:真正的写请求在「保存结算方式」按钮上。
|
||||
打上「改动未保存」标记,避免操作员勾完就走、以为已经生效(下一批发布才发觉不对)。
|
||||
-->
|
||||
<span v-if="liveDirty" class="mx-badge mx-badge-warning" title="勾选还没提交,点「保存结算方式」才会写进服务端">
|
||||
改动未保存
|
||||
</span>
|
||||
<button
|
||||
class="mx-btn mx-btn-primary mx-btn-sm"
|
||||
type="button"
|
||||
|
||||
@@ -187,6 +187,10 @@ export const baseDataApi = {
|
||||
call(() => adminApi.client.athletes.create(input), () => mockBaseData.createAthlete(input)),
|
||||
update: (id: number, input: AthleteInput): Promise<Athlete> =>
|
||||
call(() => adminApi.client.athletes.update(id, input), () => mockBaseData.updateAthlete(id, input)),
|
||||
/**
|
||||
* 软删除(`DELETE /api/athletes/{id}`):服务端只把 active 置 0,人员、报名与成绩全部保留。
|
||||
* 页面上的入口是「彻底删除」(purge),这条路目前只被 API 契约用例钉着,保留以免契约漂移。
|
||||
*/
|
||||
remove: (id: number): Promise<void> =>
|
||||
call(() => adminApi.client.athletes.remove(id), () => mockBaseData.removeAthlete(id)),
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 报名名单导入的体积上限。
|
||||
*
|
||||
* 与服务端**取同一个数**:`server/internal/httpapi/handlers_config.go` 的
|
||||
* `maxEntryImportBytes = 32 << 20`(`http.MaxBytesReader` 卡的请求体上限)。
|
||||
* 前端这份只是「少传一趟」的早退;两边不等就会出现
|
||||
* 「界面说文件太大、直连 API 却收得下」的分歧(以前这里写 16MB,服务端是 32MB)。
|
||||
*
|
||||
* multipart 还有一层边界:正文比文件本身多个几十~几百字节,所以贴着 32MB 的文件
|
||||
* 仍可能被服务端拒;这个余量不值当前端再留,提示语已说明「服务端会拒绝解析」。
|
||||
*/
|
||||
export const MAX_ENTRY_IMPORT_BYTES = 32 * 1024 * 1024
|
||||
|
||||
/** 超限时上屏的中文提示;没超返回 null(调用方据此决定要不要早退)。 */
|
||||
export function entryImportSizeError(bytes: number): string | null {
|
||||
if (bytes > MAX_ENTRY_IMPORT_BYTES) return '文件超过 32MB,服务端会拒绝解析'
|
||||
return null
|
||||
}
|
||||
@@ -573,10 +573,15 @@ export class MockBaseData {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除:与真实服务端同口径——只把人置为「停用」(active = false),报名与成绩一行不动。
|
||||
* 以前这里是物理 splice,示例数据里删一次人就没了,与真库行为相反,
|
||||
* 会让人在示例环境里以为「删除」是不可逆的。
|
||||
*/
|
||||
removeAthlete(id: number): void {
|
||||
const index = this.athletes.findIndex((athlete) => athlete.id === id)
|
||||
if (index < 0) throw new Error(`运动员 ${id} 不存在`)
|
||||
this.athletes.splice(index, 1)
|
||||
const target = this.athletes.find((athlete) => athlete.id === id)
|
||||
if (target === undefined) throw new Error(`运动员 ${id} 不存在`)
|
||||
target.active = false
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -236,11 +236,6 @@ async function saveAthlete(input: AthleteInput, id: number | null): Promise<Athl
|
||||
return saved
|
||||
}
|
||||
|
||||
async function removeAthlete(id: number): Promise<void> {
|
||||
await baseDataApi.athletes.remove(id)
|
||||
await reloadAthletes()
|
||||
}
|
||||
|
||||
/** 彻底删除:重新拉取名单,删除规模统计回给页面做提示;失败(人员已不在、网络错误)原样抛出。 */
|
||||
async function purgeAthlete(id: number): Promise<AthletePurgeResult> {
|
||||
const result = await baseDataApi.athletes.purge(id)
|
||||
@@ -342,7 +337,6 @@ export interface BaseDataController {
|
||||
saveChannels: (eventId: number, inputs: ScoreChannelInput[]) => Promise<void>
|
||||
saveProfile: (input: ScoringProfileInput, id: number | null) => Promise<ScoringProfile>
|
||||
saveAthlete: (input: AthleteInput, id: number | null) => Promise<Athlete>
|
||||
removeAthlete: (id: number) => Promise<void>
|
||||
/** 返回删除规模统计(报名 / 成绩 / 流水条数、重算过的小项),页面据此提示「榜为什么变了」。 */
|
||||
purgeAthlete: (id: number) => Promise<AthletePurgeResult>
|
||||
importEntries: (file: File) => Promise<EntryImportResult>
|
||||
@@ -410,7 +404,6 @@ export function useBaseData(): BaseDataController {
|
||||
saveChannels,
|
||||
saveProfile,
|
||||
saveAthlete,
|
||||
removeAthlete,
|
||||
purgeAthlete,
|
||||
importEntries,
|
||||
resolveImportConflicts,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ApiError } from '@/shared'
|
||||
import type { ApiErrorCode } from '@/shared'
|
||||
import { parseRevisionDetail, parseRevisions, type Revision } from './types'
|
||||
|
||||
/**
|
||||
@@ -17,6 +18,24 @@ export interface RevisionQuery {
|
||||
|
||||
const REVISIONS_PATH = '/api/revisions'
|
||||
|
||||
const API_ERROR_CODES: readonly string[] = [
|
||||
'AUTH_REQUIRED',
|
||||
'AUTH_FAILED',
|
||||
'FORBIDDEN',
|
||||
'VALIDATION_FAILED',
|
||||
'CONFLICT',
|
||||
'STATE_INVALID',
|
||||
'RATE_LIMITED',
|
||||
'INTERNAL',
|
||||
'NETWORK',
|
||||
'TIMEOUT',
|
||||
'PARSE_FAILED',
|
||||
]
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function buildUrl(query: RevisionQuery): string {
|
||||
const params = new URLSearchParams()
|
||||
if (query.eventId !== undefined) params.set('eventId', String(query.eventId))
|
||||
@@ -26,6 +45,30 @@ function buildUrl(query: RevisionQuery): string {
|
||||
return search === '' ? REVISIONS_PATH : `${REVISIONS_PATH}?${search}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 把非 2xx 响应读成 ApiError。
|
||||
*
|
||||
* 服务端对 401/403 回的是 `{ok:false,error:{code,message}}`(如 FORBIDDEN「无权访问该资源」),
|
||||
* 只按状态码猜、把 `HTTP 403` 原样上屏,访客根本读不懂自己为什么看不到(也不能靠它判断该找谁)。
|
||||
* 读不出约定结构时才退回状态码文案。
|
||||
*/
|
||||
async function toApiError(response: Response, label: string): Promise<ApiError> {
|
||||
let body: unknown = null
|
||||
try {
|
||||
body = await response.json()
|
||||
} catch {
|
||||
body = null
|
||||
}
|
||||
const error = isRecord(body) && isRecord(body.error) ? body.error : null
|
||||
const rawCode = error === null ? undefined : error.code
|
||||
const code: ApiErrorCode =
|
||||
typeof rawCode === 'string' && API_ERROR_CODES.includes(rawCode) ? (rawCode as ApiErrorCode) : 'INTERNAL'
|
||||
const message = error !== null && typeof error.message === 'string' && error.message !== ''
|
||||
? error.message
|
||||
: `${label}返回 HTTP ${response.status}`
|
||||
return new ApiError(code, message, response.status, error?.detail)
|
||||
}
|
||||
|
||||
async function request(url: string, label: string): Promise<unknown> {
|
||||
let response: Response
|
||||
try {
|
||||
@@ -33,13 +76,30 @@ async function request(url: string, label: string): Promise<unknown> {
|
||||
} catch (error) {
|
||||
throw new ApiError('NETWORK', '无法连接服务端', 0, error)
|
||||
}
|
||||
if (!response.ok) {
|
||||
const code = response.status === 403 ? 'FORBIDDEN' : 'INTERNAL'
|
||||
throw new ApiError(code, `${label}返回 HTTP ${response.status}`, response.status)
|
||||
}
|
||||
if (!response.ok) throw await toApiError(response, label)
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* 权限边界上的失败要换成人话(页面红横幅直接用这个字符串)。
|
||||
*
|
||||
* 变更历史是 recorder 起的接口,而面板未登录时会降级成「只读访客」。
|
||||
* 这时把「无权访问该资源 / HTTP 403」摔在脸上,操作员只会以为系统坏了,
|
||||
* 所以这里按错误码给出「该找谁」的说明;其它错误仍原样透传,不能被美化掉。
|
||||
*/
|
||||
export function revisionLoadErrorText(error: unknown): string {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.code === 'AUTH_REQUIRED') {
|
||||
return '变更历史需要登录后才能查看:请用录入员或管理员账号登录。'
|
||||
}
|
||||
if (error.code === 'FORBIDDEN') {
|
||||
return '变更历史需要「录入员」及以上权限,当前是只读访客视图,看不到历史记录。'
|
||||
}
|
||||
return error.message
|
||||
}
|
||||
return error instanceof Error ? error.message : '变更历史接口不可用'
|
||||
}
|
||||
|
||||
export async function fetchRevisions(query: RevisionQuery = {}): Promise<Revision[]> {
|
||||
return parseRevisions(await request(buildUrl(query), '变更历史接口'))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { BackupRestoreResult } from '@/shared'
|
||||
import MxIcon from '../MxIcon.vue'
|
||||
import ConfirmDialog from '../ConfirmDialog.vue'
|
||||
import MockBadge from './MockBadge.vue'
|
||||
import { backupsApi, describeError, waitForServerOnline, type BackupItem } from './systemApi'
|
||||
import { backupsApi, describeError, restoreFailureNotice, waitForServerOnline, type BackupItem } from './systemApi'
|
||||
import { adminApi } from '../../api/client'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { useToastStore } from '../../stores/toast'
|
||||
@@ -165,9 +165,11 @@ async function confirmRestore(): Promise<void> {
|
||||
toast.error('服务端重启未在 60 秒内完成', '请在服务管理窗口查看服务端状态')
|
||||
void load()
|
||||
} catch (caught) {
|
||||
// 失败一律发生在动库文件之前(或已自动回滚),所以这里可以直说「当前库没动」。
|
||||
restoreError.value = describeError(caught)
|
||||
toast.error('恢复未执行,当前库未被覆盖', restoreError.value)
|
||||
// 超时 / 断连不能按「没执行」报:回执在换库之后才发出,库可能已经换掉了(见 restoreFailureNotice)。
|
||||
// 业务错误(400/403/404/500)才是真的没动库,照旧直说。
|
||||
const notice = restoreFailureNotice(caught)
|
||||
restoreError.value = notice.detail
|
||||
toast.error(notice.title, notice.detail)
|
||||
} finally {
|
||||
restoring.value = false
|
||||
}
|
||||
|
||||
@@ -75,7 +75,9 @@ function openEdit(row: AdminUser): void {
|
||||
function validate(): string | null {
|
||||
if (form.value.username.trim() === '') return '账号不能为空'
|
||||
if (form.value.displayName.trim() === '') return '显示名不能为空'
|
||||
if (editingId.value === null && form.value.password.length < 8) return '新建用户必须设置至少 8 位的初始密码'
|
||||
// 按「码点」数位,与后端 utf8.RuneCountInString 同口径:
|
||||
// 直接用 .length 数的是 UTF-16 码元,emoji 一类代理对会多算一位,两边判定就不一致了。
|
||||
if (editingId.value === null && [...form.value.password].length < 8) return '新建用户必须设置至少 8 位的初始密码'
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +91,32 @@ export function describeError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : '未知错误'
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复失败后该怎么向操作员定性(标题 + 说明,供确认框下方的提示与 toast 共用)。
|
||||
*
|
||||
* 为什么必须分开:服务端的恢复回执是「拍安全副本 → 换库文件 → 复核新库 → 写审计」
|
||||
* 全部做完之后才发出的,所以 TIMEOUT / NETWORK 只说明**没收到回执**,
|
||||
* 库很可能已经被换掉了;PARSE_FAILED 同属这一类——服务端已经回了响应,只是内容读不出来。
|
||||
* 这时沿用「当前库未被覆盖」会把操作员引向「再点一次就好」,
|
||||
* 而重试会把刚恢复好的库再覆盖一遍——不可逆动作上不能这样误导。
|
||||
*
|
||||
* 剩下的业务错误(400 备份不可用 / 403 无权限 / 409 …)是服务端在动库之前给出的回答,
|
||||
* 以及 500 里那些自带「已自动回滚」说明的失败,照旧直说「没执行」。
|
||||
*/
|
||||
export function restoreFailureNotice(error: unknown): { title: string; detail: string } {
|
||||
const message = describeError(error)
|
||||
if (
|
||||
error instanceof ApiError &&
|
||||
(error.code === 'TIMEOUT' || error.code === 'NETWORK' || error.code === 'PARSE_FAILED')
|
||||
) {
|
||||
return {
|
||||
title: '没收到恢复回执,恢复可能已经生效',
|
||||
detail: `${message}。请先刷新页面确认当前库的时间点与备份列表,再决定是否重试;不要直接再点一次恢复。`,
|
||||
}
|
||||
}
|
||||
return { title: '恢复未执行,当前库未被覆盖', detail: message }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 底层 HTTP(补齐 ApiClient 未覆盖的路径)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -571,7 +597,7 @@ const RESULT_EXPORT_FILENAME: Record<ResultExportKind, string> = {
|
||||
event: '分项成绩表.xlsx',
|
||||
team: '单位积分明细.xlsx',
|
||||
teamAll: '单位积分总明细.xlsx',
|
||||
medalAll: '团体奖牌明细.xlsx',
|
||||
medalAll: '单位奖牌明细.xlsx',
|
||||
athleteAll: '个人积分总明细.xlsx',
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ interface NavItem {
|
||||
badge?: 'pending'
|
||||
/** 系统配置与审计日志只有 admin 可见(devdocs/08 第 2 节)。 */
|
||||
adminOnly?: boolean
|
||||
/** 接口要求「录入员及以上」(如变更历史):只读访客点进去只会撞 401/403。 */
|
||||
recorderOnly?: boolean
|
||||
}
|
||||
|
||||
interface NavGroup {
|
||||
@@ -47,7 +49,7 @@ const NAV: NavGroup[] = [
|
||||
items: [
|
||||
{ name: 'base-data', label: '基础数据', icon: 'database' },
|
||||
{ name: 'export', label: '导出', icon: 'export' },
|
||||
{ name: 'history', label: '变更历史', icon: 'history' },
|
||||
{ name: 'history', label: '变更历史', icon: 'history', recorderOnly: true },
|
||||
{ name: 'logs', label: '日志', icon: 'logs', adminOnly: true },
|
||||
],
|
||||
},
|
||||
@@ -68,11 +70,18 @@ const sidebarOpen = ref(false)
|
||||
const refreshing = ref(false)
|
||||
|
||||
const isAdmin = computed(() => auth.user?.role === 'admin')
|
||||
/** 非 admin 不显示系统设置 / 日志,避免点进去只看到一堆 403。 */
|
||||
/**
|
||||
* 非 admin 不显示系统设置 / 日志,避免点进去只看到一堆 403;
|
||||
* 只读访客同样不显示「变更历史」(接口是 recorder 起),否则点进去只有一句权限错误。
|
||||
*/
|
||||
const navGroups = computed<NavGroup[]>(() =>
|
||||
NAV.map((group) => ({
|
||||
...group,
|
||||
items: group.items.filter((item) => item.adminOnly !== true || isAdmin.value),
|
||||
items: group.items.filter((item) => {
|
||||
if (item.adminOnly === true && !isAdmin.value) return false
|
||||
if (item.recorderOnly === true && auth.readOnly) return false
|
||||
return true
|
||||
}),
|
||||
})).filter((group) => group.items.length > 0),
|
||||
)
|
||||
|
||||
|
||||
@@ -959,6 +959,12 @@ function buildDraftPayload(): DraftResultInput[] {
|
||||
async function saveDraft(silent = false): Promise<boolean> {
|
||||
if (selectedEventId.value === null) return false
|
||||
if (saving.value) return false
|
||||
if (data.isMock) {
|
||||
// 与发布 / 批次 / 团体名次同一口径:示例数据模式下写接口没有后端可落库,
|
||||
// 照发请求只会得到一句网络错误,操作员会以为是自己手滑而不是「这台机没连服务端」。
|
||||
toast.error('示例数据模式不能保存草稿', '后端未就绪,草稿不会写入真实赛事')
|
||||
return false
|
||||
}
|
||||
if (allPublished.value) {
|
||||
// 可见行全部 published 后服务端会拒绝这次草稿(载荷为空),必须先撤销发布。
|
||||
toast.error(`${scopeWord.value}已全部发布`, '修改前请先撤销发布')
|
||||
@@ -1056,6 +1062,12 @@ async function confirmPublish(): Promise<void> {
|
||||
|
||||
async function confirmUnpublish(): Promise<void> {
|
||||
if (selectedEventId.value === null) return
|
||||
if (data.isMock) {
|
||||
// 与发布同一口径:示例数据模式下 unpublish 只改内存,提示「已撤销发布」等于谎报。
|
||||
toast.error('示例数据模式不能撤销发布', '后端未就绪,撤销发布不会写入真实赛事')
|
||||
unpublishDialog.value = false
|
||||
return
|
||||
}
|
||||
unpublishing.value = true
|
||||
try {
|
||||
await adminApi.unpublish({
|
||||
@@ -1444,7 +1456,13 @@ function moveFocusBy(delta: number): void {
|
||||
next?.focus()
|
||||
}
|
||||
|
||||
/** 默认聚焦上次编辑的项目(07 第 7 节);URL 带 eventId 时优先。 */
|
||||
/**
|
||||
* 进入录入页时默认选中小项:URL 带 eventId 时优先,否则取第一个未开始(pending)的项目,
|
||||
* 都没有就取列表第一个。
|
||||
*
|
||||
* 注意口径:这里**没有**「上次编辑的小项」这种记忆——前端从未持久化过录入位置,
|
||||
* 所以换人换班后回到录入页看到的是兜底结论,不是他离开时的那个项目。
|
||||
*/
|
||||
async function pickInitialEvent(): Promise<void> {
|
||||
if (selectedEventId.value !== null) return
|
||||
const query = route.query.eventId
|
||||
@@ -1486,7 +1504,7 @@ watch([selectedEventId, selectedCategoryId], () => void refreshSettlement(), { i
|
||||
<button
|
||||
class="mx-btn mx-btn-secondary"
|
||||
type="button"
|
||||
:disabled="!canWrite || saving || allPublished"
|
||||
:disabled="!canWrite || saving || allPublished || data.isMock"
|
||||
:title="allPublished ? `${scopeWord}已全部发布,请先撤销发布` : ''"
|
||||
@click="saveDraft()"
|
||||
>
|
||||
@@ -1589,7 +1607,7 @@ watch([selectedEventId, selectedCategoryId], () => void refreshSettlement(), { i
|
||||
v-if="hasPublished"
|
||||
class="mx-btn mx-btn-danger mx-btn-sm"
|
||||
type="button"
|
||||
:disabled="!canWrite"
|
||||
:disabled="!canWrite || data.isMock"
|
||||
@click="unpublishDialog = true"
|
||||
>
|
||||
撤销发布
|
||||
|
||||
@@ -59,7 +59,7 @@ const EXPORT_OPTIONS: ReadonlyArray<ExportOption> = [
|
||||
{
|
||||
key: 'standings',
|
||||
title: '总表',
|
||||
desc: '总积分榜 + 团体奖牌榜 + 个人积分奖牌榜,一个工作簿',
|
||||
desc: '总积分榜 + 单位奖牌榜 + 个人积分奖牌榜,一个工作簿',
|
||||
icon: 'standings',
|
||||
},
|
||||
{ key: 'all', title: '全部', desc: '总表 + 全部分项,多 sheet 工作簿,适合归档打印', icon: 'database' },
|
||||
|
||||
@@ -14,7 +14,7 @@ import PageHeader from '../components/PageHeader.vue'
|
||||
import RevisionGraph from '../components/history/RevisionGraph.vue'
|
||||
import RevisionDetail from '../components/history/RevisionDetail.vue'
|
||||
import { buildGraph, describeRow, diffSnapshots, laneColor } from '../components/history/graph'
|
||||
import { fetchRevisionDetail, fetchRevisions } from '../components/history/revisionsSource'
|
||||
import { fetchRevisionDetail, fetchRevisions, revisionLoadErrorText } from '../components/history/revisionsSource'
|
||||
import { createMockRevisions } from '../components/history/mockRevisions'
|
||||
import { ACTION_LABELS, type Revision, type RevisionDiffRow, type TeamImpact } from '../components/history/types'
|
||||
import { adminApi } from '../api/client'
|
||||
@@ -241,7 +241,8 @@ async function loadDetail(id: number): Promise<void> {
|
||||
revisions.value = revisions.value.map((item) => (item.id === id ? { ...item, ...detail } : item))
|
||||
detailLoadedIds.value = [...detailLoadedIds.value, id]
|
||||
} catch (caught) {
|
||||
detailError.value = caught instanceof Error ? caught.message : '加载变更详情失败'
|
||||
// 与列表同一套口径:会话中途失效(403/401)也要说人话,别把状态码摔在脸上。
|
||||
detailError.value = revisionLoadErrorText(caught)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
@@ -266,7 +267,9 @@ async function load(): Promise<void> {
|
||||
if (!isUnavailable(caught)) {
|
||||
revisions.value = []
|
||||
usingMock.value = false
|
||||
loadError.value = caught instanceof Error ? caught.message : '变更历史接口不可用'
|
||||
// 权限边界(401/403)在这里换成人话:变更历史是 recorder 起的接口,
|
||||
// 只读访客点进来不该看到裸的 HTTP 状态码。
|
||||
loadError.value = revisionLoadErrorText(caught)
|
||||
return
|
||||
}
|
||||
const all = createMockRevisions()
|
||||
|
||||
@@ -14,7 +14,7 @@ type TabKey = 'points' | 'medals' | 'athletes'
|
||||
|
||||
const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'points', label: '单位总分榜' },
|
||||
{ key: 'medals', label: '团体奖牌榜' },
|
||||
{ key: 'medals', label: '单位奖牌榜' },
|
||||
{ key: 'athletes', label: '个人积分榜' },
|
||||
]
|
||||
|
||||
@@ -117,7 +117,7 @@ async function exportTeamDetail(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 榜单级明细导出(单位总分 / 团体奖牌 / 个人积分),与单位明细共用同一个单飞锁。 */
|
||||
/** 榜单级明细导出(单位总分 / 单位奖牌 / 个人积分),与单位明细共用同一个单飞锁。 */
|
||||
async function exportBoard(
|
||||
kind: 'teamAll' | 'medalAll' | 'athleteAll',
|
||||
label: string,
|
||||
@@ -275,7 +275,7 @@ async function refresh(): Promise<void> {
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 团体奖牌榜 -->
|
||||
<!-- 单位奖牌榜 -->
|
||||
<table v-else-if="activeTab === 'medals'" class="mx-table">
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
@@ -235,10 +235,13 @@ function apiError(code: unknown, message: string, status: number, detail?: unkno
|
||||
* 以为已经退赛 / 删干净了,页面必须先看 data.isMock 再决定是否调用这里。
|
||||
*/
|
||||
export async function submitEntryBatch(payload: EntryBatchPayload): Promise<EntryBatchResult> {
|
||||
// 一次调用只生成一个幂等键:header 供服务端 cached 层去重,body.requestId 是同一把钥匙。
|
||||
// 两处各生成一个就永远命中不了缓存,超时重试「移出报名」会真的把同一批人删两遍。
|
||||
const requestId = payload.requestId ?? defaultRequestId()
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'X-Request-Id': defaultRequestId(),
|
||||
'X-Request-Id': requestId,
|
||||
}
|
||||
const token = readCsrfToken()
|
||||
if (token !== null && token !== '') headers['X-CSRF-Token'] = token
|
||||
@@ -249,7 +252,7 @@ export async function submitEntryBatch(payload: EntryBatchPayload): Promise<Entr
|
||||
method: 'POST',
|
||||
headers,
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ ...payload, requestId: payload.requestId ?? defaultRequestId() }),
|
||||
body: JSON.stringify({ ...payload, requestId }),
|
||||
})
|
||||
} catch (caught) {
|
||||
throw apiError('NETWORK', '无法连接服务端,批量操作没有生效', 0, caught)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import { isGuestUser } from '@/shared'
|
||||
import type { CurrentUser } from '@/shared'
|
||||
import { adminApi, mockMode, setUnauthorizedHandler } from '../api/client'
|
||||
import { readSessionExpiresAt } from '../components/system/sessionSettings'
|
||||
@@ -23,8 +24,12 @@ export const useAuthStore = defineStore('admin-auth', () => {
|
||||
* 未登录时 /auth/me 返回 200 + guest DTO 而不是 401,
|
||||
* 所以「访客」必须按角色判定:只看 user === null 会把访客当成已登录,
|
||||
* 只读横幅与 useBaseData.canWrite 的写保护都会失效。
|
||||
*
|
||||
* 判定复用 `shared/session.ts` 的 isGuestUser(null 与 guest DTO 都算访客),
|
||||
* 不再在 store 里手写一份「按角色判访客」的等价逻辑:两处口径一旦分叉,
|
||||
* 大屏 / 面板 / 测试会各自认为「谁是访客」。
|
||||
*/
|
||||
const isGuest = computed(() => user.value === null || user.value.role === 'guest')
|
||||
const isGuest = computed(() => isGuestUser(user.value))
|
||||
const readOnly = computed(() => isGuest.value)
|
||||
const displayName = computed(() => user.value?.displayName ?? '访客')
|
||||
const roleLabel = computed(() => (isGuest.value ? '只读访客' : (user.value?.role ?? '用户')))
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { mockBaseData } from '../components/baseData/mockBaseData'
|
||||
|
||||
/**
|
||||
* 人员「删除」的口径(P2 C46)。
|
||||
*
|
||||
* 真服务端的 DELETE /api/athletes/{id} 是软删除:只把 active 置 0,人员、报名与成绩一行不动
|
||||
* (repo.go 的 deleteAthlete);示例数据却把人从内存里 splice 掉,两边行为相反。
|
||||
* 现在 mock 与真库同口径;页面上的入口只有「彻底删除」(purge)。
|
||||
*
|
||||
* 同时钉住 `useBaseData.removeAthlete` 这条零调用方的死链路已经删掉。
|
||||
*/
|
||||
|
||||
test('示例数据的软删除只置为停用,人员仍在名单里', () => {
|
||||
const victim = mockBaseData.listAthletes().find((athlete) => athlete.active)
|
||||
assert.ok(victim !== undefined, '示例数据里应当有启用状态的运动员')
|
||||
|
||||
mockBaseData.removeAthlete(victim.id)
|
||||
|
||||
const after = mockBaseData.listAthletes().find((athlete) => athlete.id === victim.id)
|
||||
assert.ok(after !== undefined, '软删除不能把人从名单里抹掉(与真服务端一致)')
|
||||
assert.equal(after.active, false)
|
||||
assert.equal(after.name, victim.name)
|
||||
})
|
||||
|
||||
test('软删除不存在的人仍然报错(不要静默成功)', () => {
|
||||
assert.throws(() => mockBaseData.removeAthlete(999999), /不存在/)
|
||||
})
|
||||
|
||||
const USE_BASE_DATA_SOURCE = readFileSync(
|
||||
new URL('../components/baseData/useBaseData.ts', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
|
||||
test('useBaseData 不再暴露没有调用方的 removeAthlete', () => {
|
||||
assert.doesNotMatch(USE_BASE_DATA_SOURCE, /removeAthlete/)
|
||||
assert.match(USE_BASE_DATA_SOURCE, /purgeAthlete/)
|
||||
})
|
||||
@@ -19,6 +19,7 @@ interface Captured {
|
||||
url?: string
|
||||
method?: string
|
||||
body?: unknown
|
||||
headers?: Record<string, string>
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
@@ -39,7 +40,12 @@ 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 }
|
||||
lastRequest = {
|
||||
url: String(input),
|
||||
method: init?.method ?? 'GET',
|
||||
body: init?.body,
|
||||
headers: (init?.headers ?? {}) as Record<string, string>,
|
||||
}
|
||||
return reply()
|
||||
}) as typeof fetch
|
||||
|
||||
@@ -138,6 +144,38 @@ test('确认写入不带 dryRun,避免预览之后又走一次只读分支', a
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 不可逆操作进行中的弹窗锁定(P2 A32)。
|
||||
*
|
||||
* `pending` 表示服务端正在执行(恢复整库、彻底删除、重算榜单…)。
|
||||
* 只禁用底部两个按钮是不够的:ESC、点遮罩、右上角关闭键都会把弹窗关掉,
|
||||
* 操作员会以为「我取消了这次操作」,而服务端其实已经做完,且再没有回执可看。
|
||||
*
|
||||
* 项目没有 @vue/test-utils / jsdom,这里按仓库既有做法读源码断言三处出口。
|
||||
*/
|
||||
|
||||
const SOURCE = readFileSync(new URL('../components/ConfirmDialog.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('pending 时统一的关闭出口直接早退', () => {
|
||||
assert.match(SOURCE, /function requestCancel\(\): void \{\n\s*if \(props\.pending\) return\n\s*emit\('cancel'\)\n\}/)
|
||||
})
|
||||
|
||||
test('ESC 走同一个出口,不再直接 emit', () => {
|
||||
assert.match(SOURCE, /if \(event\.key === 'Escape'\) requestCancel\(\)/)
|
||||
assert.doesNotMatch(SOURCE, /Escape'\) emit\('cancel'\)/)
|
||||
})
|
||||
|
||||
test('遮罩与右上角关闭键都改走出口,且关闭键在 pending 时禁用', () => {
|
||||
assert.equal((SOURCE.match(/@click="requestCancel"/g) ?? []).length, 2)
|
||||
assert.equal((SOURCE.match(/@click\.self="requestCancel"/g) ?? []).length, 1)
|
||||
assert.match(SOURCE, /class="mx-modal-close" type="button" :disabled="pending" @click="requestCancel"/)
|
||||
})
|
||||
|
||||
test('底部两个按钮仍然禁用(原有保护不回退)', () => {
|
||||
assert.equal((SOURCE.match(/:disabled="pending"/g) ?? []).length, 3)
|
||||
})
|
||||
|
||||
test('模板里没有旁路的 emit(\'cancel\')', () => {
|
||||
const template = SOURCE.slice(SOURCE.indexOf('<template>'))
|
||||
assert.doesNotMatch(template, /emit\('cancel'\)/)
|
||||
})
|
||||
@@ -95,6 +95,28 @@ test('带 csrf_token Cookie 时补上 X-CSRF-Token', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
// 服务端是两层幂等:外层 cached 认 X-Request-Id,内层 idempotent 认 body.requestId。
|
||||
// 两处各生成一个 id,服务端永远拼不出同一个 key —— 超时重试「移出报名」会真的删第二遍。
|
||||
test('X-Request-Id 与 body.requestId 是同一次调用的同一个值', async () => {
|
||||
respondWith(() => jsonResponse({ ok: true, data: { items: [], summary: emptySummary() } }))
|
||||
|
||||
await submitEntryBatch({ action: 'remove', ids: [7] })
|
||||
|
||||
const headerId = lastRequest.headers?.['X-Request-Id']
|
||||
const bodyId = (lastRequest.body as { requestId?: unknown }).requestId
|
||||
assert.equal(typeof headerId, 'string')
|
||||
assert.equal(bodyId, headerId, 'header 与 body 必须是同一个幂等键,否则服务端两层缓存都命中不了')
|
||||
})
|
||||
|
||||
test('调用方显式给的 requestId 会同时用于 header 与 body', async () => {
|
||||
respondWith(() => jsonResponse({ ok: true, data: { items: [], summary: emptySummary() } }))
|
||||
|
||||
await submitEntryBatch({ action: 'scratch', ids: [8], requestId: 'retry-1' })
|
||||
|
||||
assert.equal(lastRequest.headers?.['X-Request-Id'], 'retry-1')
|
||||
assert.equal((lastRequest.body as { requestId?: unknown }).requestId, 'retry-1')
|
||||
})
|
||||
|
||||
test('没有 document(非浏览器环境)时不带 CSRF,也不报错', async () => {
|
||||
respondWith(() => jsonResponse({ ok: true, data: { items: [], summary: emptySummary() } }))
|
||||
await submitEntryBatch({ action: 'remove', ids: [3] })
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import type { ImportConflict } from '@/shared'
|
||||
import { conflictLabel } from '../components/baseData/entrySelection'
|
||||
|
||||
/**
|
||||
* 「从已有名单勾选报名」必须消费服务端返回的 conflicts(P2 A12)。
|
||||
*
|
||||
* 勾选报名复用的是 /entries/import:服务端把「命中了库里已有人员、但字段对不上」的行放进 conflicts,
|
||||
* 这些行**既没建报名也没报错**。组件原本无条件 toast.success('报名已加入'),
|
||||
* 于是勾过的行一条都没进去、界面却说已加入,用户也就不会去导入页处理冲突。
|
||||
*
|
||||
* .vue 组件跑不进 node --test(无 jsdom,见 entryGuards.ts:6),所以按既有做法读源码断言:
|
||||
* 成功提示只许长在 conflicts 为空的分支里,冲突条数要带进提示与页内明细,并说清去哪确认。
|
||||
*/
|
||||
|
||||
const PICKER_SOURCE = readFileSync(new URL('../components/baseData/EntryPicker.vue', import.meta.url), 'utf8')
|
||||
const IMPORT_SOURCE = readFileSync(new URL('../components/baseData/ImportSection.vue', import.meta.url), 'utf8')
|
||||
|
||||
/** 截出 importSelection 的函数体(到下一个顶格 `}` 为止),断言都限定在这段里。 */
|
||||
function importSelectionBody(): string {
|
||||
const start = PICKER_SOURCE.indexOf('async function importSelection')
|
||||
assert.notEqual(start, -1, 'EntryPicker.vue 里找不到 importSelection')
|
||||
const end = PICKER_SOURCE.indexOf('\n}', start)
|
||||
assert.notEqual(end, -1, 'importSelection 没有正常闭合')
|
||||
return PICKER_SOURCE.slice(start, end)
|
||||
}
|
||||
|
||||
/** 取出 `if (result.conflicts.length === 0) { … }` 这一对花括号内的源码。 */
|
||||
function emptyConflictsBranch(body: string): string {
|
||||
const marker = 'if (result.conflicts.length === 0) {'
|
||||
const start = body.indexOf(marker)
|
||||
assert.notEqual(start, -1, 'importSelection 里没有「conflicts 为空才算成功」的分支')
|
||||
let depth = 0
|
||||
for (let i = start + marker.length - 1; i < body.length; i += 1) {
|
||||
if (body[i] === '{') depth += 1
|
||||
else if (body[i] === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return body.slice(start + marker.length, i)
|
||||
}
|
||||
}
|
||||
assert.fail('conflicts 为空的分支没有闭合')
|
||||
}
|
||||
|
||||
test('有冲突时不出现成功提示:toast.success 只长在 conflicts 为空的分支里', () => {
|
||||
const body = importSelectionBody()
|
||||
const successIndex = body.indexOf('toast.success')
|
||||
assert.notEqual(successIndex, -1, '全成功时仍要提示成功')
|
||||
|
||||
const branch = emptyConflictsBranch(body)
|
||||
const branchStart = body.indexOf(branch)
|
||||
assert.ok(
|
||||
successIndex > branchStart && successIndex < branchStart + branch.length,
|
||||
'toast.success 跑到了 conflicts 非空的路径上——冲突行没建报名却提示「已加入」',
|
||||
)
|
||||
// 页面里只该有这一处成功提示,避免别处又无条件说「已加入」。
|
||||
assert.equal([...PICKER_SOURCE.matchAll(/toast\.success\(/g)].length, 1)
|
||||
})
|
||||
|
||||
test('全成功时仍提示成功,且带上服务端的计数', () => {
|
||||
const branch = emptyConflictsBranch(importSelectionBody())
|
||||
assert.match(branch, /toast\.success\('报名已加入'/)
|
||||
assert.match(branch, /新增 \$\{result\.created\} · 更新 \$\{result\.updated\} · 跳过 \$\{result\.skipped\}/)
|
||||
})
|
||||
|
||||
test('冲突条数被正确传递:收下 conflicts 并写进失败提示', () => {
|
||||
const body = importSelectionBody()
|
||||
assert.match(body, /conflicts\.value = result\.conflicts/, '要把服务端给的冲突行收进界面状态')
|
||||
assert.match(body, /有 \$\{result\.conflicts\.length\} 行没有加入,需要逐条确认/)
|
||||
})
|
||||
|
||||
test('冲突明细显示在页内,逐条给出服务端的行号与决策键', () => {
|
||||
assert.match(PICKER_SOURCE, /v-if="conflicts\.length > 0"/)
|
||||
assert.match(PICKER_SOURCE, /v-for="conflict in conflicts"/)
|
||||
assert.match(PICKER_SOURCE, /\{\{ conflict\.row \}\}/)
|
||||
assert.match(PICKER_SOURCE, /conflictLabel\(conflict\)/)
|
||||
})
|
||||
|
||||
test('页内明细复用冲突面板的决策键标签(键为空时不留空白)', () => {
|
||||
const conflict: ImportConflict = {
|
||||
row: 3,
|
||||
idCard: '',
|
||||
bib: '101',
|
||||
athleteId: 7,
|
||||
duplicate: false,
|
||||
existing: { name: '张伟', gender: null, age: null, teamCode: 'F1', employeeNo: null, idCard: null, bib: null },
|
||||
incoming: { name: '张伟', gender: null, age: null, teamCode: 'F1', employeeNo: null, idCard: null, bib: null },
|
||||
changedFields: [],
|
||||
}
|
||||
assert.equal(conflictLabel(conflict), '101', '证件号为空时用号码布')
|
||||
assert.equal(conflictLabel({ ...conflict, idCard: '110101199001011234' }), '110101199001011234')
|
||||
})
|
||||
|
||||
test('提示说清去哪确认:本页「报名导入」分区的冲突面板 / resolve 接口', () => {
|
||||
const body = importSelectionBody()
|
||||
// 面板在同一个页面(ImportSection.vue 里先渲染 <EntryPicker />、再是「报名导入」卡片),
|
||||
// 所以文案必须点名卡片标题,否则用户不知道去哪找。
|
||||
assert.match(body, /本页「报名导入」分区的冲突面板/)
|
||||
assert.match(IMPORT_SOURCE, /<span class="mx-card-title">报名导入<\/span>/)
|
||||
assert.match(body, /POST \/api\/entries\/import\/resolve/)
|
||||
})
|
||||
|
||||
test('复用 EntryImportResult.conflicts 的类型,不另立一套', () => {
|
||||
assert.match(PICKER_SOURCE, /import type \{ Athlete, EntryWithResult, ImportConflict \} from '@\/shared'/)
|
||||
})
|
||||
|
||||
test('冲突明细照抄 ImportSection.vue 的渲染范式,没有自创样式', () => {
|
||||
for (const className of ['.errors-head', '.error-list']) {
|
||||
assert.ok(IMPORT_SOURCE.includes(className), `ImportSection.vue 里应有 ${className}`)
|
||||
assert.ok(PICKER_SOURCE.includes(className), `EntryPicker.vue 里应照抄 ${className}`)
|
||||
}
|
||||
assert.match(PICKER_SOURCE, /class="mx-badge mx-badge-warning">有 \{\{ conflicts\.length \}\} 行没有加入,需要逐条确认/)
|
||||
// 列冲突用的还是那一套 class,不是新造的面板。
|
||||
assert.match(PICKER_SOURCE, /<ul class="error-list">/)
|
||||
assert.match(IMPORT_SOURCE, /<ul class="error-list">/)
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 示例数据模式下的写操作拦截(P2 A30)与「继续录入」的口径(P2 B09)。
|
||||
*
|
||||
* A30:发布 / 批次 / 团体名次早就按「示例数据不能写」停用了,只有「存草稿」与「撤销发布」
|
||||
* 还会真的发请求,拿回一句网络错误——操作员会以为是自己手滑,而不是「这台机没连上服务端」。
|
||||
* B09:注释与 07 文档都写「默认聚焦上次编辑的项目」,实现是取第一个 pending,
|
||||
* 前端也从没持久化过录入位置,所以注释必须按实现写。
|
||||
*
|
||||
* 项目没有组件测试工具(无 @vue/test-utils / jsdom),界面部分按仓库既有做法读源码断言。
|
||||
*/
|
||||
|
||||
const ENTRY_PAGE_SOURCE = readFileSync(new URL('../pages/EntryPage.vue', import.meta.url), 'utf8')
|
||||
|
||||
function section(source: string, start: string, end: string): string {
|
||||
const from = source.indexOf(start)
|
||||
const to = source.indexOf(end, from)
|
||||
assert.ok(from >= 0 && to > from, `源码里找不到 ${start} … ${end} 这一段`)
|
||||
return source.slice(from, to)
|
||||
}
|
||||
|
||||
test('示例数据模式下「存草稿」不发请求,提示与发布同一口径', () => {
|
||||
const saveDraft = section(ENTRY_PAGE_SOURCE, 'async function saveDraft(', 'function requestPublish(')
|
||||
|
||||
assert.match(saveDraft, /if \(data\.isMock\) \{/)
|
||||
assert.match(saveDraft, /toast\.error\('示例数据模式不能保存草稿', '后端未就绪,草稿不会写入真实赛事'\)/)
|
||||
// 早退必须发生在真正调用写接口之前。
|
||||
assert.ok(
|
||||
saveDraft.indexOf('data.isMock') < saveDraft.indexOf('await adminApi.saveDraft('),
|
||||
'isMock 判断要在 saveDraft 调用之前',
|
||||
)
|
||||
})
|
||||
|
||||
test('示例数据模式下「撤销发布」不发请求,提示与发布同一口径', () => {
|
||||
const confirmUnpublish = section(ENTRY_PAGE_SOURCE, 'async function confirmUnpublish(', '// ── 分批结算')
|
||||
|
||||
assert.match(confirmUnpublish, /if \(data\.isMock\) \{/)
|
||||
assert.match(confirmUnpublish, /toast\.error\('示例数据模式不能撤销发布', '后端未就绪,撤销发布不会写入真实赛事'\)/)
|
||||
assert.ok(
|
||||
confirmUnpublish.indexOf('data.isMock') < confirmUnpublish.indexOf('await adminApi.unpublish('),
|
||||
'isMock 判断要在 unpublish 调用之前',
|
||||
)
|
||||
})
|
||||
|
||||
test('两个按钮在示例数据模式下直接禁用,避免点了才被告知不能写', () => {
|
||||
assert.match(ENTRY_PAGE_SOURCE, /:disabled="!canWrite \|\| saving \|\| allPublished \|\| data\.isMock"/)
|
||||
assert.match(ENTRY_PAGE_SOURCE, /:disabled="!canWrite \|\| data\.isMock"/)
|
||||
})
|
||||
|
||||
test('「继续录入」的注释按实现写:第一个 pending,没有持久化的「上次编辑」', () => {
|
||||
const pickInitial = section(ENTRY_PAGE_SOURCE, '进入录入页时默认选中小项', 'onMounted(')
|
||||
|
||||
assert.doesNotMatch(pickInitial, /默认聚焦上次编辑/, '实现里没有「上次编辑」的记忆,注释不能那么写')
|
||||
assert.match(pickInitial, /第一个未开始(pending)的项目/)
|
||||
assert.match(pickInitial, /event\.status === 'pending'/)
|
||||
})
|
||||
|
||||
test('整份 EntryPage 里不再残留「默认聚焦上次编辑」这类与实现不符的说法', () => {
|
||||
assert.doesNotMatch(ENTRY_PAGE_SOURCE, /默认聚焦上次编辑/)
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { GUEST_ROLE, isGuestRole, isGuestUser } from '@/shared'
|
||||
import type { CurrentUser } from '@/shared'
|
||||
|
||||
/**
|
||||
* 访客判定只有一份实现(P2 C44)。
|
||||
*
|
||||
* `shared/session.ts` 早就写好 isGuestRole / isGuestUser,但 admin 的 auth store
|
||||
* 又内联手写了一遍 `role === 'guest'`:两处口径一旦分叉,
|
||||
* 「只读横幅 / 写保护 / 侧栏可见性」会各按各的理解走。这里钉住唯一实现与调用点。
|
||||
*/
|
||||
|
||||
function user(role: string): CurrentUser {
|
||||
return {
|
||||
id: 1,
|
||||
username: 'u',
|
||||
displayName: '用户',
|
||||
role,
|
||||
mustChangePassword: false,
|
||||
lastLoginAt: null,
|
||||
}
|
||||
}
|
||||
|
||||
test('GUEST_ROLE 与服务端 auth.RoleGuest 的字符串一致', () => {
|
||||
assert.equal(GUEST_ROLE, 'guest')
|
||||
})
|
||||
|
||||
test('null / undefined / guest DTO 都算访客', () => {
|
||||
assert.equal(isGuestUser(null), true)
|
||||
assert.equal(isGuestUser(undefined), true)
|
||||
assert.equal(isGuestUser(user('guest')), true)
|
||||
})
|
||||
|
||||
test('recorder / admin 不算访客', () => {
|
||||
assert.equal(isGuestUser(user('recorder')), false)
|
||||
assert.equal(isGuestUser(user('admin')), false)
|
||||
})
|
||||
|
||||
test('角色判定容忍大小写与空白(服务端不该发这种值,但脏值不能让人凭空变成已登录)', () => {
|
||||
assert.equal(isGuestRole(' GUEST '), true)
|
||||
assert.equal(isGuestRole('Guest'), true)
|
||||
assert.equal(isGuestRole('guest2'), false)
|
||||
assert.equal(isGuestRole(undefined), false)
|
||||
assert.equal(isGuestRole(1), false)
|
||||
})
|
||||
|
||||
const AUTH_STORE_SOURCE = readFileSync(new URL('../stores/auth.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('auth store 复用共享判定,不再内联重写一遍', () => {
|
||||
assert.match(AUTH_STORE_SOURCE, /const isGuest = computed\(\(\) => isGuestUser\(user\.value\)\)/)
|
||||
assert.doesNotMatch(AUTH_STORE_SOURCE, /role === 'guest'/)
|
||||
assert.match(AUTH_STORE_SOURCE, /import \{ isGuestUser \} from '@\/shared'/)})
|
||||
@@ -0,0 +1,116 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { ApiError } from '@/shared'
|
||||
import { fetchRevisions, revisionLoadErrorText } from '../components/history/revisionsSource'
|
||||
|
||||
/**
|
||||
* 访客进「变更历史」时的口径(P2 A31)。
|
||||
*
|
||||
* `/api/revisions` 是 recorder 起的接口,而面板未登录时会降级成「只读访客」。
|
||||
* 以前:侧栏照样给出入口,点进去页面把服务端/状态码原样(「变更历史接口返回 HTTP 401」)
|
||||
* 摔在红横幅上——操作员只会以为系统坏了。
|
||||
* 现在:侧栏对只读访客隐藏入口,页面把权限失败换成人话,其它错误仍原样透传。
|
||||
*/
|
||||
|
||||
interface Captured {
|
||||
url?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function stubFetch(reply: () => Response, captured: Captured): void {
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
captured.url = String(input)
|
||||
const response = reply()
|
||||
captured.status = response.status
|
||||
return response
|
||||
}) as typeof fetch
|
||||
}
|
||||
|
||||
test('403 按权限边界换成人话,不出现 HTTP 状态码', () => {
|
||||
const text = revisionLoadErrorText(
|
||||
new ApiError('FORBIDDEN', '无权访问该资源', 403, { required: 'recorder' }),
|
||||
)
|
||||
|
||||
assert.match(text, /录入员/)
|
||||
assert.match(text, /只读访客/)
|
||||
assert.doesNotMatch(text, /HTTP/)
|
||||
})
|
||||
|
||||
test('未登录(401 AUTH_REQUIRED)提示去登录', () => {
|
||||
const text = revisionLoadErrorText(new ApiError('AUTH_REQUIRED', '请先登录', 401))
|
||||
assert.match(text, /登录/)
|
||||
assert.doesNotMatch(text, /HTTP/)
|
||||
})
|
||||
|
||||
test('其它错误原样透传,不被美化掉', () => {
|
||||
assert.equal(revisionLoadErrorText(new ApiError('INTERNAL', '数据库忙', 500)), '数据库忙')
|
||||
assert.equal(revisionLoadErrorText(new Error('boom')), 'boom')
|
||||
assert.equal(revisionLoadErrorText(undefined), '变更历史接口不可用')
|
||||
})
|
||||
|
||||
test('服务端 403 的 error.code / message 被读出来(不再只看状态码猜)', async () => {
|
||||
const captured: Captured = {}
|
||||
stubFetch(
|
||||
() => jsonResponse({ ok: false, error: { code: 'FORBIDDEN', message: '无权访问该资源' } }, 403),
|
||||
captured,
|
||||
)
|
||||
|
||||
await assert.rejects(
|
||||
() => fetchRevisions(),
|
||||
(error: unknown) => {
|
||||
assert.ok(error instanceof ApiError)
|
||||
assert.equal(error.code, 'FORBIDDEN')
|
||||
assert.equal(error.message, '无权访问该资源')
|
||||
assert.equal(revisionLoadErrorText(error).includes('无权访问该资源'), false)
|
||||
return true
|
||||
},
|
||||
)
|
||||
assert.equal(captured.url, '/api/revisions')
|
||||
})
|
||||
|
||||
test('只有一个 eventId 过滤条件时拼 query,成功路径照旧解析', async () => {
|
||||
const captured: Captured = {}
|
||||
stubFetch(() => jsonResponse({ ok: true, data: [] }), captured)
|
||||
|
||||
const rows = await fetchRevisions({ eventId: 3 })
|
||||
|
||||
assert.equal(captured.url, '/api/revisions?eventId=3')
|
||||
assert.deepEqual(rows, [])
|
||||
})
|
||||
|
||||
test('连不上服务端仍是 NETWORK(页面据此降级示例数据)', async () => {
|
||||
globalThis.fetch = (async () => {
|
||||
throw new TypeError('fetch failed')
|
||||
}) as typeof fetch
|
||||
|
||||
await assert.rejects(
|
||||
() => fetchRevisions(),
|
||||
(error: unknown) => error instanceof ApiError && error.code === 'NETWORK',
|
||||
)
|
||||
})
|
||||
|
||||
function readSource(relative: string): string {
|
||||
return readFileSync(new URL(relative, import.meta.url), 'utf8')
|
||||
}
|
||||
|
||||
const HISTORY_PAGE_SOURCE = readSource('../pages/HistoryPage.vue')
|
||||
const LAYOUT_SOURCE = readSource('../layouts/AdminLayout.vue')
|
||||
|
||||
test('HistoryPage 的两个失败分支都走统一口径', () => {
|
||||
const hits = HISTORY_PAGE_SOURCE.match(/revisionLoadErrorText\(caught\)/g) ?? []
|
||||
assert.equal(hits.length, 2, '列表与详情都要走同一套文案')
|
||||
assert.doesNotMatch(HISTORY_PAGE_SOURCE, /loadError\.value = caught instanceof Error/)
|
||||
})
|
||||
|
||||
test('侧栏对只读访客隐藏「变更历史」,不再让人点进权限墙', () => {
|
||||
assert.match(LAYOUT_SOURCE, /name: 'history'[^}]*recorderOnly: true/)
|
||||
assert.match(LAYOUT_SOURCE, /item\.recorderOnly === true && auth\.readOnly/)
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 报名表导入的体积上限(P2 C26)。
|
||||
*
|
||||
* 服务端的硬上限是 `handlers_config.go` 的 `maxEntryImportBytes = 32 << 20`,
|
||||
* 而前端提示与用户文档一直写 16MB:界面先拦下的文件,直连 API 其实收得下。
|
||||
* 这条契约两边必须是同一个数,所以这里同时钉住数值与上屏文案。
|
||||
*/
|
||||
|
||||
const ImportSection = readFileSync(
|
||||
new URL('../components/baseData/ImportSection.vue', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
const { MAX_ENTRY_IMPORT_BYTES, entryImportSizeError } = await import(
|
||||
'../components/baseData/importLimits'
|
||||
)
|
||||
|
||||
test('上限与服务端的 32MB 取同一个数', () => {
|
||||
assert.equal(MAX_ENTRY_IMPORT_BYTES, 32 * 1024 * 1024)
|
||||
assert.equal(MAX_ENTRY_IMPORT_BYTES, 32 << 20)
|
||||
})
|
||||
|
||||
test('16MB 的文件不再被前端拦下(服务端本来就收得下)', () => {
|
||||
assert.equal(entryImportSizeError(16 * 1024 * 1024), null)
|
||||
assert.equal(entryImportSizeError(31 * 1024 * 1024), null)
|
||||
})
|
||||
|
||||
test('刚好等于上限放行,超过一个字节才拦', () => {
|
||||
assert.equal(entryImportSizeError(MAX_ENTRY_IMPORT_BYTES), null)
|
||||
assert.equal(entryImportSizeError(MAX_ENTRY_IMPORT_BYTES + 1), '文件超过 32MB,服务端会拒绝解析')
|
||||
})
|
||||
|
||||
test('页面用这个判定,且说明文案也改成 32MB', () => {
|
||||
assert.match(ImportSection, /entryImportSizeError\(file\.size\)/)
|
||||
assert.doesNotMatch(ImportSection, /16MB/)
|
||||
assert.match(ImportSection, /单个文件不超过 32MB/)
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { ApiError } from '@/shared'
|
||||
import { restoreFailureNotice } from '../components/system/systemApi'
|
||||
|
||||
/**
|
||||
* 恢复失败时的提示口径(P2 A29)。
|
||||
*
|
||||
* 服务端的恢复是很长一串:校验备份 → 拍恢复前安全副本 → 断连接 → 换库文件 → 复核新库 → 写审计,
|
||||
* **回执在这之后才发出**。所以「没收到回执」与「没执行」是两件事:
|
||||
* 前者可能库已经换掉了。这里钉住这两类失败必须给出不同的说法,
|
||||
* 免得操作员看到「当前库未被覆盖」就再点一次恢复,把刚恢复好的库再覆盖一遍。
|
||||
*/
|
||||
|
||||
test('超时按「没收到回执、可能已生效」定性,并给出确认步骤', () => {
|
||||
const notice = restoreFailureNotice(new ApiError('TIMEOUT', '请求超时(60000ms)', 0))
|
||||
|
||||
assert.equal(notice.title, '没收到恢复回执,恢复可能已经生效')
|
||||
assert.match(notice.detail, /请求超时/)
|
||||
assert.match(notice.detail, /刷新页面确认/)
|
||||
assert.match(notice.detail, /不要直接再点一次恢复/)
|
||||
assert.doesNotMatch(notice.title, /未被覆盖/)
|
||||
})
|
||||
|
||||
test('断连同样按「没收到回执、可能已生效」定性', () => {
|
||||
const notice = restoreFailureNotice(new ApiError('NETWORK', '无法连接服务端', 0))
|
||||
assert.equal(notice.title, '没收到恢复回执,恢复可能已经生效')
|
||||
assert.match(notice.detail, /刷新页面确认/)
|
||||
})
|
||||
|
||||
// 拿到了 2xx 却读不出约定结构:服务端已经做完并回了响应,同样不能宣称「库没动」。
|
||||
test('响应读不出结构(PARSE_FAILED)也算「没拿到回执」', () => {
|
||||
const notice = restoreFailureNotice(
|
||||
new ApiError('PARSE_FAILED', '服务端响应不是约定的 {ok,data} 结构', 200),
|
||||
)
|
||||
assert.equal(notice.title, '没收到恢复回执,恢复可能已经生效')
|
||||
})
|
||||
|
||||
test('服务端在动库之前给出的业务错误照旧说「未执行、库未被覆盖」', () => {
|
||||
const notice = restoreFailureNotice(
|
||||
new ApiError('VALIDATION_FAILED', '备份文件不可用:缺少关键表 teams', 400),
|
||||
)
|
||||
|
||||
assert.equal(notice.title, '恢复未执行,当前库未被覆盖')
|
||||
assert.equal(notice.detail, '备份文件不可用:缺少关键表 teams')
|
||||
})
|
||||
|
||||
test('回滚类错误把服务端原文带上(它的说明比笼统措辞更准)', () => {
|
||||
const notice = restoreFailureNotice(
|
||||
new ApiError('INTERNAL', '恢复后校验失败,已自动回滚到恢复前状态', 500, 'pre-restore-event.db'),
|
||||
)
|
||||
|
||||
assert.equal(notice.title, '恢复未执行,当前库未被覆盖')
|
||||
assert.match(notice.detail, /已自动回滚/)
|
||||
})
|
||||
|
||||
test('非 ApiError 的异常不让页面白屏,仍给出可读文案', () => {
|
||||
const notice = restoreFailureNotice(new Error('boom'))
|
||||
assert.equal(notice.detail, 'boom')
|
||||
|
||||
const unknown = restoreFailureNotice(undefined)
|
||||
assert.equal(unknown.detail, '未知错误')
|
||||
})
|
||||
|
||||
// 页面必须走这个函数(而不是自己拼一句「当前库未被覆盖」),否则口径会再次分叉。
|
||||
const BACKUP_PANEL_SOURCE = readSource('../components/system/BackupPanel.vue')
|
||||
|
||||
function readSource(relative: string): string {
|
||||
return readFileSync(new URL(relative, import.meta.url), 'utf8')
|
||||
}
|
||||
|
||||
test('BackupPanel 的失败分支用 restoreFailureNotice 定性', () => {
|
||||
assert.match(BACKUP_PANEL_SOURCE, /restoreFailureNotice\(caught\)/)
|
||||
assert.match(BACKUP_PANEL_SOURCE, /toast\.error\(notice\.title, notice\.detail\)/)
|
||||
})
|
||||
|
||||
test('恢复请求走的是放大过超时的那条客户端路径', () => {
|
||||
const apiSource = readSource('../../shared/api.ts')
|
||||
assert.match(apiSource, /timeoutMs: RESTORE_TIMEOUT_MS/)
|
||||
assert.match(apiSource, /export const RESTORE_TIMEOUT_MS = 60_000/)
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
/**
|
||||
* 「分批发布时实时更新榜单」勾选框的口径(P2 B10)。
|
||||
*
|
||||
* devdocs/07 §5.6 写它「即时保存」,实现却是勾选后还要点「保存结算方式」:
|
||||
* 操作员勾完就走,下一批发布才发现榜单没按预期更新,而且看不出自己漏了一步。
|
||||
* 这里钉住「不是即时保存」这件事必须在界面上说清楚(勾选框旁 + 说明文字 + 按钮)。
|
||||
*/
|
||||
|
||||
const SOURCE = readFileSync(
|
||||
new URL('../components/baseData/ProfilesSection.vue', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
|
||||
test('勾选框有未保存标记,只有改动后出现', () => {
|
||||
assert.match(SOURCE, /<span v-if="liveDirty" class="mx-badge mx-badge-warning"/)
|
||||
assert.match(SOURCE, /改动未保存/)
|
||||
})
|
||||
|
||||
test('仍由按钮提交,勾选框本身不触发保存', () => {
|
||||
assert.match(SOURCE, /v-model="liveOnPublish"/)
|
||||
assert.doesNotMatch(SOURCE, /v-model="liveOnPublish"[\s\S]{0,200}@change=/)
|
||||
assert.match(SOURCE, /@click="saveLiveOnPublishSetting"/)
|
||||
assert.match(SOURCE, /:disabled="!isAdmin \|\| !liveDirty \|\| liveSaving"/)
|
||||
})
|
||||
|
||||
test('说明文字写明「不是即时保存」', () => {
|
||||
assert.match(SOURCE, /勾选本身不是即时保存,改完要点「保存结算方式」才写进服务端/)
|
||||
})
|
||||
@@ -145,14 +145,14 @@ test('连不上服务端时降级为占位文件,网络错误留在 mockReason
|
||||
assert.equal(lastRequest.url, '/api/export/teams.xlsx')
|
||||
})
|
||||
|
||||
test('奖牌明细导出走 GET /api/export/medals.xlsx,文件名是「团体奖牌明细.xlsx」', async () => {
|
||||
test('奖牌明细导出走 GET /api/export/medals.xlsx,文件名是「单位奖牌明细.xlsx」', async () => {
|
||||
respondWith(() => xlsxResponse())
|
||||
|
||||
const result = await resultsExportApi.download({ kind: 'medalAll' })
|
||||
|
||||
assert.equal(lastRequest.url, '/api/export/medals.xlsx')
|
||||
assert.equal(lastRequest.method, 'GET')
|
||||
assert.equal(result.data.filename, '团体奖牌明细.xlsx')
|
||||
assert.equal(result.data.filename, '单位奖牌明细.xlsx')
|
||||
assert.equal(result.mock, false, '正常响应不应被当成示例数据')
|
||||
})
|
||||
|
||||
@@ -218,5 +218,5 @@ test('连不上时新 kind 的占位文件名也正确', async () => {
|
||||
const result = await resultsExportApi.download({ kind: 'medalAll' })
|
||||
|
||||
assert.equal(result.mock, true)
|
||||
assert.equal(result.data.filename, '团体奖牌明细(示例数据).txt')
|
||||
assert.equal(result.data.filename, '单位奖牌明细(示例数据).txt')
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
import { useScoreboard } from '../useScoreboard'
|
||||
import { DEFAULT_ROTATE_SECONDS } from '../guards'
|
||||
|
||||
type TickerKind = 'medals' | 'results' | 'announcement'
|
||||
|
||||
@@ -11,7 +12,7 @@ interface TickerItem {
|
||||
|
||||
const { standings, latestResults, announceText, detail, settings } = useScoreboard()
|
||||
|
||||
// 与团体奖牌榜页同一口径:按服务端名次(总分优先)取前 3,不在前端按金→银→铜重排。
|
||||
// 与单位奖牌榜页同一口径:按服务端名次(总分优先)取前 3,不在前端按金→银→铜重排。
|
||||
const topMedals = computed(() => standings.value.slice(0, 3))
|
||||
|
||||
const latestGroup = computed(() => latestResults.value[0] ?? null)
|
||||
@@ -28,7 +29,9 @@ const items = computed<TickerItem[]>(() => {
|
||||
const index = ref(0)
|
||||
const current = computed<TickerItem | null>(() => items.value[index.value] ?? items.value[0] ?? null)
|
||||
const paused = computed(() => detail.value !== null)
|
||||
const rotateMs = computed(() => Math.max(2, settings.value?.display?.rotateSeconds ?? 8) * 1000)
|
||||
const rotateMs = computed(
|
||||
() => Math.max(2, settings.value?.display?.rotateSeconds ?? DEFAULT_ROTATE_SECONDS) * 1000,
|
||||
)
|
||||
|
||||
let timer = 0
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ const rowFont = computed(() => fitRowFont(rows.value.length, BOARD_AVAILABLE_PX)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PageFrame title="团体奖牌榜">
|
||||
<PageFrame title="单位奖牌榜">
|
||||
<div class="board" :style="{ '--row-font': rowFont }">
|
||||
<div class="row head">
|
||||
<span>名次</span>
|
||||
|
||||
@@ -32,6 +32,15 @@ import type {
|
||||
} from '@/shared'
|
||||
import type { LiveEventSource } from './live'
|
||||
|
||||
/**
|
||||
* `display.rotateSeconds` 缺配置时的兜底秒数。
|
||||
*
|
||||
* 必须与服务端同一个数:`dto/settings.go` 用 `atoiDefault(values["display.rotate_seconds"], 15)`,
|
||||
* 所以「没配过」的库下发出来的就是 15。前端自己填 8 会让底栏 / 整页轮播比服务端口径快一倍,
|
||||
* 现场只会觉得「说好的 15 秒怎么变快了」。
|
||||
*/
|
||||
export const DEFAULT_ROTATE_SECONDS = 15
|
||||
|
||||
/**
|
||||
* WebSocket 与 localStorage 里的东西一律先当 unknown 再收窄。
|
||||
*
|
||||
@@ -487,7 +496,10 @@ export function parseSettings(source: unknown): DisplaySettings {
|
||||
title: str(settingValue(rec, 'display.title', 'display.title')),
|
||||
subtitle: strOrNull(settingValue(rec, 'display.subtitle', 'display.subtitle')),
|
||||
primaryColor: strOrNull(settingValue(rec, 'display.primaryColor', 'display.theme_color')),
|
||||
rotateSeconds: num(settingValue(rec, 'display.rotateSeconds', 'display.rotate_seconds'), 8),
|
||||
rotateSeconds: num(
|
||||
settingValue(rec, 'display.rotateSeconds', 'display.rotate_seconds'),
|
||||
DEFAULT_ROTATE_SECONDS,
|
||||
),
|
||||
announce: announce === '' ? null : announce,
|
||||
fontTitle: fontTitle === '' ? null : fontTitle,
|
||||
fontBody: fontBody === '' ? null : fontBody,
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
Team,
|
||||
} from '@/shared'
|
||||
import type { DisplaySettings } from './guards'
|
||||
import { DEFAULT_ROTATE_SECONDS } from './guards'
|
||||
|
||||
/**
|
||||
* 后端未就绪时的降级数据(任务要求:降级 mock 并标注「示例数据」)。
|
||||
@@ -268,7 +269,8 @@ const MOCK_SETTINGS: DisplaySettings = {
|
||||
title: '2026 职工运动会',
|
||||
subtitle: '积分榜 · 示例数据',
|
||||
primaryColor: '#4fd8ff',
|
||||
rotateSeconds: 8,
|
||||
// 与服务端默认一致(dto/settings.go 的 display.rotate_seconds 兜底 15)。
|
||||
rotateSeconds: DEFAULT_ROTATE_SECONDS,
|
||||
// 示例数据里有 3 个已完成项目,取前两个演示双栏分栏。
|
||||
liveEvents: [1, 2],
|
||||
liveSource: 'manual',
|
||||
|
||||
@@ -47,6 +47,8 @@ export type TemplateErrorCode =
|
||||
| 'block-mismatch'
|
||||
| 'unexpected-else'
|
||||
| 'duplicate-else'
|
||||
/** `{{else if …}}` / `{{else anything}}`:设计稿 §3.3 只支持块内一层 else,链式写法必须报错 */
|
||||
| 'unsupported-else-chain'
|
||||
| 'unknown-block'
|
||||
| 'empty-block-path'
|
||||
/** 嵌套层数超过 MAX_TEMPLATE_DEPTH(安全阀,位置指向超出的那个块标记) */
|
||||
@@ -243,6 +245,7 @@ const ERROR_TEXT: Record<TemplateErrorCode, string> = {
|
||||
'block-mismatch': '结束标记与最近的块不配对',
|
||||
'unexpected-else': '{{else}} 只能出现在 {{#if}} 块内',
|
||||
'duplicate-else': '同一个 {{#if}} 块里出现了多个 {{else}}',
|
||||
'unsupported-else-chain': '不支持 {{else if}} 这种链式写法({{else}} 只能出现一层),请改成嵌套的 {{#if}}',
|
||||
'unknown-block': '不支持的块标记',
|
||||
'empty-block-path': '块标记缺少路径',
|
||||
'too-deep': '模板嵌套太深',
|
||||
@@ -359,6 +362,11 @@ function tokenize(
|
||||
tokens.push({ kind: 'close', block: keyword as 'each' | 'if', rawPath: '', raw: false, start: open, end, line, column })
|
||||
} else if (inner === 'else') {
|
||||
tokens.push({ kind: 'else', block: null, rawPath: '', raw: false, start: open, end, line, column })
|
||||
} else if (/^else\s/.test(inner)) {
|
||||
// `{{else if b}}` 这类链式写法:设计稿 §3.3 明确不支持(else 只有一层)。
|
||||
// 绝不能当插值塞进 then 分支——那是整块内容静默消失、连警告都没有的坑,
|
||||
// 所以这里直接给结构化错误,让预览能指出位置。
|
||||
return { tokens, error: makeError('unsupported-else-chain', starts, open, `{{${inner}}}`) }
|
||||
} else if (!triple && inner.startsWith('&')) {
|
||||
// {{& x}} 与 {{{ x }}} 同义(设计稿 §3.4)
|
||||
tokens.push({ kind: 'value', block: null, rawPath: inner.slice(1).trim(), raw: true, start: open, end, line, column })
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { parseAthleteStandings, parseStandingRows } from '../guards'
|
||||
|
||||
/**
|
||||
* REST 兜底也要过 guards(P2 C39)。
|
||||
*
|
||||
* `api.standings.*` 只做 `{ok,data}` 拆包,字段缺失 / 类型不对时照样把裸值交出来;
|
||||
* WS 快照那条路一直过 guards,REST 兜底却直接把返回值塞进 ref。
|
||||
* 大屏是无人值守的,少一个字段就可能让模板整块渲染成空,两条路必须同口径。
|
||||
*/
|
||||
|
||||
const USE_SCOREBOARD_SOURCE = readFileSync(new URL('../useScoreboard.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('个人榜 REST 数据经 guards 归一:缺字段补默认值,不抛异常', () => {
|
||||
const rows = parseAthleteStandings([{ athleteId: 7, teamId: 2, athleteName: '张三' }])
|
||||
|
||||
assert.equal(rows.length, 1)
|
||||
const row = rows[0]
|
||||
assert.equal(row?.athleteId, 7)
|
||||
assert.equal(row?.teamId, 2)
|
||||
assert.equal(row?.athleteName, '张三')
|
||||
assert.equal(row?.rank, 0)
|
||||
assert.equal(row?.totalPoints, 0)
|
||||
assert.equal(row?.shortName, null)
|
||||
assert.equal(row?.logoPath, null)
|
||||
})
|
||||
|
||||
test('脏行也不炸:非对象 / 缺字段都按默认值收下', () => {
|
||||
assert.doesNotThrow(() => parseAthleteStandings([null, 1, 'x', []]))
|
||||
assert.equal(parseAthleteStandings([null, 1, 'x']).length, 3)
|
||||
assert.equal(parseAthleteStandings('not-an-array').length, 0)
|
||||
})
|
||||
|
||||
test('单位榜 REST 数据同样过 guards', () => {
|
||||
const rows = parseStandingRows([{ teamId: 1, teamName: '第一分公司' }])
|
||||
|
||||
assert.equal(rows[0]?.teamId, 1)
|
||||
assert.equal(rows[0]?.rank, 0)
|
||||
assert.equal(rows[0]?.medalTotal, 0)
|
||||
assert.equal(rows[0]?.rankChange, null)
|
||||
})
|
||||
|
||||
test('loadRest 的两条路都走 guards,不再把裸值塞进 ref', () => {
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /applyStandings\(parseStandingRows\(standingsResult\.value\)\)/)
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /athletes\.value = parseAthleteStandings\(athletesResult\.value\)/)
|
||||
assert.doesNotMatch(USE_SCOREBOARD_SOURCE, /athletes\.value = athletesResult\.value/)
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { DEFAULT_ROTATE_SECONDS, parseSettings } from '../guards'
|
||||
import { createMockSnapshot } from '../mock'
|
||||
|
||||
/**
|
||||
* 轮播间隔的两条口径(P2 B05 / B06)。
|
||||
*
|
||||
* B05:缺 `display.rotateSeconds` 时前端兜底 8 秒,而服务端默认(dto/settings.go 的
|
||||
* atoiDefault(..., 15))是 15 秒——同一个「没配过」的库,底栏在大屏上快了近一倍。
|
||||
* B06:整页轮播写死 20 秒,完全不读这个配置;06 §4 承诺两者「同间隔」。
|
||||
*/
|
||||
|
||||
const USE_SCOREBOARD_SOURCE = readFileSync(new URL('../useScoreboard.ts', import.meta.url), 'utf8')
|
||||
const TICKER_SOURCE = readFileSync(
|
||||
new URL('../components/TickerBar.vue', import.meta.url),
|
||||
'utf8',
|
||||
)
|
||||
|
||||
test('缺配置时按服务端默认 15 秒兜底', () => {
|
||||
assert.equal(DEFAULT_ROTATE_SECONDS, 15)
|
||||
assert.equal(parseSettings({}).display.rotateSeconds, 15)
|
||||
})
|
||||
|
||||
test('配了就用配置的值(15 以外的值也照收)', () => {
|
||||
assert.equal(parseSettings({ display: { rotateSeconds: 30 } }).display.rotateSeconds, 30)
|
||||
// 服务端快照里也可能给扁平键,两种形状都要认。
|
||||
assert.equal(parseSettings({ 'display.rotate_seconds': 5 }).display.rotateSeconds, 5)
|
||||
})
|
||||
|
||||
test('示例数据与真服务端同口径(不再写 8)', () => {
|
||||
assert.equal(createMockSnapshot().settings.display.rotateSeconds, DEFAULT_ROTATE_SECONDS)
|
||||
})
|
||||
|
||||
test('整页轮播读 display.rotateSeconds,不再写死 20 秒', () => {
|
||||
assert.doesNotMatch(USE_SCOREBOARD_SOURCE, /PAGE_ROTATE_MS/)
|
||||
assert.doesNotMatch(USE_SCOREBOARD_SOURCE, /20_000/)
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /settings\.value\?\.display\?\.rotateSeconds/)
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /\}, pageRotateMs\.value\)/)
|
||||
})
|
||||
|
||||
test('配置变化后重排计时器(setInterval 的周期不会自己变)', () => {
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /watch\(pageRotateMs, \(\) => \{\n\s*if \(pageTimer !== null\) startPageRotation\(\)/)
|
||||
})
|
||||
|
||||
test('配置非法或过小时有下限,不会疯狂翻页', () => {
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /const MIN_ROTATE_SECONDS = 2/)
|
||||
assert.match(USE_SCOREBOARD_SOURCE, /Math\.max\(MIN_ROTATE_SECONDS, safe\) \* 1000/)
|
||||
})
|
||||
|
||||
test('底栏的兜底值同样来自共享常量', () => {
|
||||
assert.match(TICKER_SOURCE, /settings\.value\?\.display\?\.rotateSeconds \?\? DEFAULT_ROTATE_SECONDS/)
|
||||
assert.doesNotMatch(TICKER_SOURCE, /\?\? 8\)/)
|
||||
})
|
||||
@@ -102,3 +102,60 @@ test('行号按实际换行统计(\\r\\n 模板也不偏)', () => {
|
||||
const result = renderTemplate('a\r\nb\r\n{{#each rows}}\r\nx\r\n', { rows: [] })
|
||||
assert.equal(result.error?.line, 3)
|
||||
})
|
||||
|
||||
/*
|
||||
* `{{else if b}}`:设计稿 §3.3 明确只支持块内一层 {{else}},不支持链式 else。
|
||||
* 以前它落到「当作插值」那条分支,被塞进 then 分支里——条件为假时整块内容**静默消失**,
|
||||
* 连一条警告都没有(警告只在渲染到的节点上产生),现场只会看到「屏幕少了一块」。
|
||||
* 现在必须走结构化错误,让预览能指出是哪一行。
|
||||
*/
|
||||
test('{{else if b}} 报 unsupported-else-chain,而不是被当成插值', () => {
|
||||
const result = renderTemplate('{{#if a}}A{{else if b}}B{{/if}}', { a: false, b: true })
|
||||
|
||||
assert.equal(result.error?.code, 'unsupported-else-chain')
|
||||
assert.equal(result.html, '', '结构错误时 html 恒为空,不渲染半截')
|
||||
assert.deepEqual(result.warnings, [], '不该退化成「插值取不到值」的警告')
|
||||
assert.equal(result.error?.line, 1)
|
||||
})
|
||||
|
||||
test('条件为真也一样报错:错误要在解析期定死,不随数据变', () => {
|
||||
const result = renderTemplate('{{#if a}}A{{else if b}}B{{/if}}', { a: true, b: true })
|
||||
|
||||
assert.equal(result.error?.code, 'unsupported-else-chain')
|
||||
assert.equal(result.html, '')
|
||||
})
|
||||
|
||||
test('错误信息给出原文、位置与替代写法', () => {
|
||||
const parsed = parseTemplate('第一行\n{{#if x}}1{{else if y}}2{{/if}}')
|
||||
|
||||
assert.equal(parsed.error?.code, 'unsupported-else-chain')
|
||||
assert.equal(parsed.error?.line, 2)
|
||||
assert.ok(parsed.error?.message.includes('{{else if y}}'), '要带上原文,才知道改哪一处')
|
||||
assert.ok(parsed.error?.message.includes('{{#if}}'), '要给出「改成嵌套 if」的替代写法')
|
||||
assert.deepEqual(parsed.ast, [])
|
||||
})
|
||||
|
||||
test('带空白的写法({{ else if b }})同样拦下', () => {
|
||||
assert.equal(
|
||||
renderTemplate('{{#if a}}A{{ else if b }}B{{/if}}', { a: false }).error?.code,
|
||||
'unsupported-else-chain',
|
||||
)
|
||||
})
|
||||
|
||||
test('其它链式写法({{else each rows}})也拦下,不静默', () => {
|
||||
assert.equal(
|
||||
renderTemplate('{{#if a}}A{{else each rows}}B{{/if}}', { a: false }).error?.code,
|
||||
'unsupported-else-chain',
|
||||
)
|
||||
})
|
||||
|
||||
test('块外的 {{else if}} 也报错(不落进插值分支)', () => {
|
||||
assert.equal(renderTemplate('{{else if b}}', {}).error?.code, 'unsupported-else-chain')
|
||||
})
|
||||
|
||||
test('正常的 {{else}} 不受影响', () => {
|
||||
const result = renderTemplate('{{#if a}}1{{else}}2{{/if}}', { a: false })
|
||||
|
||||
assert.equal(result.error, null)
|
||||
assert.equal(result.html, '2')
|
||||
})
|
||||
@@ -5,7 +5,7 @@ import type { TeamBreakdown } from '@/shared'
|
||||
*/
|
||||
export const DISPLAY_PAGES = [
|
||||
{ key: 'standings', title: '总积分榜' },
|
||||
{ key: 'team-medals', title: '团体奖牌榜' },
|
||||
{ key: 'team-medals', title: '单位奖牌榜' },
|
||||
{ key: 'athlete-standings', title: '个人积分奖牌榜' },
|
||||
{ key: 'event-results', title: '分项成绩' },
|
||||
{ key: 'live', title: '实时赛况' },
|
||||
@@ -25,7 +25,9 @@ const PAGE_ALIASES: Record<string, DisplayPageKey> = {
|
||||
medals: 'team-medals',
|
||||
medal: 'team-medals',
|
||||
奖牌榜: 'team-medals',
|
||||
// 「团体奖牌榜」是旧叫法(容易与「团体项目的奖牌」混淆),保留为别名让老链接/老配置继续可用。
|
||||
团体奖牌榜: 'team-medals',
|
||||
单位奖牌榜: 'team-medals',
|
||||
'athlete-standings': 'athlete-standings',
|
||||
athletes: 'athlete-standings',
|
||||
individual: 'athlete-standings',
|
||||
|
||||
@@ -10,6 +10,8 @@ import type {
|
||||
StandingRow,
|
||||
} from '@/shared'
|
||||
import {
|
||||
DEFAULT_ROTATE_SECONDS,
|
||||
parseAthleteStandings,
|
||||
parseLiveFeed,
|
||||
parseSettings,
|
||||
parseSnapshot,
|
||||
@@ -32,8 +34,8 @@ import type {
|
||||
} from './types'
|
||||
import { prefersReducedMotion } from './useReducedMotion'
|
||||
|
||||
/** 整页轮播间隔(06 第 4 节:后台可切换为整页轮播,每页 20s)。 */
|
||||
const PAGE_ROTATE_MS = 20_000
|
||||
/** 轮播间隔下限(秒):配置成 0 或负数时按 2 秒兜底,不然会疯狂翻页。 */
|
||||
const MIN_ROTATE_SECONDS = 2
|
||||
/** 名次升降箭头保留时长(06 第 7 节:2s 后淡出)。 */
|
||||
const RANK_DELTA_MS = 2_000
|
||||
|
||||
@@ -114,6 +116,22 @@ const rotationPages = computed<DisplayPageKey[]>(() =>
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 整页轮播间隔:与服务端 `display.rotateSeconds` 同源(06 第 4 节「与底栏同间隔」)。
|
||||
*
|
||||
* 以前写死 20s,管理员把轮播改成 15s 或 30s 只影响底栏,整页轮播毫无反应。
|
||||
* 缺配置 / 配置非法时按服务端默认值兜底(`dto/settings.go` 的 rotate_seconds 兜底 15),
|
||||
* 并结合下限,避免配成 0 时疯狂翻页。
|
||||
*/
|
||||
const pageRotateMs = computed(() => {
|
||||
const seconds = settings.value?.display?.rotateSeconds
|
||||
const safe =
|
||||
typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0
|
||||
? seconds
|
||||
: DEFAULT_ROTATE_SECONDS
|
||||
return Math.max(MIN_ROTATE_SECONDS, safe) * 1000
|
||||
})
|
||||
|
||||
function compareStanding(a: StandingRow, b: StandingRow): number {
|
||||
return a.rank - b.rank || b.totalPoints - a.totalPoints
|
||||
}
|
||||
@@ -305,6 +323,10 @@ function hydrateFromCache(): void {
|
||||
* 大屏不请求 /api/settings(admin-only,guest 必然 403),配置只认 WS 快照与本地缓存;
|
||||
* 快照比 REST 权威(REST 没有 version),且请求飞行途中可能已有快照到达,
|
||||
* 所以是否套用 REST 必须在 await 之后重新判断,不能沿用发请求前的结论。
|
||||
*
|
||||
* 两条路都必须过 guards:`api.standings.*` 只做了 JSON 解析(`{ok,data}` 拆包),
|
||||
* 字段缺失 / 类型不对时它照样把裸值交出来,而大屏是无人值守的——
|
||||
* 少一个字段就可能让整页模板渲染成空。WS 快照那条路一直是过 guards 的,两边口径要一致。
|
||||
*/
|
||||
async function loadRest(): Promise<boolean> {
|
||||
const [standingsResult, athletesResult] = await Promise.allSettled([
|
||||
@@ -315,11 +337,11 @@ async function loadRest(): Promise<boolean> {
|
||||
|
||||
let ok = false
|
||||
if (standingsResult.status === 'fulfilled' && !hasSnapshot) {
|
||||
applyStandings(standingsResult.value)
|
||||
applyStandings(parseStandingRows(standingsResult.value))
|
||||
ok = true
|
||||
}
|
||||
if (athletesResult.status === 'fulfilled') {
|
||||
athletes.value = athletesResult.value
|
||||
athletes.value = parseAthleteStandings(athletesResult.value)
|
||||
ok = true
|
||||
}
|
||||
return ok
|
||||
@@ -390,7 +412,7 @@ function startPageRotation(): void {
|
||||
const current = order.indexOf(page.value)
|
||||
const next = order[(current + 1) % order.length]
|
||||
if (next !== undefined) page.value = next
|
||||
}, PAGE_ROTATE_MS)
|
||||
}, pageRotateMs.value)
|
||||
}
|
||||
|
||||
function setLocked(value: boolean): void {
|
||||
@@ -492,6 +514,13 @@ watch(
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// 轮播间隔也来自 settings(display.rotateSeconds),而 setInterval 的周期在建表时就固定了:
|
||||
// 设置到达 / 被改后必须重排计时器,否则首屏(快照还没到)会一直按兜底间隔翻。
|
||||
// 只在轮播真在跑时才动它——锁定、全屏公告、明细覆盖期间本来就该停着。
|
||||
watch(pageRotateMs, () => {
|
||||
if (pageTimer !== null) startPageRotation()
|
||||
})
|
||||
|
||||
/**
|
||||
* 服务端把当前公告持久化在设置里(display.announce),快照与设置接口都带它。
|
||||
*
|
||||
|
||||
+51
-46
@@ -10,7 +10,6 @@ import type {
|
||||
AthleteStanding,
|
||||
AuditLog,
|
||||
AuditLogQuery,
|
||||
BackupResult,
|
||||
BackupRestoreInput,
|
||||
BackupRestoreResult,
|
||||
CurrentUser,
|
||||
@@ -80,6 +79,14 @@ interface RequestOptions {
|
||||
query?: object
|
||||
body?: unknown
|
||||
signal?: AbortSignal
|
||||
/**
|
||||
* 单次请求的超时覆盖值(毫秒);不传用客户端默认的 `ApiClientOptions.timeoutMs`。
|
||||
*
|
||||
* 停机类动作(用备份恢复整库)在服务端要拍安全副本、换文件、校验、再写审计,
|
||||
* 回执是**全部做完之后**才发出的:默认 15s 会在库已经换掉之后把请求判成超时,
|
||||
* 于是客户端以为「没执行」而重试。这类接口必须单独放大超时。
|
||||
*/
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'
|
||||
@@ -369,15 +376,8 @@ export interface DisplayApi {
|
||||
live(): Promise<LiveEvents>
|
||||
}
|
||||
|
||||
export interface ExportQuery {
|
||||
eventId?: number
|
||||
teamId?: number
|
||||
}
|
||||
|
||||
export interface ExportApi {
|
||||
/** 返回可直接放进 <a download> 的地址,省掉一次内存中的 Blob。 */
|
||||
standingsUrl(query?: ExportQuery): string
|
||||
standings(query?: ExportQuery): Promise<Blob>
|
||||
/** 把服务端返回的 Blob 存成文件(积分榜 / 结果导出的唯一入口)。 */
|
||||
save(blob: Blob, filename: string): void
|
||||
}
|
||||
|
||||
@@ -393,7 +393,6 @@ export interface RulesApi {
|
||||
}
|
||||
|
||||
export interface SystemApi {
|
||||
backup(): Promise<BackupResult>
|
||||
/**
|
||||
* 用一份备份恢复当前库(`POST /api/backup/restore`,仅 admin)。
|
||||
*
|
||||
@@ -428,8 +427,6 @@ interface Http {
|
||||
requestVoid(path: string, options?: RequestOptions): Promise<void>
|
||||
requestJson(path: string, options?: RequestOptions): Promise<unknown>
|
||||
requestText(path: string, options?: RequestOptions): Promise<string>
|
||||
url(path: string, query?: object): string
|
||||
blob(path: string, options?: RequestOptions): Promise<Blob>
|
||||
}
|
||||
|
||||
function createCrudApi<T, Input>(http: Http, base: string): CrudApi<T, Input> {
|
||||
@@ -596,13 +593,9 @@ function createResultsApi(http: Http): ResultsApi {
|
||||
}
|
||||
}
|
||||
|
||||
function createExportApi(http: Http): ExportApi {
|
||||
// 服务端只注册了 /export/standings.xlsx 与 /export/all.xlsx 等;
|
||||
// 单位明细 / 分项成绩导出分别是 /export/teams/{id}、/export/events/{id},由各自页面拼地址。
|
||||
const standingsPath = '/export/standings.xlsx'
|
||||
/** 导出只剩下「把 Blob 存成文件」这一件事:路径与文件名由各页面按服务端 Content-Disposition 拼。 */
|
||||
function createExportApi(): ExportApi {
|
||||
return {
|
||||
standingsUrl: (query) => http.url(standingsPath, query),
|
||||
standings: (query) => http.blob(standingsPath, { query }),
|
||||
save: (blob, filename) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
@@ -718,6 +711,15 @@ function defaultRequestId(): string {
|
||||
return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复整库的超时(毫秒)。
|
||||
*
|
||||
* 服务端的恢复是「结束请求才写回执」:拍安全副本、换文件、复核、写审计全部做完才 writeJSON。
|
||||
* 而备份体积随赛事数据增长(几百 MB 很常见),默认 15s 会把「已经在换库」的请求判成超时;
|
||||
* 60s 相对默认留了 4 倍余量,又远小于现场操作员的等待耐心。
|
||||
*/
|
||||
export const RESTORE_TIMEOUT_MS = 60_000
|
||||
|
||||
export class ApiClient {
|
||||
readonly auth: AuthApi
|
||||
readonly settings: SettingsApi
|
||||
@@ -761,8 +763,6 @@ export class ApiClient {
|
||||
requestVoid: (path, requestOptions) => this.requestVoid(path, requestOptions),
|
||||
requestJson: (path, requestOptions) => this.requestJson(path, requestOptions),
|
||||
requestText: (path, requestOptions) => this.requestText(path, requestOptions),
|
||||
url: (path, query) => this.buildUrl(path, query),
|
||||
blob: (path, requestOptions) => this.fetchBlob(path, requestOptions),
|
||||
}
|
||||
|
||||
this.auth = {
|
||||
@@ -845,15 +845,22 @@ export class ApiClient {
|
||||
live: () => http.request<LiveEvents>('/display/live'),
|
||||
}
|
||||
|
||||
this.exports = createExportApi(http)
|
||||
this.exports = createExportApi()
|
||||
this.auditLogs = {
|
||||
list: (query) => http.request<Page<AuditLog>>('/audit-logs', { query }),
|
||||
}
|
||||
this.rules = createRulesApi(http)
|
||||
this.system = {
|
||||
backup: () => http.request<BackupResult>('/backup', { method: 'POST' }),
|
||||
// 恢复要走幂等(X-Request-Id):现场断网重试时,重复请求不能把库换两遍。
|
||||
restore: (input) => http.request<BackupRestoreResult>('/backup/restore', { method: 'POST', body: input }),
|
||||
// 恢复是停机动作:服务端先拍安全副本、换库文件、复核新库、写审计,**全部做完才发回执**,
|
||||
// 库越大这一串越慢。用默认 15s 会在库已经换掉之后把请求判成超时,
|
||||
// 操作员看到「未执行」而重试,等于把刚恢复好的库再覆盖一遍,所以单独放大超时。
|
||||
// 幂等(X-Request-Id)照旧:现场断网重试时,重复请求不能把库换两遍。
|
||||
restore: (input) =>
|
||||
http.request<BackupRestoreResult>('/backup/restore', {
|
||||
method: 'POST',
|
||||
body: input,
|
||||
timeoutMs: RESTORE_TIMEOUT_MS,
|
||||
}),
|
||||
}
|
||||
this.projects = createProjectsApi(http)
|
||||
|
||||
@@ -924,23 +931,16 @@ export class ApiClient {
|
||||
return response.text()
|
||||
}
|
||||
|
||||
private async fetchBlob(path: string, options: RequestOptions = {}): Promise<Blob> {
|
||||
const response = await this.send(path, options)
|
||||
if (!response.ok) {
|
||||
const body = await readBody(response)
|
||||
if (response.status === 401) {
|
||||
const error = this.toApiError(body, response.status)
|
||||
this.notifyUnauthorized(error)
|
||||
throw error
|
||||
}
|
||||
throw this.toApiError(body, response.status)
|
||||
}
|
||||
return response.blob()
|
||||
}
|
||||
|
||||
private async send(path: string, options: RequestOptions): Promise<Response> {
|
||||
const method: HttpMethod = options.method ?? 'GET'
|
||||
const payload = this.prepareBody(method, options.body)
|
||||
// 一次调用只用**一个**幂等键,header 与 body 共用它。
|
||||
// 服务端是两层缓存:外层 cached 认 X-Request-Id,内层 idempotent 认 body.requestId,
|
||||
// 两边各生成一个就永远拼不出同一个 key,幂等缓存从未命中——现场超时后重试
|
||||
// 「发布 / 撤销发布 / 存草稿 / 移出报名」会真的重复执行一遍。
|
||||
// 调用方已经在 body 里给了 key(例如重发同一次写操作)就沿用它,否则这里新建一个。
|
||||
const given = isRecord(options.body) ? options.body['requestId'] : undefined
|
||||
const requestId = method === 'GET' ? null : (typeof given === 'string' && given !== '' ? given : this.newRequestId())
|
||||
const payload = this.prepareBody(method, options.body, requestId)
|
||||
// 断言:二进制 / 表单载荷只能原样透传,一旦被归一化展开就会静默丢内容(报名表导入踩过)。
|
||||
if (isRawBody(options.body) && payload !== options.body) {
|
||||
throw new ApiError('INTERNAL', '请求体归一化破坏了 FormData/Blob 载荷', 0, options.body)
|
||||
@@ -958,11 +958,13 @@ export class ApiClient {
|
||||
if (method !== 'GET') {
|
||||
const token = this.csrfToken()
|
||||
if (token !== null && token !== '') headers['X-CSRF-Token'] = token
|
||||
headers['X-Request-Id'] = this.newRequestId()
|
||||
// 与 body.requestId 是同一个值:服务端两层幂等缓存(cached / idempotent)才能命中。
|
||||
if (requestId !== null) headers['X-Request-Id'] = requestId
|
||||
}
|
||||
|
||||
const timeoutMs = options.timeoutMs ?? this.timeoutMs
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs)
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
const external = options.signal
|
||||
let abortedByCaller = false
|
||||
if (external !== undefined) {
|
||||
@@ -991,7 +993,7 @@ export class ApiClient {
|
||||
// 外部取消与服务端超时共用同一个 signal,必须分开归类,调用方才能决定要不要提示。
|
||||
if (abortedByCaller) throw new ApiError('ABORTED', '请求已取消', 0, error)
|
||||
if (controller.signal.aborted) {
|
||||
throw new ApiError('TIMEOUT', `请求超时(${this.timeoutMs}ms)`, 0, error)
|
||||
throw new ApiError('TIMEOUT', `请求超时(${timeoutMs}ms)`, 0, error)
|
||||
}
|
||||
throw new ApiError('NETWORK', '无法连接服务端', 0, error)
|
||||
} finally {
|
||||
@@ -999,13 +1001,16 @@ export class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** 写操作注入 requestId:网络抖动重发时服务端能返回首次结果而不是重复执行。 */
|
||||
private prepareBody(method: HttpMethod, body: unknown): unknown {
|
||||
/**
|
||||
* 写操作注入 requestId:网络抖动重发时服务端能返回首次结果而不是重复执行。
|
||||
* `requestId` 由 `send()` 生成一次并同时用于 header,两者必须是同一个值(见 send 的注释)。
|
||||
*/
|
||||
private prepareBody(method: HttpMethod, body: unknown, requestId: string | null): unknown {
|
||||
if (method === 'GET' || body === undefined) return undefined
|
||||
// FormData/Blob/URLSearchParams 不能展开,否则文件/二进制内容会被丢掉。
|
||||
if (isRawBody(body)) return body
|
||||
if (isRecord(body) && !('requestId' in body)) {
|
||||
return { ...body, requestId: this.newRequestId() }
|
||||
if (requestId !== null && isRecord(body) && !('requestId' in body)) {
|
||||
return { ...body, requestId }
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -101,6 +101,10 @@ export function downloadBaseDataXLSX(): Promise<DownloadFile> {
|
||||
/**
|
||||
* 上传基础数据包。
|
||||
* `dryRun=true` 只算差异不写库;用户确认后再用 `dryRun=false` 提交同一个文件。
|
||||
*
|
||||
* 写请求要带 X-Request-Id:服务端对这条路由挂了基于该 header 的幂等缓存,
|
||||
* 一次导入要么只执行一次,要么重放首次回执——现场网络抖动重发不会把整包数据写两遍。
|
||||
* 表单载荷(FormData)撑不进 body 里的 requestId,所以这里只能走 header。
|
||||
*/
|
||||
export async function importBaseDataXLSX(
|
||||
file: File,
|
||||
@@ -114,7 +118,7 @@ export async function importBaseDataXLSX(
|
||||
method: 'POST',
|
||||
body: form,
|
||||
// 浏览器自己带 multipart 边界,显式设 Content-Type 反而会漏掉 boundary。
|
||||
headers: csrfHeader(),
|
||||
headers: { ...csrfHeader(), 'X-Request-Id': newRequestId() },
|
||||
}, UPLOAD_TIMEOUT_MS)
|
||||
|
||||
const body = await readBody(response)
|
||||
@@ -186,6 +190,15 @@ function csrfHeader(): Record<string, string> {
|
||||
return { 'X-CSRF-Token': decodeURIComponent(raw) }
|
||||
}
|
||||
|
||||
/** 与 shared/api.ts 同口径的幂等键生成器:一次调用一个,服务端据此防重复导入。 */
|
||||
function newRequestId(): string {
|
||||
const cryptoApi: Crypto | undefined = globalThis.crypto
|
||||
if (cryptoApi !== undefined && typeof cryptoApi.randomUUID === 'function') {
|
||||
return cryptoApi.randomUUID()
|
||||
}
|
||||
return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
function toApiError(body: unknown, status: number): ApiError {
|
||||
const record = isRecord(body) ? body : {}
|
||||
const error = isRecord(record.error) ? record.error : {}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { ApiClient, ApiError, RESTORE_TIMEOUT_MS } from '../api'
|
||||
|
||||
/**
|
||||
* 写请求的幂等键与停机动作的超时。
|
||||
*
|
||||
* 三件事必须钉住:
|
||||
* 1. 一次调用只生成**一个** requestId,header 与 body 共用——服务端外层 `cached` 认
|
||||
* `X-Request-Id`、内层 `idempotent` 认 `body.requestId`,两个值不同就永远命中不了缓存,
|
||||
* 现场超时重试「发布 / 撤销发布 / 存草稿 / 移出报名」会真重复执行;
|
||||
* 2. 恢复整库的回执在服务端换完库之后才发出,客户端必须给它单独放大超时,
|
||||
* 否则会在库已经换掉之后把请求判成超时(配套的提示语见 restoreFailureNotice);
|
||||
* 3. 导出接口只剩「存文件」这一件事(standingsUrl / system.backup 都是零调用方的死路)。
|
||||
*/
|
||||
|
||||
interface Captured {
|
||||
url?: string
|
||||
method?: string
|
||||
headers?: Record<string, string>
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function capture(reply: () => Response, captured: Captured): typeof fetch {
|
||||
return (async (input: unknown, init?: RequestInit) => {
|
||||
captured.url = String(input)
|
||||
captured.method = init?.method ?? 'GET'
|
||||
captured.headers = (init?.headers ?? {}) as Record<string, string>
|
||||
captured.body = init?.body === undefined ? undefined : JSON.parse(String(init.body))
|
||||
return reply()
|
||||
}) as typeof fetch
|
||||
}
|
||||
|
||||
test('写请求的 X-Request-Id 与 body.requestId 是同一个值', async () => {
|
||||
const captured: Captured = {}
|
||||
const client = new ApiClient({
|
||||
requestId: () => 'req-fixed',
|
||||
fetchImpl: capture(() => jsonResponse({ ok: true, data: { id: 1, username: 'admin' } }), captured),
|
||||
})
|
||||
|
||||
await client.auth.login('admin', 'pw')
|
||||
|
||||
assert.equal(captured.headers?.['X-Request-Id'], 'req-fixed')
|
||||
assert.equal((captured.body as { requestId?: unknown }).requestId, 'req-fixed')
|
||||
})
|
||||
|
||||
test('默认生成器下 header 与 body 也一致(不是各生成一次)', async () => {
|
||||
const captured: Captured = {}
|
||||
const client = new ApiClient({
|
||||
fetchImpl: capture(() => jsonResponse({ ok: true, data: { ok: true } }), captured),
|
||||
})
|
||||
|
||||
await client.entries.setHeat({ entryIds: [2], heat: 3 })
|
||||
|
||||
const headerId = captured.headers?.['X-Request-Id']
|
||||
assert.equal(typeof headerId, 'string')
|
||||
assert.equal((captured.body as { requestId?: unknown }).requestId, headerId)
|
||||
})
|
||||
|
||||
test('调用方在 body 里给了 requestId 时,header 沿用同一个值', async () => {
|
||||
const captured: Captured = {}
|
||||
const client = new ApiClient({ fetchImpl: capture(() => jsonResponse({ ok: true, data: [] }), captured) })
|
||||
|
||||
await client.results.publish({ eventId: 1, requestId: 'caller-provided' })
|
||||
|
||||
assert.equal(captured.headers?.['X-Request-Id'], 'caller-provided')
|
||||
assert.equal((captured.body as { requestId?: unknown }).requestId, 'caller-provided')
|
||||
})
|
||||
|
||||
test('没有请求体的写操作仍带 X-Request-Id,读请求不带', async () => {
|
||||
const captured: Captured = {}
|
||||
const client = new ApiClient({ fetchImpl: capture(() => jsonResponse({ ok: true, data: [] }), captured) })
|
||||
|
||||
await client.auth.logout()
|
||||
assert.equal(typeof captured.headers?.['X-Request-Id'], 'string')
|
||||
assert.equal(captured.body, undefined)
|
||||
|
||||
await client.teams.list()
|
||||
assert.equal(captured.headers?.['X-Request-Id'], undefined, 'GET 不该消耗幂等键')
|
||||
})
|
||||
|
||||
/** 模拟真实 fetch:只有它才认 AbortSignal(自定义的 stub 不认,超时测试就测不到东西)。 */
|
||||
function slowFetch(delayMs: number, body: unknown): typeof fetch {
|
||||
return ((_input: unknown, init?: RequestInit) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => resolve(jsonResponse(body)), delayMs)
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
clearTimeout(timer)
|
||||
reject(new DOMException('The operation was aborted.', 'AbortError'))
|
||||
})
|
||||
})) as typeof fetch
|
||||
}
|
||||
|
||||
test('恢复整库用单独放大的超时,不被客户端默认 15s 那一档掐断', async () => {
|
||||
// 客户端默认超时 10ms,恢复请求实测要跑 50ms:只要它没被 abort,就说明走的是自己的超时。
|
||||
const client = new ApiClient({
|
||||
timeoutMs: 10,
|
||||
fetchImpl: slowFetch(50, { ok: true, data: { kind: 'event', dbKind: 'event', restarting: true } }),
|
||||
})
|
||||
|
||||
const result = await client.system.restore({ file: 'event-1.db', kind: 'event' })
|
||||
|
||||
assert.equal(result.restarting, true)
|
||||
assert.ok(RESTORE_TIMEOUT_MS > 15_000, '恢复的超时必须比默认那一档宽')
|
||||
})
|
||||
|
||||
test('同一个客户端上,普通接口仍按默认超时被掐断', async () => {
|
||||
const client = new ApiClient({
|
||||
timeoutMs: 10,
|
||||
fetchImpl: slowFetch(60, { ok: true, data: [] }),
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
() => client.teams.list(),
|
||||
(error: unknown) => error instanceof ApiError && error.code === 'TIMEOUT',
|
||||
)
|
||||
})
|
||||
|
||||
test('导出接口只保留「存文件」,恢复接口只保留 restore', () => {
|
||||
const client = new ApiClient({ fetchImpl: async () => jsonResponse({ ok: true, data: null }) })
|
||||
|
||||
assert.deepEqual(Object.keys(client.exports), ['save'])
|
||||
assert.deepEqual(Object.keys(client.system), ['restore'])
|
||||
})
|
||||
@@ -591,11 +591,6 @@ export interface AuditLog {
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface BackupResult {
|
||||
path: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复请求体(POST /api/backup/restore)。
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user