fix: 审查修复波次(P0x4 + P1x30+)
- domain/rules: 计分与排名解耦、破纪录按组别、tieBreak 生效、调整分不丢、移除 aggregate 假能力 - realtime: 新建 internal/dto,快照三项契约对齐,/ws 只认会话身份 - httpapi: 流水幂等、standings 整表载荷、广播接线、强制改密、XFF 防伪造、records 写入、审计、赛事包内容、发布前备份、result.points、实例列表 - web: FormData 上传、YAML 解析、快照归一化、大屏解析层、bootstrap 降级、访客判定、主题切换 - console: 优雅关闭握手、中文化、免验证改管理员账号、选屏与日志轮转修复 - docs: 用户文档三份 + README - 主代理: 破纪录加分接线(levels 未加载导致恒 0)
This commit is contained in:
1 parent
8dae63ee70
commit
7f9701c465
61 files changed
+3844
-333
No files matched your search
@@ -97,7 +97,7 @@ async function bootstrap(): Promise<Bootstrap> {
|
||||
client.scoringProfiles.list(),
|
||||
client.standings.teams(),
|
||||
client.standings.athletes(),
|
||||
])
|
||||
] as const)
|
||||
// GET /api/settings 是 admin-only,guest/recorder 必然 403。
|
||||
// 这是权限边界而非服务不可用,不能让整页数据跟着失败,所以 settings 单独降级为 null。
|
||||
return {
|
||||
|
||||
@@ -90,11 +90,10 @@ function handleDoubleClick(event: MouseEvent): void {
|
||||
min-width: 0;
|
||||
}
|
||||
.desktop-titlebar-mark {
|
||||
width: 8px;
|
||||
height: 22px;
|
||||
flex: 0 0 auto;
|
||||
border-radius: 4px;
|
||||
background: linear-gradient(180deg, var(--mx-primary), var(--mx-primary-active));
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
flex: none;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.desktop-titlebar-title {
|
||||
font-size: 14px;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
|
||||
import MxIcon from '../components/MxIcon.vue'
|
||||
import ToastHost from '../components/ToastHost.vue'
|
||||
import type { IconName } from '../components/icons'
|
||||
import { theme, toggleTheme } from '../theme'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { useEventStore } from '../stores/event'
|
||||
import { useToastStore } from '../stores/toast'
|
||||
@@ -65,6 +66,7 @@ const refreshing = ref(false)
|
||||
|
||||
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' ? '切换到浅色模式' : '切换到深色模式'))
|
||||
|
||||
const connection = computed(() => {
|
||||
if (data.isMock) return { tone: 'warning', text: '示例数据', hint: data.mockLabel ?? '' }
|
||||
@@ -153,6 +155,16 @@ onMounted(async () => {
|
||||
{{ connection.text }}
|
||||
</span>
|
||||
<span v-if="data.serverHealth" class="version mono">v{{ data.serverHealth }}</span>
|
||||
<button
|
||||
class="mx-btn mx-btn-ghost mx-btn-icon"
|
||||
type="button"
|
||||
:title="themeToggleLabel"
|
||||
:aria-label="themeToggleLabel"
|
||||
:aria-pressed="theme === 'light'"
|
||||
@click="toggleTheme()"
|
||||
>
|
||||
<MxIcon name="display" :size="17" />
|
||||
</button>
|
||||
<button
|
||||
class="mx-btn mx-btn-ghost mx-btn-icon"
|
||||
type="button"
|
||||
|
||||
@@ -2,7 +2,10 @@ import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import { router } from './router'
|
||||
import { initTheme } from './theme'
|
||||
import '@/shared/styles/base.css'
|
||||
import './styles/miuix.css'
|
||||
|
||||
initTheme()
|
||||
|
||||
createApp(App).use(createPinia()).use(router).mount('#app')
|
||||
@@ -108,14 +108,7 @@ onMounted(async () => {
|
||||
<img class="app-icon" src="/scoreboard.png" alt="" width="56" height="56" />
|
||||
<div style="display: flex; flex-direction: column; gap: 2px">
|
||||
<strong style="font-size: 18px">{{ SYSTEM_NAME }}</strong>
|
||||
<span style="font-size: 12px; color: var(--mx-t3)">{{ SYSTEM_EN }} · v{{ versionText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="internalSignature" class="mx-card" style="margin-bottom: 16px">
|
||||
<div class="mx-card-body" style="display: flex; flex-direction: column; gap: 4px">
|
||||
<span style="font-size: 12px; color: var(--mx-t3)">内部署名</span>
|
||||
<strong style="font-size: 15px">{{ internalSignature }}</strong>
|
||||
<span style="font-size: 12px; color: var(--mx-t3)">{{ SYSTEM_EN }} · {{ versionText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -272,6 +265,17 @@ onMounted(async () => {
|
||||
<p class="foot-hint">
|
||||
本系统为内部赛事使用;MiSans 字体授权仅限内部赛事,对外分发前请替换为 OFL-1.1 字体。
|
||||
</p>
|
||||
|
||||
<!-- 值来自构建期注入的内部配置(GET /api/system/about 的 internalSignature),不是用户输入,
|
||||
因此允许用 v-html 渲染其中的标签;为空时整张卡片不渲染。 -->
|
||||
<section v-if="internalSignature" class="mx-card">
|
||||
<div class="mx-card-head">
|
||||
<span class="mx-card-title">开发者</span>
|
||||
</div>
|
||||
<div class="mx-card-body">
|
||||
<div class="signature" v-html="internalSignature"></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -340,4 +344,9 @@ kbd {
|
||||
font-size: 12px;
|
||||
color: var(--mx-t3);
|
||||
}
|
||||
.signature {
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
color: var(--mx-text);
|
||||
}
|
||||
</style>
|
||||
@@ -54,7 +54,15 @@ const localItems = ref<PointAdjustment[]>([])
|
||||
let nextLocalId = -1
|
||||
|
||||
const canWrite = computed(() => !auth.readOnly && data.canWrite)
|
||||
const adjustmentEnabled = computed(() => rulePack.value?.manualAdjustment.enabled ?? false)
|
||||
/**
|
||||
* 人工调整开关:true / false / null(未知)。
|
||||
*
|
||||
* 规则包只有 admin 能读(GET /api/rules/export 是 admin-only),录入员必然 403——
|
||||
* 不能据此断言「已关闭」,那会把已启用的功能谎报成关闭。读不到时为 null,
|
||||
* 界面如实显示「未知」,最终由服务端校验决定是否受理。
|
||||
* 后端补一个 recorder 可读的只读开关端点后,把 loadRules 换成读该端点即可。
|
||||
*/
|
||||
const adjustmentEnabled = computed<boolean | null>(() => rulePack.value?.manualAdjustment.enabled ?? null)
|
||||
|
||||
const items = computed(() => [...localItems.value, ...serverItems.value])
|
||||
|
||||
@@ -132,7 +140,7 @@ async function load(pageNumber = page.value): Promise<void> {
|
||||
}
|
||||
|
||||
function openCreate(): void {
|
||||
if (!adjustmentEnabled.value) {
|
||||
if (adjustmentEnabled.value === false) {
|
||||
toast.error('本期人工调整已关闭', '规则包 manualAdjustment.enabled = false')
|
||||
return
|
||||
}
|
||||
@@ -254,7 +262,12 @@ onMounted(() => {
|
||||
<button class="mx-btn mx-btn-secondary" type="button" :disabled="loading" @click="load()">
|
||||
<MxIcon name="refresh" :size="15" /> 刷新
|
||||
</button>
|
||||
<button class="mx-btn mx-btn-primary" type="button" :disabled="!adjustmentEnabled || !canWrite" @click="openCreate">
|
||||
<button
|
||||
class="mx-btn mx-btn-primary"
|
||||
type="button"
|
||||
:disabled="adjustmentEnabled === false || !canWrite"
|
||||
@click="openCreate"
|
||||
>
|
||||
<MxIcon name="adjust" :size="15" /> 新增调整
|
||||
</button>
|
||||
</template>
|
||||
@@ -265,22 +278,41 @@ onMounted(() => {
|
||||
<span class="notice-icon"><MxIcon name="warning" :size="18" /></span>
|
||||
<div>
|
||||
<div class="notice-title">
|
||||
{{ adjustmentEnabled ? '人工调整已启用' : '本期人工调整已关闭' }}
|
||||
<span class="mx-badge" :class="adjustmentEnabled ? 'mx-badge-success' : 'mx-badge-warning'">
|
||||
manualAdjustment.enabled = {{ adjustmentEnabled ? 'true' : 'false' }}
|
||||
{{
|
||||
adjustmentEnabled === null
|
||||
? '人工调整开关未知'
|
||||
: adjustmentEnabled
|
||||
? '人工调整已启用'
|
||||
: '本期人工调整已关闭'
|
||||
}}
|
||||
<span
|
||||
class="mx-badge"
|
||||
:class="
|
||||
adjustmentEnabled === true
|
||||
? 'mx-badge-success'
|
||||
: adjustmentEnabled === false
|
||||
? 'mx-badge-warning'
|
||||
: 'mx-badge-neutral'
|
||||
"
|
||||
>
|
||||
manualAdjustment.enabled = {{ adjustmentEnabled === null ? '未知' : adjustmentEnabled ? 'true' : 'false' }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="notice-desc">
|
||||
<template v-if="adjustmentEnabled">
|
||||
<template v-if="adjustmentEnabled === true">
|
||||
分值可正可负,类别为处罚 / 补分 / 更正,理由必填;作废会同时作废对应积分流水。
|
||||
</template>
|
||||
<template v-else>
|
||||
<template v-else-if="adjustmentEnabled === false">
|
||||
本次运动会扣分 / 处罚完全在系统外处理,系统只负责成绩分(02 第 4 节)。
|
||||
功能与数据表已保留,以后赛事开一个开关即可启用。
|
||||
</template>
|
||||
<template v-else>
|
||||
当前角色读不到规则包(/api/rules/export 仅管理员可读),无法判断开关状态,不再按「关闭」显示;
|
||||
「新增调整」提交后由服务端校验决定是否受理。
|
||||
</template>
|
||||
</p>
|
||||
<p v-if="ruleError !== null" class="notice-error">
|
||||
读取规则包失败:{{ ruleError }},当前按「关闭」处理。
|
||||
读取规则包失败:{{ ruleError }};开关状态未知,不再按「关闭」处理。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -323,7 +355,11 @@ onMounted(() => {
|
||||
<div class="mx-empty-icon"><MxIcon name="adjust" :size="26" /></div>
|
||||
<div class="mx-empty-title">没有调整记录</div>
|
||||
<div class="mx-empty-desc">
|
||||
{{ adjustmentEnabled ? '点击「新增调整」录入第一条' : '本期人工调整关闭,故为空' }}
|
||||
{{
|
||||
adjustmentEnabled === false
|
||||
? '本期人工调整关闭,故为空'
|
||||
: '点击「新增调整」录入第一条'
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
<template v-else>
|
||||
|
||||
@@ -254,13 +254,14 @@ async function loadSuspected(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function bonusFor(level: RecordLevel): number {
|
||||
const definition = rulePack.value?.recordBonus.levels.find((item) => item.code === level)
|
||||
return definition?.points ?? 0
|
||||
function bonusFor(level: RecordLevel): number | null {
|
||||
if (rulePack.value === null) return null
|
||||
const definition = rulePack.value.recordBonus.levels.find((item) => item.code === level)
|
||||
return definition?.points ?? null
|
||||
}
|
||||
|
||||
function requestApprove(item: SuspectedBreak): void {
|
||||
if (!recordBonusEnabled.value) {
|
||||
if (recordBonusEnabled.value === false) {
|
||||
toast.error('本期破纪录加分已关闭', '规则包 recordBonus.enabled = false,确认后不会生成加分流水')
|
||||
return
|
||||
}
|
||||
@@ -268,6 +269,9 @@ function requestApprove(item: SuspectedBreak): void {
|
||||
toast.error('当前不可写入', auth.readOnly ? '请先登录' : '服务端未连接')
|
||||
return
|
||||
}
|
||||
if (recordBonusEnabled.value === null) {
|
||||
toast.info('加分开关状态未知', '当前角色读不到规则包,将由服务端校验后决定是否加分')
|
||||
}
|
||||
approveTarget.value = item
|
||||
}
|
||||
|
||||
@@ -286,7 +290,12 @@ async function confirmApprove(): Promise<void> {
|
||||
await adminApi.client.records.approveBreak(created.id)
|
||||
approvedKeys.value = [...approvedKeys.value, item.key]
|
||||
approveTarget.value = null
|
||||
toast.success('已确认破纪录', `+${formatPoints(item.bonusPoints)} 分(${LEVEL_LABELS[item.level]})`)
|
||||
toast.success(
|
||||
'已确认破纪录',
|
||||
item.bonusPoints === null
|
||||
? `${LEVEL_LABELS[item.level]}纪录,加分分值以服务端结果为准`
|
||||
: `+${formatPoints(item.bonusPoints)} 分(${LEVEL_LABELS[item.level]})`,
|
||||
)
|
||||
await Promise.all([loadRecords(), data.refreshStandings()])
|
||||
} catch (caught) {
|
||||
if (isFallback(caught)) {
|
||||
@@ -343,22 +352,41 @@ watch(
|
||||
<span class="notice-icon"><MxIcon name="warning" :size="18" /></span>
|
||||
<div>
|
||||
<div class="notice-title">
|
||||
{{ recordBonusEnabled ? '破纪录加分已启用' : '本期破纪录加分已关闭' }}
|
||||
<span class="mx-badge" :class="recordBonusEnabled ? 'mx-badge-success' : 'mx-badge-warning'">
|
||||
recordBonus.enabled = {{ recordBonusEnabled ? 'true' : 'false' }}
|
||||
{{
|
||||
recordBonusEnabled === null
|
||||
? '破纪录加分开关未知'
|
||||
: recordBonusEnabled
|
||||
? '破纪录加分已启用'
|
||||
: '本期破纪录加分已关闭'
|
||||
}}
|
||||
<span
|
||||
class="mx-badge"
|
||||
:class="
|
||||
recordBonusEnabled === true
|
||||
? 'mx-badge-success'
|
||||
: recordBonusEnabled === false
|
||||
? 'mx-badge-warning'
|
||||
: 'mx-badge-neutral'
|
||||
"
|
||||
>
|
||||
recordBonus.enabled = {{ recordBonusEnabled === null ? '未知' : recordBonusEnabled ? 'true' : 'false' }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="notice-desc">
|
||||
<template v-if="recordBonusEnabled">
|
||||
<template v-if="recordBonusEnabled === true">
|
||||
确认破纪录会生成加分流水并更新纪录库;加分档位 {{ bonusMode }},与成绩积分相互独立(不随权重翻倍)。
|
||||
</template>
|
||||
<template v-else>
|
||||
<template v-else-if="recordBonusEnabled === false">
|
||||
规则包 `recordBonus.enabled = false`(02 第 3 节)。疑似破纪录仍会列出,但「确认加分」不会生成加分流水;
|
||||
以后开一个开关即可启用,档位与分值已预置。
|
||||
</template>
|
||||
<template v-else>
|
||||
当前角色读不到规则包(/api/rules/export 仅管理员可读),无法判断开关状态,不再按「关闭」显示;
|
||||
疑似破纪录仍会列出,「确认加分」提交后由服务端校验决定是否生成加分流水。
|
||||
</template>
|
||||
</p>
|
||||
<p v-if="ruleError !== null" class="notice-error">
|
||||
读取规则包失败:{{ ruleError }},当前按「关闭」处理。
|
||||
读取规则包失败:{{ ruleError }};开关状态未知,不再按「关闭」处理。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -411,12 +439,14 @@ watch(
|
||||
<td class="mono highlight">{{ item.resultText }}</td>
|
||||
<td class="mono">{{ item.recordText }}</td>
|
||||
<td><span class="mx-tag mx-tag-primary">{{ LEVEL_LABELS[item.level] }}</span></td>
|
||||
<td class="right mono points">+{{ formatPoints(item.bonusPoints) }}</td>
|
||||
<td class="right mono points">
|
||||
{{ item.bonusPoints === null ? '—' : `+${formatPoints(item.bonusPoints)}` }}
|
||||
</td>
|
||||
<td class="right actions">
|
||||
<button
|
||||
class="mx-btn mx-btn-primary mx-btn-sm"
|
||||
type="button"
|
||||
:disabled="!recordBonusEnabled || !canWrite || approving"
|
||||
:disabled="recordBonusEnabled === false || !canWrite || approving"
|
||||
@click="requestApprove(item)"
|
||||
>
|
||||
确认加分
|
||||
@@ -427,9 +457,12 @@ watch(
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-if="!recordBonusEnabled && pendingBreaks.length > 0" class="hint">
|
||||
<p v-if="recordBonusEnabled === false && pendingBreaks.length > 0" class="hint">
|
||||
「确认加分」在 recordBonus 关闭时不可用,避免生成无规则的积分流水。
|
||||
</p>
|
||||
<p v-else-if="recordBonusEnabled === null && pendingBreaks.length > 0" class="hint">
|
||||
当前角色读不到规则包,加分开关状态未知;「确认加分」可提交,由服务端校验决定。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -519,7 +552,9 @@ watch(
|
||||
:message="
|
||||
approveTarget === null
|
||||
? ''
|
||||
: `将登记「${approveTarget.eventName} · ${approveTarget.athleteName}」的 ${LEVEL_LABELS[approveTarget.level]}纪录,并生成 +${formatPoints(approveTarget.bonusPoints)} 分加分流水。`
|
||||
: approveTarget.bonusPoints === null
|
||||
? `将登记「${approveTarget.eventName} · ${approveTarget.athleteName}」的 ${LEVEL_LABELS[approveTarget.level]}纪录;加分分值未知,以服务端结果为准。`
|
||||
: `将登记「${approveTarget.eventName} · ${approveTarget.athleteName}」的 ${LEVEL_LABELS[approveTarget.level]}纪录,并生成 +${formatPoints(approveTarget.bonusPoints)} 分加分流水。`
|
||||
"
|
||||
:details="[
|
||||
`成绩:${approveTarget?.resultText ?? ''}(原纪录 ${approveTarget?.recordText ?? ''})`,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
export type Theme = 'light' | 'dark'
|
||||
|
||||
const STORAGE_KEY = 'scoreboard.admin.theme'
|
||||
|
||||
function readStored(): Theme {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (raw === 'light' || raw === 'dark') return raw
|
||||
} catch {
|
||||
// 隐私模式等场景 localStorage 会抛错,退回 admin.html 里的静态默认值
|
||||
}
|
||||
return document.documentElement.dataset.theme === 'light' ? 'light' : 'dark'
|
||||
}
|
||||
|
||||
/** 当前主题;MIUIx 的浅色令牌挂在 :root,深色令牌挂在 [data-theme="dark"]。 */
|
||||
export const theme = ref<Theme>(readStored())
|
||||
|
||||
export function applyTheme(next: Theme): void {
|
||||
theme.value = next
|
||||
document.documentElement.dataset.theme = next
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, next)
|
||||
} catch {
|
||||
// 持久化失败不影响本次会话内的切换
|
||||
}
|
||||
}
|
||||
|
||||
export function toggleTheme(): void {
|
||||
applyTheme(theme.value === 'dark' ? 'light' : 'dark')
|
||||
}
|
||||
|
||||
/** 在应用挂载前调用,避免首屏先渲染静态默认值再跳变。 */
|
||||
export function initTheme(): void {
|
||||
document.documentElement.dataset.theme = theme.value
|
||||
}
|
||||
+62
-6
@@ -1,4 +1,7 @@
|
||||
import { isRecord, readString } from './internal'
|
||||
import { isRawBody, isRecord, readString } from './internal'
|
||||
import { normalizeRulePack } from './rules'
|
||||
import { isGuestRole } from './session'
|
||||
import { parseYaml } from './yaml'
|
||||
import type {
|
||||
AdjustmentInput,
|
||||
ApiErrorCode,
|
||||
@@ -204,6 +207,7 @@ interface Http {
|
||||
request<T>(path: string, options?: RequestOptions): Promise<T>
|
||||
requestVoid(path: string, options?: RequestOptions): Promise<void>
|
||||
requestJson(path: string, options?: RequestOptions): Promise<unknown>
|
||||
requestText(path: string, options?: RequestOptions): Promise<string>
|
||||
url(path: string, query?: object): string
|
||||
blob(path: string, options?: RequestOptions): Promise<Blob>
|
||||
}
|
||||
@@ -276,7 +280,21 @@ function createExportApi(http: Http): ExportApi {
|
||||
|
||||
function createRulesApi(http: Http): RulesApi {
|
||||
return {
|
||||
get: () => http.request<RulePack>('/rules/export'),
|
||||
// 导出接口返回的是裸 YAML 文本(不是 {ok,data}),必须按文本取回再解析。
|
||||
get: async () => {
|
||||
const text = await http.requestText('/rules/export')
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = parseYaml(text)
|
||||
} catch (error) {
|
||||
throw new ApiError('PARSE_FAILED', '规则包 YAML 解析失败', 0, error)
|
||||
}
|
||||
const pack = normalizeRulePack(parsed)
|
||||
if (pack === null) {
|
||||
throw new ApiError('PARSE_FAILED', '规则包格式不符(需要 scoreboard-rules v1)', 0, parsed)
|
||||
}
|
||||
return pack
|
||||
},
|
||||
preview: (pack) =>
|
||||
http.request<RulePackImportPreview>('/rules/import', {
|
||||
method: 'POST',
|
||||
@@ -343,20 +361,27 @@ export class ApiClient {
|
||||
request: (path, requestOptions) => this.request(path, requestOptions),
|
||||
requestVoid: (path, requestOptions) => this.requestVoid(path, requestOptions),
|
||||
requestJson: (path, requestOptions) => this.requestJson(path, requestOptions),
|
||||
requestText: (path, requestOptions) => this.requestText(path, requestOptions),
|
||||
url: (path, query) => this.buildUrl(path, query),
|
||||
blob: (path, requestOptions) => this.fetchBlob(path, requestOptions),
|
||||
}
|
||||
|
||||
this.auth = {
|
||||
login: (username, password) =>
|
||||
http.request<CurrentUser>('/auth/login', { method: 'POST', body: { username, password } }),
|
||||
login: async (username, password) =>
|
||||
markGuest(
|
||||
await http.request<CurrentUser>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username, password },
|
||||
}),
|
||||
),
|
||||
changePassword: (currentPassword, newPassword) =>
|
||||
http.request<{ relogin: boolean }>('/auth/password', {
|
||||
method: 'POST',
|
||||
body: { currentPassword, newPassword },
|
||||
}),
|
||||
logout: () => http.requestVoid('/auth/logout', { method: 'POST' }),
|
||||
me: () => http.request<CurrentUser>('/auth/me'),
|
||||
// 未登录时服务端回 200 + guest DTO,这里补出 guest 标记供 isGuestUser 判定。
|
||||
me: async () => markGuest(await http.request<CurrentUser>('/auth/me')),
|
||||
}
|
||||
|
||||
this.settings = {
|
||||
@@ -452,6 +477,21 @@ export class ApiClient {
|
||||
return body
|
||||
}
|
||||
|
||||
/** 规则包导出等接口返回裸文本(非 JSON),错误体仍按 {ok,error} 解析。 */
|
||||
private async requestText(path: string, options: RequestOptions = {}): Promise<string> {
|
||||
const response = await this.send(path, options)
|
||||
if (!response.ok) {
|
||||
const body = await readBody(response)
|
||||
if (response.status === 401) {
|
||||
const error = this.toApiError(body, response.status)
|
||||
this.onUnauthorized?.(error)
|
||||
throw error
|
||||
}
|
||||
throw this.toApiError(body, response.status)
|
||||
}
|
||||
return response.text()
|
||||
}
|
||||
|
||||
private async fetchBlob(path: string, options: RequestOptions = {}): Promise<Blob> {
|
||||
const response = await this.send(path, options)
|
||||
if (!response.ok) {
|
||||
@@ -469,10 +509,16 @@ export class ApiClient {
|
||||
private async send(path: string, options: RequestOptions): Promise<Response> {
|
||||
const method: HttpMethod = options.method ?? 'GET'
|
||||
const payload = this.prepareBody(method, options.body)
|
||||
// 断言:二进制 / 表单载荷只能原样透传,一旦被归一化展开就会静默丢内容(报名表导入踩过)。
|
||||
if (isRawBody(options.body) && payload !== options.body) {
|
||||
throw new ApiError('INTERNAL', '请求体归一化破坏了 FormData/Blob 载荷', 0, options.body)
|
||||
}
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
|
||||
if (payload instanceof FormData) {
|
||||
// 交给浏览器带 multipart boundary,手动设置 Content-Type 会丢 boundary。
|
||||
} else if (isRawBody(payload)) {
|
||||
// Blob / URLSearchParams 自带类型语义,Content-Type 交给 fetch 决定。
|
||||
} else if (payload !== undefined) {
|
||||
headers['Content-Type'] = 'application/json; charset=utf-8'
|
||||
}
|
||||
@@ -499,7 +545,7 @@ export class ApiClient {
|
||||
body:
|
||||
payload === undefined
|
||||
? undefined
|
||||
: payload instanceof FormData
|
||||
: isRawBody(payload)
|
||||
? payload
|
||||
: JSON.stringify(payload),
|
||||
signal: controller.signal,
|
||||
@@ -517,6 +563,8 @@ export class ApiClient {
|
||||
/** 写操作注入 requestId:网络抖动重发时服务端能返回首次结果而不是重复执行。 */
|
||||
private prepareBody(method: HttpMethod, body: unknown): unknown {
|
||||
if (method === 'GET' || body === undefined) return undefined
|
||||
// FormData/Blob/URLSearchParams 不能展开,否则文件/二进制内容会被丢掉。
|
||||
if (isRawBody(body)) return body
|
||||
if (isRecord(body) && !('requestId' in body)) {
|
||||
return { ...body, requestId: this.newRequestId() }
|
||||
}
|
||||
@@ -568,6 +616,14 @@ function isScalar(value: unknown): value is string | number | boolean {
|
||||
return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务端未登录时 /auth/me 也回 200 + guest DTO,
|
||||
* 这里把 role 结论固化成 guest 字段,调用方用 isGuestUser(user) 判定即可。
|
||||
*/
|
||||
function markGuest(user: CurrentUser): CurrentUser {
|
||||
return { ...user, guest: isGuestRole(user.role) }
|
||||
}
|
||||
|
||||
async function readBody(response: Response): Promise<unknown> {
|
||||
if (response.status === 204) return null
|
||||
const text = await response.text()
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
export * from './types'
|
||||
export { ApiClient, ApiError, createApiClient } from './api'
|
||||
export type { ApiClientOptions, QueryParams, QueryValue } from './api'
|
||||
export { normalizeSettings, normalizeStandingRows } from './normalize'
|
||||
export { GUEST_ROLE, isGuestRole, isGuestUser } from './session'
|
||||
export { RealtimeClient } from './realtime'
|
||||
export type {
|
||||
RealtimeInfo,
|
||||
|
||||
@@ -30,7 +30,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
const nestedStandings = isRecord(source.standings) ? source.standings : null
|
||||
const isFlat = nestedEvent === null && nestedDisplay === null && nestedStandings === null
|
||||
|
||||
const name = firstString(isFlat ? source['event.name'] : undefined, nestedEvent?.name) ?? '未命名赛事'
|
||||
const name =
|
||||
emptyToNull(firstString(isFlat ? source['event.name'] : undefined, nestedEvent?.name)) ??
|
||||
'未命名赛事'
|
||||
const subtitle = emptyToNull(
|
||||
firstString(isFlat ? source['event.subtitle'] : undefined, nestedEvent?.subtitle),
|
||||
)
|
||||
@@ -52,7 +54,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
firstString(isFlat ? source['display.background'] : undefined, nestedDisplay?.background),
|
||||
),
|
||||
logo: displayLogo ?? logoPath,
|
||||
title: firstString(isFlat ? source['display.title'] : undefined, nestedDisplay?.title) ?? name,
|
||||
title:
|
||||
emptyToNull(firstString(isFlat ? source['display.title'] : undefined, nestedDisplay?.title)) ??
|
||||
name,
|
||||
subtitle:
|
||||
emptyToNull(
|
||||
firstString(isFlat ? source['display.subtitle'] : undefined, nestedDisplay?.subtitle),
|
||||
@@ -71,8 +75,9 @@ export function normalizeSettings(raw: unknown): EventSettings {
|
||||
nestedStandings?.individualToTeamWeight,
|
||||
),
|
||||
rankingMode:
|
||||
firstString(isFlat ? source['standings.mode'] : undefined, nestedStandings?.rankingMode) ??
|
||||
'points',
|
||||
emptyToNull(
|
||||
firstString(isFlat ? source['standings.mode'] : undefined, nestedStandings?.rankingMode),
|
||||
) ?? 'points',
|
||||
showIndividualBoard: firstBool(
|
||||
true,
|
||||
isFlat ? source['standings.show_individual_board'] : undefined,
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* 规则包归一化。
|
||||
*
|
||||
* `GET /api/rules/export` 返回裸 YAML(服务端 rules.Marshal),这里把解析出的
|
||||
* unknown 收敛成 shared 的 RulePack 契约:补齐缺省值、丢弃未知字段。
|
||||
* 校验口径与服务端 rules.Canonical 对齐,避免前端拿到的规则包和实际生效规则不一致。
|
||||
*/
|
||||
|
||||
import {
|
||||
asRecord,
|
||||
emptyToNull,
|
||||
firstBool,
|
||||
firstNumber,
|
||||
firstNumberOrNull,
|
||||
firstString,
|
||||
isRecord,
|
||||
} from './internal'
|
||||
import type {
|
||||
ChannelBasis,
|
||||
ChannelScope,
|
||||
ChannelTemplate,
|
||||
EventOverride,
|
||||
EventType,
|
||||
RecordBonusLevel,
|
||||
RecordBonusMode,
|
||||
ResultType,
|
||||
RuleChannel,
|
||||
RulePack,
|
||||
RulePackManualAdjustment,
|
||||
RulePackMeta,
|
||||
RulePackRecordBonus,
|
||||
RulePackStandings,
|
||||
RuleProfile,
|
||||
ScoringProfileRule,
|
||||
TieBreakKey,
|
||||
TieMode,
|
||||
} from './types'
|
||||
|
||||
const TIE_BREAK_KEYS: readonly TieBreakKey[] = [
|
||||
'points',
|
||||
'gold',
|
||||
'silver',
|
||||
'bronze',
|
||||
'teamCode',
|
||||
'name',
|
||||
]
|
||||
const DEFAULT_TIE_BREAK: TieBreakKey[] = ['points', 'gold', 'silver', 'bronze', 'teamCode']
|
||||
const TIE_MODES: readonly TieMode[] = ['skip', 'average', 'higher']
|
||||
const RECORD_BONUS_MODES: readonly RecordBonusMode[] = ['max', 'sum']
|
||||
const SCOPES: readonly ChannelScope[] = ['athlete', 'team']
|
||||
const BASES: readonly ChannelBasis[] = ['result', 'manual', 'aggregate']
|
||||
const EVENT_TYPES: readonly EventType[] = ['individual', 'team', 'match']
|
||||
const RESULT_TYPES: readonly ResultType[] = ['time', 'distance', 'count', 'score', 'none']
|
||||
|
||||
export function normalizeRulePack(raw: unknown): RulePack | null {
|
||||
if (!isRecord(raw)) return null
|
||||
if (firstString(raw.format) !== 'scoreboard-rules') return null
|
||||
if (firstNumber(0, raw.formatVersion) !== 1) return null
|
||||
return {
|
||||
format: 'scoreboard-rules',
|
||||
formatVersion: 1,
|
||||
meta: normalizeMeta(raw.meta),
|
||||
standings: normalizeStandings(raw.standings),
|
||||
profiles: normalizeProfiles(raw.profiles),
|
||||
recordBonus: normalizeRecordBonus(raw.recordBonus),
|
||||
manualAdjustment: normalizeManualAdjustment(raw.manualAdjustment),
|
||||
channelTemplates: normalizeTemplates(raw.channelTemplates),
|
||||
eventOverrides: normalizeOverrides(raw.eventOverrides),
|
||||
}
|
||||
}
|
||||
|
||||
function oneOf<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: fallback
|
||||
}
|
||||
|
||||
function optionalOneOf<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {
|
||||
return typeof value === 'string' && (allowed as readonly string[]).includes(value)
|
||||
? (value as T)
|
||||
: undefined
|
||||
}
|
||||
|
||||
function normalizeMeta(raw: unknown): RulePackMeta {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
code: firstString(rec.code) ?? '',
|
||||
name: firstString(rec.name) ?? '',
|
||||
version: firstString(rec.version) ?? '',
|
||||
updatedAt: firstString(rec.updatedAt) ?? '',
|
||||
author: emptyToNull(firstString(rec.author)),
|
||||
note: emptyToNull(firstString(rec.note)),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeStandings(raw: unknown): RulePackStandings {
|
||||
const rec = asRecord(raw)
|
||||
const tieBreakRaw = rec.tieBreak
|
||||
const tieBreak = Array.isArray(tieBreakRaw)
|
||||
? tieBreakRaw.filter(
|
||||
(item): item is TieBreakKey =>
|
||||
typeof item === 'string' && (TIE_BREAK_KEYS as readonly string[]).includes(item),
|
||||
)
|
||||
: []
|
||||
return {
|
||||
individualToTeamWeight: firstNumber(1, rec.individualToTeamWeight),
|
||||
tieBreak: tieBreak.length > 0 ? tieBreak : [...DEFAULT_TIE_BREAK],
|
||||
medalCountsTeamEvents: firstBool(true, rec.medalCountsTeamEvents),
|
||||
showIndividualBoard: firstBool(true, rec.showIndividualBoard),
|
||||
showIndividualMedals: firstBool(true, rec.showIndividualMedals),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeProfiles(raw: unknown): RuleProfile[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RuleProfile[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const code = firstString(rec.code)
|
||||
if (code === null || code === '') continue
|
||||
out.push({
|
||||
code,
|
||||
name: firstString(rec.name) ?? code,
|
||||
awardRanks: firstNumber(0, rec.awardRanks),
|
||||
lastPlaceZero: firstBool(false, rec.lastPlaceZero),
|
||||
tieMode: oneOf(rec.tieMode, TIE_MODES, 'skip'),
|
||||
recordBonusMode: optionalOneOf(rec.recordBonusMode, RECORD_BONUS_MODES),
|
||||
rules: normalizeScoringRules(rec.rules),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeScoringRules(raw: unknown): ScoringProfileRule[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: ScoringProfileRule[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const rank = firstNumberOrNull(rec.rank)
|
||||
const points = firstNumberOrNull(rec.points)
|
||||
if (rank === null || points === null) continue
|
||||
out.push({ rank, points })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeRecordBonus(raw: unknown): RulePackRecordBonus {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
enabled: firstBool(false, rec.enabled),
|
||||
mode: oneOf(rec.mode, RECORD_BONUS_MODES, 'max'),
|
||||
levels: normalizeLevels(rec.levels),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLevels(raw: unknown): RecordBonusLevel[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RecordBonusLevel[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const code = firstString(rec.code)
|
||||
if (code === null || code === '') continue
|
||||
out.push({ code, name: firstString(rec.name) ?? code, points: firstNumber(0, rec.points) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeManualAdjustment(raw: unknown): RulePackManualAdjustment {
|
||||
const rec = asRecord(raw)
|
||||
return {
|
||||
enabled: firstBool(false, rec.enabled),
|
||||
reasonRequired: firstBool(true, rec.reasonRequired),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTemplates(raw: unknown): ChannelTemplate[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
return raw.map((item) => {
|
||||
const rec = asRecord(item)
|
||||
const match = asRecord(rec.match)
|
||||
return {
|
||||
match: {
|
||||
eventType: optionalOneOf(match.eventType, EVENT_TYPES),
|
||||
resultType: optionalOneOf(match.resultType, RESULT_TYPES),
|
||||
sportCode: firstString(match.sportCode) ?? undefined,
|
||||
},
|
||||
channels: normalizeChannels(rec.channels),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeOverrides(raw: unknown): EventOverride[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: EventOverride[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const eventCode = firstString(rec.eventCode)
|
||||
if (eventCode === null || eventCode === '') continue
|
||||
const override: EventOverride = { eventCode }
|
||||
const name = firstString(rec.name)
|
||||
if (name !== null) override.name = name
|
||||
if (typeof rec.scored === 'boolean') override.scored = rec.scored
|
||||
const multiplier = firstNumberOrNull(rec.multiplier)
|
||||
if (multiplier !== null) override.multiplier = multiplier
|
||||
if (Array.isArray(rec.channels)) override.channels = normalizeChannels(rec.channels)
|
||||
out.push(override)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeChannels(raw: unknown): RuleChannel[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: RuleChannel[] = []
|
||||
for (const item of raw) {
|
||||
const rec = asRecord(item)
|
||||
const profile = firstString(rec.profile)
|
||||
if (profile === null || profile === '') continue
|
||||
const channel: RuleChannel = {
|
||||
scope: oneOf(rec.scope, SCOPES, 'athlete'),
|
||||
basis: oneOf(rec.basis, BASES, 'result'),
|
||||
profile,
|
||||
}
|
||||
const aggregate = firstString(rec.aggregate)
|
||||
if (aggregate !== null && aggregate !== '') channel.aggregate = aggregate
|
||||
out.push(channel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user