refactor(前端): 拆掉 camelCase→snake_case 转换层,契约成为唯一真相

utils/legacy.ts 是迁移期的临时层:新后端一律 camelCase,而组件读的还是
旧 Django 的 snake_case,于是在 api 层做一次递归键名重写。它自己的注释就
写了「迁移完成后这一层应当整体拆掉」。现在拆了。

代价不只是那 96 处包装:每个响应都要递归遍历整个对象重写一遍键名,而且
utils/types.ts 和 packages/contract 是两份真相 —— 手抄的那份还抄歪了好几处。

做法是按域推进,每域都用 vue-tsc 相对基线做差,确认零新增错误后再往下走。
前端的类型现在一律以契约为准,只在必要处窄化(比如 languages/template 的键
窄化成 LANGUAGE),删掉的重复定义包括 WebsiteConfig、LoginSummary、
AchievementSummary、ProblemSet、Contest、User、Profile、AdminTag、
StuckProblem 等等,其中 ClassComparison 有两个组件各手抄了一份。

## 顺带修掉的真 bug

- 管理端公告列表的「可见」开关每次都 400:列表响应被契约 omit 掉了 content,
  而更新接口要求 content 必填,toggleVisible 把列表行原样回传。而且是乐观
  翻转、不 await 不 catch,管理员看到开关动了、实际没存也没有提示。
  改成先 GET 整条再 PUT,加失败提示。

- 删有提交的题时只显示笼统的「删除失败」:前端还在 match 旧 Django 的英文
  文案,而后端返回的是 problem-has-submissions + 中文。连同另外 8 处同类
  匹配一起改成判错误码 —— 文案是后端随时能改的,match 文案改一个字就静默失效。

- SubmissionStatus.time_limit_exceeded 写成 `1 | 2`,TS 按位或算成 3,和
  memory_limit_exceeded 撞了同一个值。后端 judge/status.ts 里这是分开的
  两个码,按后端拆成 cpu_/real_ 两项。当前没有代码读这两个成员,但
  CLAUDE.md 明确要求判题状态码三处同步。

- 流程图历史翻到没有提交的那一页会直接抛:契约里 submission 是 nullable,
  被 any 掩盖成看起来非空。补了 null 分支。

## 契约里被逼出来的三处不诚实

- grade 写成 z.string(),但 averageGrade() 在没有可用数据时返回空串,
  前端三张图表拿它查 Record<Grade,...> 会查出 undefined。按实际收紧成
  z.enum([...,""]),四个查表点都补了「无评级」分支。

- difficulty 写成 z.string()。核对过生产库 dump:956 道题只有
  Low/Mid/High 三个值(761/149/46)。收紧成枚举。

- topReaction 写成 z.string(),既对不上前端渲染的 {type,count},也对不上
  旧后端 get_top_reactions 下发的形状。改成正确形状并注明当前恒传 null。

## 明确保留 snake_case 的 54 处

判题沙箱原始输出(cpu_time/exit_code/output_md5/compile_output)、
statistic_info 内容(err_info/time_cost/ast_results)、submission_info
JSONB(is_ac/ac_time/error_number,回滚时旧后端还要读)、SQL 判题引擎的
total_rows/order_sensitive/changed_tables、WebSocket 的 submission_id、
以及数据库选项键 enable_maxkb。每一处都在类型定义旁写了为什么不能改。

language 没有跟着收紧契约 —— 它是配置项、随时可能加语言,收紧会让新语言
在后端 parse 时直接抛。改在 api 边界一处窄化。

## 另外

- utils/http.ts 整个模块已是死代码(四处引用全是 import type),删除。
- profile 的 blog/github/school/major/language 五个字段全链路空转,没有
  任何组件读,从契约到类型一并摘除(数据库列不动)。
- admin/account.ts 往 user_profile 塞的 totalScore 是 OI 模式遗留,表里
  没这一列。Drizzle 按表定义拼列名会把它静默丢弃,所以没出过错,是死代码。

验证:vue-tsc 143 → 54 条且无新增,apps/api tsc、check:routes、web build
全通过;各域响应形状逐条打接口核对过。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-25 13:44:24 -06:00
parent b5edd6faf5
commit c2a81209d7
125 changed files with 1651 additions and 2253 deletions

View File

@@ -1,6 +1,6 @@
import { userProfileSchema } from "@oj2/contract"
import api2 from "utils/api2"
import type { ApiResponse } from "utils/http"
import type { ApiResponse } from "utils/api2"
import type { Profile, Tag } from "utils/types"
export function login(data: { username: string; password: string }) {
@@ -26,37 +26,10 @@ export async function getProfile(
username ? `profiles/${encodeURIComponent(username)}` : "me",
)
if (response.data === null) return { error: null, data: null }
const profile = userProfileSchema.parse(response.data)
// 形状与契约一致不再逐字段搬运zod 解析仍保留,形状对不上要当场炸
return {
error: null,
data: {
id: profile.id,
user: {
id: profile.user.id,
username: profile.user.username,
real_name: profile.realName ?? "",
email: profile.user.email ?? "",
admin_type: profile.user.adminType as Profile["user"]["admin_type"],
problem_permission: profile.user.problemPermission,
create_time: profile.user.createTime as unknown as Date,
last_login: profile.user.lastLogin as unknown as Date,
open_api: profile.user.openApi,
is_disabled: profile.user.isDisabled,
class_name: profile.user.className,
},
real_name: profile.realName ?? "",
acm_problems_status:
profile.acmProblemsStatus as Profile["acm_problems_status"],
avatar: profile.avatar,
blog: profile.blog as null,
mood: profile.mood ?? "",
github: profile.github ?? "",
school: profile.school ?? "",
major: profile.major ?? "",
language: profile.language ?? "",
accepted_number: profile.acceptedNumber,
submission_number: profile.submissionNumber,
},
data: userProfileSchema.parse(response.data) as Profile,
}
}

View File

@@ -24,12 +24,10 @@ const authorOptions = ref([{ label: "全部", value: "" }])
async function getAuthorOptions() {
authorOptions.value = [{ label: "全部", value: "" }]
const res = await getAuthors(all)
const remotes = res.data.map(
(item: { username: string; problem_count: number }) => ({
label: `${item.username} (${item.problem_count})`,
value: item.username,
}),
)
const remotes = res.data.map((item) => ({
label: `${item.username} (${item.problemCount})`,
value: item.username,
}))
authorOptions.value = [...authorOptions.value, ...remotes]
}
</script>

View File

@@ -1,14 +1,14 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { ContestType } from "utils/constants"
import type { Contest } from "utils/types"
import type { Contest, OjContest } from "utils/types"
defineProps<{ contest: Contest }>()
defineProps<{ contest: Contest | OjContest }>()
</script>
<template>
<n-flex>
<Icon
v-if="contest.contest_type === ContestType.private"
v-if="contest.contestType === ContestType.private"
:height="24"
icon="streamline-ultimate-color:shield-lock"
></Icon>

View File

@@ -1,16 +1,16 @@
<script setup lang="ts">
import { ContestType } from "utils/constants"
import type { Contest } from "utils/types"
import type { Contest, OjContest } from "utils/types"
interface Props {
contest: Contest
contest: Contest | OjContest
size?: "small"
}
const props = defineProps<Props>()
const isPrivate = computed(
() => props.contest.contest_type === ContestType.private,
() => props.contest.contestType === ContestType.private,
)
</script>

View File

@@ -278,7 +278,7 @@ function handleMenuSelect(key: string) {
<n-flex align="center">
<n-flex align="center" class="title" @click="goHome">
<Icon icon="streamline-emojis:dog" :height="30"></Icon>
<div>{{ configStore.config?.website_name }}</div>
<div>{{ configStore.config?.websiteName }}</div>
<div v-if="showEnvVersion">({{ envVersion }})</div>
</n-flex>
<div>
@@ -331,7 +331,7 @@ function handleMenuSelect(key: string) {
</n-button>
<n-button
tertiary
v-if="configStore.config?.allow_register"
v-if="configStore.config?.allowRegister"
@click="authStore.openSignupModal()"
>
注册

View File

@@ -22,7 +22,7 @@ const isClassLogin = computed(() => Boolean(form.value.class))
const classList = computed<SelectOption[]>(() => {
const defaults = [{ label: "没有我所在的班级", value: "" }]
const configs =
configStore.config?.class_list.map((item) => ({
configStore.config?.classList.map((item) => ({
label: `${item.slice(0, 2)}计算机${item.slice(2)}`,
value: `ks${item}`,
})) ?? []
@@ -53,9 +53,10 @@ async function submit() {
}
await login(merged)
} catch (err: any) {
if (err.data === "Your account has been disabled") {
// 判错误码而不是错误文案:文案在后端,改一个字这里就静默掉进「无法登录」
if (err.error === "account-disabled") {
authStore.setLoginError("此账号已被封禁")
} else if (err.data === "Invalid username or password") {
} else if (err.error === "invalid-credentials") {
authStore.setLoginError("用户名或密码不正确")
} else {
authStore.setLoginError("无法登录")
@@ -177,12 +178,12 @@ onMounted(() => {
:loading="isLoading"
@click="submit"
:style="{
flex: configStore.config?.allow_register ? '0 0 auto' : '1',
flex: configStore.config?.allowRegister ? '0 0 auto' : '1',
}"
>
登录
</n-button>
<n-button v-if="configStore.config?.allow_register" @click="goSignup">
<n-button v-if="configStore.config?.allowRegister" @click="goSignup">
没有账号立即注册
</n-button>
</n-flex>

View File

@@ -33,33 +33,31 @@ const hasAnalysis = computed(() => !!loginSummaryStore.analysis)
<n-gi>
<n-statistic
label="新增题目"
:value="loginSummaryStore.summary?.new_problem_count ?? 0"
:value="loginSummaryStore.summary?.newProblemCount ?? 0"
/>
</n-gi>
<n-gi>
<n-statistic
label="提交次数"
:value="loginSummaryStore.summary?.submission_count ?? 0"
:value="loginSummaryStore.summary?.submissionCount ?? 0"
/>
</n-gi>
<n-gi>
<n-statistic
label="AC 次数"
:value="loginSummaryStore.summary?.accepted_count ?? 0"
:value="loginSummaryStore.summary?.acceptedCount ?? 0"
/>
</n-gi>
<n-gi>
<n-statistic
label="AC 题目数"
:value="loginSummaryStore.summary?.solved_count ?? 0"
:value="loginSummaryStore.summary?.solvedCount ?? 0"
/>
</n-gi>
<n-gi>
<n-statistic
label="流程图提交"
:value="
loginSummaryStore.summary?.flowchart_submission_count ?? 0
"
:value="loginSummaryStore.summary?.flowchartSubmissionCount ?? 0"
/>
</n-gi>
</n-grid>

View File

@@ -48,9 +48,9 @@ function submit() {
password: form.value.password,
})
} catch (err: any) {
if (err.data === "Username already exists") {
if (err.error === "username-exists") {
authStore.setSignupError("用户名已存在")
} else if (err.data === "Email already exists") {
} else if (err.error === "email-exists") {
authStore.setSignupError("邮箱已存在")
} else {
authStore.setSignupError("无法注册")

View File

@@ -15,7 +15,7 @@
<n-text strong>{{ badge.badge.name }}</n-text>
<n-tag type="info"> 获得条件{{ getConditionText() }} </n-tag>
<n-text depth="3">
获得时间{{ parseTime(badge.earned_time, "YYYY-MM-DD HH:mm:ss") }}
获得时间{{ parseTime(badge.earnedTime, "YYYY-MM-DD HH:mm:ss") }}
</n-text>
</n-flex>
</n-card>
@@ -38,15 +38,15 @@ function handleImageError(event: Event) {
}
function getConditionText() {
const { condition_type, condition_value } = props.badge.badge
const { conditionType, conditionValue } = props.badge.badge
switch (condition_type) {
switch (conditionType) {
case "all_problems":
return "完成所有题目"
case "problem_count":
return `完成 ${condition_value} 道题目`
return `完成 ${conditionValue} 道题目`
case "score":
return `获得 ${condition_value}`
return `获得 ${conditionValue}`
default:
return "未知条件"
}

View File

@@ -38,9 +38,9 @@ export function useMaxKB() {
)
const loadMaxKBScript = () => {
const { enable_maxkb } = configStore.config
const { enableMaxkb } = configStore.config
if (!enable_maxkb) {
if (!enableMaxkb) {
return
}
@@ -113,7 +113,7 @@ export function useMaxKB() {
})
watch(
() => configStore.config.enable_maxkb,
() => configStore.config.enableMaxkb,
(enabled) => {
if (enabled) {
loadMaxKBScript()

View File

@@ -25,7 +25,7 @@ const chineseAnnotations: Record<string, ChineseCompletion[]> = {
// SQL 题:当前题目的表名和字段名补全,数据来自 sql_display
function sqlSchemaCompletions(): Completion[] {
const tables = useProblemStore().problem?.sql_display?.tables ?? []
const tables = useProblemStore().problem?.sqlDisplay?.tables ?? []
return tables.flatMap((table) => [
{
label: table.name,

View File

@@ -2,7 +2,7 @@ import {
getPendingAchievements,
markAchievementsRead,
} from "oj/achievement/api"
import type { PendingAchievement } from "utils/types"
import type { QueuedAchievement } from "utils/types"
/**
* 成就解锁弹窗队列。
@@ -15,16 +15,16 @@ import type { PendingAchievement } from "utils/types"
* 才建连,纯推会丢消息(尤其是题单奖章,那些页面根本没建连接)。
*/
export const useAchievementStore = defineStore("achievement", () => {
const queue = ref<PendingAchievement[]>([])
const current = ref<PendingAchievement | null>(null)
const queue = ref<QueuedAchievement[]>([])
const current = ref<QueuedAchievement | null>(null)
// 成就和题单奖章的 id 来自两张不同的表,数值会重叠,
// 只按 id 去重会让奖章 5 把成就 5 挤掉
function keyOf(item: PendingAchievement) {
function keyOf(item: QueuedAchievement) {
return `${item.kind ?? "achievement"}:${item.id}`
}
function enqueue(items: PendingAchievement[]) {
function enqueue(items: QueuedAchievement[]) {
if (!items?.length) return
// 去重WebSocket 推来的和 pending 拉来的可能是同一批
const known = new Set([
@@ -49,7 +49,7 @@ export const useAchievementStore = defineStore("achievement", () => {
return current.value
}
async function markRead(item: PendingAchievement) {
async function markRead(item: QueuedAchievement) {
// 奖章不在 UserAchievement 表里,它的 id 传给标记接口会被当成成就 id
// 把一个恰好同号、还没弹过的成就静默标记为已弹——那个奖杯就再也不会出现
if (item.kind === "badge") return

View File

@@ -3,19 +3,19 @@ import type { WebsiteConfig } from "utils/types"
export const useConfigStore = defineStore("config", () => {
const config = ref<WebsiteConfig>({
website_base_url: "",
website_name: "",
website_name_shortcut: "",
website_footer: "",
submission_list_show_all: true,
allow_register: false,
class_list: [],
enable_maxkb: true,
websiteBaseUrl: "",
websiteName: "",
websiteNameShortcut: "",
websiteFooter: "",
submissionListShowAll: true,
allowRegister: false,
classList: [],
enableMaxkb: true,
})
async function getConfig() {
const res = await getWebsiteConfig()
config.value = res.data
document.title = res.data.website_name
document.title = res.data.websiteName
}
return {
config,

View File

@@ -1,14 +1,7 @@
import type { LoginSummary as ContractLoginSummary } from "@oj2/contract"
import { getAILoginSummary } from "oj/api"
interface LoginSummary {
start: string
end: string
new_problem_count: number
submission_count: number
accepted_count: number
solved_count: number
flowchart_submission_count: number
}
type LoginSummary = ContractLoginSummary["summary"]
export const useLoginSummaryStore = defineStore("loginSummary", () => {
const show = ref(false)
@@ -22,11 +15,11 @@ export const useLoginSummaryStore = defineStore("loginSummary", () => {
return false
}
const values = [
nextSummary.new_problem_count,
nextSummary.submission_count,
nextSummary.accepted_count,
nextSummary.solved_count,
nextSummary.flowchart_submission_count,
nextSummary.newProblemCount,
nextSummary.submissionCount,
nextSummary.acceptedCount,
nextSummary.solvedCount,
nextSummary.flowchartSubmissionCount,
]
const zeroCount = values.filter((value) => value === 0).length
return zeroCount < Math.floor(values.length / 2) + 1
@@ -40,7 +33,7 @@ export const useLoginSummaryStore = defineStore("loginSummary", () => {
const res = await getAILoginSummary()
summary.value = res.data.summary
analysis.value = res.data.analysis || ""
analysisError.value = res.data.analysis_error || ""
analysisError.value = res.data.analysisError || ""
} catch (err) {
analysisError.value = "获取登录统计失败,请稍后再试"
} finally {

View File

@@ -1,6 +1,6 @@
import { PROBLEM_PERMISSION, STORAGE_KEY, USER_TYPE } from "utils/constants"
import storage from "utils/storage"
import type { Profile, User } from "utils/types"
import type { Profile, SessionUser } from "utils/types"
import { getProfile } from "../api"
import { useConfigStore } from "./config"
@@ -9,7 +9,7 @@ export const useUserStore = defineStore("user", () => {
const profile = ref<Profile | null>(null)
const [isFinished] = useToggle(false)
const user = computed<User | null>(() => profile.value?.user ?? null)
const user = computed<SessionUser | null>(() => profile.value?.user ?? null)
const isAuthed = computed(() => !!user.value?.email)
// 演示模式:超管临时把界面伪装成普通学生,方便上课投屏
@@ -18,33 +18,33 @@ export const useUserStore = defineStore("user", () => {
// 不受伪装影响的真实身份,只用于判断能否切换演示模式。
// 若这里用被伪装后的 isSuperAdmin一进入演示模式入口就消失了退不出来。
const realIsSuperAdmin = computed(
() => user.value?.admin_type === USER_TYPE.SUPER_ADMIN,
() => user.value?.adminType === USER_TYPE.SUPER_ADMIN,
)
const isAdminRole = computed(
() =>
!demoMode.value &&
(user.value?.admin_type === USER_TYPE.STUDENT_ADMIN ||
user.value?.admin_type === USER_TYPE.TEACHER_ADMIN ||
user.value?.admin_type === USER_TYPE.SUPER_ADMIN),
(user.value?.adminType === USER_TYPE.STUDENT_ADMIN ||
user.value?.adminType === USER_TYPE.TEACHER_ADMIN ||
user.value?.adminType === USER_TYPE.SUPER_ADMIN),
)
const isStudentAdmin = computed(
() => !demoMode.value && user.value?.admin_type === USER_TYPE.STUDENT_ADMIN,
() => !demoMode.value && user.value?.adminType === USER_TYPE.STUDENT_ADMIN,
)
const isTeacherAdmin = computed(
() => !demoMode.value && user.value?.admin_type === USER_TYPE.TEACHER_ADMIN,
() => !demoMode.value && user.value?.adminType === USER_TYPE.TEACHER_ADMIN,
)
const isTeacherOrAbove = computed(
() =>
!demoMode.value &&
(user.value?.admin_type === USER_TYPE.TEACHER_ADMIN ||
user.value?.admin_type === USER_TYPE.SUPER_ADMIN),
(user.value?.adminType === USER_TYPE.TEACHER_ADMIN ||
user.value?.adminType === USER_TYPE.SUPER_ADMIN),
)
const isSuperAdmin = computed(() => !demoMode.value && realIsSuperAdmin.value)
const hasProblemPermission = computed(
() =>
!demoMode.value &&
user.value?.problem_permission !== PROBLEM_PERMISSION.NONE,
user.value?.problemPermission !== PROBLEM_PERMISSION.NONE,
)
const canToggleDemoMode = computed(() => realIsSuperAdmin.value)
@@ -55,7 +55,7 @@ export const useUserStore = defineStore("user", () => {
}
const showSubmissions = computed(() => {
let flag = configStore.config.submission_list_show_all
let flag = configStore.config.submissionListShowAll
if (isAdminRole.value) flag = true
return flag
})