fix: 修掉十路审查发现的 9 个 P0 与一批 P1(数据正确性 / 越权 / 现场可用性)

P0(9 条全修):
- 多通道项目奖牌重复计数:domain 层按 (EventID,CategoryID,EntryID/Subject) 去重,
  通道优先级 athlete→team→id
- 「只排名不计分」项目(scored:false)不再进奖牌榜,REST/WS/导出口径统一
- aggregate 流水 entry_id 恒 NULL 导致重算后分数翻倍:作废范围改按 event+category 定位
- 已发布成绩仍可被「存草稿」覆盖并清空 rank:服务端 409 STATE_INVALID + 前端禁编辑
- voidResult / 规则导入重算后名次不回写:接住 Ranked 调 applyComputedRanks
- 赛事包覆盖导入可能「旧项目已删、新项目没成」:先改名成功再清理,失败回滚
- 导入赛事包可覆盖正在运行的赛事目录:name==当前项目直接 400
- Console spawn 失败后守护器永久卡死:清 child/pid + 调度重启 + stop 超时兜底
- /ws 快照向非 admin 下发 admin-only 配置:按角色裁剪 settings

P1(计分口径 / 契约 / 现场):
- standings.tieBreak 三处接线;profiles[].recordBonusMode 生效;破纪录校验
  RecordEligible 与 entry 归属;破纪录登记校验已发布成绩
- export.loadRanked 与主路径对齐;ListBackups reason 解析;CLI backup 前缀修正
  (原来只增不减会撑爆磁盘);单位积分明细/导出统一权重折算;停用单位展示
- 规则导入原子化(重算并入同一事务)+ 返回 compatible/affectedEventCount/
  recalculatedLedgerRows;登录审计 user_id 修正
- WS 策略性断开用 Close(code,reason);HelloMessage 补 page/instanceId;
  实例注册表清理;settings/单位/项目写操作补 change_log 触发大屏刷新
- 大屏:全量快照不再被版本守卫丢弃;个人积分榜刷新;公告返回页/轮播;行数截断;
  REST 竞态;1008 停止重连;握手超时;时区补 Z;401 仅 AUTH_REQUIRED 才登出
- 管理端:published 行禁编辑;saveDraft 补 unit(1:06.33 显示);前端预览改用服务端
  points;空成绩行不再恒「已修改」;修订详情按 id 拉取;切项目请求序号与 dirty 保护;
  发布后刷新项目状态;NAV/路由按角色过滤;recorder 不再打 admin-only 接口
- Console:大屏窗口销毁后重建;大屏 URL 复用 host 归一化;backup.bat 改纯 ASCII
  (已在 Meowhome 实跑验证)

自检:服务端 gofmt/build/vet 通过、12 包测试全绿;前端 vue-tsc + build 通过、
node --test 24/24;console check-syntax 12 文件通过。
This commit is contained in:
AskaEth committed 2026-09-09 22:16:58 +08:00
1 parent 96cf181ae3
commit 13f1f03cd0
124 files changed
+5658 -1820

No files matched your search

+35 -32
View File
@@ -27,12 +27,14 @@ import { mockDb } from './mock'
/**
* 管理端数据入口。
*
* 后端未就绪(连接失败 / 超时 / 响应不是约定结构)时自动降级到内存示例数据,
* 并把 `mockMode` 置为 true,界面据此显示「示例数据」标记。
* 业务错误(鉴权失败、校验失败、冲突)不降级——那些是真实服务端的回答,必须原样呈现。
* 后端未就绪(连接失败 / 超时)时自动降级到内存示例数据,并把 `mockMode` 置为 true,
* 界面据此显示「示例数据」标记。
* 业务错误(404、鉴权失败、校验失败、冲突)与写操作一律不降级——那些是真实服务端的回答。
*/
const FALLBACK_CODES = ['NETWORK', 'TIMEOUT', 'PARSE_FAILED']
// 只有「根本连不上服务端」才降级到示例数据;404 / 解析失败是服务端给出的真实回答,
// 必须原样抛出,否则「用户不存在」「接口不存在」会被伪装成「后端未就绪」。
const FALLBACK_CODES = ['NETWORK', 'TIMEOUT']
export const mockMode = ref(false)
export const mockReason = ref<string | null>(null)
@@ -48,26 +50,38 @@ const client = createApiClient({
})
function isFallback(error: unknown): boolean {
// 404 表示该接口在当前服务端尚未实现(或整个后端没起来),同样按「未就绪」降级。
return error instanceof ApiError && (FALLBACK_CODES.includes(error.code) || error.status === 404)
return error instanceof ApiError && FALLBACK_CODES.includes(error.code)
}
async function call<T>(real: () => Promise<T>, mock: () => T | Promise<T>): Promise<T> {
/** 与 call 同构,但把「本次是否降级」一并返回,供页面显示局部示例数据标记。 */
async function callWithMock<T>(
real: () => Promise<T>,
mock: () => T | Promise<T>,
): Promise<{ data: T; mock: boolean }> {
try {
const value = await real()
const data = await real()
if (mockMode.value) {
mockMode.value = false
mockReason.value = null
}
return value
return { data, mock: false }
} catch (error) {
if (!isFallback(error)) throw error
mockMode.value = true
mockReason.value = error instanceof Error ? error.message : '无法连接服务端'
return await mock()
return { data: await mock(), mock: true }
}
}
async function call<T>(real: () => Promise<T>, mock: () => T | Promise<T>): Promise<T> {
return (await callWithMock(real, mock)).data
}
/** 写操作一律不降级:示例数据里的「保存成功」会让操作员以为成绩已经落库。 */
async function callWrite<T>(real: () => Promise<T>): Promise<T> {
return real()
}
export interface Bootstrap {
/** settings 是 admin-only;访客/录入员读不到时为 null,其余赛事数据照常返回。 */
settings: EventSettings | null
@@ -125,13 +139,13 @@ export const adminApi = {
call(() => client.events.entries(eventId), () => mockDb.listEntries(eventId)),
saveDraft: (payload: SaveDraftPayload): Promise<Result[]> =>
call(() => client.results.saveDraft(payload), () => mockDb.saveDraft(payload)),
callWrite(() => client.results.saveDraft(payload)),
publish: (payload: PublishPayload): Promise<Result[]> =>
call(() => client.results.publish(payload), () => mockDb.publish(payload)),
callWrite(() => client.results.publish(payload)),
unpublish: (payload: PublishPayload): Promise<Result[]> =>
call(() => client.results.unpublish(payload), () => mockDb.unpublish(payload)),
callWrite(() => client.results.unpublish(payload)),
standings: (): Promise<StandingRow[]> =>
call(() => client.standings.teams(), () => mockDb.standings()),
@@ -151,16 +165,17 @@ export const adminApi = {
auditLogs: (query: PageQuery = {}): Promise<Page<AuditLog>> =>
call(() => client.auditLogs.list(query), () => mockDb.auditLogs(query.page ?? 1, query.size ?? 20)),
/** 审计日志需要知道「这一批是不是示例数据」,用局部标记而不是读全局 mockMode。 */
auditLogsWithMock: (query: PageQuery = {}): Promise<{ data: Page<AuditLog>; mock: boolean }> =>
callWithMock(() => client.auditLogs.list(query), () => mockDb.auditLogs(query.page ?? 1, query.size ?? 20)),
displayCommand: (command: DisplayCommand): Promise<void> =>
call(() => client.display.command(command), () => undefined),
callWrite(() => client.display.command(command)),
login: (username: string, password: string): Promise<CurrentUser> =>
call(
() => client.auth.login(username, password),
() => mockDb.login(username),
),
callWrite(() => client.auth.login(username, password)),
logout: (): Promise<void> => call(() => client.auth.logout(), () => undefined),
logout: (): Promise<void> => callWrite(() => client.auth.logout()),
me: (): Promise<CurrentUser> =>
call(
@@ -172,25 +187,13 @@ export const adminApi = {
),
changePassword: (currentPassword: string, newPassword: string): Promise<{ relogin: boolean }> =>
call(
() => client.auth.changePassword(currentPassword, newPassword),
() => {
throw new ApiError('INTERNAL', '示例数据模式下无法修改密码', 0)
},
),
callWrite(() => client.auth.changePassword(currentPassword, newPassword)),
health: (): Promise<HealthInfo> =>
call(
() => client.health(),
() => mockDb.health(),
),
exportUrl: (kind: 'standings' | 'breakdown' | 'results'): string | null => {
if (mockMode.value) return null
if (kind === 'standings') return client.exports.standingsUrl()
if (kind === 'breakdown') return client.exports.breakdownUrl({})
return client.exports.resultsUrl()
},
}
export type AdminApi = typeof adminApi
+2
View File
@@ -381,6 +381,7 @@ class MockDb {
return {
entryId: entry.id,
teamId: entry.teamId,
athleteId: entry.athleteId,
resultValue: result?.resultValue ?? null,
rank: result?.rank ?? null,
status: result?.status ?? 'ok',
@@ -421,6 +422,7 @@ class MockDb {
return {
entryId: input.entryId,
teamId: entry?.teamId ?? 0,
athleteId: entry?.athleteId ?? null,
resultValue,
rank: input.rank ?? existing?.rank ?? null,
status: input.status ?? existing?.status ?? 'ok',
+264 -108
View File
@@ -1,4 +1,6 @@
import type {
ChannelBasis,
ChannelScope,
CompareMode,
Event,
EventCategory,
@@ -9,16 +11,19 @@ import type {
} from '@/shared'
/**
* 名次与积分的纯函数实现。
* 名次与积分的纯函数实现,只用于录入页的实时预览与 mock 数据源。
*
* 录入页的「实时预览」和 mock 数据源的发布结果必须用同一套算法,
* 否则演示态与真实态算出的分会不一致,预览就失去意义。
* 服务端就绪后这里只用于预览,真值仍以 /api/standings 为准。
* 口径必须与服务端 domain/scoring.go 的 ScoreEvent 一致:按计分通道逐条排名、
* 录取名次 awardRanks、末位零分 lastPlaceZero、并列三种口径、多通道叠加,
* 个人通道分再按 standings.individual_to_team_weight 折算进单位总分。
* 任何一处偏差都会让「预览说加分、发布后不加分」,改动本文件时必须同步核对 scoring.go。
*/
export interface ScorableRow {
entryId: number
teamId: number
/** 聚合到运动员的通道需要;缺失时该行不参与个人维度的聚合。 */
athleteId?: number | null
resultValue: number | null
rank: number | null
status: ResultStatus
@@ -27,97 +32,245 @@ export interface ScorableRow {
const EPSILON = 1e-9
function isRanked(row: ScorableRow): boolean {
return row.status === 'ok' && row.resultValue !== null
/** 不计分项目的占位模板:名次要算,但不可能算出非零分。 */
const EMPTY_PROFILE: ScoringProfile = {
id: 0,
code: '',
name: '',
tieMode: 'skip',
recordBonusMode: 'max',
rules: [],
}
/** 按比较方向排序并赋名次;并列按 tieMode 处理。manual / compare=none 时直接用录入的名次。 */
export function assignRanks(
rows: readonly ScorableRow[],
compare: CompareMode,
tieMode: TieMode,
manual: boolean,
): Map<number, number | null> {
const result = new Map<number, number | null>()
const ranked = rows.filter(isRanked)
interface Candidate {
row: ScorableRow
/** 比较值(result / aggregate 通道)。 */
value: number
/** 录入名次(manual 通道)。 */
rankIn: number
/** 聚合通道的排名主体(单位 id 或运动员 id)。 */
subject: number
}
if (manual || compare === 'none') {
for (const row of rows) result.set(row.entryId, row.status === 'ok' ? row.rank : null)
return result
}
interface RankedRow {
/** 聚合通道不对应单条报名项,此时为 0。 */
entryId: number
teamId: number
scope: ChannelScope
rank: number
points: number
}
const direction = compare === 'asc' ? 1 : -1
const sorted = [...ranked].sort(
(a, b) => direction * ((a.resultValue ?? 0) - (b.resultValue ?? 0)),
)
function effectiveMultiplier(value: number): number {
return value > 0 ? value : 1
}
let index = 0
while (index < sorted.length) {
const group: ScorableRow[] = [sorted[index] as ScorableRow]
const head = group[0] as ScorableRow
let cursor = index + 1
while (
cursor < sorted.length &&
Math.abs((sorted[cursor] as ScorableRow).resultValue! - head.resultValue!) < EPSILON
) {
group.push(sorted[cursor] as ScorableRow)
cursor += 1
function tieModeOf(profile: ScoringProfile): TieMode {
return profile.tieMode === 'average' || profile.tieMode === 'higher' ? profile.tieMode : 'skip'
}
/** 查表得分并乘项目 / 组别权重;超出录取名次或表中无名次一律 0(scoring.go basePoints)。 */
function basePoints(
profile: ScoringProfile,
rank: number,
eventMultiplier: number,
categoryMultiplier: number,
): number {
if (rank <= 0) return 0
if (profile.awardRanks !== undefined && profile.awardRanks > 0 && rank > profile.awardRanks) return 0
const rule = profile.rules.find((item) => item.rank === rank)
if (rule === undefined) return 0
return rule.points * eventMultiplier * categoryMultiplier
}
/**
* 一组并列者拿到的分(scoring.go groupPoints)。
* 先确定这组占用的名次区间 startRank .. startRank+size-1,再按并列口径取值。
*/
function groupPoints(
profile: ScoringProfile,
startRank: number,
size: number,
lastRank: number,
eventMultiplier: number,
categoryMultiplier: number,
): number {
if (startRank <= 0 || size <= 0) return 0
// lastPlaceZero 覆盖「最后一名」;并列在末位的整组都按最后一名处理,保证并列同分。
if (profile.lastPlaceZero === true && startRank <= lastRank && lastRank <= startRank + size - 1) return 0
const mode = tieModeOf(profile)
if (mode === 'average') {
let sum = 0
for (let rank = startRank; rank < startRank + size; rank += 1) {
sum += basePoints(profile, rank, eventMultiplier, categoryMultiplier)
}
const position = index + 1
const tied = group.length > 1
let rank = position
if (tied && tieMode === 'average') {
rank = (position + (position + group.length - 1)) / 2
}
// skip / higher:并列者都拿靠前的名次,后续名次顺延(02 第 2.2 节)。
for (const row of group) result.set(row.entryId, rank)
index = cursor
return sum / size
}
if (mode === 'higher') {
let best = 0
for (let rank = startRank; rank < startRank + size; rank += 1) {
best = Math.max(best, basePoints(profile, rank, eventMultiplier, categoryMultiplier))
}
return best
}
return basePoints(profile, startRank, eventMultiplier, categoryMultiplier)
}
/** 收集本通道真正参与排名的行:状态正常,且带有本通道所需数据。 */
function collectCandidates(rows: readonly ScorableRow[], basis: ChannelBasis): Candidate[] {
const out: Candidate[] = []
for (const row of rows) {
if (!result.has(row.entryId)) result.set(row.entryId, null)
if (row.status !== 'ok') continue
if (basis === 'manual') {
if (row.rank === null || row.rank <= 0) continue
out.push({ row, value: 0, rankIn: row.rank, subject: 0 })
continue
}
if (row.resultValue === null) continue
out.push({ row, value: row.resultValue, rankIn: 0, subject: 0 })
}
return result
return out
}
/** 名次 → 分值;并列平均产生小数名次时,取相邻两档的均值。 */
export function pointsForRank(rank: number | null, profile: ScoringProfile | null): number {
if (rank === null || profile === null || !Number.isFinite(rank)) return 0
const exact = profile.rules.find((rule) => rule.rank === rank)
if (exact !== undefined) return exact.points
const lower = profile.rules.find((rule) => rule.rank === Math.floor(rank))
const upper = profile.rules.find((rule) => rule.rank === Math.ceil(rank))
if (lower === undefined && upper === undefined) return 0
if (lower === undefined) return upper?.points ?? 0
if (upper === undefined) return lower.points
return (lower.points + upper.points) / 2
function sortByValue(cands: Candidate[], compare: CompareMode): void {
cands.sort((a, b) => {
if (Math.abs(a.value - b.value) <= EPSILON) return a.row.entryId - b.row.entryId
return compare === 'desc' ? b.value - a.value : a.value - b.value
})
}
export interface ChannelPlan {
athleteProfile: ScoringProfile | null
teamProfile: ScoringProfile | null
interface TieGroup {
startRank: number
members: Candidate[]
}
/** 一个项目可挂多个通道;预览只关心「个人表」和「团体表」两张。 */
export function planChannels(
channels: readonly ScoreChannel[],
profiles: readonly ScoringProfile[],
): ChannelPlan {
const pick = (scope: ScoreChannel['scope']): ScoringProfile | null => {
const channel = channels.find((item) => item.scope === scope)
if (channel === undefined) return null
return profiles.find((profile) => profile.id === channel.profileId) ?? null
/** 值相同即并列,名次按「占位顺推」计算(skip 口径)。 */
function groupByValue(cands: readonly Candidate[]): TieGroup[] {
const groups: TieGroup[] = []
let pos = 1
for (let i = 0; i < cands.length; ) {
let j = i + 1
while (j < cands.length && Math.abs((cands[j] as Candidate).value - (cands[i] as Candidate).value) <= EPSILON) {
j += 1
}
groups.push({ startRank: pos, members: cands.slice(i, j) })
pos += j - i
i = j
}
return groups
}
/** 录入名次就是展示名次,不做顺推改写。 */
function groupByManualRank(cands: readonly Candidate[]): TieGroup[] {
const groups: TieGroup[] = []
for (let i = 0; i < cands.length; ) {
let j = i + 1
while (j < cands.length && (cands[j] as Candidate).rankIn === (cands[i] as Candidate).rankIn) j += 1
groups.push({ startRank: (cands[i] as Candidate).rankIn, members: cands.slice(i, j) })
i = j
}
return groups
}
function sortManual(cands: Candidate[]): void {
cands.sort((a, b) => (a.rankIn === b.rankIn ? a.row.entryId - b.row.entryId : a.rankIn - b.rankIn))
}
/**
* 聚合通道:先把同一主体的成绩求和,再按值排名(scoring.go scoreByAggregate)。
* 运动员维度缺 athleteId 的行按服务端口径直接跳过(subject == 0)。
*/
function aggregateCandidates(rows: readonly ScorableRow[], channel: ScoreChannel): Candidate[] {
const order: number[] = []
const buckets = new Map<number, { row: ScorableRow; total: number }>()
for (const candidate of collectCandidates(rows, 'result')) {
const subject = channel.scope === 'team' ? candidate.row.teamId : (candidate.row.athleteId ?? 0)
if (subject === 0) continue
const bucket = buckets.get(subject)
if (bucket === undefined) {
buckets.set(subject, { row: candidate.row, total: candidate.value })
order.push(subject)
} else {
bucket.total += candidate.value
}
}
return order.map((subject) => {
const bucket = buckets.get(subject) as { row: ScorableRow; total: number }
return { row: bucket.row, value: bucket.total, rankIn: 0, subject }
})
}
function scoreChannel(
rows: readonly ScorableRow[],
channel: ScoreChannel,
profile: ScoringProfile,
event: Event,
category: EventCategory | null,
scoreEnabled: boolean,
): RankedRow[] {
// compare=none 无法按值排名,退回录入名次;服务端当前会拒绝该组合(见 P1-6)。
const basis: ChannelBasis = channel.basis === 'manual' || event.compare === 'none' ? 'manual' : channel.basis
const eventMultiplier = effectiveMultiplier(event.multiplier)
const categoryMultiplier = effectiveMultiplier(category?.multiplier ?? 1)
let groups: TieGroup[]
if (basis === 'aggregate') {
const aggregated = aggregateCandidates(rows, channel)
sortByValue(aggregated, event.compare)
groups = groupByValue(aggregated)
} else if (basis === 'manual') {
const cands = collectCandidates(rows, 'manual')
sortManual(cands)
groups = groupByManualRank(cands)
} else {
const cands = collectCandidates(rows, 'result')
sortByValue(cands, event.compare)
groups = groupByValue(cands)
}
let lastRank = 0
for (const group of groups) {
lastRank = Math.max(lastRank, group.startRank + group.members.length - 1)
}
const out: RankedRow[] = []
for (const group of groups) {
const points = scoreEnabled
? groupPoints(profile, group.startRank, group.members.length, lastRank, eventMultiplier, categoryMultiplier)
: 0
for (const member of group.members) {
out.push({
entryId: basis === 'aggregate' ? 0 : member.row.entryId,
teamId: basis === 'aggregate' && channel.scope === 'team' ? member.subject : member.row.teamId,
scope: channel.scope,
rank: group.startRank,
points,
})
}
}
return out
}
/** 没有计分通道时按小项自身的录入方式推导一个排名通道(scoring.go rankOnlyChannel)。 */
function rankOnlyChannel(event: Event): ScoreChannel {
const scope: ChannelScope = event.eventType === 'team' || event.eventType === 'match' ? 'team' : 'athlete'
return {
id: 0,
eventId: event.id,
scope,
basis: event.resultMode === 'manual' ? 'manual' : 'result',
profileId: 0,
sortOrder: 0,
}
return { athleteProfile: pick('athlete'), teamProfile: pick('team') }
}
export interface EventScoreResult {
/** 每行「直接产生」的积分,用于表格里的积分列。 */
/** 每行各通道原始分之和(未乘个人→单位系数),用于表格积分列。 */
rowPoints: Map<number, number>
/** 每行名次,用于自动排名展示。 */
/** 每行折算到单位的贡献(个人通道分 × 系数 + 团体通道分),用于预览差值。 */
rowTeamPoints: Map<number, number>
/** 每行展示名次;多通道时优先个人通道,与 applyComputedRanks 一致。 */
ranks: Map<number, number | null>
/** 按单位聚合的得分增量,用于预览面板。 */
teamPoints: Map<number, number>
@@ -132,45 +285,48 @@ export interface ScoreContext {
weight: number
}
/**
* 计算一组成绩的积分。
*
* 个人项目:行分记给个人,单位获得 `个人分 × 系数`;
* 团体 / 对抗项目:行分直接记给单位(02 第 2.4 节)。
*/
export function computeEventScore(
rows: readonly ScorableRow[],
context: ScoreContext,
): EventScoreResult {
const manual = context.event.resultMode === 'manual'
const ranks = assignRanks(rows, context.event.compare, tieModeOf(context), manual)
const plan = planChannels(context.channels, context.profiles)
const multiplier = context.event.multiplier * (context.category?.multiplier ?? 1)
const isIndividual = context.event.eventType === 'individual'
/** 计分通道处理顺序:sortOrder 升序,其次 id 升序(scoring.go sortedChannels)。 */
function sortedChannels(channels: readonly ScoreChannel[]): ScoreChannel[] {
return [...channels].sort((a, b) => (a.sortOrder === b.sortOrder ? a.id - b.id : a.sortOrder - b.sortOrder))
}
export function computeEventScore(rows: readonly ScorableRow[], context: ScoreContext): EventScoreResult {
const event = context.event
const rankOnly = context.channels.length === 0
// 只排名不计分:scored=false 或没有计分通道时都算出名次,但一律 0 分。
const scoreEnabled = event.scored && !rankOnly
const channels = rankOnly ? [rankOnlyChannel(event)] : sortedChannels(context.channels)
const weight = context.weight > 0 ? context.weight : 1
const rowPoints = new Map<number, number>()
const rowTeamPoints = new Map<number, number>()
const ranks = new Map<number, number | null>()
const rankScope = new Map<number, ChannelScope>()
const teamPoints = new Map<number, number>()
const addTeam = (teamId: number, points: number): void => {
if (points === 0) return
teamPoints.set(teamId, (teamPoints.get(teamId) ?? 0) + points)
for (const channel of channels) {
const profile = context.profiles.find((item) => item.id === channel.profileId) ?? null
// 不计分时不需要积分表,按空模板处理即可(名次仍要算出来)。
const ranked = scoreChannel(rows, channel, profile ?? EMPTY_PROFILE, event, context.category, scoreEnabled && profile !== null)
for (const row of ranked) {
if (row.entryId > 0) {
rowPoints.set(row.entryId, (rowPoints.get(row.entryId) ?? 0) + row.points)
const teamContribution = row.scope === 'athlete' ? row.points * weight : row.points
rowTeamPoints.set(row.entryId, (rowTeamPoints.get(row.entryId) ?? 0) + teamContribution)
// 名次优先取个人通道;同一优先级下先处理的通道胜出。
const current = rankScope.get(row.entryId)
if (current === undefined || (current === 'team' && row.scope === 'athlete')) {
ranks.set(row.entryId, row.rank)
rankScope.set(row.entryId, row.scope)
}
}
const teamContribution = row.scope === 'athlete' ? row.points * weight : row.points
teamPoints.set(row.teamId, (teamPoints.get(row.teamId) ?? 0) + teamContribution)
}
}
for (const row of rows) {
const rank = ranks.get(row.entryId) ?? null
const profile = isIndividual
? (plan.athleteProfile ?? plan.teamProfile)
: (plan.teamProfile ?? plan.athleteProfile)
const points = pointsForRank(rank, profile) * multiplier
rowPoints.set(row.entryId, points)
if (isIndividual) addTeam(row.teamId, points * context.weight)
else addTeam(row.teamId, points)
if (!ranks.has(row.entryId)) ranks.set(row.entryId, null)
}
return { rowPoints, ranks, teamPoints }
}
function tieModeOf(context: ScoreContext): TieMode {
const profile = planChannels(context.channels, context.profiles).athleteProfile
return profile?.tieMode ?? 'skip'
return { rowPoints, rowTeamPoints, ranks, teamPoints }
}
@@ -1,10 +1,12 @@
import { parseRevisions, type Revision } from './types'
import { ApiError } from '@/shared'
import { parseRevisionDetail, parseRevisions, type Revision } from './types'
/**
* `GET /api/revisions`(05 §7 的变更历史接口,由服务端另一处实现)。
* `GET /api/revisions` 与 `GET /api/revisions/{id}`(05 §7 的变更历史接口)。
*
* 直接 fetch 而不是走 adminApi:client.ts 的接口表里暂时没有这个方法,
* 而 api/** 不在本页的改动范围内;解析失败 / 404 时由页面降级到示例数据。
* 直接 fetch 而不是走 adminApi:client.ts 的接口表里暂时没有这组方法。
* 只有网络不可达(NETWORK)才由页面降级到示例数据;403 / 404 / 500 是服务端的真实回答,
* 必须原样抛出,否则访客会看到一批冒充历史的假数据。
*/
export interface RevisionQuery {
@@ -24,12 +26,28 @@ function buildUrl(query: RevisionQuery): string {
return search === '' ? REVISIONS_PATH : `${REVISIONS_PATH}?${search}`
}
async function request(url: string, label: string): Promise<unknown> {
let response: Response
try {
response = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'include' })
} 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)
}
return response.json()
}
export async function fetchRevisions(query: RevisionQuery = {}): Promise<Revision[]> {
const response = await fetch(buildUrl(query), {
headers: { Accept: 'application/json' },
credentials: 'include',
})
if (!response.ok) throw new Error(`变更历史接口返回 HTTP ${response.status}`)
const body: unknown = await response.json()
return parseRevisions(body)
return parseRevisions(await request(buildUrl(query), '变更历史接口'))
}
/**
* 列表接口不含成绩快照,只有 `GET /api/revisions/{id}` 才带 snapshot。
* 选中节点后必须补拉一次,否则真机上的 diff、影响单位与积分流水全是 0。
*/
export async function fetchRevisionDetail(id: number): Promise<Revision | null> {
return parseRevisionDetail(await request(`${REVISIONS_PATH}/${id}`, '变更详情接口'))
}
+7 -1
View File
@@ -131,7 +131,7 @@ function parseLedgerIds(value: unknown): number[] {
.filter((item): item is number => item !== null)
}
function parseRevision(value: unknown): Revision | null {
export function parseRevision(value: unknown): Revision | null {
if (!isRecord(value)) return null
const id = readNumber(value, 'id')
const eventId = readNumber(value, 'eventId')
@@ -165,3 +165,9 @@ export function parseRevisions(body: unknown): Revision[] {
.map(parseRevision)
.filter((item): item is Revision => item !== null)
}
/** 解析 GET /api/revisions/{id}:单个对象,兼容未拆包的 {ok,data} 统一响应。 */
export function parseRevisionDetail(body: unknown): Revision | null {
const source = isRecord(body) && 'data' in body ? body['data'] : body
return parseRevision(source)
}
@@ -44,10 +44,12 @@ function clone(value: EventSettings): EventSettings {
return JSON.parse(JSON.stringify(value)) as EventSettings
}
/** 可选文本:空串在接口里等于「没有」,必须转成 null,否则大屏会显示空白标题。 */
function optional(value: string | null): string | null {
const trimmed = (value ?? '').trim()
return trimmed === '' ? null : trimmed
/**
* 可选文本:服务端对 `*string` 的 nil 是「保持原值」,所以清空必须传空串。
* 若这里把空串转成 null,副标题 / 主办方将永远清不掉。
*/
function optional(value: string | null): string {
return (value ?? '').trim()
}
function reset(): void {
@@ -64,6 +66,11 @@ async function save(): Promise<void> {
return
}
// 清空轮播间隔时 v-model.number 会给出空串,直接提交会被服务端按 *float64 解码失败(400)。
// 空值按「不改动」处理(服务端对 nil 也是保持原值),回填当前值即可。
const rotate = Number(next.display.rotateSeconds)
const rotateSeconds = Number.isFinite(rotate) && rotate > 0 ? rotate : current.display.rotateSeconds
const patch: EventSettingsPatch = {
event: {
...next.event,
@@ -71,14 +78,19 @@ async function save(): Promise<void> {
subtitle: optional(next.event.subtitle),
host: optional(next.event.host),
},
display: { ...next.display, title: next.display.title.trim(), subtitle: optional(next.display.subtitle) },
display: {
...next.display,
title: next.display.title.trim(),
subtitle: optional(next.display.subtitle),
rotateSeconds,
},
standings: { ...next.standings },
}
saving.value = true
saveError.value = null
try {
const result = await settingsApi.save(patch, current)
const result = await settingsApi.save(patch)
usingMock.value = result.mock
data.settings = result.data
form.value = clone(result.data)
+37 -38
View File
@@ -7,8 +7,9 @@ import { mockMode, mockReason } from '../../api/client'
* `api/client.ts` 只封装了 ApiClient 已有的端点,用户管理 / 备份列表 / 赛事项目包 /
* 规则包这几组接口还没进共享客户端(且本任务不允许改 api 层),所以在组件目录里补一层薄封装。
*
* 降级策略与 client.ts 完全一致:只有「连不上 / 超时 / 响应不是约定结构 / 404 未实现」
* 才降级示例数据;403、校验失败这类业务回答必须原样抛出,否则会把「没权限」伪装成「示例数据」。
* 降级策略与 client.ts 完全一致:只有「连不上 / 超时」才降级示例数据;
* 403、404、校验失败这类业务回答必须原样抛出,否则会把「没权限 / 不存在」伪装成「示例数据」。
* 写操作(用户、备份、设置、规则落地、项目导入)一律不降级,避免假成功。
*/
const BASE_URL = '/api'
@@ -16,7 +17,8 @@ const DEFAULT_TIMEOUT_MS = 15_000
/** 上传整包可能上百 MB,超时必须放宽,否则现场弱网必然失败。 */
const UPLOAD_TIMEOUT_MS = 120_000
const FALLBACK_CODES: readonly string[] = ['NETWORK', 'TIMEOUT', 'PARSE_FAILED']
// 与 client.ts 一致:只有连不上 / 超时才降级;解析失败说明服务端在跑但响应不对,必须暴露。
const FALLBACK_CODES: readonly string[] = ['NETWORK', 'TIMEOUT']
const API_ERROR_CODES: readonly string[] = [
'AUTH_REQUIRED',
@@ -36,8 +38,9 @@ function isApiErrorCode(value: unknown): value is ApiErrorCode {
return typeof value === 'string' && API_ERROR_CODES.includes(value)
}
export function isBackendUnavailable(error: unknown): boolean {
return error instanceof ApiError && (FALLBACK_CODES.includes(error.code) || error.status === 404)
function isBackendUnavailable(error: unknown): boolean {
// 404 / 403 / 校验失败都是服务端的真实回答,只有连不上 / 超时才算「后端未就绪」。
return error instanceof ApiError && FALLBACK_CODES.includes(error.code)
}
export interface MockAware<T> {
@@ -51,10 +54,15 @@ function markMock(reason: string): void {
mockReason.value = reason
}
/** 与 client.ts 的 call() 同构,额外把「是否降级」返回给调用方。 */
export async function withMockInfo<T>(
/**
* 与 client.ts 的 call() 同构,额外把「是否降级」返回给调用方。
*
* `mock` 传 null 表示不降级,用于所有写操作:示例数据里的「保存成功」会让操作员
* 以为改动已经落库(最典型的是重置密码),因此写操作一律原样抛错。
*/
async function withMockInfo<T>(
real: () => Promise<T>,
mock: () => T | Promise<T>,
mock: (() => T | Promise<T>) | null,
): Promise<MockAware<T>> {
try {
const data = await real()
@@ -64,16 +72,12 @@ export async function withMockInfo<T>(
}
return { data, mock: false }
} catch (error) {
if (!isBackendUnavailable(error)) throw error
if (mock === null || !isBackendUnavailable(error)) throw error
markMock(error instanceof Error ? error.message : '无法连接服务端')
return { data: await mock(), mock: true }
}
}
export async function withMock<T>(real: () => Promise<T>, mock: () => T | Promise<T>): Promise<T> {
return (await withMockInfo(real, mock)).data
}
/**
* 服务端只回一句「服务端异常」,真正的线索在 error.detail 里(例如「赛事项目名非法: 名称为空」)。
* 展示时把 detail 一并带上,现场才不用去翻服务端日志。
@@ -166,10 +170,14 @@ async function send(path: string, options: RawOptions = {}): Promise<Response> {
if (options.json !== undefined) headers['Content-Type'] = 'application/json; charset=utf-8'
else if (options.contentType !== undefined) headers['Content-Type'] = options.contentType
let json = options.json
if (method !== 'GET') {
const token = readCsrfToken()
if (token !== null && token !== '') headers['X-CSRF-Token'] = token
headers['X-Request-Id'] = newRequestId()
const requestId = newRequestId()
headers['X-Request-Id'] = requestId
// 服务端幂等缓存同时看 header 与 body.requestId,两边必须一致才可能命中。
if (isRecord(json) && !('requestId' in json)) json = { ...json, requestId }
}
const controller = new AbortController()
@@ -180,7 +188,7 @@ async function send(path: string, options: RawOptions = {}): Promise<Response> {
method,
headers,
credentials: 'include',
body: options.json !== undefined ? JSON.stringify(options.json) : options.body,
body: json !== undefined ? JSON.stringify(json) : options.body,
signal: controller.signal,
})
} catch (error) {
@@ -402,7 +410,8 @@ export const usersApi = {
if (created === null) throw new ApiError('PARSE_FAILED', '新建用户响应格式不符', 0, body)
return created
},
() => mockUsers().create(input),
// 写操作不降级:假成功会让管理员以为账号已建好。
null,
)
},
@@ -414,7 +423,7 @@ export const usersApi = {
if (updated === null) throw new ApiError('PARSE_FAILED', '更新用户响应格式不符', 0, body)
return updated
},
() => mockUsers().update(id, patch),
null,
)
},
@@ -426,7 +435,8 @@ export const usersApi = {
if (password === null) throw new ApiError('PARSE_FAILED', '重置密码响应缺少 password', 0, body)
return { password }
},
() => mockUsers().resetPassword(id),
// 这里绝不能降级:mock 会返回一个假密码,等于谎报「重置成功」。
null,
)
},
}
@@ -496,16 +506,8 @@ export const backupsApi = {
if (created === null) throw new ApiError('PARSE_FAILED', '备份响应格式不符', 0, body)
return created
},
() => {
const createdAt = new Date().toISOString()
return {
name: `event-${createdAt.replace(/[:.]/g, '-')}.db`,
path: `data/backups/event-${createdAt.replace(/[:.]/g, '-')}.db`,
size: 1_486_848,
reason: 'manual',
createdAt,
}
},
// 备份是写操作:示例数据里假装备份成功会让现场以为已经落盘。
null,
)
},
}
@@ -633,12 +635,8 @@ export const projectApi = {
meta: body.meta,
}
},
() => ({
name: options.rename.trim() === '' ? file.name.replace(/\.zip$/i, '') : options.rename.trim(),
dir: `data/event_projs/${options.rename.trim() === '' ? file.name.replace(/\.zip$/i, '') : options.rename.trim()}`,
eventDB: 'event.db',
meta: { note: '示例数据:未真正解压落盘' },
}),
// 导入会覆盖赛事目录,绝不能降级成「示例数据导入成功」。
null,
)
},
}
@@ -803,7 +801,8 @@ export const rulesApi = {
contentType: 'application/yaml; charset=utf-8',
timeoutMs: 60_000,
}).then(toRuleApplyResult),
() => ({ ...mockPreview(), recalculatedLedgerRows: 128 }),
// 落地规则包会重算积分,不能降级成假的「已应用」。
null,
)
},
}
@@ -815,7 +814,7 @@ export const rulesApi = {
export type EventSettingsPatch = Partial<EventSettings>
export const settingsApi = {
async save(patch: EventSettingsPatch, current: EventSettings): Promise<MockAware<EventSettings>> {
async save(patch: EventSettingsPatch): Promise<MockAware<EventSettings>> {
return withMockInfo(
async () => {
const body = await requestJson<unknown>('/settings', { method: 'PUT', json: patch })
@@ -823,8 +822,8 @@ export const settingsApi = {
// 服务端返回的字段与 shared/types 的 EventSettings 一一对应,这里只做结构校验后透传。
return body as unknown as EventSettings
},
// 示例模式下把改动合并进当前设置,让表单交互能完整走通。
() => ({ ...current, ...patch }),
// 写操作不降级:示例数据里的「保存成功」会让管理员以为设置已生效。
null,
)
},
}
+14 -3
View File
@@ -14,6 +14,8 @@ interface NavItem {
label: string
icon: IconName
badge?: 'pending'
/** 系统配置与审计日志只有 admin 可见(devdocs/08 第 2 节)。 */
adminOnly?: boolean
}
interface NavGroup {
@@ -45,11 +47,11 @@ const NAV: NavGroup[] = [
{ name: 'base-data', label: '基础数据', icon: 'database' },
{ name: 'export', label: '导出', icon: 'export' },
{ name: 'history', label: '变更历史', icon: 'history' },
{ name: 'logs', label: '日志', icon: 'logs' },
{ name: 'logs', label: '日志', icon: 'logs', adminOnly: true },
],
},
{ section: '系统', items: [
{ name: 'system', label: '系统设置', icon: 'system' },
{ name: 'system', label: '系统设置', icon: 'system', adminOnly: true },
{ name: 'password', label: '修改密码', icon: 'lock' },
{ name: 'about', label: '关于', icon: 'info' },
] },
@@ -64,6 +66,15 @@ const toast = useToastStore()
const sidebarOpen = ref(false)
const refreshing = ref(false)
const isAdmin = computed(() => auth.user?.role === 'admin')
/** 非 admin 不显示系统设置 / 日志,避免点进去只看到一堆 403。 */
const navGroups = computed<NavGroup[]>(() =>
NAV.map((group) => ({
...group,
items: group.items.filter((item) => item.adminOnly !== true || isAdmin.value),
})).filter((group) => group.items.length > 0),
)
const currentTitle = computed(() => (typeof route.meta.title === 'string' ? route.meta.title : '管理面板'))
const pendingCount = computed(() => data.events.filter((event) => event.status === 'pending').length)
const themeToggleLabel = computed(() => (theme.value === 'dark' ? '切换到浅色模式' : '切换到深色模式'))
@@ -112,7 +123,7 @@ onMounted(async () => {
</div>
<nav class="nav">
<div v-for="group in NAV" :key="group.section" class="nav-group">
<div v-for="group in navGroups" :key="group.section" class="nav-group">
<div class="mx-sidebar-section">{{ group.section }}</div>
<RouterLink
v-for="item in group.items"
+3 -2
View File
@@ -8,8 +8,9 @@ const data = useEventStore()
const SYSTEM_NAME = '运动会积分榜系统'
const SYSTEM_EN = 'Scoreboard'
// /api/health 只回 version,没有构建时间字段;构建期常量要改 vite.config,本页按约定显示 dev
const BUILD_TIME = 'dev'
// /api/health 只回 version,/api/system/about 也不带构建时间;前端构建期未注入该常量,
// 因此这里如实显示「未注入」,不再用假的 'dev' 冒充构建时间。
const BUILD_TIME = '未注入'
const version = ref<string | null>(null)
const versionChecked = ref(false)
+26 -9
View File
@@ -56,6 +56,7 @@ const localItems = ref<PointAdjustment[]>([])
let nextLocalId = -1
const canWrite = computed(() => !auth.readOnly && data.canWrite)
const isAdmin = computed(() => auth.user?.role === 'admin')
/**
* 人工调整开关:true / false / null(未知)。
*
@@ -77,12 +78,15 @@ const filteredItems = computed(() => {
})
})
// 分页只作用于服务端记录;本地降级条目固定显示在当前页,不能混进 total 的页码计算。
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / size)))
const rangeText = computed(() => {
if (total.value === 0) return '共 0 条'
const local = localItems.value.length
const suffix = local > 0 ? `,另有 ${local} 条本地示例记录` : ''
if (total.value === 0) return local > 0 ? `共 ${local} 条本地示例记录` : '共 0 条'
const from = (page.value - 1) * size + 1
const to = Math.min(page.value * size, total.value)
return `第 ${from}–${to} 条,共 ${total.value} 条`
return `第 ${from}–${to} 条,共 ${total.value} 条${suffix}`
})
function teamLabel(teamId: number): string {
@@ -109,20 +113,33 @@ function isLocal(item: PointAdjustment): boolean {
return item.id < 0
}
/** 只有真的连不上服务端才做本地降级;业务 404 / 解析失败必须原样呈现。 */
function isFallback(error: unknown): boolean {
return (
error instanceof ApiError &&
(['NETWORK', 'TIMEOUT', 'PARSE_FAILED'].includes(error.code) || error.status === 404)
)
return error instanceof ApiError && ['NETWORK', 'TIMEOUT'].includes(error.code)
}
function isForbidden(error: unknown): boolean {
return error instanceof ApiError && (error.status === 403 || error.code === 'FORBIDDEN')
}
async function loadRules(): Promise<void> {
try {
rulePack.value = await adminApi.client.rules.get()
ruleError.value = null
// /api/rules/export 是 admin-only:录入员跳过它,改用下面的只读开关端点,
// 否则页面会常驻一条红色「读取规则包失败:无权访问该资源」。
if (isAdmin.value) {
rulePack.value = await adminApi.client.rules.get()
ruleError.value = null
} else {
rulePack.value = null
ruleError.value = null
}
} catch (caught) {
rulePack.value = null
ruleError.value = caught instanceof Error ? caught.message : '无法读取规则包'
ruleError.value = isForbidden(caught)
? null
: caught instanceof Error
? caught.message
: '无法读取规则包'
}
// 规则包只有 admin 能读;录入员改用只读开关端点,避免把已启用功能误报成关闭。
try {
+91 -22
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import {
formatPoints,
@@ -25,6 +25,7 @@ interface EditableRow {
categoryId: number
bib: string | null
teamId: number
athleteId: number | null
teamName: string
teamShort: string
athleteName: string
@@ -78,6 +79,8 @@ const unpublishDialog = ref(false)
const focusedEntryId = ref<number | null>(null)
const tableRef = ref<HTMLElement | null>(null)
const recordForEvent = ref<{ resultText: string; resultValue: number } | null>(null)
/** 项目切换的请求序号:只有最新一次请求的响应才允许写入页面状态。 */
let requestSeq = 0
const canWrite = computed(() => !auth.readOnly && data.canWrite)
@@ -93,7 +96,6 @@ const selectedEvent = computed(() => detail.value ?? (selectedEventId.value ===
const categories = computed(() => detail.value?.categories ?? [])
const channels = computed(() => detail.value?.channels ?? [])
const weight = computed(() => data.settings?.standings.individualToTeamWeight ?? 1)
const isIndividual = computed(() => selectedEvent.value?.eventType === 'individual')
const manualRank = computed(() => selectedEvent.value?.resultMode === 'manual' || selectedEvent.value?.compare === 'none')
function unitOf(type: Event['resultType']): string {
@@ -114,6 +116,7 @@ const scorable = computed<ScorableRow[]>(() =>
visibleRows.value.map((row) => ({
entryId: row.entryId,
teamId: row.teamId,
athleteId: row.athleteId,
resultValue: parseResultValue(row.resultText, unit.value),
rank: row.rank,
status: row.status,
@@ -136,16 +139,15 @@ const score = computed(() => {
/**
* 已发布行产生的分已经计入当前总分,预览时必须先扣掉,差值才是「本次发布」的影响。
*
* 不能用 result.points:服务端从不返回该字段(恒为 0),否则已发布分会被重复计算。
* 这里改用与预览同一套算法算出的 rowPoints,口径与服务端计分一致。
* 用 rowTeamPoints(各通道原始分,个人通道已按权重折算)而不是服务端 result.points:
* 后者只覆盖已发布行,且编辑中的行服务端还没算分,两边口径无法混用。
*/
const publishedContribution = computed(() => {
const map = new Map<number, number>()
const rowPoints = score.value?.rowPoints
const rowTeamPoints = score.value?.rowTeamPoints
for (const row of visibleRows.value) {
if (row.resultState !== 'published') continue
const points = rowPoints?.get(row.entryId) ?? 0
map.set(row.teamId, (map.get(row.teamId) ?? 0) + (isIndividual.value ? points * weight.value : points))
map.set(row.teamId, (map.get(row.teamId) ?? 0) + (rowTeamPoints?.get(row.entryId) ?? 0))
}
return map
})
@@ -165,7 +167,13 @@ const preview = computed<PreviewRow[]>(() => {
const maxDelta = computed(() => preview.value.reduce((max, row) => Math.max(max, Math.abs(row.delta)), 0))
const affectedTeams = computed(() => preview.value.filter((row) => row.delta !== 0).length)
const isPublished = computed(() => visibleRows.value.some((row) => row.resultState === 'published'))
const dirty = computed(() => visibleRows.value.some((row) => rowDirty(row)))
/** dirty 必须扫描全部组别,否则切到另一组别后「有未保存修改」徽标会凭空消失。 */
const dirty = computed(() => allRows.value.some((row) => rowDirty(row)))
/** 已发布的行由服务端锁定:只能先撤销发布,不能就地改草稿。 */
function rowLocked(row: EditableRow): boolean {
return row.resultState === 'published'
}
const issues = computed<Issue[]>(() => {
const list: Issue[] = []
@@ -233,9 +241,10 @@ function round(value: number): number {
return Number(value.toFixed(2))
}
/** 空缺成绩的快照必须与 rowDirty 拼出的默认行一致,否则一进页面就亮「已修改」。 */
function snapshotOf(entry: EntryWithResult): string {
const result = entry.result
if (result === null) return '||||'
if (result === null) return ['', '', 'ok', '0', ''].join('|')
return [result.resultText, result.rank ?? '', result.status, result.isTie ? '1' : '0', result.note ?? ''].join('|')
}
@@ -246,6 +255,7 @@ function toRow(entry: EntryWithResult): EditableRow {
categoryId: entry.categoryId,
bib: entry.bib,
teamId: entry.teamId,
athleteId: entry.athleteId,
teamName: entry.teamName ?? data.teamById(entry.teamId)?.name ?? '未知单位',
teamShort: entry.shortName ?? data.teamById(entry.teamId)?.shortName ?? '',
athleteName: entry.athleteName ?? '',
@@ -266,6 +276,14 @@ function rowDirty(row: EditableRow): boolean {
return row.original !== [row.resultText, row.rank ?? '', row.status, row.isTie ? '1' : '0', row.note].join('|')
}
/** 名次输入框清空时 v-model.number 会给出空串,必须在入口就归一为 null。 */
function rankInputValue(event: InputEvent): number | null {
const raw = (event.target as HTMLInputElement).value.trim()
if (raw === '') return null
const value = Number(raw)
return Number.isFinite(value) ? Math.trunc(value) : null
}
function rankOf(row: EditableRow): number | null {
if (manualRank.value) return row.rank
return score.value?.ranks.get(row.entryId) ?? null
@@ -279,9 +297,17 @@ function issueFor(entryId: number): Issue | undefined {
return issues.value.find((issue) => issue.entryId === entryId)
}
/** 切换项目会丢弃当前编辑,先让操作员确认。 */
function confirmDiscard(): boolean {
if (!dirty.value) return true
return window.confirm('当前有未保存的成绩修改,切换项目会丢弃这些修改。确定继续吗?')
}
async function selectEvent(id: number): Promise<void> {
if (selectedEventId.value === id && detail.value !== null) return
if (!confirmDiscard()) return
selectedEventId.value = id
const seq = (requestSeq += 1)
loading.value = true
try {
const [event, entries, records] = await Promise.all([
@@ -289,28 +315,35 @@ async function selectEvent(id: number): Promise<void> {
adminApi.entries(id),
adminApi.records(),
])
// 切换过快时旧响应可能后到,只有最新一次请求的结果才允许覆盖页面。
if (seq !== requestSeq) return
detail.value = event
selectedCategoryId.value = event.categories?.[0]?.id ?? null
allRows.value = entries.map(toRow)
const record = records.find((item) => item.eventId === id && item.isCurrent) ?? null
recordForEvent.value = record === null ? null : { resultText: record.resultText, resultValue: record.resultValue }
} catch (caught) {
if (seq !== requestSeq) return
toast.error(caught instanceof Error ? caught.message : '加载项目失败')
} finally {
loading.value = false
if (seq === requestSeq) loading.value = false
}
}
async function reload(): Promise<void> {
if (selectedEventId.value === null) return
const id = selectedEventId.value
const seq = requestSeq
loading.value = true
try {
allRows.value = (await adminApi.entries(id)).map(toRow)
const entries = await adminApi.entries(id)
if (seq !== requestSeq) return
allRows.value = entries.map(toRow)
} catch (caught) {
if (seq !== requestSeq) return
toast.error(caught instanceof Error ? caught.message : '重新加载失败')
} finally {
loading.value = false
if (seq === requestSeq) loading.value = false
}
}
@@ -320,6 +353,8 @@ function buildDraftPayload(): DraftResultInput[] {
rank: manualRank.value ? row.rank : null,
resultText: row.resultText.trim(),
resultValue: parseResultValue(row.resultText, unit.value),
// 不传 unit 时服务端会把已有单位覆盖成 NULL,大屏 100 米就会显示成 66.33。
unit: unit.value,
status: row.status,
isTie: row.isTie,
note: row.note.trim() === '' ? null : row.note.trim(),
@@ -328,6 +363,12 @@ function buildDraftPayload(): DraftResultInput[] {
async function saveDraft(silent = false): Promise<boolean> {
if (selectedEventId.value === null) return false
if (saving.value) return false
if (isPublished.value) {
// 已发布行由服务端锁定:就地存草稿会清掉名次却不重算积分,必须先撤销发布。
toast.error('该组已发布', '修改前请先撤销发布')
return false
}
if (!canWrite.value) {
toast.error('当前不可写入', auth.readOnly ? '请先登录' : '服务端未连接')
return false
@@ -361,6 +402,10 @@ function requestPublish(): void {
toast.error('当前不可发布', auth.readOnly ? '请先登录' : '服务端未连接')
return
}
if (isPublished.value) {
toast.error('该组已发布', '如需修改请先撤销发布')
return
}
if (errors.value.length > 0) {
toast.error(`有 ${errors.value.length} 处校验未通过`, errors.value[0]?.message ?? null)
return
@@ -384,7 +429,7 @@ async function confirmPublish(): Promise<void> {
})
publishDialog.value = false
await reload()
await data.refreshStandings()
await Promise.all([data.refreshStandings(), data.refreshEvents()])
toast.success('发布成功,积分榜已更新')
} catch (caught) {
toast.error('发布失败', caught instanceof Error ? caught.message : null)
@@ -403,7 +448,7 @@ async function confirmUnpublish(): Promise<void> {
})
unpublishDialog.value = false
await reload()
await data.refreshStandings()
await Promise.all([data.refreshStandings(), data.refreshEvents()])
toast.warning('已撤销发布,大屏将回退该组成绩')
} catch (caught) {
toast.error('撤销发布失败', caught instanceof Error ? caught.message : null)
@@ -442,10 +487,18 @@ function onPageKeydown(event: KeyboardEvent): void {
if (!event.ctrlKey && !event.altKey) return
if (event.key !== 'Enter') return
event.preventDefault()
if (saving.value || publishing.value || unpublishing.value) return
if (event.altKey) requestPublish()
else void saveDraft()
}
/** 关闭/刷新页面前拦住未保存的编辑,避免一整组成绩静默丢失。 */
function onBeforeUnload(event: BeforeUnloadEvent): void {
if (!dirty.value) return
event.preventDefault()
event.returnValue = ''
}
/**
* Excel 粘贴:两列及以上时,第一列按单位名匹配行,最后一列作为成绩;
* 单列时从当前行往下顺序填充(07 第 2 节第 4 条)。
@@ -502,9 +555,14 @@ async function pickInitialEvent(): Promise<void> {
}
onMounted(() => {
window.addEventListener('beforeunload', onBeforeUnload)
void pickInitialEvent()
})
onUnmounted(() => {
window.removeEventListener('beforeunload', onBeforeUnload)
})
// 项目列表由布局层异步加载,加载完成后补一次默认选中。
watch(
() => data.loaded,
@@ -519,13 +577,19 @@ watch(
<PageHeader title="成绩录入" :subtitle="selectedEvent?.name ?? '选择左侧项目开始录入'">
<template #actions>
<span v-if="dirty" class="mx-badge mx-badge-warning">有未保存修改</span>
<button class="mx-btn mx-btn-secondary" type="button" :disabled="!canWrite || saving" @click="saveDraft()">
<button
class="mx-btn mx-btn-secondary"
type="button"
:disabled="!canWrite || saving || isPublished"
:title="isPublished ? '该组已发布,请先撤销发布' : ''"
@click="saveDraft()"
>
<MxIcon name="check" :size="15" /> 存草稿
</button>
<button
class="mx-btn mx-btn-primary"
type="button"
:disabled="!canWrite || publishing || data.isMock"
:disabled="!canWrite || publishing || data.isMock || isPublished"
@click="requestPublish"
>
<MxIcon name="push" :size="15" /> 发布
@@ -612,7 +676,7 @@ watch(
<div v-if="isPublished" class="published-note">
<MxIcon name="lock" :size="15" />
该组已发布,修改前需先「撤销发布」;草稿态不会上屏。
该组已发布,成绩与名次已锁定上屏:如需修改,请先「撤销发布」。草稿态不会上屏。
</div>
<div class="entry-body">
@@ -648,7 +712,8 @@ watch(
data-cell
class="mx-cell-input mono"
:class="{ 'is-invalid': issueFor(row.entryId)?.level === 'error' }"
:disabled="!canWrite"
:disabled="!canWrite || rowLocked(row)"
:title="rowLocked(row) ? '已发布,请先撤销发布' : ''"
:placeholder="unit === 's' ? '1:06.33' : unit"
@focus="focusedEntryId = row.entryId"
@blur="focusedEntryId = null"
@@ -659,12 +724,14 @@ watch(
<td class="center">
<input
v-if="manualRank"
v-model.number="row.rank"
:value="row.rank ?? ''"
data-cell
type="number"
min="1"
class="mx-cell-input rank-input"
:disabled="!canWrite"
:disabled="!canWrite || rowLocked(row)"
:title="rowLocked(row) ? '已发布,请先撤销发布' : ''"
@input="row.rank = rankInputValue($event)"
@focus="focusedEntryId = row.entryId"
@blur="focusedEntryId = null"
@keydown="onCellKeydown($event, $event.currentTarget as HTMLElement)"
@@ -676,7 +743,8 @@ watch(
v-model="row.status"
data-cell
class="mx-cell-input status-select"
:disabled="!canWrite"
:disabled="!canWrite || rowLocked(row)"
:title="rowLocked(row) ? '已发布,请先撤销发布' : ''"
@focus="focusedEntryId = row.entryId"
@blur="focusedEntryId = null"
@keydown="onCellKeydown($event, $event.currentTarget as HTMLElement)"
@@ -696,7 +764,8 @@ watch(
v-model="row.note"
data-cell
class="mx-cell-input"
:disabled="!canWrite"
:disabled="!canWrite || rowLocked(row)"
:title="rowLocked(row) ? '已发布,请先撤销发布' : ''"
placeholder="—"
@focus="focusedEntryId = row.entryId"
@blur="focusedEntryId = null"
+89 -5
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import {
ApiError,
formatDateTime,
type EntryWithResult,
type Event,
@@ -13,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 { fetchRevisions } from '../components/history/revisionsSource'
import { fetchRevisionDetail, fetchRevisions } 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'
@@ -36,16 +37,21 @@ const revisions = ref<Revision[]>([])
const loading = ref(false)
const usingMock = ref(false)
const mockReason = ref<string | null>(null)
const loadError = ref<string | null>(null)
const eventFilter = ref<number | 'all'>('all')
const timeFilter = ref<TimeFilter>('all')
const selectedId = ref<number | null>(null)
const contexts = ref<Record<number, EventContext>>({})
/** 已成功拉到快照的修订 id,避免 watch 反复请求。 */
const detailLoadedIds = ref<number[]>([])
const detailLoading = ref(false)
const detailError = ref<string | null>(null)
const weight = computed(() => data.settings?.standings.individualToTeamWeight ?? 1)
const visibleRevisions = computed(() => {
const threshold = timeThreshold(timeFilter.value)
const list = threshold === null ? revisions.value : revisions.value.filter((item) => item.createdAt >= threshold)
const list = threshold === null ? revisions.value : revisions.value.filter((item) => toTime(item.createdAt) >= threshold)
return [...list].sort((a, b) => (a.createdAt === b.createdAt ? b.id - a.id : a.createdAt < b.createdAt ? 1 : -1))
})
@@ -129,10 +135,21 @@ function round(value: number): number {
return Number(value.toFixed(2))
}
function timeThreshold(filter: TimeFilter): string | null {
function timeThreshold(filter: TimeFilter): number | null {
if (filter === 'all') return null
const hours = filter === '24h' ? 24 : 24 * 7
return new Date(Date.now() - hours * 3_600_000).toISOString()
return Date.now() - hours * 3_600_000
}
/**
* 服务端存的是 SQLite `datetime('now')`,即无时区后缀的 UTC 串。
* 直接做字符串比较会因空格(0x20)小于 'T'(0x54)而整体误判,必须先转时间戳。
*/
function toTime(value: string): number {
if (value === '') return 0
const normalized = /[zZ]|[+-]\d{2}:?\d{2}$/.test(value) ? value : `${value.replace(' ', 'T')}Z`
const parsed = Date.parse(normalized)
return Number.isNaN(parsed) ? 0 : parsed
}
function teamLabel(teamId: number): string {
@@ -171,6 +188,7 @@ function teamTotals(revision: Revision, context: EventContext | null): Map<numbe
scorable.push({
entryId: row.entryId,
teamId,
athleteId: context.entryById.get(row.entryId)?.athleteId ?? null,
resultValue: row.resultValue,
rank: row.rank,
status: normalizeStatus(row.status),
@@ -205,14 +223,48 @@ async function ensureContext(eventId: number): Promise<void> {
}
}
/**
* 列表接口不含成绩快照,只有详情接口才带;选中节点后补拉一次,
* 否则真机上 diff 恒 0、影响单位恒空、积分流水恒 0。
*/
async function loadDetail(id: number): Promise<void> {
if (usingMock.value || detailLoadedIds.value.includes(id)) return
detailLoading.value = true
detailError.value = null
try {
const detail = await fetchRevisionDetail(id)
if (detail === null) return
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 : '加载变更详情失败'
} finally {
detailLoading.value = false
}
}
/** 只有网络不可达才降级示例数据;403 / 404 / 500 必须原样呈现。 */
function isUnavailable(error: unknown): boolean {
return error instanceof ApiError && ['NETWORK', 'TIMEOUT'].includes(error.code)
}
async function load(): Promise<void> {
loading.value = true
const eventId = eventFilter.value === 'all' ? undefined : eventFilter.value
detailLoadedIds.value = []
detailError.value = null
loadError.value = null
try {
revisions.value = await fetchRevisions(eventId === undefined ? {} : { eventId })
usingMock.value = false
mockReason.value = null
} catch (caught) {
if (!isUnavailable(caught)) {
revisions.value = []
usingMock.value = false
loadError.value = caught instanceof Error ? caught.message : '变更历史接口不可用'
return
}
const all = createMockRevisions()
revisions.value = eventId === undefined ? all : all.filter((item) => item.eventId === eventId)
usingMock.value = true
@@ -245,7 +297,9 @@ watch(
watch(
selectedRevision,
(revision) => {
if (revision !== null) void ensureContext(revision.eventId)
if (revision === null) return
void ensureContext(revision.eventId)
if (revision.snapshot.length === 0) void loadDetail(revision.id)
},
{ immediate: true },
)
@@ -268,6 +322,12 @@ watch(
<span class="mock-hint">接口就绪后自动切换为真实数据</span>
</div>
<div v-if="loadError !== null" class="error-banner">
<MxIcon name="warning" :size="15" />
<span>{{ loadError }}</span>
<button class="mx-btn mx-btn-secondary mx-btn-sm" type="button" @click="load">重试</button>
</div>
<div class="filter-bar">
<label class="filter">
<span>小项</span>
@@ -341,6 +401,8 @@ watch(
<span v-if="selectedRevision" class="mx-badge mx-badge-neutral mono">#{{ selectedRevision.id }}</span>
</div>
<div class="mx-card-body">
<p v-if="detailLoading" class="detail-hint">正在加载节点详情…</p>
<p v-else-if="detailError !== null" class="detail-hint error">加载节点详情失败:{{ detailError }}</p>
<RevisionDetail
v-if="selectedRevision"
:revision="selectedRevision"
@@ -381,6 +443,20 @@ watch(
color: var(--mx-t3);
font-size: 12px;
}
.error-banner {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
margin-top: 14px;
border-radius: var(--mx-r-sm);
background: rgba(248, 113, 113, 0.08);
color: var(--mx-red);
font-size: 13px;
}
.error-banner .mx-btn {
margin-left: auto;
}
.filter-bar {
display: flex;
align-items: center;
@@ -464,6 +540,14 @@ watch(
background: rgba(251, 191, 36, 0.12);
color: var(--mx-amber);
}
.detail-hint {
font-size: 12px;
color: var(--mx-t3);
margin-bottom: 10px;
}
.detail-hint.error {
color: var(--mx-error);
}
.foot-hint {
display: flex;
align-items: center;
+9 -5
View File
@@ -6,7 +6,7 @@ import PageHeader from '../components/PageHeader.vue'
import MockBadge from '../components/system/MockBadge.vue'
import JsonDiff from '../components/system/JsonDiff.vue'
import { describeError } from '../components/system/systemApi'
import { adminApi, mockMode } from '../api/client'
import { adminApi } from '../api/client'
import { useAuthStore } from '../stores/auth'
import { useToastStore } from '../stores/toast'
@@ -81,14 +81,18 @@ function onFilterChange(): void {
page.value = 1
}
const isAdmin = computed(() => auth.user?.role === 'admin')
async function load(): Promise<void> {
// /api/audit-logs 是 admin-only;非 admin 直接不请求,避免常驻 403 报错。
if (!isAdmin.value) return
loading.value = true
loadError.value = null
try {
const result = await adminApi.auditLogs({ page: 1, size: WINDOW_SIZE })
rows.value = result.items
// adminApi 内部静默降级,只能从全局标记反推这批数据是不是示例。
usingMock.value = mockMode.value
// 用局部 mock 标记判断本批数据是不是示例,不读会被并发请求清掉的全局状态。
const result = await adminApi.auditLogsWithMock({ page: 1, size: WINDOW_SIZE })
rows.value = result.data.items
usingMock.value = result.mock
if (page.value > pageCount.value) page.value = 1
} catch (caught) {
loadError.value = describeError(caught)
-159
View File
@@ -1,159 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import MxIcon from '../components/MxIcon.vue'
import PageHeader from '../components/PageHeader.vue'
import type { IconName } from '../components/icons'
/**
* 未实现页面的统一骨架。
* M4 只要求占位路由,这里把「这页将来做什么」写清楚,避免点进来是一片空白。
*/
const route = useRoute()
const TITLE_ICONS: Record<string, IconName> = {
review: 'review',
records: 'record',
adjustments: 'adjust',
'base-data': 'database',
export: 'export',
history: 'history',
logs: 'logs',
system: 'system',
}
const title = computed(() => (typeof route.meta.title === 'string' ? route.meta.title : '页面'))
const note = computed(() => (typeof route.meta.note === 'string' ? route.meta.note : ''))
const icon = computed<IconName>(() => TITLE_ICONS[String(route.name)] ?? 'system')
const PLANNED: Record<string, string[]> = {
review: ['草稿列表(按项目 / 时间筛选)', '并排对比历史版本', '批量发布 / 退回,留审计'],
records: ['疑似破纪录自动提示', '裁判长确认后生成加分流水', '本期破纪录加分关闭,功能保留'],
adjustments: ['人工加减分(分值可正可负)', '类别:处罚 / 补分 / 更正', '理由必填、可作废、全程审计'],
'base-data': ['单位 / 大项 / 小项 / 组别', '积分模板与计分通道', '运动员与报名表 xlsx 导入'],
export: ['总表 / 分项成绩表 / 单位明细', '按小项、组别单独导出', '赛事项目包 zip 导入导出'],
history: ['仿 Git Graph 的时间轴 + 分支线', '节点详情:操作人 / 动作 / 分数增减', '只读,不做一键回滚'],
logs: ['审计日志:谁在什么时候改了什么', '按实体类型 / 用户 / 时间筛选', '可关联 requestId 追查重试'],
system: ['用户与角色管理', '备份与恢复', '赛事信息与项目切换'],
}
</script>
<template>
<div>
<PageHeader :title="title" :subtitle="note">
<template #actions>
<span class="mx-badge mx-badge-neutral">规划中</span>
</template>
</PageHeader>
<div class="mx-card">
<div class="mx-card-body">
<div class="skeleton-head">
<span class="skeleton-icon"><MxIcon :name="icon" :size="22" /></span>
<div>
<h2>{{ title }}页面将在后续里程碑实现</h2>
<p>M4 只交付占位路由与骨架,核心链路(成绩录入 → 积分榜 → 大屏)已可用。</p>
</div>
</div>
<div class="planned">
<div class="planned-title">计划能力</div>
<ul>
<li v-for="item in PLANNED[String(route.name)] ?? []" :key="item">
<MxIcon name="check" :size="14" />
<span>{{ item }}</span>
</li>
</ul>
</div>
<div class="mx-stat-grid skeleton-grid">
<div v-for="index in 3" :key="index" class="mx-stat skeleton-stat">
<div class="mx-skeleton line short"></div>
<div class="mx-skeleton line tall"></div>
<div class="mx-skeleton line"></div>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.skeleton-head {
display: flex;
gap: 14px;
align-items: flex-start;
margin-bottom: 20px;
}
.skeleton-icon {
width: 44px;
height: 44px;
border-radius: var(--mx-r-sm);
background: var(--mx-primary-glow);
color: var(--mx-primary);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.skeleton-head h2 {
font-size: 16px;
font-weight: 700;
margin-bottom: 6px;
}
.skeleton-head p {
font-size: 13px;
color: var(--mx-t3);
line-height: 1.6;
}
.planned {
padding: 14px 16px;
border-radius: var(--mx-r-sm);
background: var(--mx-s3);
margin-bottom: 20px;
}
.planned-title {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--mx-t3);
margin-bottom: 10px;
}
.planned ul {
display: flex;
flex-direction: column;
gap: 8px;
}
.planned li {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
color: var(--mx-t2);
}
.planned li svg {
color: var(--mx-green);
flex-shrink: 0;
}
.skeleton-grid {
opacity: 0.6;
}
.skeleton-stat {
cursor: default;
display: flex;
flex-direction: column;
gap: 10px;
}
.line {
height: 12px;
border-radius: 6px;
}
.line.short {
width: 40%;
}
.line.tall {
height: 24px;
width: 60%;
}
</style>
+29 -8
View File
@@ -78,6 +78,7 @@ const rejectedKeys = ref<string[]>([])
const approvedKeys = ref<string[]>([])
const canWrite = computed(() => !auth.readOnly && data.canWrite)
const isAdmin = computed(() => auth.user?.role === 'admin')
/**
* 破纪录加分开关:true / false / null(未知)。
*
@@ -139,11 +140,13 @@ function levelRank(level: RecordLevel): number {
return index < 0 ? 0 : index
}
/** 只有真的连不上服务端才做本地降级;业务 404 / 解析失败必须原样呈现。 */
function isFallback(error: unknown): boolean {
return (
error instanceof ApiError &&
(['NETWORK', 'TIMEOUT', 'PARSE_FAILED'].includes(error.code) || error.status === 404)
)
return error instanceof ApiError && ['NETWORK', 'TIMEOUT'].includes(error.code)
}
function isForbidden(error: unknown): boolean {
return error instanceof ApiError && (error.status === 403 || error.code === 'FORBIDDEN')
}
function teamLabel(teamId: number): string {
@@ -161,11 +164,22 @@ function beats(compare: Event['compare'], value: number, recordValue: number): b
async function loadRules(): Promise<void> {
rulesLoading.value = true
try {
rulePack.value = await adminApi.client.rules.get()
ruleError.value = null
// /api/rules/export 是 admin-only:录入员跳过它,改用下面的只读开关端点,
// 否则页面会常驻一条红色「读取规则包失败:无权访问该资源」。
if (isAdmin.value) {
rulePack.value = await adminApi.client.rules.get()
ruleError.value = null
} else {
rulePack.value = null
ruleError.value = null
}
} catch (caught) {
rulePack.value = null
ruleError.value = caught instanceof Error ? caught.message : '无法读取规则包'
ruleError.value = isForbidden(caught)
? null
: caught instanceof Error
? caught.message
: '无法读取规则包'
} finally {
rulesLoading.value = false
}
@@ -459,7 +473,14 @@ watch(
>
确认加分
</button>
<button class="mx-btn mx-btn-ghost mx-btn-sm" type="button" @click="rejectTarget = item">拒绝</button>
<button
class="mx-btn mx-btn-ghost mx-btn-sm"
type="button"
:disabled="!canWrite"
@click="rejectTarget = item"
>
拒绝
</button>
</td>
</tr>
</tbody>
+41 -9
View File
@@ -3,6 +3,7 @@ import { computed, onMounted, ref, watch } from 'vue'
import {
ApiError,
formatPoints,
parseResultValue,
type EntryWithResult,
type Event,
type EventCategory,
@@ -128,11 +129,35 @@ function teamLabel(teamId: number, fallback: string): string {
return team?.shortName ?? team?.name ?? fallback
}
/** 只有真的连不上服务端才做本地降级;业务 404 / 解析失败必须原样呈现。 */
function isFallback(error: unknown): boolean {
return (
error instanceof ApiError &&
(['NETWORK', 'TIMEOUT', 'PARSE_FAILED'].includes(error.code) || error.status === 404)
)
return error instanceof ApiError && ['NETWORK', 'TIMEOUT'].includes(error.code)
}
function unitOf(type: Event['resultType']): string {
if (type === 'time') return 's'
if (type === 'distance') return 'm'
if (type === 'count') return '次'
if (type === 'score') return 'pts'
return ''
}
/** 发布前防呆:与录入页同一套校验,避免整组发布缺成绩 / 无法解析的行。 */
function publishBlockers(group: DraftGroup): string[] {
const unit = unitOf(group.event.resultType)
const manual = group.event.resultMode === 'manual' || group.event.compare === 'none'
const blockers: string[] = []
for (const row of group.rows) {
if (row.status !== 'ok') continue
const label = row.athleteName || row.memberNames?.join('、') || row.teamShort || `#${row.entryId}`
if (row.resultText.trim() === '') {
if (!(manual && row.rank !== null)) blockers.push(`${label}:缺少成绩`)
} else if (parseResultValue(row.resultText, unit) === null) {
blockers.push(`${label}:成绩格式无法解析`)
}
if (manual && row.rank === null) blockers.push(`${label}:缺少名次`)
}
return blockers
}
function sportNameOf(event: Event): string {
@@ -147,6 +172,7 @@ function buildGroup(event: Event, category: EventCategory | null, entries: Entry
const scorable: ScorableRow[] = scoped.map((entry) => ({
entryId: entry.id,
teamId: entry.teamId,
athleteId: entry.athleteId,
resultValue: entry.result?.resultValue ?? null,
rank: entry.result?.rank ?? null,
status: entry.result?.status ?? 'ok',
@@ -160,15 +186,16 @@ function buildGroup(event: Event, category: EventCategory | null, entries: Entry
weight: weight.value,
}
const score = computeEventScore(scorable, context)
const individual = event.eventType === 'individual'
// 已发布行的分已经计入当前总分,对比时必须先扣掉,差值才是「本次发布」的影响。
// result.points 服务端从不返回(恒为 0),改用与预览同一套算法算出的 rowPoints。
// rowTeamPoints 已按通道 scope 折算好个人→单位系数,与服务端流水口径一致。
const published = new Map<number, number>()
for (const entry of scoped) {
if (entry.result?.state !== 'published') continue
const points = round(score.rowPoints.get(entry.id) ?? 0) * (individual ? weight.value : 1)
published.set(entry.teamId, (published.get(entry.teamId) ?? 0) + points)
published.set(
entry.teamId,
(published.get(entry.teamId) ?? 0) + round(score.rowTeamPoints.get(entry.id) ?? 0),
)
}
const teamIds = new Set<number>([...score.teamPoints.keys(), ...published.keys()])
@@ -277,6 +304,11 @@ function requestPublish(group: DraftGroup): void {
toast.error('当前不可发布', auth.readOnly ? '请先登录' : '服务端未连接')
return
}
const blockers = publishBlockers(group)
if (blockers.length > 0) {
toast.error(`有 ${blockers.length} 处校验未通过`, blockers[0] ?? null)
return
}
publishTarget.value = group
}
@@ -288,7 +320,7 @@ async function confirmPublish(): Promise<void> {
await adminApi.publish({ eventId: group.event.id, categoryId: group.category?.id })
publishTarget.value = null
await load()
await data.refreshStandings()
await Promise.all([data.refreshStandings(), data.refreshEvents()])
toast.success('发布成功,积分榜已更新', `${group.eventName} · ${group.categoryName}`)
} catch (caught) {
toast.error('发布失败', caught instanceof Error ? caught.message : null)
+15 -5
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import PageHeader from '../components/PageHeader.vue'
import UsersPanel from '../components/system/UsersPanel.vue'
import BackupPanel from '../components/system/BackupPanel.vue'
@@ -28,6 +28,16 @@ const data = useEventStore()
const activeTab = ref<TabKey>('users')
const isAdmin = computed(() => auth.user?.role === 'admin')
/** 用户管理 / 备份的后端接口是 admin-only,非 admin 不挂载这两个面板。 */
const visibleTabs = computed(() => (isAdmin.value ? TABS : TABS.filter((tab) => tab.key === 'event')))
watch(
isAdmin,
(admin) => {
if (!admin && activeTab.value !== 'event') activeTab.value = 'event'
},
{ immediate: true },
)
</script>
<template>
@@ -37,7 +47,7 @@ const isAdmin = computed(() => auth.user?.role === 'admin')
<div class="system-toolbar">
<div class="mx-tabs">
<button
v-for="tab in TABS"
v-for="tab in visibleTabs"
:key="tab.key"
class="mx-tab"
:class="{ active: activeTab === tab.key }"
@@ -48,7 +58,7 @@ const isAdmin = computed(() => auth.user?.role === 'admin')
</button>
</div>
<span class="mx-badge" :class="isAdmin ? 'mx-badge-success' : 'mx-badge-neutral'">
{{ isAdmin ? `当前身份:${auth.displayName}` : `只读访客 · ${auth.displayName}` }}
{{ isAdmin ? `当前身份:${auth.displayName}` : `${auth.roleLabel} · ${auth.displayName}` }}
</span>
</div>
@@ -59,8 +69,8 @@ const isAdmin = computed(() => auth.user?.role === 'admin')
<p v-if="data.error !== null" class="role-note error">数据加载失败:{{ data.error }}</p>
<UsersPanel v-if="activeTab === 'users'" />
<BackupPanel v-else-if="activeTab === 'backup'" />
<UsersPanel v-if="isAdmin && activeTab === 'users'" />
<BackupPanel v-else-if="isAdmin && activeTab === 'backup'" />
<EventInfoPanel v-else />
</div>
</template>
+16 -3
View File
@@ -1,8 +1,12 @@
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
import AdminLayout from './layouts/AdminLayout.vue'
import { useAuthStore } from './stores/auth'
/**
* 路由表。页面已全部落地,不再使用 PlaceholderPage。
* 路由表。
*
* 系统设置与日志的接口是 admin-only,这里用 meta.requiresAdmin 兜底:
* 直接改 hash 深链也进不去,避免 recorder/guest 触发一串 403 请求。
*/
const routes: RouteRecordRaw[] = [
{
@@ -80,13 +84,13 @@ const routes: RouteRecordRaw[] = [
path: 'logs',
name: 'logs',
component: () => import('./pages/LogsPage.vue'),
meta: { title: '日志' },
meta: { title: '日志', requiresAdmin: true },
},
{
path: 'system',
name: 'system',
component: () => import('./pages/SystemPage.vue'),
meta: { title: '系统设置' },
meta: { title: '系统设置', requiresAdmin: true },
},
{
path: 'password',
@@ -112,6 +116,15 @@ export const router = createRouter({
routes,
})
router.beforeEach(async (to) => {
if (to.meta.requiresAdmin !== true) return true
const auth = useAuthStore()
// 刷新页面时深链先于布局层挂载,这里补一次会话探测,避免把管理员误判成访客。
if (!auth.initialized) await auth.load()
if (auth.user?.role === 'admin') return true
return { name: 'dashboard' }
})
router.afterEach((to) => {
const title = typeof to.meta.title === 'string' ? to.meta.title : ''
document.title = title === '' ? '管理面板' : `${title} · 管理面板`
+1
View File
@@ -73,6 +73,7 @@ export const useAuthStore = defineStore('admin-auth', () => {
user,
loading,
error,
initialized,
isGuest,
readOnly,
displayName,
-9
View File
@@ -34,7 +34,6 @@ export const useEventStore = defineStore('admin-event', () => {
const realtimeStatus = ref<RealtimeStatus>('idle')
const serverVersion = ref<number | null>(null)
const serverTime = ref<string | null>(null)
const serverHealth = ref<string | null>(null)
let realtime: RealtimeClient | null = null
@@ -111,12 +110,6 @@ export const useEventStore = defineStore('admin-event', () => {
realtime.connect()
}
function stopRealtime(): void {
realtime?.close()
realtime = null
realtimeStatus.value = 'idle'
}
async function refreshStandings(): Promise<void> {
try {
const [next, athletes] = await Promise.all([
@@ -161,7 +154,6 @@ export const useEventStore = defineStore('admin-event', () => {
lastRefreshAt,
realtimeStatus,
serverVersion,
serverTime,
serverHealth,
isMock,
mockLabel,
@@ -173,6 +165,5 @@ export const useEventStore = defineStore('admin-event', () => {
refreshEvents,
eventById,
teamById,
stopRealtime,
}
})
-7
View File
@@ -96,10 +96,3 @@ body {
.mx-table-entry tbody tr.is-focus {
background: var(--mx-primary-glow);
}
/* 只读访客态:禁用写操作控件。 */
.is-readonly .mx-btn-primary,
.is-readonly .mx-btn-danger {
opacity: 0.45;
pointer-events: none;
}
+230
View File
@@ -0,0 +1,230 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import type { Event, EventCategory, ScoreChannel, ScoringProfile } from '@/shared'
import { computeEventScore, type ScorableRow, type ScoreContext } from '../api/scoring'
// 逐条对齐服务端 internal/domain/scoring.go 的 ScoreEvent 口径。
// 运行:node --test --import ./src/shared/tests/register.mjs src/admin/tests/
function makeEvent(overrides: Partial<Event> = {}): Event {
return {
id: 1,
sportId: 1,
code: 'M100',
name: '100 米',
eventType: 'individual',
resultMode: 'auto',
resultType: 'time',
compare: 'asc',
recordEligible: false,
scored: true,
multiplier: 1,
status: 'pending',
scheduledAt: null,
venue: null,
sortOrder: 1,
remark: null,
...overrides,
}
}
function makeProfile(overrides: Partial<ScoringProfile> = {}): ScoringProfile {
return { id: 1, code: 'p', name: 'p', tieMode: 'skip', recordBonusMode: 'max', rules: [], ...overrides }
}
function makeChannel(overrides: Partial<ScoreChannel> = {}): ScoreChannel {
return { id: 1, eventId: 1, scope: 'athlete', basis: 'result', profileId: 1, sortOrder: 1, ...overrides }
}
function makeRow(entryId: number, resultValue: number | null, teamId: number, rank: number | null = null): ScorableRow {
return { entryId, teamId, athleteId: entryId, resultValue, rank, status: 'ok', isTie: false }
}
function makeContext(overrides: Partial<ScoreContext> = {}): ScoreContext {
return { event: makeEvent(), category: null, channels: [], profiles: [], weight: 1, ...overrides }
}
function close(actual: number, expected: number): void {
assert.ok(Math.abs(actual - expected) < 1e-9, `${actual} != ${expected}`)
}
test('awardRanks 之外的名次一律 0 分', () => {
const profile = makeProfile({
awardRanks: 2,
rules: [
{ rank: 1, points: 9 },
{ rank: 2, points: 6 },
{ rank: 3, points: 3 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 11, 101), makeRow(3, 12, 102)],
makeContext({ channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, 9)
close(result.rowPoints.get(2) ?? 0, 6)
close(result.rowPoints.get(3) ?? 0, 0)
close(result.teamPoints.get(102) ?? 0, 0)
})
test('lastPlaceZero 让末位整组 0 分', () => {
const profile = makeProfile({
lastPlaceZero: true,
rules: [
{ rank: 1, points: 9 },
{ rank: 2, points: 6 },
{ rank: 3, points: 3 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 11, 101), makeRow(3, 12, 102)],
makeContext({ channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, 9)
close(result.rowPoints.get(2) ?? 0, 6)
close(result.rowPoints.get(3) ?? 0, 0)
})
test('末位并列整组都按最后一名处理', () => {
const profile = makeProfile({
lastPlaceZero: true,
rules: [
{ rank: 1, points: 9 },
{ rank: 2, points: 6 },
{ rank: 3, points: 3 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 11, 101), makeRow(3, 11, 102)],
makeContext({ channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, 9)
close(result.rowPoints.get(2) ?? 0, 0)
close(result.rowPoints.get(3) ?? 0, 0)
})
test('scored=false 只排名不计分', () => {
const profile = makeProfile({
rules: [
{ rank: 1, points: 9 },
{ rank: 2, points: 6 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 11, 101)],
makeContext({ event: makeEvent({ scored: false }), channels: [makeChannel()], profiles: [profile] }),
)
assert.equal(result.ranks.get(1), 1)
assert.equal(result.ranks.get(2), 2)
close(result.rowPoints.get(1) ?? 0, 0)
close(result.teamPoints.get(100) ?? 0, 0)
})
test('多通道叠加,个人通道分按权重折算进单位总分', () => {
const athleteProfile = makeProfile({ id: 1, rules: [{ rank: 1, points: 10 }] })
const teamProfile = makeProfile({ id: 2, rules: [{ rank: 1, points: 4 }] })
const result = computeEventScore(
[makeRow(1, 10, 100)],
makeContext({
channels: [
makeChannel({ id: 1, scope: 'athlete', profileId: 1 }),
makeChannel({ id: 2, scope: 'team', profileId: 2 }),
],
profiles: [athleteProfile, teamProfile],
weight: 2,
}),
)
// 行分是两条通道的原始分之和;折算到单位时只有个人通道乘系数。
close(result.rowPoints.get(1) ?? 0, 14)
close(result.rowTeamPoints.get(1) ?? 0, 24)
close(result.teamPoints.get(100) ?? 0, 24)
})
test('并列 average 取占用名次区间的均值', () => {
const profile = makeProfile({
tieMode: 'average',
rules: [
{ rank: 1, points: 10 },
{ rank: 2, points: 6 },
{ rank: 3, points: 3 },
{ rank: 4, points: 1 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 10, 101), makeRow(3, 10, 102)],
makeContext({ channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, (10 + 6 + 3) / 3)
close(result.rowPoints.get(2) ?? 0, (10 + 6 + 3) / 3)
close(result.rowPoints.get(3) ?? 0, (10 + 6 + 3) / 3)
assert.equal(result.ranks.get(1), 1)
})
test('并列 higher 取区间最高档', () => {
const profile = makeProfile({
tieMode: 'higher',
rules: [
{ rank: 1, points: 10 },
{ rank: 2, points: 6 },
{ rank: 3, points: 3 },
],
})
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 10, 101), makeRow(3, 10, 102)],
makeContext({ channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, 10)
close(result.rowPoints.get(2) ?? 0, 10)
close(result.rowPoints.get(3) ?? 0, 10)
})
test('没有计分通道时算出名次但一律 0 分', () => {
const result = computeEventScore(
[makeRow(1, 10, 100), makeRow(2, 11, 101)],
makeContext({ channels: [], profiles: [] }),
)
assert.equal(result.ranks.get(1), 1)
assert.equal(result.ranks.get(2), 2)
close(result.rowPoints.get(1) ?? 0, 0)
close(result.teamPoints.get(100) ?? 0, 0)
})
test('manual 通道使用录入名次,不做顺推改写', () => {
const profile = makeProfile({
rules: [
{ rank: 1, points: 10 },
{ rank: 2, points: 6 },
],
})
const result = computeEventScore(
[makeRow(1, null, 100, 2), makeRow(2, null, 101, 1)],
makeContext({
event: makeEvent({ resultMode: 'manual', compare: 'none' }),
channels: [makeChannel({ basis: 'manual' })],
profiles: [profile],
}),
)
close(result.rowPoints.get(1) ?? 0, 6)
close(result.rowPoints.get(2) ?? 0, 10)
assert.equal(result.ranks.get(1), 2)
assert.equal(result.ranks.get(2), 1)
})
test('项目与组别权重相乘', () => {
const profile = makeProfile({ rules: [{ rank: 1, points: 10 }] })
const category: EventCategory = {
id: 7,
eventId: 1,
name: '甲组',
multiplier: 3,
gender: null,
ageMin: null,
ageMax: null,
sortOrder: 1,
}
const result = computeEventScore(
[makeRow(1, 10, 100)],
makeContext({ event: makeEvent({ multiplier: 2 }), category, channels: [makeChannel()], profiles: [profile] }),
)
close(result.rowPoints.get(1) ?? 0, 60)
})