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

+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 }
}