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')
|
||||
})
|
||||
Reference in new issue
Block a user