style(格式化): 改成单引号、一行最长 160,全仓重新格式化
Deploy / deploy (push) Canceled after 0s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
xuyueandClaude Opus 5.5 committed 2026-10-26 13:52:24 +08:00
1 parent 530e1a3d5d
commit 195069450f
480 files changed
+15507 -24650

No files matched your search

@@ -1,16 +1,9 @@
<script setup lang="ts">
import type { AchievementRarity } from "utils/types"
import {
createAchievement,
getMetricOptions,
updateAchievement,
type AdminAchievement,
type MetricOption,
deleteAchievement,
} from "admin/api"
import AchievementIcon from "shared/components/AchievementIcon.vue"
import { RARITY_LABEL } from "utils/constants"
import { useBreakpoints } from "shared/composables/breakpoints"
import type { AchievementRarity } from 'utils/types'
import { createAchievement, getMetricOptions, updateAchievement, type AdminAchievement, type MetricOption, deleteAchievement } from 'admin/api'
import AchievementIcon from 'shared/components/AchievementIcon.vue'
import { RARITY_LABEL } from 'utils/constants'
import { useBreakpoints } from 'shared/composables/breakpoints'
const rarityOptions = Object.entries(RARITY_LABEL).map(([value, label]) => ({
label,
@@ -21,7 +14,7 @@ const props = defineProps<{
show: boolean
editing: AdminAchievement | null
}>()
const emit = defineEmits<{ "update:show": [boolean]; saved: [] }>()
const emit = defineEmits<{ 'update:show': [boolean]; saved: [] }>()
const dialog = useDialog()
/** 删除放在编辑框左下角(列表改成阶梯之后,每一档上只留「点了就编辑」) */
@@ -30,16 +23,14 @@ function confirmDelete() {
if (!target) return
dialog.warning({
title: `删除「${target.name}」?`,
content: target.unlockCount
? `${target.unlockCount} 人已经拿到了,删掉会连他们的记录一起删。只是不想再发,关掉「上架」就行。`
: "删掉就找不回来了。",
positiveText: "删除",
negativeText: "不删",
content: target.unlockCount ? `${target.unlockCount} 人已经拿到了,删掉会连他们的记录一起删。只是不想再发,关掉「上架」就行。` : '删掉就找不回来了。',
positiveText: '删除',
negativeText: '不删',
onPositiveClick: async () => {
await deleteAchievement(target.id)
message.success("删掉了")
emit("update:show", false)
emit("saved")
message.success('删掉了')
emit('update:show', false)
emit('saved')
},
})
}
@@ -51,13 +42,13 @@ const saving = ref(false)
function emptyForm() {
return {
name: "",
description: "",
icon: "noto:trophy",
rarity: "bronze" as AchievementRarity,
name: '',
description: '',
icon: 'noto:trophy',
rarity: 'bronze' as AchievementRarity,
hidden: false,
metric: "",
operator: "gte" as "gte" | "lte",
metric: '',
operator: 'gte' as 'gte' | 'lte',
threshold: 1,
visible: true,
order: 0,
@@ -68,9 +59,7 @@ const form = ref(emptyForm())
const metricOptions = computed(() => metrics.value.map((m) => ({ label: m.name, value: m.key })))
const metricHelp = computed(
() => metrics.value.find((m) => m.key === form.value.metric)?.helpText ?? "",
)
const metricHelp = computed(() => metrics.value.find((m) => m.key === form.value.metric)?.helpText ?? '')
watch(
() => props.show,
@@ -83,14 +72,14 @@ watch(
if (props.editing) {
form.value = { ...emptyForm(), ...props.editing }
} else {
form.value = { ...emptyForm(), metric: metrics.value[0]?.key ?? "" }
form.value = { ...emptyForm(), metric: metrics.value[0]?.key ?? '' }
}
},
)
async function save() {
if (!form.value.name || !form.value.metric) {
message.error("名称和指标不能为空")
message.error('名称和指标不能为空')
return
}
saving.value = true
@@ -100,9 +89,9 @@ async function save() {
} else {
await createAchievement(form.value)
}
message.success("保存成功")
emit("update:show", false)
emit("saved")
message.success('保存成功')
emit('update:show', false)
emit('saved')
} finally {
saving.value = false
}
@@ -110,24 +99,14 @@ async function save() {
</script>
<template>
<n-modal
:show="show"
preset="card"
style="width: 560px"
:title="editing ? '编辑成就' : '新建成就'"
@update:show="emit('update:show', $event)"
>
<n-modal :show="show" preset="card" style="width: 560px" :title="editing ? '编辑成就' : '新建成就'" @update:show="emit('update:show', $event)">
<!-- 手机上弹框只有 350 宽,标签放到上面,输入框才有地方 -->
<n-form :label-placement="isMobile ? 'top' : 'left'" :label-width="80">
<n-form-item label="名称" required>
<n-input v-model:value="form.name" placeholder="成就名称" />
</n-form-item>
<n-form-item label="描述" required>
<n-input
v-model:value="form.description"
type="textarea"
placeholder="达成条件的描述,展示给学生看"
/>
<n-input v-model:value="form.description" type="textarea" placeholder="达成条件的描述,展示给学生看" />
</n-form-item>
<n-form-item label="图标">
<n-flex vertical :size="4" style="flex: 1">
@@ -138,8 +117,7 @@ async function save() {
<n-input v-model:value="form.icon" placeholder="iconify 图标名,例如 noto:owl" />
</n-flex>
<n-text depth="3" style="font-size: 12px">
填 iconify 图标名(推荐 noto: 开头的彩色 emoji 图标),左侧是实时
预览;预览不出来说明名字写错了。图标名可在 icon-sets.iconify.design 搜索。
填 iconify 图标名(推荐 noto: 开头的彩色 emoji 图标),左侧是实时 预览;预览不出来说明名字写错了。图标名可在 icon-sets.iconify.design 搜索。
</n-text>
</n-flex>
</n-form-item>
@@ -178,9 +156,7 @@ async function save() {
</n-form>
<template #footer>
<n-flex justify="end">
<n-button v-if="editing" quaternary type="error" class="delete" @click="confirmDelete">
删除
</n-button>
<n-button v-if="editing" quaternary type="error" class="delete" @click="confirmDelete"> 删除 </n-button>
<n-button @click="emit('update:show', false)">取消</n-button>
<n-button type="primary" :loading="saving" @click="save"> 保存 </n-button>
</n-flex>
+19 -37
View File
@@ -1,16 +1,10 @@
<script setup lang="ts">
import PageHeader from "admin/components/PageHeader.vue"
import { useThemeVars } from "naive-ui"
import {
getAdminAchievements,
getBaseInfo,
getMetricOptions,
type AdminAchievement,
type MetricOption,
} from "admin/api"
import AchievementIcon from "shared/components/AchievementIcon.vue"
import AchievementModal from "./components/AchievementModal.vue"
import { RARITY_LABEL } from "utils/constants"
import PageHeader from 'admin/components/PageHeader.vue'
import { useThemeVars } from 'naive-ui'
import { getAdminAchievements, getBaseInfo, getMetricOptions, type AdminAchievement, type MetricOption } from 'admin/api'
import AchievementIcon from 'shared/components/AchievementIcon.vue'
import AchievementModal from './components/AchievementModal.vue'
import { RARITY_LABEL } from 'utils/constants'
/**
* 后台成就(设计稿「我的成就重设计」AchAdmin):按指标分组,一组一行排成阶梯 ——
@@ -37,11 +31,7 @@ const groups = computed(() => {
for (const a of list.value) byMetric.set(a.metric, [...(byMetric.get(a.metric) ?? []), a])
const order = metrics.value.map((m) => m.key)
return [...byMetric.entries()]
.sort(
([a], [b]) =>
(order.indexOf(a) === -1 ? 99 : order.indexOf(a)) -
(order.indexOf(b) === -1 ? 99 : order.indexOf(b)),
)
.sort(([a], [b]) => (order.indexOf(a) === -1 ? 99 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 99 : order.indexOf(b)))
.map(([metric, items]) => ({
metric,
name: items[0]?.metricName ?? metric,
@@ -50,9 +40,9 @@ const groups = computed(() => {
})
function percent(a: AdminAchievement) {
if (!students.value) return ""
if (!students.value) return ''
const value = (a.unlockCount / students.value) * 100
return value > 0 && value < 1 ? "<1%" : `${Math.round(value)}%`
return value > 0 && value < 1 ? '<1%' : `${Math.round(value)}%`
}
async function load() {
@@ -103,20 +93,12 @@ onMounted(load)
<div class="steps">
<template v-for="(a, i) in group.items" :key="a.id">
<span v-if="i" class="arrow" aria-hidden="true">→</span>
<button
type="button"
class="step"
:class="{ off: !a.visible }"
:title="`${RARITY_LABEL[a.rarity] ?? a.rarity} · 点了编辑`"
@click="edit(a)"
>
<button type="button" class="step" :class="{ off: !a.visible }" :title="`${RARITY_LABEL[a.rarity] ?? a.rarity} · 点了编辑`" @click="edit(a)">
<AchievementIcon :icon="a.icon" :size="26" />
<span class="step-text">
<b>
{{ a.name }}
<span class="muted small"
>{{ a.operator === "gte" ? "≥" : "≤" }} {{ a.threshold }}</span
>
<span class="muted small">{{ a.operator === 'gte' ? '≥' : '≤' }} {{ a.threshold }}</span>
</b>
<span class="small">
{{ a.unlockCount }} 人
@@ -143,7 +125,7 @@ onMounted(load)
/* 斑马底纹,和后台其它列表一样 */
.group:nth-child(even) {
background: v-bind("theme.tableColorStriped");
background: v-bind('theme.tableColorStriped');
}
.group {
@@ -151,7 +133,7 @@ onMounted(load)
align-items: center;
gap: 12px;
padding: 8px 10px;
border-bottom: 1px solid v-bind("theme.dividerColor");
border-bottom: 1px solid v-bind('theme.dividerColor');
}
.metric {
@@ -168,7 +150,7 @@ onMounted(load)
}
.arrow {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.step {
@@ -178,8 +160,8 @@ onMounted(load)
min-width: 160px;
padding: 6px 10px;
border-radius: 8px;
border: 1px solid v-bind("theme.dividerColor");
background: v-bind("theme.cardColor");
border: 1px solid v-bind('theme.dividerColor');
background: v-bind('theme.cardColor');
font: inherit;
color: inherit;
text-align: left;
@@ -187,7 +169,7 @@ onMounted(load)
}
.step:hover {
border-color: v-bind("theme.primaryColor");
border-color: v-bind('theme.primaryColor');
}
.step.off {
@@ -210,11 +192,11 @@ onMounted(load)
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.off-note {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
/* 手机上指标名放在一组上头,下面两档一行;箭头拿掉(折行之后箭头会单独落在行首) */
+34 -42
View File
@@ -1,19 +1,19 @@
<script lang="ts" setup>
import { Icon } from "@iconify/vue"
import PageHeader from "admin/components/PageHeader.vue"
import { useThemeVars } from "naive-ui"
import { classLabel } from "utils/classes"
import { useBackClose } from "shared/composables/backClose"
import { useBreakpoints } from "shared/composables/breakpoints"
import Pagination from "shared/components/Pagination.vue"
import UserName from "shared/components/UserName.vue"
import { parseTime } from "utils/functions"
import type { AdminAiReport, AdminAiReportListItem } from "utils/types"
import { getAIReportDetail, getAIReportList, pinAIReport } from "../api"
import { useListLoader } from "shared/composables/listLoader"
import { Icon } from '@iconify/vue'
import PageHeader from 'admin/components/PageHeader.vue'
import { useThemeVars } from 'naive-ui'
import { classLabel } from 'utils/classes'
import { useBackClose } from 'shared/composables/backClose'
import { useBreakpoints } from 'shared/composables/breakpoints'
import Pagination from 'shared/components/Pagination.vue'
import UserName from 'shared/components/UserName.vue'
import { parseTime } from 'utils/functions'
import type { AdminAiReport, AdminAiReportListItem } from 'utils/types'
import { getAIReportDetail, getAIReportList, pinAIReport } from '../api'
import { useListLoader } from 'shared/composables/listLoader'
// Markdown 连着整套代码高亮(两百多 KB),这里要等点开 / AI 写完才用得上,别让它拖慢页面
const Markdown = defineAsyncComponent(() => import("shared/components/Markdown.vue"))
const Markdown = defineAsyncComponent(() => import('shared/components/Markdown.vue'))
/**
* 后台 AI 报告(设计稿「智能分析重设计」AiAdmin):左边一份一行(用户名、班级、时间、
@@ -45,7 +45,7 @@ const route = useRoute()
const query = reactive({
limit: 10,
page: 1,
username: typeof route.query.username === "string" ? route.query.username : "",
username: typeof route.query.username === 'string' ? route.query.username : '',
})
const selectedId = ref<number | null>(null)
@@ -86,9 +86,9 @@ async function togglePin() {
/** 摘要里去掉 Markdown 的记号:粗体星号、标题井号,还有表格的竖线和分隔线 */
function excerpt(text: string) {
return text
.replace(/[*#>`|]+/g, " ")
.replace(/-{2,}/g, " ")
.replace(/\s+/g, " ")
.replace(/[*#>`|]+/g, ' ')
.replace(/-{2,}/g, ' ')
.replace(/\s+/g, ' ')
.trim()
}
@@ -116,20 +116,13 @@ watchDebounced(
<div v-else class="layout">
<div class="list-col">
<div class="list">
<button
v-for="r in reports"
:key="r.id"
type="button"
class="item"
:class="{ on: r.id === selectedId }"
@click="pick(r.id)"
>
<button v-for="r in reports" :key="r.id" type="button" class="item" :class="{ on: r.id === selectedId }" @click="pick(r.id)">
<span class="item-head">
<UserName :username="r.username" />
<span class="muted small">{{ r.className ? classLabel(r.className) : "" }}</span>
<span class="muted small">{{ r.className ? classLabel(r.className) : '' }}</span>
<span v-if="r.isPinned" class="pinned">固定</span>
<span class="spacer"></span>
<span class="muted small num">{{ parseTime(r.createTime, "MM-DD HH:mm") }}</span>
<span class="muted small num">{{ parseTime(r.createTime, 'MM-DD HH:mm') }}</span>
</span>
<span class="item-text">{{ excerpt(r.analysisExcerpt) }}</span>
</button>
@@ -149,8 +142,7 @@ watchDebounced(
<div class="detail-head">
<UserName :username="selected.username" />
<span class="muted">
{{ selected.className ? classLabel(selected.className) + " · " : ""
}}{{ parseTime(selected.createTime, "YYYY-MM-DD HH:mm") }}
{{ selected.className ? classLabel(selected.className) + ' · ' : '' }}{{ parseTime(selected.createTime, 'YYYY-MM-DD HH:mm') }}
</span>
<span class="spacer"></span>
<label class="pin">
@@ -183,7 +175,7 @@ watchDebounced(
}
.list {
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
border-radius: 8px;
overflow: hidden;
}
@@ -195,7 +187,7 @@ watchDebounced(
width: 100%;
padding: 10px 12px;
border: 0;
border-bottom: 1px solid v-bind("theme.dividerColor");
border-bottom: 1px solid v-bind('theme.dividerColor');
background: none;
font: inherit;
text-align: left;
@@ -209,16 +201,16 @@ watchDebounced(
/* 斑马底纹,和后台其它列表一样 */
.item:nth-child(even) {
background: v-bind("theme.tableColorStriped");
background: v-bind('theme.tableColorStriped');
}
.item:hover {
background: v-bind("theme.hoverColor");
background: v-bind('theme.hoverColor');
}
.item.on {
background: v-bind("theme.hoverColor");
box-shadow: inset 3px 0 0 v-bind("theme.primaryColor");
background: v-bind('theme.hoverColor');
box-shadow: inset 3px 0 0 v-bind('theme.primaryColor');
}
.item-head {
@@ -232,7 +224,7 @@ watchDebounced(
.item-text {
font-size: 13px;
line-height: 20px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
@@ -241,7 +233,7 @@ watchDebounced(
.pinned {
font-size: 12px;
color: v-bind("theme.warningColor");
color: v-bind('theme.warningColor');
}
.detail {
@@ -255,7 +247,7 @@ watchDebounced(
gap: 10px;
font-size: 16px;
padding-bottom: 12px;
border-bottom: 1px solid v-bind("theme.dividerColor");
border-bottom: 1px solid v-bind('theme.dividerColor');
}
.pin {
@@ -277,7 +269,7 @@ watchDebounced(
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
font-size: 14px;
}
@@ -316,7 +308,7 @@ watchDebounced(
z-index: 2000;
overflow-y: auto;
padding: 0 16px 32px;
background: v-bind("theme.bodyColor");
background: v-bind('theme.bodyColor');
}
.detail-bar {
@@ -330,8 +322,8 @@ watchDebounced(
margin: 0 -16px 12px;
padding: 0 8px;
font-weight: 600;
border-bottom: 1px solid v-bind("theme.dividerColor");
background: v-bind("theme.bodyColor");
border-bottom: 1px solid v-bind('theme.dividerColor');
background: v-bind('theme.bodyColor');
}
.detail-head {
@@ -1,5 +1,5 @@
<script lang="ts" setup>
import { deleteAnnouncement } from "admin/api"
import { deleteAnnouncement } from 'admin/api'
/**
* 公告一行的操作:编辑、置顶、删除直接摆出来(用户说的:不要收进 ⋯)
@@ -17,21 +17,21 @@ const dialog = useDialog()
function goEdit() {
router.push({
name: "admin announcement edit",
name: 'admin announcement edit',
params: { announcementID: props.announcementID },
})
}
function confirmDelete() {
dialog.warning({
title: "删除这条公告?",
content: "删掉就找不回来了。只是不想让学生看到的话,关掉「学生看得到」就行。",
positiveText: "删除",
negativeText: "不删",
title: '删除这条公告?',
content: '删掉就找不回来了。只是不想让学生看到的话,关掉「学生看得到」就行。',
positiveText: '删除',
negativeText: '不删',
onPositiveClick: async () => {
await deleteAnnouncement(props.announcementID)
message.success("删掉了")
emit("deleted")
message.success('删掉了')
emit('deleted')
},
})
}
@@ -40,7 +40,7 @@ function confirmDelete() {
<n-flex :size="6" :wrap="false">
<n-button size="small" @click="goEdit">编辑</n-button>
<n-button size="small" @click="emit('toggleTop')">
{{ props.top ? "取消置顶" : "置顶" }}
{{ props.top ? '取消置顶' : '置顶' }}
</n-button>
<n-button size="small" quaternary type="error" @click="confirmDelete">删除</n-button>
</n-flex>
+21 -30
View File
@@ -1,9 +1,9 @@
<script lang="ts" setup>
import PageHeader from "admin/components/PageHeader.vue"
import { errorMessage } from "utils/api"
import TextEditor from "shared/components/TextEditor.vue"
import type { AnnouncementEdit } from "utils/types"
import { createAnnouncement, editAnnouncement, getAnnouncement } from "../api"
import PageHeader from 'admin/components/PageHeader.vue'
import { errorMessage } from 'utils/api'
import TextEditor from 'shared/components/TextEditor.vue'
import type { AnnouncementEdit } from 'utils/types'
import { createAnnouncement, editAnnouncement, getAnnouncement } from '../api'
interface Props {
announcementID?: string
@@ -17,16 +17,16 @@ const [ready, toggleReady] = useToggle()
const announcement = reactive<AnnouncementEdit>({
id: 0,
title: "",
tag: "公告",
content: "",
title: '',
tag: '公告',
content: '',
visible: false,
top: false,
})
const tags: SelectOption[] = [
{ label: "公告", value: "公告" },
{ label: "更新", value: "更新" },
{ label: '公告', value: '公告' },
{ label: '更新', value: '更新' },
]
async function init() {
@@ -46,25 +46,25 @@ async function init() {
}
async function submit() {
if (announcement.content === "<p><br></p>") {
announcement.content = ""
if (announcement.content === '<p><br></p>') {
announcement.content = ''
}
if (!announcement.title || !announcement.content) {
message.error("标题和正文必填")
message.error('标题和正文必填')
return
}
const api = {
"admin announcement create": createAnnouncement,
"admin announcement edit": editAnnouncement,
'admin announcement create': createAnnouncement,
'admin announcement edit': editAnnouncement,
}[route.name as string]
try {
await api!(announcement)
if (route.name === "admin announcement create") {
message.success("发好了")
if (route.name === 'admin announcement create') {
message.success('发好了')
} else {
message.success("改好了")
message.success('改好了')
}
router.push({ name: "admin announcement list" })
router.push({ name: 'admin announcement list' })
} catch (err) {
message.error(errorMessage(err))
}
@@ -73,23 +73,14 @@ async function submit() {
onMounted(init)
</script>
<template>
<PageHeader
:title="route.name === 'admin announcement create' ? '写一条公告' : '改公告'"
:back="{ name: 'admin announcement list' }"
>
<PageHeader :title="route.name === 'admin announcement create' ? '写一条公告' : '改公告'" :back="{ name: 'admin announcement list' }">
<template #actions>
<n-button type="primary" @click="submit">保存</n-button>
</template>
</PageHeader>
<!-- 标题、类型、置顶、学生看得到排一行;保存在右上角,不用滚到正文底下去点 -->
<div class="meta">
<n-input
v-model:value="announcement.title"
placeholder="标题"
size="large"
class="title"
aria-label="标题"
/>
<n-input v-model:value="announcement.title" placeholder="标题" size="large" class="title" aria-label="标题" />
<n-radio-group v-model:value="announcement.tag" aria-label="类型">
<n-radio-button v-for="t in tags" :key="String(t.value)" :value="t.value">
{{ t.label }}
+51 -59
View File
@@ -1,14 +1,14 @@
<script setup lang="ts">
import PageHeader from "admin/components/PageHeader.vue"
import { NSwitch, useThemeVars } from "naive-ui"
import { RouterLink } from "vue-router"
import Pagination from "shared/components/Pagination.vue"
import { parseTime } from "utils/functions"
import type { AdminAnnouncementListItem } from "utils/types"
import { editAnnouncement, getAnnouncement, getAnnouncementList } from "../api"
import Actions from "./components/Actions.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import PageHeader from 'admin/components/PageHeader.vue'
import { NSwitch, useThemeVars } from 'naive-ui'
import { RouterLink } from 'vue-router'
import Pagination from 'shared/components/Pagination.vue'
import { parseTime } from 'utils/functions'
import type { AdminAnnouncementListItem } from 'utils/types'
import { editAnnouncement, getAnnouncement, getAnnouncementList } from '../api'
import Actions from './components/Actions.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
const message = useMessage()
const total = ref(0)
@@ -27,26 +27,26 @@ const theme = useThemeVars()
const { isMobile } = useBreakpoints()
function renderTitle(row: AdminAnnouncementListItem) {
return h("span", { class: "title-cell" }, [
return h('span', { class: 'title-cell' }, [
h(
RouterLink,
{
class: "title-link",
to: { name: "admin announcement edit", params: { announcementID: row.id } },
class: 'title-link',
to: { name: 'admin announcement edit', params: { announcementID: row.id } },
},
() => row.title,
),
row.top ? h("span", { class: "top" }, "置顶") : null,
h("span", { class: "muted small" }, row.tag),
row.top ? h('span', { class: 'top' }, '置顶') : null,
h('span', { class: 'muted small' }, row.tag),
])
}
function renderVisible(row: AdminAnnouncementListItem) {
return h(NSwitch, {
value: row.visible,
size: isMobile.value ? "medium" : "small",
size: isMobile.value ? 'medium' : 'small',
rubberBand: false,
onUpdateValue: () => toggle(row, "visible"),
onUpdateValue: () => toggle(row, 'visible'),
})
}
@@ -55,61 +55,61 @@ function renderActions(row: AdminAnnouncementListItem) {
announcementID: row.id,
top: row.top,
onDeleted: listAnnouncements,
onToggleTop: () => toggle(row, "top"),
onToggleTop: () => toggle(row, 'top'),
})
}
/** 手机上一条一张卡:标题一行,发布 · 改过一行小字,操作一行;「学生看得到」单独一列靠右 */
function renderMobileCard(row: AdminAnnouncementListItem) {
const created = parseTime(row.createTime, "YYYY-MM-DD")
const updated = parseTime(row.lastUpdateTime, "YYYY-MM-DD")
return h("div", { class: "m-card" }, [
const created = parseTime(row.createTime, 'YYYY-MM-DD')
const updated = parseTime(row.lastUpdateTime, 'YYYY-MM-DD')
return h('div', { class: 'm-card' }, [
renderTitle(row),
h("div", { class: "m-meta muted num" }, [
h("span", { class: "m-item" }, `${created} 发布`),
updated === created ? null : h("span", { class: "m-item" }, ` · ${updated} 改过`),
h('div', { class: 'm-meta muted num' }, [
h('span', { class: 'm-item' }, `${created} 发布`),
updated === created ? null : h('span', { class: 'm-item' }, ` · ${updated} 改过`),
]),
renderActions(row),
])
}
const mobileColumns: DataTableColumn<AdminAnnouncementListItem>[] = [
{ title: "标题", key: "title", render: renderMobileCard },
{ title: "看得到", key: "visible", width: 72, align: "center", render: renderVisible },
{ title: '标题', key: 'title', render: renderMobileCard },
{ title: '看得到', key: 'visible', width: 72, align: 'center', render: renderVisible },
]
const desktopColumns: DataTableColumn<AdminAnnouncementListItem>[] = [
{
title: "标题",
key: "title",
title: '标题',
key: 'title',
width: 360,
render: renderTitle,
},
{
title: "发布",
key: "createTime",
title: '发布',
key: 'createTime',
width: 120,
render: (row) => h("span", { class: "num" }, parseTime(row.createTime, "YYYY-MM-DD")),
render: (row) => h('span', { class: 'num' }, parseTime(row.createTime, 'YYYY-MM-DD')),
},
{
title: "改过",
key: "lastUpdateTime",
title: '改过',
key: 'lastUpdateTime',
width: 120,
render: (row) => {
const created = parseTime(row.createTime, "YYYY-MM-DD")
const updated = parseTime(row.lastUpdateTime, "YYYY-MM-DD")
return h("span", { class: "num muted" }, updated === created ? "—" : updated)
const created = parseTime(row.createTime, 'YYYY-MM-DD')
const updated = parseTime(row.lastUpdateTime, 'YYYY-MM-DD')
return h('span', { class: 'num muted' }, updated === created ? '—' : updated)
},
},
{
title: "学生看得到",
key: "visible",
title: '学生看得到',
key: 'visible',
width: 100,
render: renderVisible,
},
{
title: "",
key: "actions",
title: '',
key: 'actions',
minWidth: 240,
render: renderActions,
},
@@ -119,7 +119,7 @@ const columns = computed(() => (isMobile.value ? mobileColumns : desktopColumns)
// 列表响应不含 content(正文是 8MB 上限的富文本),而更新接口要求 content 必填 ——
// 拿列表里那行直接回传会 400。所以先取回整条再改。
async function toggle(announcement: AdminAnnouncementListItem, field: "visible" | "top") {
async function toggle(announcement: AdminAnnouncementListItem, field: 'visible' | 'top') {
try {
const full = await getAnnouncement(announcement.id)
await editAnnouncement({
@@ -127,13 +127,13 @@ async function toggle(announcement: AdminAnnouncementListItem, field: "visible"
title: full.title,
tag: full.tag,
content: full.content,
visible: field === "visible" ? !full.visible : full.visible,
top: field === "top" ? !full.top : full.top,
visible: field === 'visible' ? !full.visible : full.visible,
top: field === 'top' ? !full.top : full.top,
})
if (field === "top") listAnnouncements()
if (field === 'top') listAnnouncements()
else announcement.visible = !full.visible
} catch {
message.error("没改成,刷新一下再试")
message.error('没改成,刷新一下再试')
}
}
@@ -153,18 +153,10 @@ watch(query, listAnnouncements, { deep: true })
<template>
<PageHeader title="公告">
<template #actions>
<n-button type="primary" @click="$router.push({ name: 'admin announcement create' })">
写一条公告
</n-button>
<n-button type="primary" @click="$router.push({ name: 'admin announcement create' })"> 写一条公告 </n-button>
</template>
</PageHeader>
<n-data-table
:loading="loading"
striped
class="ann-table"
:columns="columns"
:data="announcements"
/>
<n-data-table :loading="loading" striped class="ann-table" :columns="columns" :data="announcements" />
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
</template>
@@ -197,7 +189,7 @@ watch(query, listAnnouncements, { deep: true })
}
.ann-table :deep(.title-link) {
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
font-weight: 500;
text-decoration: none;
}
@@ -210,12 +202,12 @@ watch(query, listAnnouncements, { deep: true })
font-size: 12px;
padding: 0 6px;
border-radius: 3px;
color: v-bind("theme.warningColor");
background: v-bind("theme.actionColor");
color: v-bind('theme.warningColor');
background: v-bind('theme.actionColor');
}
.ann-table :deep(.muted) {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.ann-table :deep(.small) {
+100 -175
View File
@@ -1,4 +1,4 @@
import { toAdminType, toProblemPermission } from "@oj2/contract"
import { toAdminType, toProblemPermission } from '@oj2/contract'
import type {
AddContestProblemRequest,
ChallengeSuggestionsResponse,
@@ -39,9 +39,9 @@ import type {
UpdateTutorialRequest,
UpdateUserRequest,
UpdateWebsiteConfigRequest,
} from "@oj2/contract"
import api from "utils/api"
import { toAdminProblemRow } from "admin/transforms"
} from '@oj2/contract'
import api from 'utils/api'
import { toAdminProblemRow } from 'admin/transforms'
import type {
BatchProblemTagResponse,
GenerateSqlTestCaseResponse,
@@ -87,7 +87,7 @@ import type {
TutorialListItem,
TutorialEdit,
TagCategory,
} from "utils/types"
} from 'utils/types'
import type {
TutorialProblemCandidate,
AstCheckRequest,
@@ -96,14 +96,14 @@ import type {
GenerateTestInputsResponse,
TestCaseFiles,
CheckUsernamesResponse,
} from "@oj2/contract"
} from '@oj2/contract'
export function getBaseInfo() {
return api.get<DashboardInfo>("admin/dashboard")
return api.get<DashboardInfo>('admin/dashboard')
}
export function randomUser10(classroom: string) {
return api.get<string[]>("admin/random-usernames", {
return api.get<string[]>('admin/random-usernames', {
params: { classroom },
})
}
@@ -116,11 +116,11 @@ export async function getProblemList(
contestID?: string,
tagId?: number,
/** 题型:sql = SQL 题,code = 编程题;不传是全部(比赛题列表不认) */
kind?: "sql" | "code" | "",
kind?: 'sql' | 'code' | '',
/** 1 = 学生看得到的,0 = 藏着的;不传是全部(比赛题列表不认) */
visible?: "1" | "0" | "",
visible?: '1' | '0' | '',
) {
const endpoint = contestID ? `admin/contests/${contestID}/problems` : "admin/problems"
const endpoint = contestID ? `admin/contests/${contestID}/problems` : 'admin/problems'
const res = await api.get<AdminProblemList>(endpoint, {
params: {
offset,
@@ -141,7 +141,7 @@ export async function getProblemList(
/** 勾了几道,一次让学生看得到 / 藏起来 */
export function batchSetProblemVisible(problemIds: number[], visible: boolean) {
return api.post<{ problemCount: number }>("admin/problems/batch-visible", {
return api.post<{ problemCount: number }>('admin/problems/batch-visible', {
problemIds,
visible,
} satisfies BatchProblemVisibleRequest)
@@ -149,7 +149,7 @@ export function batchSetProblemVisible(problemIds: number[], visible: boolean) {
// 比赛「从题库中选择」用:列所有可见的公开题,不只是自己创建的
export async function getLibraryProblemList(offset = 0, limit = 10, keyword: string) {
const res = await api.get<AdminProblemList>("admin/problems", {
const res = await api.get<AdminProblemList>('admin/problems', {
params: { offset, limit, keyword, library: 1 },
})
return {
@@ -170,10 +170,7 @@ export function deleteContestProblem(id: number) {
// 比赛题也走这条:后端是同一条 PUT admin/problems/:id,比赛由题目自己推导,
// 所以不像新建那样需要分两个函数
export function editProblem(problem: AdminProblem | BlankProblem) {
return api.put<AdminProblem>(
`admin/problems/${(problem as AdminProblem).id}`,
toProblemBody(problem) satisfies Partial<UpdateProblemRequest>,
)
return api.put<AdminProblem>(`admin/problems/${(problem as AdminProblem).id}`, toProblemBody(problem) satisfies Partial<UpdateProblemRequest>)
}
export function toggleProblemVisible(problemID: number) {
@@ -181,7 +178,7 @@ export function toggleProblemVisible(problemID: number) {
}
export function generateFlowchartFromPythonCode(python: string) {
return api.post<{ doc: Record<string, unknown> }>("admin/problems/flowchart", {
return api.post<{ doc: Record<string, unknown> }>('admin/problems/flowchart', {
python,
} satisfies GenerateFlowchartRequest)
}
@@ -191,8 +188,8 @@ export function getProblem(id: string | number) {
}
// 标签管理
export function getTagAdminList(keyword = "") {
return api.get<AdminTag[]>("admin/problem-tags", { params: { keyword } })
export function getTagAdminList(keyword = '') {
return api.get<AdminTag[]>('admin/problem-tags', { params: { keyword } })
}
export function renameTag(id: number, name: string) {
@@ -209,12 +206,8 @@ export function deleteTag(id: number) {
return api.delete(`admin/problem-tags/${id}`)
}
export function batchTagProblems(
problemIds: number[],
tagNames: string[],
action: "add" | "remove",
) {
return api.post<BatchProblemTagResponse>("admin/problems/batch-tag", {
export function batchTagProblems(problemIds: number[], tagNames: string[], action: 'add' | 'remove') {
return api.post<BatchProblemTagResponse>('admin/problems/batch-tag', {
problemIds,
tagNames,
action,
@@ -223,7 +216,7 @@ export function batchTagProblems(
// 用户排名(后台版,无 100 名上限;公开榜单是 oj/api.ts 的 getRank)
export function getAdminUserRank(offset: number, limit: number, keyword: string) {
return api.get<AdminUserRank>("admin/rankings/users", {
return api.get<AdminUserRank>('admin/rankings/users', {
params: { offset, limit, keyword },
})
}
@@ -232,13 +225,13 @@ export function getAdminUserRank(offset: number, limit: number, keyword: string)
export function getUserList(
offset = 0,
limit = 10,
type = "",
type = '',
keyword: string,
orderBy = "",
orderBy = '',
/** 班级,NO_CLASS 是「没填班级」 */
className = "",
className = '',
) {
return api.get<AdminUserList>("admin/users", {
return api.get<AdminUserList>('admin/users', {
// "-last_login" 是旧接口传下来的取值(路由 query 里可能还存着),改叫 "-lastLogin";
// "-online" 是新增的,原样透传
params: {
@@ -246,7 +239,7 @@ export function getUserList(
limit,
keyword,
type,
orderBy: orderBy === "-last_login" ? "-lastLogin" : orderBy,
orderBy: orderBy === '-last_login' ? '-lastLogin' : orderBy,
className: className || undefined,
},
})
@@ -254,7 +247,7 @@ export function getUserList(
/** 批量建号之前查重:这些用户名哪些已经有了 */
export function checkUsernames(usernames: string[]) {
return api.post<CheckUsernamesResponse>("admin/users/check", {
return api.post<CheckUsernamesResponse>('admin/users/check', {
usernames,
} satisfies CheckUsernamesRequest)
}
@@ -264,12 +257,12 @@ export function editUser(user: AdminUserForm) {
return api.put<AdminUser>(`admin/users/${user.id}`, {
username: user.username,
// 库里 email 没有空的(2026-10 核过),响应类型是 nullable 只因为列可空
email: user.email ?? "",
email: user.email ?? '',
adminType: toAdminType(user.adminType),
problemPermission: toProblemPermission(user.problemPermission),
realName: user.realName ?? null,
isDisabled: user.isDisabled,
password: user.password ?? "",
password: user.password ?? '',
} satisfies UpdateUserRequest)
}
@@ -281,19 +274,19 @@ export async function resetPassword(userID: number) {
// 导入用户
/** 批量建号。addedClasses:这批里的新班级,后端已经顺手加进了班级列表 */
export function importUsers(users: ImportUsersRequest["users"]) {
return api.post<{ imported: number; addedClasses: string[] }>("admin/users", {
export function importUsers(users: ImportUsersRequest['users']) {
return api.post<{ imported: number; addedClasses: string[] }>('admin/users', {
users,
} satisfies ImportUsersRequest)
}
// 批量删除用户
export function deleteUsers(userIDs: number[]) {
return api.delete("admin/users", { data: { ids: userIDs } })
return api.delete('admin/users', { data: { ids: userIDs } })
}
export function getContestList(offset = 0, limit = 10, keyword: string) {
return api.get<AdminContestList>("admin/contests", {
return api.get<AdminContestList>('admin/contests', {
params: { offset, limit, keyword },
})
}
@@ -301,34 +294,34 @@ export function getContestList(offset = 0, limit = 10, keyword: string) {
// 上传图片
export async function uploadImage(file: File): Promise<string> {
const form = new window.FormData()
form.append("image", file)
form.append('image', file)
const res = await api.post<{
success: boolean
filePath: string
msg: string
}>("admin/upload-image", form)
return res.success ? res.filePath : ""
}>('admin/upload-image', form)
return res.success ? res.filePath : ''
}
// 上传测试用例;SQL 题的压缩包是 1.sql..N.sql(每个文件一个测试点的建表+数据脚本)
export function uploadTestcases(file: File, options: { sql?: boolean } = {}) {
const form = new window.FormData()
form.append("file", file)
form.append('file', file)
if (options.sql) {
form.append("sql", "1")
form.append('sql', '1')
}
return api.post<UploadTestCaseResponse>("admin/test-cases", form)
return api.post<UploadTestCaseResponse>('admin/test-cases', form)
}
// SQL 题测试点预览:后端跑一遍初始化脚本+标准答案,返回数据表和期望结果展示数据
export function previewSQLTestcase(data: {
initSql: string
refSql: string
mode: "query" | "modify"
mode: 'query' | 'modify'
/** 是不是题面上展示的那组(第 1 组):增删改题只有它必须改到行 */
shown: boolean
}) {
return api.post<SqlDisplay>("admin/sql-test-cases/preview", data satisfies SqlPreviewRequest)
return api.post<SqlDisplay>('admin/sql-test-cases/preview', data satisfies SqlPreviewRequest)
}
// 回显已上传的 SQL 测试点脚本内容(按 1.sql, 2.sql... 排序)
@@ -337,11 +330,8 @@ export function getSQLTestcaseScripts(problemId: number) {
}
// AI 根据标准答案生成一个 SQL 测试点初始化脚本
export function generateSQLTestcase(data: { refSql: string; mode: "query" | "modify" }) {
return api.post<GenerateSqlTestCaseResponse>(
"admin/sql-test-cases/generate",
data satisfies GenerateSqlTestCaseRequest,
)
export function generateSQLTestcase(data: { refSql: string; mode: 'query' | 'modify' }) {
return api.post<GenerateSqlTestCaseResponse>('admin/sql-test-cases/generate', data satisfies GenerateSqlTestCaseRequest)
}
// 编程题出题页:读回已有测试点的原文(太大的只给数量和大小)
@@ -351,38 +341,32 @@ export function getTestCaseFiles(problemId: number) {
// 拿标准答案自测语法要求
export function checkAstRules(data: AstCheckRequest) {
return api.post<AstCheckResponse>("admin/ast-check", data satisfies AstCheckRequest)
return api.post<AstCheckResponse>('admin/ast-check', data satisfies AstCheckRequest)
}
// 出题页「挑战」的候选:拿这道题历史上做对的代码挖
export function getChallengeSuggestions(problemId: number, language: string) {
return api.post<ChallengeSuggestionsResponse>(
`admin/problems/${problemId}/challenge-suggestions`,
{
language,
},
)
return api.post<ChallengeSuggestionsResponse>(`admin/problems/${problemId}/challenge-suggestions`, {
language,
})
}
// AI 按题面和标准答案想几组测试输入(输出由标准答案跑)
export function generateTestInputs(data: GenerateTestInputsRequest) {
return api.post<GenerateTestInputsResponse>(
"admin/test-inputs/generate",
data satisfies GenerateTestInputsRequest,
)
return api.post<GenerateTestInputsResponse>('admin/test-inputs/generate', data satisfies GenerateTestInputsRequest)
}
/** 出站补默认值。字段名两边已经一致,不再做键名转换 */
function toProblemBody(problem: AdminProblem | BlankProblem) {
const p = problem as Partial<Omit<AdminProblem, "flowchartData">> & {
const p = problem as Partial<Omit<AdminProblem, 'flowchartData'>> & {
flowchartData?: Record<string, unknown> | null
}
return {
_id: p._id,
title: p.title,
description: p.description,
inputDescription: p.inputDescription ?? "",
outputDescription: p.outputDescription ?? "",
inputDescription: p.inputDescription ?? '',
outputDescription: p.outputDescription ?? '',
samples: p.samples ?? [],
testCaseId: p.testCaseId,
testCaseScore: p.testCaseScore ?? [],
@@ -408,18 +392,12 @@ function toProblemBody(problem: AdminProblem | BlankProblem) {
}
export function createProblem(problem: BlankProblem) {
return api.post<AdminProblem>(
"admin/problems",
toProblemBody(problem) satisfies Partial<CreateProblemRequest>,
)
return api.post<AdminProblem>('admin/problems', toProblemBody(problem) satisfies Partial<CreateProblemRequest>)
}
export function createContestProblem(problem: BlankProblem) {
// contestId 由 detail.vue 在提交前写进 problem 对象
return api.post<AdminProblem>(
`admin/contests/${problem.contestId}/problems`,
toProblemBody(problem) satisfies Partial<CreateProblemRequest>,
)
return api.post<AdminProblem>(`admin/contests/${problem.contestId}/problems`, toProblemBody(problem) satisfies Partial<CreateProblemRequest>)
}
/** 组件里的比赛对象是 snake_case,出站转成新后端要的 camelCase */
@@ -436,17 +414,11 @@ function toContestBody(contest: AdminContest | BlankContest) {
}
export function createContest(contest: BlankContest) {
return api.post<AdminContest>(
"admin/contests",
toContestBody(contest) satisfies CreateContestRequest,
)
return api.post<AdminContest>('admin/contests', toContestBody(contest) satisfies CreateContestRequest)
}
export function editContest(contest: AdminContest | BlankContest) {
return api.put<AdminContest>(
`admin/contests/${(contest as AdminContest).id}`,
toContestBody(contest) satisfies UpdateContestRequest,
)
return api.put<AdminContest>(`admin/contests/${(contest as AdminContest).id}`, toContestBody(contest) satisfies UpdateContestRequest)
}
export function cloneContest(contestId: number) {
@@ -472,32 +444,32 @@ export function reorderContestProblems(contestID: string, problemIds: number[])
}
export function getWebsite() {
return api.get<WebsiteConfig>("admin/website")
return api.get<WebsiteConfig>('admin/website')
}
export function editWebsite(data: WebsiteConfig) {
return api.post<WebsiteConfig>("admin/website", data satisfies UpdateWebsiteConfigRequest)
return api.post<WebsiteConfig>('admin/website', data satisfies UpdateWebsiteConfigRequest)
}
export function listInvalidTestcases() {
return api.get<OrphanTestCase[]>("admin/orphan-test-cases")
return api.get<OrphanTestCase[]>('admin/orphan-test-cases')
}
export function pruneInvalidTestcases(id?: string) {
return api.delete("admin/orphan-test-cases", { params: { id } })
return api.delete('admin/orphan-test-cases', { params: { id } })
}
export function listOrphanImages() {
return api.get<OrphanImage[]>("admin/orphan-images")
return api.get<OrphanImage[]>('admin/orphan-images')
}
/** 不带参数是全删;带 folder 只删那个目录的,再带 name 只删一张 */
export function pruneOrphanImages(target?: Pick<OrphanImage, "folder"> & { name?: string }) {
return api.delete<{ deleted: number }>("admin/orphan-images", { params: target })
export function pruneOrphanImages(target?: Pick<OrphanImage, 'folder'> & { name?: string }) {
return api.delete<{ deleted: number }>('admin/orphan-images', { params: target })
}
export function getJudgeServer() {
return api.get<JudgeServerList>("admin/judge-servers")
return api.get<JudgeServerList>('admin/judge-servers')
}
export function deleteJudgeServer(hostname: string) {
@@ -505,7 +477,7 @@ export function deleteJudgeServer(hostname: string) {
}
export function getAnnouncementList(offset = 0, limit = 10) {
return api.get<{ results: AdminAnnouncementListItem[]; total: number }>("admin/announcements", {
return api.get<{ results: AdminAnnouncementListItem[]; total: number }>('admin/announcements', {
params: { offset, limit },
})
}
@@ -520,22 +492,16 @@ export function deleteAnnouncement(id: number) {
export function editAnnouncement(announcement: AnnouncementEdit) {
const { id, ...body } = announcement
return api.put<AdminAnnouncement>(
`admin/announcements/${id}`,
body satisfies UpdateAnnouncementRequest,
)
return api.put<AdminAnnouncement>(`admin/announcements/${id}`, body satisfies UpdateAnnouncementRequest)
}
export function createAnnouncement(announcement: AnnouncementEdit) {
const { id: _id, ...body } = announcement
return api.post<AdminAnnouncement>(
"admin/announcements",
body satisfies CreateAnnouncementRequest,
)
return api.post<AdminAnnouncement>('admin/announcements', body satisfies CreateAnnouncementRequest)
}
export function getTutorialList() {
return api.get<{ [key: string]: TutorialListItem[] }>("admin/tutorials")
return api.get<{ [key: string]: TutorialListItem[] }>('admin/tutorials')
}
export function getTutorial(id: number) {
@@ -555,14 +521,11 @@ function toTutorialBody(data: TutorialEdit) {
}
export function createTutorial(data: TutorialEdit) {
return api.post<Tutorial>("admin/tutorials", toTutorialBody(data) satisfies CreateTutorialRequest)
return api.post<Tutorial>('admin/tutorials', toTutorialBody(data) satisfies CreateTutorialRequest)
}
export function updateTutorial(data: TutorialEdit) {
return api.put<Tutorial>(
`admin/tutorials/${data.id}`,
toTutorialBody(data) satisfies UpdateTutorialRequest,
)
return api.put<Tutorial>(`admin/tutorials/${data.id}`, toTutorialBody(data) satisfies UpdateTutorialRequest)
}
export function setTutorialProblems(id: number, problemIds: number[]) {
@@ -572,17 +535,17 @@ export function setTutorialProblems(id: number, problemIds: number[]) {
}
export function getTutorialProblemCandidates(keyword: string) {
return api.get<TutorialProblemCandidate[]>("admin/tutorial-problem-candidates", {
return api.get<TutorialProblemCandidate[]>('admin/tutorial-problem-candidates', {
params: keyword ? { keyword } : {},
})
}
export function reorderTutorials(ids: number[]) {
return api.put<null>("admin/tutorial-order", { ids } satisfies ReorderTutorialsRequest)
return api.put<null>('admin/tutorial-order', { ids } satisfies ReorderTutorialsRequest)
}
export function renameTutorialProject(type: "python" | "c", from: string, to: string) {
return api.put<null>("admin/tutorial-projects", {
export function renameTutorialProject(type: 'python' | 'c', from: string, to: string) {
return api.put<null>('admin/tutorial-projects', {
type,
from,
to,
@@ -603,22 +566,11 @@ export function getAdminExercises(tutorialId: number) {
return api.get<Exercise[]>(`admin/tutorials/${tutorialId}/exercises`)
}
export async function createExercise(data: {
tutorialId: number
type: ExerciseType
data: Record<string, unknown>
order: number
}) {
return api.post<Exercise>("admin/exercises", data satisfies CreateExerciseRequest)
export async function createExercise(data: { tutorialId: number; type: ExerciseType; data: Record<string, unknown>; order: number }) {
return api.post<Exercise>('admin/exercises', data satisfies CreateExerciseRequest)
}
export async function updateExercise(data: {
id: number
type: ExerciseType
data: Record<string, unknown>
order: number
resetAttempts: boolean
}) {
export async function updateExercise(data: { id: number; type: ExerciseType; data: Record<string, unknown>; order: number; resetAttempts: boolean }) {
return api.put<Exercise>(`admin/exercises/${data.id}`, {
type: data.type,
data: data.data,
@@ -639,12 +591,7 @@ export function makeProblemPublic(id: number, displayId: string) {
}
// 比赛辅助检查
export function updateACMHelperChecked(
contest_id: number,
rank_id: number,
problem_id: string,
checked: boolean,
) {
export function updateACMHelperChecked(contest_id: number, rank_id: number, problem_id: string, checked: boolean) {
return api.put(`admin/contests/${contest_id}/acm-helper`, {
rankId: rank_id,
problemId: problem_id,
@@ -653,8 +600,8 @@ export function updateACMHelperChecked(
}
// 题单管理 API
export function getProblemSetList(offset = 0, limit = 10, keyword = "") {
return api.get<AdminProblemSetList>("admin/problem-sets", {
export function getProblemSetList(offset = 0, limit = 10, keyword = '') {
return api.get<AdminProblemSetList>('admin/problem-sets', {
params: { offset, limit, keyword },
})
}
@@ -672,14 +619,11 @@ export interface ProblemSetBody {
}
export function createProblemSet(data: ProblemSetBody) {
return api.post<AdminProblemSet>("admin/problem-sets", data satisfies CreateProblemSetRequest)
return api.post<AdminProblemSet>('admin/problem-sets', data satisfies CreateProblemSetRequest)
}
export function editProblemSet(id: number, data: ProblemSetBody) {
return api.put<AdminProblemSet>(
`admin/problem-sets/${id}`,
data satisfies UpdateProblemSetRequest,
)
return api.put<AdminProblemSet>(`admin/problem-sets/${id}`, data satisfies UpdateProblemSetRequest)
}
export function deleteProblemSet(id: number) {
@@ -727,22 +671,16 @@ export interface BadgeBody {
name: string
description: string
icon: string
conditionType: AdminProblemSetBadge["conditionType"]
conditionType: AdminProblemSetBadge['conditionType']
conditionValue: number
}
export function createProblemSetBadge(problemSetId: number, data: BadgeBody) {
return api.post<AdminProblemSetBadge>(
`admin/problem-sets/${problemSetId}/badges`,
data satisfies CreateProblemSetBadgeRequest,
)
return api.post<AdminProblemSetBadge>(`admin/problem-sets/${problemSetId}/badges`, data satisfies CreateProblemSetBadgeRequest)
}
export function editProblemSetBadge(problemSetId: number, badgeId: number, data: BadgeBody) {
return api.put<AdminProblemSetBadge>(
`admin/problem-sets/${problemSetId}/badges/${badgeId}`,
data satisfies UpdateProblemSetBadgeRequest,
)
return api.put<AdminProblemSetBadge>(`admin/problem-sets/${problemSetId}/badges/${badgeId}`, data satisfies UpdateProblemSetBadgeRequest)
}
export function deleteProblemSetBadge(problemSetId: number, badgeId: number) {
@@ -751,41 +689,38 @@ export function deleteProblemSetBadge(problemSetId: number, badgeId: number) {
// 卡点分析:start 是时间段的起点(ISO),不给就是全部时间
export function getStuckProblems(params: { className?: string; start?: string }) {
return api.get<StuckProblem[]>("admin/problem-analytics/stuck", { params })
return api.get<StuckProblem[]>('admin/problem-analytics/stuck', { params })
}
export function getStuckProblemDetail(id: number, params: { className?: string; start?: string }) {
return api.get<StuckProblemDetail>(`admin/problem-analytics/stuck/${id}`, { params })
}
export function getLearnBoard(params: { type: "python" | "c"; className?: string }) {
return api.get<LearnBoard>("admin/learn-analytics/board", { params })
export function getLearnBoard(params: { type: 'python' | 'c'; className?: string }) {
return api.get<LearnBoard>('admin/learn-analytics/board', { params })
}
export function getLearnExercises(params: { type: "python" | "c"; className?: string }) {
return api.get<LearnExerciseProgressList>("admin/learn-analytics/exercises", {
export function getLearnExercises(params: { type: 'python' | 'c'; className?: string }) {
return api.get<LearnExerciseProgressList>('admin/learn-analytics/exercises', {
params,
})
}
export function getLearnExerciseAttempts(exerciseId: number, params: { className?: string }) {
return api.get<LearnExerciseAttemptList>(
`admin/learn-analytics/exercises/${exerciseId}/attempts`,
{ params },
)
return api.get<LearnExerciseAttemptList>(`admin/learn-analytics/exercises/${exerciseId}/attempts`, { params })
}
export function getLearnStudent(userId: number, params: { type: "python" | "c" }) {
export function getLearnStudent(userId: number, params: { type: 'python' | 'c' }) {
return api.get<LearnStudentDetail>(`admin/learn-analytics/students/${userId}`, { params })
}
export function getGradeTrend(params: { grade?: string; compare?: string }) {
return api.get<GradeTrend>("admin/problem-analytics/grades", { params })
return api.get<GradeTrend>('admin/problem-analytics/grades', { params })
}
// AI 学习分析报告
export function getAIReportList(offset = 0, limit = 10, username = "") {
return api.get<AdminAiReportList>("admin/ai/reports", {
export function getAIReportList(offset = 0, limit = 10, username = '') {
return api.get<AdminAiReportList>('admin/ai/reports', {
params: { offset, limit, username: username || undefined },
})
}
@@ -799,18 +734,14 @@ export function pinAIReport(id: number) {
}
export function getPinnedAIReports() {
return api.get<AdminAiReportList>("admin/ai/reports", {
params: { pinnedOnly: "true" },
return api.get<AdminAiReportList>('admin/ai/reports', {
params: { pinnedOnly: 'true' },
})
}
// ==================== 成就 ====================
import type {
AdminAchievement,
AchievementMetric as MetricOption,
AdminUserRank,
} from "@oj2/contract"
import type { AdminAchievement, AchievementMetric as MetricOption, AdminUserRank } from '@oj2/contract'
export type { AdminAchievement, MetricOption }
function toAchievementBody(data: Partial<AdminAchievement>) {
@@ -829,25 +760,19 @@ function toAchievementBody(data: Partial<AdminAchievement>) {
}
export function getAdminAchievements() {
return api.get<AdminAchievement[]>("admin/achievements")
return api.get<AdminAchievement[]>('admin/achievements')
}
export function getMetricOptions() {
return api.get<MetricOption[]>("admin/achievement-metrics")
return api.get<MetricOption[]>('admin/achievement-metrics')
}
export function createAchievement(data: Partial<AdminAchievement>) {
return api.post<AdminAchievement>(
"admin/achievements",
toAchievementBody(data) satisfies Partial<CreateAchievementRequest>,
)
return api.post<AdminAchievement>('admin/achievements', toAchievementBody(data) satisfies Partial<CreateAchievementRequest>)
}
export function updateAchievement(data: Partial<AdminAchievement>) {
return api.put<AdminAchievement>(
`admin/achievements/${data.id}`,
toAchievementBody(data) satisfies Partial<UpdateAchievementRequest>,
)
return api.put<AdminAchievement>(`admin/achievements/${data.id}`, toAchievementBody(data) satisfies Partial<UpdateAchievementRequest>)
}
export function deleteAchievement(id: number) {
+5 -11
View File
@@ -1,15 +1,9 @@
<template>
<n-select
style="width: 140px"
v-model:value="author"
remote
@update:show="getAuthorOptions"
:options="authorOptions"
/>
<n-select style="width: 140px" v-model:value="author" remote @update:show="getAuthorOptions" :options="authorOptions" />
</template>
<script setup lang="ts">
import { getAuthors } from "shared/api"
import { getAuthors } from 'shared/api'
interface Props {
all?: boolean
@@ -17,12 +11,12 @@ interface Props {
const { all = false } = defineProps<Props>()
const author = defineModel<string>("value")
const author = defineModel<string>('value')
const authorOptions = ref([{ label: "全部", value: "" }])
const authorOptions = ref([{ label: '全部', value: '' }])
async function getAuthorOptions() {
authorOptions.value = [{ label: "全部", value: "" }]
authorOptions.value = [{ label: '全部', value: '' }]
const res = await getAuthors(all)
const remotes = res.map((item) => ({
label: `${item.username} (${item.problemCount})`,
+2 -2
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import type { RouteLocationRaw } from "vue-router"
import { Icon } from '@iconify/vue'
import type { RouteLocationRaw } from 'vue-router'
/**
* 后台每一页顶上的那一块:标题行(返回 · 标题 · 标签 ········ 操作按钮),
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import type { AdminContest } from "utils/types"
import { cloneContest } from "../../api"
import { useBreakpoints } from "shared/composables/breakpoints"
import type { AdminContest } from 'utils/types'
import { cloneContest } from '../../api'
import { useBreakpoints } from 'shared/composables/breakpoints'
interface Props {
contest: AdminContest
@@ -14,30 +14,30 @@ const { isMobile } = useBreakpoints()
function goEdit() {
router.push({
name: "admin contest edit",
name: 'admin contest edit',
params: { contestID: props.contest.id },
})
}
// 原来的「审核」页并进了前台比赛页老师的「全班情况 / 成绩」:点格子看代码、标看过了
function goClass() {
window.open(`/contest/${props.contest.id}/class`, "_blank")
window.open(`/contest/${props.contest.id}/class`, '_blank')
}
function openFront() {
window.open(`/contest/${props.contest.id}`, "_blank")
window.open(`/contest/${props.contest.id}`, '_blank')
}
async function clone() {
try {
const res = await cloneContest(props.contest.id)
message.success("复制成功")
message.success('复制成功')
router.push({
name: "admin contest edit",
name: 'admin contest edit',
params: { contestID: res.id },
})
} catch {
message.error("复制失败")
message.error('复制失败')
}
}
</script>
@@ -46,7 +46,7 @@ async function clone() {
<n-flex :size="4" :wrap="isMobile">
<n-button size="small" @click="goEdit">编辑</n-button>
<n-button size="small" @click="goClass">
{{ contest.status === "-1" ? "成绩" : "全班情况" }}
{{ contest.status === '-1' ? '成绩' : '全班情况' }}
</n-button>
<n-button size="small" @click="clone">复制一份</n-button>
<n-button size="small" title="在前台打开这场比赛" @click="openFront">前台看</n-button>
+65 -143
View File
@@ -1,11 +1,11 @@
<script setup lang="ts">
import { useThemeVars } from "naive-ui"
import PageHeader from "admin/components/PageHeader.vue"
import { errorCode, errorMessage } from "utils/api"
import TextEditor from "shared/components/TextEditor.vue"
import { DIFFICULTY } from "utils/constants"
import { fromPickerValue, parseTime, toPickerValue } from "utils/functions"
import type { AdminProblemRow, BlankContest } from "utils/types"
import { useThemeVars } from 'naive-ui'
import PageHeader from 'admin/components/PageHeader.vue'
import { errorCode, errorMessage } from 'utils/api'
import TextEditor from 'shared/components/TextEditor.vue'
import { DIFFICULTY } from 'utils/constants'
import { fromPickerValue, parseTime, toPickerValue } from 'utils/functions'
import type { AdminProblemRow, BlankContest } from 'utils/types'
import {
addProblemForContest,
createContest,
@@ -15,7 +15,7 @@ import {
getLibraryProblemList,
getProblemList,
reorderContestProblems,
} from "../api"
} from '../api'
/**
* 新建 / 编辑比赛,一屏做完(设计稿「比赛重设计」后台那块):左边名字、类型、时间、密码,
@@ -38,12 +38,12 @@ const saving = ref(false)
const contest = reactive<BlankContest & { id: number }>({
id: 0,
title: "",
description: "",
tag: "练习",
startTime: "",
endTime: "",
password: "",
title: '',
description: '',
tag: '练习',
startTime: '',
endTime: '',
password: '',
// 不列出来学生就进不去(隐藏比赛对学生是 404),新建默认就列出来
visible: true,
})
@@ -68,21 +68,17 @@ function roundedNow() {
return ms - (ms % 60_000)
}
const startMs = computed(() =>
waitMins.value !== null
? roundedNow() + waitMins.value * 60_000
: fromPickerValue(pickedStart.value),
)
const startMs = computed(() => (waitMins.value !== null ? roundedNow() + waitMins.value * 60_000 : fromPickerValue(pickedStart.value)))
const endMs = computed(() => startMs.value + durationMins.value * 60_000)
const WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"]
const WEEKDAYS = ['日', '一', '二', '三', '四', '五', '六']
const timeHint = computed(() => {
const start = new Date(startMs.value).toISOString()
const end = new Date(endMs.value).toISOString()
// 东八区的星期几:平移 8 小时后读 UTC
const weekday = WEEKDAYS[new Date(startMs.value + 8 * 3600_000).getUTCDay()]
const sameDay = parseTime(start, "YYYY-MM-DD") === parseTime(end, "YYYY-MM-DD")
return `${parseTime(start, "M月D日")} 周${weekday} ${parseTime(start, "HH:mm")} 开始,${parseTime(end, sameDay ? "HH:mm" : "M月D日 HH:mm")} 结束`
const sameDay = parseTime(start, 'YYYY-MM-DD') === parseTime(end, 'YYYY-MM-DD')
return `${parseTime(start, 'M月D日')} 周${weekday} ${parseTime(start, 'HH:mm')} 开始,${parseTime(end, sameDay ? 'HH:mm' : 'M月D日 HH:mm')} 结束`
})
function pickWait(minutes: number | null) {
@@ -104,7 +100,7 @@ const items = ref<Item[]>([])
const pickedPublic = computed(() => new Set(items.value.map((item) => item.id)))
async function loadContestProblems() {
const res = await getProblemList(0, 250, "", undefined, props.contestID)
const res = await getProblemList(0, 250, '', undefined, props.contestID)
items.value = res.results
.map((row: AdminProblemRow) => ({
id: row.id,
@@ -112,12 +108,10 @@ async function loadContestProblems() {
title: row.title,
difficulty: row.difficulty,
}))
.sort(
(a, b) => a.displayId.length - b.displayId.length || a.displayId.localeCompare(b.displayId),
)
.sort((a, b) => a.displayId.length - b.displayId.length || a.displayId.localeCompare(b.displayId))
}
const keyword = ref("")
const keyword = ref('')
const results = ref<AdminProblemRow[]>([])
const searching = ref(false)
watchDebounced(
@@ -139,9 +133,7 @@ watchDebounced(
/** 编辑时比赛题是复制品,没法知道它从哪道公开题来,按题名比一下防重复 */
function added(row: AdminProblemRow) {
return editing.value
? items.value.some((item) => item.title === row.title)
: pickedPublic.value.has(row.id)
return editing.value ? items.value.some((item) => item.title === row.title) : pickedPublic.value.has(row.id)
}
async function add(row: AdminProblemRow) {
@@ -160,13 +152,7 @@ async function add(row: AdminProblemRow) {
await loadContestProblems()
} catch (err) {
const code = errorCode(err)
message.error(
code === "contest-ended"
? "比赛已经结束,不能再加题"
: code === "display-id-exists"
? "题号重了,刷新一下再加"
: errorMessage(err),
)
message.error(code === 'contest-ended' ? '比赛已经结束,不能再加题' : code === 'display-id-exists' ? '题号重了,刷新一下再加' : errorMessage(err))
}
}
@@ -177,21 +163,17 @@ function remove(item: Item) {
return
}
dialog.warning({
title: "从比赛里删掉这道题?",
title: '从比赛里删掉这道题?',
content: `第 ${item.displayId} 题「${item.title}」。已经有人交过的题删不掉。`,
positiveText: "删掉",
negativeText: "不删",
positiveText: '删掉',
negativeText: '不删',
onPositiveClick: async () => {
try {
await deleteContestProblem(item.id)
await loadContestProblems()
if (items.value.length) await saveOrder()
} catch (err) {
message.error(
errorCode(err) === "problem-has-submissions"
? "已经有人交过这道题,删不掉;不想让学生看到可以在题目里关掉「可见」"
: errorMessage(err),
)
message.error(errorCode(err) === 'problem-has-submissions' ? '已经有人交过这道题,删不掉;不想让学生看到可以在题目里关掉「可见」' : errorMessage(err))
}
},
})
@@ -237,7 +219,7 @@ function onDragEnd() {
function editProblem(item: Item) {
router.push({
name: "admin contest problem edit",
name: 'admin contest problem edit',
params: { contestID: props.contestID, problemID: item.id },
})
}
@@ -245,7 +227,7 @@ function editProblem(item: Item) {
// ---------------------------------------------------------------- 载入 / 保存
async function load() {
keyword.value = ""
keyword.value = ''
if (!props.contestID) {
ready.value = true
return
@@ -272,33 +254,31 @@ async function load() {
async function submit() {
if (!contest.title.trim()) {
message.error("比赛还没起名字")
message.error('比赛还没起名字')
return
}
if (durationMins.value <= 0) {
message.error("时长要大于 0")
message.error('时长要大于 0')
return
}
contest.startTime = new Date(startMs.value).toISOString()
contest.endTime = new Date(endMs.value).toISOString()
if (!contest.description || contest.description === "<p><br></p>") {
if (!contest.description || contest.description === '<p><br></p>') {
contest.description = contest.title
}
saving.value = true
try {
if (editing.value) {
await editContest(contest)
message.success("改好了")
message.success('改好了')
return
}
const created = await createContest(contest)
for (const [index, item] of items.value.entries()) {
await addProblemForContest(String(created.id), item.id, String(index + 1))
}
message.success(
items.value.length ? `比赛建好了,${items.value.length} 道题都加进去了` : "比赛建好了",
)
router.replace({ name: "admin contest edit", params: { contestID: created.id } })
message.success(items.value.length ? `比赛建好了,${items.value.length} 道题都加进去了` : '比赛建好了')
router.replace({ name: 'admin contest edit', params: { contestID: created.id } })
} catch (err) {
message.error(errorMessage(err))
} finally {
@@ -313,9 +293,7 @@ onMounted(load)
<template>
<PageHeader :title="editing ? '编辑比赛' : '新建比赛'" :back="{ name: 'admin contest list' }">
<template v-if="editing" #actions>
<n-button tag="a" :href="`/contest/${contestID}/class`" target="_blank">
到前台看这场比赛
</n-button>
<n-button tag="a" :href="`/contest/${contestID}/class`" target="_blank"> 到前台看这场比赛 </n-button>
</template>
</PageHeader>
@@ -334,9 +312,7 @@ onMounted(load)
<n-radio-button value="期中">期中</n-radio-button>
<n-radio-button value="期末">期末</n-radio-button>
</n-radio-group>
<span class="hint">
练习:学生边做边看排名。期中、期末:考试中学生看不到排名和每题做对人数,考完一起公布。
</span>
<span class="hint"> 练习:学生边做边看排名。期中、期末:考试中学生看不到排名和每题做对人数,考完一起公布。 </span>
</div>
</div>
@@ -345,26 +321,10 @@ onMounted(load)
<div class="stack">
<n-flex :size="6">
<template v-if="!editing">
<button
v-for="m in WAIT_CHOICES"
:key="m"
class="chip"
:class="{ on: waitMins === m }"
@click="pickWait(m)"
>
{{ m }} 分钟后
</button>
<button class="chip" :class="{ on: waitMins === null }" @click="pickWait(null)">
选时间…
</button>
<button v-for="m in WAIT_CHOICES" :key="m" class="chip" :class="{ on: waitMins === m }" @click="pickWait(m)">{{ m }} 分钟后</button>
<button class="chip" :class="{ on: waitMins === null }" @click="pickWait(null)">选时间…</button>
</template>
<n-date-picker
v-if="waitMins === null"
v-model:value="pickedStart"
type="datetime"
format="yyyy-MM-dd HH:mm"
style="width: 200px"
/>
<n-date-picker v-if="waitMins === null" v-model:value="pickedStart" type="datetime" format="yyyy-MM-dd HH:mm" style="width: 200px" />
</n-flex>
</div>
</div>
@@ -373,25 +333,11 @@ onMounted(load)
<span class="label">时长</span>
<div class="stack">
<n-flex :size="6" align="center">
<button
v-for="m in DURATION_CHOICES"
:key="m"
class="chip"
:class="{ on: !customDuration && durationMins === m }"
@click="pickDuration(m)"
>
{{ m === 60 ? "1 小时" : `${m} 分钟` }}
<button v-for="m in DURATION_CHOICES" :key="m" class="chip" :class="{ on: !customDuration && durationMins === m }" @click="pickDuration(m)">
{{ m === 60 ? '1 小时' : `${m} 分钟` }}
</button>
<button class="chip" :class="{ on: customDuration }" @click="pickDuration(null)">
自己填
</button>
<n-input-number
v-if="customDuration"
v-model:value="durationMins"
:min="1"
:step="5"
style="width: 130px"
>
<button class="chip" :class="{ on: customDuration }" @click="pickDuration(null)">自己填</button>
<n-input-number v-if="customDuration" v-model:value="durationMins" :min="1" :step="5" style="width: 130px">
<template #suffix>分钟</template>
</n-input-number>
</n-flex>
@@ -407,9 +353,7 @@ onMounted(load)
<div class="field">
<span class="label">列出来</span>
<n-switch v-model:value="contest.visible" />
<span class="hint">{{
contest.visible ? "学生在比赛列表里看得到" : "藏起来,学生进不去"
}}</span>
<span class="hint">{{ contest.visible ? '学生在比赛列表里看得到' : '藏起来,学生进不去' }}</span>
</div>
<div class="field top">
@@ -432,18 +376,8 @@ onMounted(load)
<span class="hint">{{ items.length }} 道 · 拖动排顺序,题号自动按 1、2、3 排</span>
</div>
<div class="search">
<n-input
v-model:value="keyword"
clearable
:loading="searching"
placeholder="输入题号或题目名,从题库里加"
/>
<n-button
v-if="editing"
@click="router.push({ name: 'admin contest problem create', params: { contestID } })"
>
+ 新出一道
</n-button>
<n-input v-model:value="keyword" clearable :loading="searching" placeholder="输入题号或题目名,从题库里加" />
<n-button v-if="editing" @click="router.push({ name: 'admin contest problem create', params: { contestID } })"> + 新出一道 </n-button>
<n-tooltip v-else>
<template #trigger>
<n-button disabled>+ 新出一道</n-button>
@@ -476,25 +410,13 @@ onMounted(load)
<span class="grip" aria-hidden="true">⋮⋮</span>
<b class="num">{{ item.displayId }}</b>
<span class="ell grow">{{ item.title }}</span>
<span class="muted tiny">{{
DIFFICULTY[item.difficulty as keyof typeof DIFFICULTY]
}}</span>
<n-button v-if="editing" size="small" text type="primary" @click="editProblem(item)"
>改</n-button
>
<n-button
size="small"
text
:aria-label="`删掉第 ${item.displayId} 题`"
@click="remove(item)"
>✕</n-button
>
<span class="muted tiny">{{ DIFFICULTY[item.difficulty as keyof typeof DIFFICULTY] }}</span>
<n-button v-if="editing" size="small" text type="primary" @click="editProblem(item)">改</n-button>
<n-button size="small" text :aria-label="`删掉第 ${item.displayId} 题`" @click="remove(item)">✕</n-button>
</div>
</div>
<div v-else class="empty hint">还没加题。在上面输入题号,比如 2033</div>
<span class="hint">
从题库加的题会复制一份进比赛:比赛里改它不影响原题,学生在题库里也搜不到比赛题。
</span>
<span class="hint"> 从题库加的题会复制一份进比赛:比赛里改它不影响原题,学生在题库里也搜不到比赛题。 </span>
</section>
</div>
</template>
@@ -513,9 +435,9 @@ onMounted(load)
display: flex;
flex-direction: column;
gap: 16px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.form {
@@ -547,7 +469,7 @@ onMounted(load)
width: 52px;
flex-shrink: 0;
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
}
.stack {
@@ -565,11 +487,11 @@ onMounted(load)
.hint {
font-size: 12px;
line-height: 1.6;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.tiny {
@@ -592,17 +514,17 @@ onMounted(load)
height: 28px;
padding: 0 12px;
border-radius: 14px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
background: transparent;
font: inherit;
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
cursor: pointer;
}
.chip.on {
border-color: v-bind("theme.primaryColor");
color: v-bind("theme.primaryColor");
border-color: v-bind('theme.primaryColor');
color: v-bind('theme.primaryColor');
font-weight: 600;
}
@@ -611,7 +533,7 @@ onMounted(load)
align-items: center;
gap: 10px;
padding-top: 12px;
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
}
.picker-head {
@@ -627,7 +549,7 @@ onMounted(load)
.results,
.list {
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
overflow: hidden;
}
@@ -649,12 +571,12 @@ onMounted(load)
.result + .result,
.item + .item {
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
}
.item {
cursor: grab;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.item.dragging {
@@ -662,7 +584,7 @@ onMounted(load)
}
.grip {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
letter-spacing: -3px;
}
+49 -73
View File
@@ -1,15 +1,15 @@
<script setup lang="ts">
import type { AdminContestListItem } from "@oj2/contract"
import PageHeader from "admin/components/PageHeader.vue"
import { NSwitch, useThemeVars } from "naive-ui"
import ContestTitle from "shared/components/ContestTitle.vue"
import Pagination from "shared/components/Pagination.vue"
import { CONTEST_STATUS } from "utils/constants"
import { parseTime } from "utils/functions"
import { editContest, getContestList } from "../api"
import Actions from "./components/Actions.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import type { AdminContestListItem } from '@oj2/contract'
import PageHeader from 'admin/components/PageHeader.vue'
import { NSwitch, useThemeVars } from 'naive-ui'
import ContestTitle from 'shared/components/ContestTitle.vue'
import Pagination from 'shared/components/Pagination.vue'
import { CONTEST_STATUS } from 'utils/constants'
import { parseTime } from 'utils/functions'
import { editContest, getContestList } from '../api'
import Actions from './components/Actions.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
/**
* 后台比赛列表(设计稿「比赛重设计」CtAdminList)。一行一场:比赛名(期中 / 期末挂标,
@@ -24,7 +24,7 @@ const total = ref(0)
const query = reactive({
limit: 10,
page: 1,
keyword: "",
keyword: '',
})
function toggleVisible(contest: AdminContestListItem) {
@@ -44,31 +44,24 @@ function duration(row: AdminContestListItem) {
return `${Math.round(minutes / 1440)} 天`
}
const EXAM_TAGS = ["期中", "期末"]
const EXAM_TAGS = ['期中', '期末']
function renderTitle(row: AdminContestListItem) {
return h("span", { class: "title-cell" }, [
h(ContestTitle, { contest: row }),
EXAM_TAGS.includes(row.tag) ? h("span", { class: "exam" }, row.tag) : null,
])
return h('span', { class: 'title-cell' }, [h(ContestTitle, { contest: row }), EXAM_TAGS.includes(row.tag) ? h('span', { class: 'exam' }, row.tag) : null])
}
function renderStatus(row: AdminContestListItem) {
return h(
"span",
{ class: row.status === "0" ? "live" : row.status === "-1" ? "muted" : "" },
row.status === "-1"
? "结束了"
: row.status === "0"
? "进行中"
: CONTEST_STATUS[row.status].name,
'span',
{ class: row.status === '0' ? 'live' : row.status === '-1' ? 'muted' : '' },
row.status === '-1' ? '结束了' : row.status === '0' ? '进行中' : CONTEST_STATUS[row.status].name,
)
}
function renderVisible(row: AdminContestListItem) {
return h(NSwitch, {
value: row.visible,
size: isMobile.value ? "medium" : "small",
size: isMobile.value ? 'medium' : 'small',
rubberBand: false,
onUpdateValue: () => toggleVisible(row),
})
@@ -80,75 +73,71 @@ function renderVisible(row: AdminContestListItem) {
*/
function renderMobileCard(row: AdminContestListItem) {
const items = [
h("span", { class: "num" }, parseTime(row.startTime, "YYYY-MM-DD HH:mm")),
h('span', { class: 'num' }, parseTime(row.startTime, 'YYYY-MM-DD HH:mm')),
duration(row),
renderStatus(row),
`${row.problemCount} 题`,
row.participantCount ? `${row.participantCount} 人参加` : null,
row.createdBy.username,
].filter((it) => it !== null)
return h("div", { class: "m-card" }, [
return h('div', { class: 'm-card' }, [
renderTitle(row),
h(
"div",
{ class: "m-meta muted" },
items.map((it, i) => h("span", { class: "m-item", key: i }, i ? [" · ", it] : [it])),
'div',
{ class: 'm-meta muted' },
items.map((it, i) => h('span', { class: 'm-item', key: i }, i ? [' · ', it] : [it])),
),
h(Actions, { contest: row }),
])
}
const mobileColumns: DataTableColumn<AdminContestListItem>[] = [
{ title: "比赛", key: "title", render: renderMobileCard },
{ title: "看得到", key: "visible", width: 72, align: "center", render: renderVisible },
{ title: '比赛', key: 'title', render: renderMobileCard },
{ title: '看得到', key: 'visible', width: 72, align: 'center', render: renderVisible },
]
const desktopColumns: DataTableColumn<AdminContestListItem>[] = [
{
title: "比赛",
key: "title",
title: '比赛',
key: 'title',
width: 260,
render: renderTitle,
},
{
title: "开始 · 多长",
key: "start_time",
title: '开始 · 多长',
key: 'start_time',
width: 200,
render: (row) =>
h("span", { class: "num" }, [
parseTime(row.startTime, "YYYY-MM-DD HH:mm"),
h("span", { class: "muted" }, ` · ${duration(row)}`),
]),
render: (row) => h('span', { class: 'num' }, [parseTime(row.startTime, 'YYYY-MM-DD HH:mm'), h('span', { class: 'muted' }, ` · ${duration(row)}`)]),
},
{
title: "状态",
key: "status",
title: '状态',
key: 'status',
width: 72,
render: renderStatus,
},
{ title: "题", key: "problemCount", width: 56 },
{ title: '题', key: 'problemCount', width: 56 },
{
title: "参加",
key: "participantCount",
title: '参加',
key: 'participantCount',
width: 64,
render: (row) => (row.participantCount ? String(row.participantCount) : "—"),
render: (row) => (row.participantCount ? String(row.participantCount) : '—'),
},
{
title: "出卷",
key: "created_by",
title: '出卷',
key: 'created_by',
width: 84,
ellipsis: { tooltip: true },
render: (row) => row.createdBy.username,
},
{
title: "学生看得到",
key: "visible",
title: '学生看得到',
key: 'visible',
width: 96,
render: renderVisible,
},
{
title: "",
key: "actions",
title: '',
key: 'actions',
minWidth: 270,
render: (row) => h(Actions, { contest: row }),
},
@@ -175,26 +164,13 @@ watchDebounced(() => query.keyword, listContests, {
<template>
<PageHeader title="比赛">
<template #actions>
<n-button type="primary" @click="$router.push({ name: 'admin contest create' })">
新建比赛
</n-button>
<n-button type="primary" @click="$router.push({ name: 'admin contest create' })"> 新建比赛 </n-button>
</template>
<template #filters>
<n-input
v-model:value="query.keyword"
placeholder="比赛名"
clearable
:style="{ width: isMobile ? '100%' : '220px' }"
/>
<n-input v-model:value="query.keyword" placeholder="比赛名" clearable :style="{ width: isMobile ? '100%' : '220px' }" />
</template>
</PageHeader>
<n-data-table
:loading="loading"
striped
class="contest-table"
:columns="columns"
:data="contests"
/>
<n-data-table :loading="loading" striped class="contest-table" :columns="columns" :data="contests" />
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
</template>
@@ -236,8 +212,8 @@ watchDebounced(() => query.keyword, listContests, {
border-radius: 3px;
font-size: 12px;
font-weight: 400;
color: v-bind("theme.errorColor");
background: v-bind("theme.actionColor");
color: v-bind('theme.errorColor');
background: v-bind('theme.actionColor');
}
.contest-table :deep(.num) {
@@ -246,11 +222,11 @@ watchDebounced(() => query.keyword, listContests, {
}
.contest-table :deep(.muted) {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.contest-table :deep(.live) {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
font-weight: 600;
}
</style>
+27 -45
View File
@@ -1,10 +1,10 @@
<script setup lang="ts">
import { NText } from "naive-ui"
import { getLearnExerciseAttempts } from "admin/api"
import { parseTime } from "utils/functions"
import type { LearnExerciseAttempt } from "utils/types"
import UserName from "shared/components/UserName.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { NText } from 'naive-ui'
import { getLearnExerciseAttempts } from 'admin/api'
import { parseTime } from 'utils/functions'
import type { LearnExerciseAttempt } from 'utils/types'
import UserName from 'shared/components/UserName.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
const props = defineProps<{ exerciseId: number; className: string }>()
const { isMobile } = useBreakpoints()
@@ -14,57 +14,53 @@ const rows = ref<LearnExerciseAttempt[]>([])
const untried = ref<{ userId: number; username: string }[]>([])
function renderResult(row: LearnExerciseAttempt) {
return row.solved
? h(NText, { type: "success" }, () => `做对了(第 ${row.attemptsToSolve} 次)`)
: h(NText, { type: "error" }, () => "还没做对")
return row.solved ? h(NText, { type: 'success' }, () => `做对了(第 ${row.attemptsToSolve} 次)`) : h(NText, { type: 'error' }, () => '还没做对')
}
const desktopColumns: DataTableColumn<LearnExerciseAttempt>[] = [
// 一个弹框只看一个班,班级列多余;用户名里本来就带名字,不再单列真名
{
title: "学生",
key: "username",
title: '学生',
key: 'username',
width: 140,
render: (row) => h(UserName, { username: row.username }),
},
{
title: "结果",
key: "solved",
title: '结果',
key: 'solved',
width: 130,
render: renderResult,
},
{ title: "提交次数", key: "attempts", width: 110, sorter: "default" },
{ title: '提交次数', key: 'attempts', width: 110, sorter: 'default' },
{
// 学生最后一次做错时提交的内容,前端拼好的一句人话。选择题看这一列
// 就知道全班是不是都掉进同一个干扰项
title: "最后一次错在",
key: "lastWrongAnswer",
title: '最后一次错在',
key: 'lastWrongAnswer',
minWidth: 180,
ellipsis: { tooltip: true },
render: (row) => row.lastWrongAnswer || "-",
render: (row) => row.lastWrongAnswer || '-',
},
{
title: "最后作答",
key: "lastAttemptAt",
title: '最后作答',
key: 'lastAttemptAt',
width: 120,
render: (row) => parseTime(row.lastAttemptAt, "M月D日 HH:mm"),
render: (row) => parseTime(row.lastAttemptAt, 'M月D日 HH:mm'),
},
]
/** 手机上五列放不下:一个人一格,名字和结果一行,下面一行小字是交了几次、最后错在哪 */
const mobileColumns: DataTableColumn<LearnExerciseAttempt>[] = [
{
title: "学生",
key: "username",
title: '学生',
key: 'username',
render: (row) =>
h("div", { class: "m-row" }, [
h("div", { class: "m-line" }, [h(UserName, { username: row.username }), renderResult(row)]),
h('div', { class: 'm-row' }, [
h('div', { class: 'm-line' }, [h(UserName, { username: row.username }), renderResult(row)]),
h(
NText,
{ depth: 3, class: "m-sub" },
() =>
`交了 ${row.attempts} 次 · ${parseTime(row.lastAttemptAt, "M月D日 HH:mm")}` +
(row.lastWrongAnswer ? ` · 最后错在 ${row.lastWrongAnswer}` : ""),
{ depth: 3, class: 'm-sub' },
() => `交了 ${row.attempts} 次 · ${parseTime(row.lastAttemptAt, 'M月D日 HH:mm')}` + (row.lastWrongAnswer ? ` · 最后错在 ${row.lastWrongAnswer}` : ''),
),
]),
},
@@ -86,29 +82,15 @@ onMounted(async () => {
</script>
<template>
<n-data-table
striped
:loading="loading"
:columns="columns"
:data="rows"
size="small"
:pagination="rows.length > 10 ? { pageSize: 10 } : false"
/>
<n-empty
v-if="!loading && rows.length === 0"
description="还没有人做过这道练习"
size="small"
style="padding: 16px 0"
/>
<n-data-table striped :loading="loading" :columns="columns" :data="rows" size="small" :pagination="rows.length > 10 ? { pageSize: 10 } : false" />
<n-empty v-if="!loading && rows.length === 0" description="还没有人做过这道练习" size="small" style="padding: 16px 0" />
<div v-if="untried.length" class="untried">
<div class="untried-head">
<span class="strong">读了这课还没做</span>
<n-text depth="3">{{ untried.length }} 人</n-text>
</div>
<div class="chips">
<span v-for="row in untried" :key="row.userId" class="chip"
><UserName :username="row.username"
/></span>
<span v-for="row in untried" :key="row.userId" class="chip"><UserName :username="row.username" /></span>
</div>
</div>
</template>
+21 -27
View File
@@ -1,19 +1,19 @@
<script lang="ts">
import type { LearnBoardStudent } from "utils/types"
import type { LearnBoardStudent } from 'utils/types'
/** 读过这课的一个人,和他在这道配套题上的情况(一次没交是 null) */
export interface ProblemReader {
userId: number
username: string
state: LearnBoardStudent["problems"][number] | null
state: LearnBoardStudent['problems'][number] | null
}
</script>
<script setup lang="ts">
import { NText } from "naive-ui"
import { parseTime } from "utils/functions"
import UserName from "shared/components/UserName.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { NText } from 'naive-ui'
import { parseTime } from 'utils/functions'
import UserName from 'shared/components/UserName.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
/**
* 一道配套题,读过这课的人各自做没做对。数据就是方块格那份,不另外请求。
@@ -31,49 +31,43 @@ function rank(row: ProblemReader) {
const rows = computed(() => [...props.people].sort((a, b) => rank(a) - rank(b)))
function renderResult(row: ProblemReader) {
if (!row.state) return h(NText, { depth: 3 }, () => "没交")
return row.state.solved
? h(NText, { type: "success" }, () => "做对了")
: h(NText, { type: "error" }, () => `交了 ${row.state!.submissions} 次还没对`)
if (!row.state) return h(NText, { depth: 3 }, () => '没交')
return row.state.solved ? h(NText, { type: 'success' }, () => '做对了') : h(NText, { type: 'error' }, () => `交了 ${row.state!.submissions} 次还没对`)
}
/** 提交列表按这个人、这道题筛好,新标签页打开,后台这页不动 */
function renderLink(row: ProblemReader) {
if (!row.state) return null
const { href } = router.resolve({
path: "/submission",
query: { problem: props.displayId, username: row.username, exactUsername: "1" },
path: '/submission',
query: { problem: props.displayId, username: row.username, exactUsername: '1' },
})
return h("a", { href, target: "_blank", class: "link" }, "看提交")
return h('a', { href, target: '_blank', class: 'link' }, '看提交')
}
const desktopColumns: DataTableColumn<ProblemReader>[] = [
{
title: "学生",
key: "username",
title: '学生',
key: 'username',
width: 150,
render: (row) => h(UserName, { username: row.username }),
},
{ title: "结果", key: "result", width: 150, render: renderResult },
{ title: '结果', key: 'result', width: 150, render: renderResult },
{
title: "最后提交",
key: "lastSubmitAt",
title: '最后提交',
key: 'lastSubmitAt',
width: 150,
render: (row) =>
row.state ? parseTime(row.state.lastSubmitAt, "YYYY年M月D日") : h(NText, { depth: 3 }, "-"),
render: (row) => (row.state ? parseTime(row.state.lastSubmitAt, 'YYYY年M月D日') : h(NText, { depth: 3 }, '-')),
},
{ title: "", key: "link", render: renderLink },
{ title: '', key: 'link', render: renderLink },
]
const mobileColumns: DataTableColumn<ProblemReader>[] = [
{
title: "学生",
key: "username",
title: '学生',
key: 'username',
render: (row) =>
h("div", { class: "m-line" }, [
h(UserName, { username: row.username }),
h("span", { class: "m-right" }, [renderResult(row), renderLink(row)]),
]),
h('div', { class: 'm-line' }, [h(UserName, { username: row.username }), h('span', { class: 'm-right' }, [renderResult(row), renderLink(row)])]),
},
]
+35 -70
View File
@@ -1,14 +1,14 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { useThemeVars } from "naive-ui"
import { getLearnStudent } from "admin/api"
import { parseTime, readableDuration } from "utils/functions"
import type { LearnStudentDetail } from "utils/types"
import UserName from "shared/components/UserName.vue"
import { useBackClose } from "shared/composables/backClose"
import { useBreakpoints } from "shared/composables/breakpoints"
import { splitTitle, type TutorialType } from "oj/learn/lesson"
import { EXERCISE_KIND } from "./kinds"
import { Icon } from '@iconify/vue'
import { useThemeVars } from 'naive-ui'
import { getLearnStudent } from 'admin/api'
import { parseTime, readableDuration } from 'utils/functions'
import type { LearnStudentDetail } from 'utils/types'
import UserName from 'shared/components/UserName.vue'
import { useBackClose } from 'shared/composables/backClose'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { splitTitle, type TutorialType } from 'oj/learn/lesson'
import { EXERCISE_KIND } from './kinds'
/**
* 一个学生的自学明细:点方块格里的名字从右边滑出来。
@@ -24,15 +24,15 @@ const props = defineProps<{
/** 课 id → 第几课,跟方块格表头的编号一致 */
steps: Map<number, number>
}>()
const show = defineModel<boolean>("show", { required: true })
const show = defineModel<boolean>('show', { required: true })
const theme = useThemeVars()
const { isDesktop } = useBreakpoints()
useBackClose(show, () => !isDesktop.value)
type Lesson = LearnStudentDetail["lessons"][number]
type Exercise = Lesson["exercises"][number]
type Problem = Lesson["problems"][number]
type Lesson = LearnStudentDetail['lessons'][number]
type Exercise = Lesson['exercises'][number]
type Problem = Lesson['problems'][number]
const detail = ref<LearnStudentDetail | null>(null)
const loading = ref(false)
@@ -58,20 +58,20 @@ function solvedOf(lesson: Lesson) {
}
function stateOf(ex: Exercise) {
if (ex.solved) return "solved"
return ex.attempts > 0 ? "wrong" : "todo"
if (ex.solved) return 'solved'
return ex.attempts > 0 ? 'wrong' : 'todo'
}
function problemStateOf(problem: Problem) {
if (problem.solved) return "solved"
return problem.submissions > 0 ? "wrong" : "todo"
if (problem.solved) return 'solved'
return problem.submissions > 0 ? 'wrong' : 'todo'
}
/** 提交列表按这个人、这道题筛好,新标签页打开 */
function submissionsHref(problem: Problem) {
return router.resolve({
path: "/submission",
query: { problem: problem.displayId, username: detail.value?.username, exactUsername: "1" },
path: '/submission',
query: { problem: problem.displayId, username: detail.value?.username, exactUsername: '1' },
}).href
}
@@ -95,8 +95,7 @@ watch(
data.lessons
.filter(
(lesson) =>
(lesson.exercises.some((ex) => ex.attempts > 0) &&
lesson.exercises.some((ex) => !ex.solved)) ||
(lesson.exercises.some((ex) => ex.attempts > 0) && lesson.exercises.some((ex) => !ex.solved)) ||
lesson.problems.some((p) => p.submissions > 0 && !p.solved),
)
.map((lesson) => lesson.tutorialId),
@@ -118,15 +117,9 @@ watch(
<UserName :username="detail.username" class="head-name" />
<span class="muted small num">
打开过 {{ summary.opened }} 课
<template v-if="summary.seconds">
· 停留 {{ readableDuration(summary.seconds) }}</template
>
<template v-if="summary.total">
· 练一练 {{ summary.solved }}/{{ summary.total }}</template
>
<template v-if="summary.problemTotal">
· 配套题 {{ summary.problemSolved }}/{{ summary.problemTotal }}</template
>
<template v-if="summary.seconds"> · 停留 {{ readableDuration(summary.seconds) }}</template>
<template v-if="summary.total"> · 练一练 {{ summary.solved }}/{{ summary.total }}</template>
<template v-if="summary.problemTotal"> · 配套题 {{ summary.problemSolved }}/{{ summary.problemTotal }}</template>
</span>
</div>
<span v-else>自学明细</span>
@@ -149,22 +142,13 @@ watch(
{{ splitTitle(lesson.title).kp }}
</span>
<span class="grow" />
<span v-if="lesson.exercises.length" class="small num">
{{ solvedOf(lesson) }}/{{ lesson.exercises.length }}
</span>
<span v-if="lesson.exercises.length" class="small num"> {{ solvedOf(lesson) }}/{{ lesson.exercises.length }} </span>
<span class="squares">
<span
v-for="ex in lesson.exercises"
:key="ex.exerciseId"
class="square"
:class="stateOf(ex)"
/>
<span v-for="ex in lesson.exercises" :key="ex.exerciseId" class="square" :class="stateOf(ex)" />
</span>
<Icon
v-if="lesson.exercises.length || lesson.problems.length"
:icon="
expanded.has(lesson.tutorialId) ? 'ph:caret-down-bold' : 'ph:caret-right-bold'
"
:icon="expanded.has(lesson.tutorialId) ? 'ph:caret-down-bold' : 'ph:caret-right-bold'"
:width="12"
class="muted"
/>
@@ -172,35 +156,22 @@ watch(
<span class="lesson-line small muted num">
<template v-if="lesson.viewCount">
打开 {{ lesson.viewCount }} 次
<template v-if="lesson.totalSeconds">
· 停留 {{ readableDuration(lesson.totalSeconds) }}</template
>
<template v-if="lesson.lastViewedAt">
· {{ parseTime(lesson.lastViewedAt, "M月D日 HH:mm") }}</template
>
<template v-if="lesson.totalSeconds"> · 停留 {{ readableDuration(lesson.totalSeconds) }}</template>
<template v-if="lesson.lastViewedAt"> · {{ parseTime(lesson.lastViewedAt, 'M月D日 HH:mm') }}</template>
</template>
<template v-else>没打开过,直接做的练一练</template>
<template v-if="!lesson.exercises.length"> · 这课没有练一练</template>
<template v-if="lesson.problems.length">
· 配套题 {{ lesson.problems.filter((p) => p.solved).length }}/{{
lesson.problems.length
}}</template
>
<template v-if="lesson.problems.length"> · 配套题 {{ lesson.problems.filter((p) => p.solved).length }}/{{ lesson.problems.length }}</template>
</span>
</button>
<div
v-if="
expanded.has(lesson.tutorialId) && (lesson.exercises.length || lesson.problems.length)
"
class="ex-list"
>
<div v-if="expanded.has(lesson.tutorialId) && (lesson.exercises.length || lesson.problems.length)" class="ex-list">
<div v-for="ex in lesson.exercises" :key="ex.exerciseId" class="ex">
<span class="square" :class="stateOf(ex)" />
<div class="ex-body">
<div class="ex-question">
<span class="kind">{{ EXERCISE_KIND[ex.type] ?? ex.type }}</span>
{{ ex.question || "(没有题干)" }}
{{ ex.question || '(没有题干)' }}
</div>
<div class="small num">
<span v-if="ex.solved" class="ok">做对了(第 {{ ex.attemptsToSolve }} 次)</span>
@@ -208,9 +179,7 @@ watch(
<span class="bad">还没做对,交了 {{ ex.attempts }} 次</span>
</template>
<span v-else class="muted">没做</span>
<span v-if="ex.lastWrongAnswer" class="muted">
· 最后错在 {{ ex.lastWrongAnswer }}</span
>
<span v-if="ex.lastWrongAnswer" class="muted"> · 最后错在 {{ ex.lastWrongAnswer }}</span>
</div>
</div>
</div>
@@ -224,14 +193,10 @@ watch(
</div>
<div class="small num">
<span v-if="problem.solved" class="ok">做对了</span>
<span v-else-if="problem.submissions" class="bad"
>交了 {{ problem.submissions }} 次还没对</span
>
<span v-else-if="problem.submissions" class="bad">交了 {{ problem.submissions }} 次还没对</span>
<span v-else class="muted">没交</span>
<template v-if="problem.lastSubmitAt">
<span class="muted">
· {{ parseTime(problem.lastSubmitAt, "YYYY年M月D日") }} ·
</span>
<span class="muted"> · {{ parseTime(problem.lastSubmitAt, 'YYYY年M月D日') }} · </span>
<a :href="submissionsHref(problem)" target="_blank" class="link">看提交</a>
</template>
</div>
+58 -140
View File
@@ -1,18 +1,18 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { useThemeVars } from "naive-ui"
import type { LearnBoard, LearnBoardStudent, LearnExerciseProgress } from "utils/types"
import { getLearnBoard, getLearnExercises } from "admin/api"
import { parseTime, readableDuration } from "utils/functions"
import { useConfigStore } from "shared/store/config"
import UserName from "shared/components/UserName.vue"
import { groupClassOptions } from "utils/classes"
import { groupByProject, splitTitle, type TutorialType } from "oj/learn/lesson"
import "oj/learn/learn.css"
import ExerciseAttempts from "./ExerciseAttempts.vue"
import ProblemReaders, { type ProblemReader } from "./ProblemReaders.vue"
import StudentDrawer from "./StudentDrawer.vue"
import { EXERCISE_KIND } from "./kinds"
import { Icon } from '@iconify/vue'
import { useThemeVars } from 'naive-ui'
import type { LearnBoard, LearnBoardStudent, LearnExerciseProgress } from 'utils/types'
import { getLearnBoard, getLearnExercises } from 'admin/api'
import { parseTime, readableDuration } from 'utils/functions'
import { useConfigStore } from 'shared/store/config'
import UserName from 'shared/components/UserName.vue'
import { groupClassOptions } from 'utils/classes'
import { groupByProject, splitTitle, type TutorialType } from 'oj/learn/lesson'
import 'oj/learn/learn.css'
import ExerciseAttempts from './ExerciseAttempts.vue'
import ProblemReaders, { type ProblemReader } from './ProblemReaders.vue'
import StudentDrawer from './StudentDrawer.vue'
import { EXERCISE_KIND } from './kinds'
/**
* 自学情况(设计稿「后台 · 自学情况」):一个班学到哪了。
@@ -26,43 +26,30 @@ import { EXERCISE_KIND } from "./kinds"
const configStore = useConfigStore()
const theme = useThemeVars()
const type = ref<TutorialType>("python")
const type = ref<TutorialType>('python')
const className = ref<string | null>(null)
const board = ref<LearnBoard | null>(null)
const exercises = ref<LearnExerciseProgress[]>([])
const lessonId = ref<number | null>(null)
const expanded = ref<number | null>(null)
const side = ref<"exercise" | "problem">("exercise")
const side = ref<'exercise' | 'problem'>('exercise')
const problemOpen = ref<number | null>(null)
const studentId = ref<number | null>(null)
const showStudent = ref(false)
const loading = ref(false)
const classOptions = computed(() => groupClassOptions(configStore.config?.classList ?? []))
const groups = computed(() =>
groupByProject(
(board.value?.tutorials ?? []).map(({ id, title, project }) => ({ id, title, project })),
),
)
const groups = computed(() => groupByProject((board.value?.tutorials ?? []).map(({ id, title, project }) => ({ id, title, project }))))
const started = computed(() =>
(board.value?.students ?? [])
.filter((row) => row.opened.length || row.exerciseSolved)
.sort(
(a, b) =>
b.done.length - a.done.length ||
b.opened.length - a.opened.length ||
(b.lastViewedAt ?? "").localeCompare(a.lastViewedAt ?? ""),
),
)
const idle = computed(() =>
(board.value?.students ?? []).filter((row) => !row.opened.length && !row.exerciseSolved),
.sort((a, b) => b.done.length - a.done.length || b.opened.length - a.opened.length || (b.lastViewedAt ?? '').localeCompare(a.lastViewedAt ?? '')),
)
const idle = computed(() => (board.value?.students ?? []).filter((row) => !row.opened.length && !row.exerciseSolved))
const finishedOne = computed(() => started.value.filter((row) => row.done.length > 0).length)
const avgSeconds = computed(() => {
const rows = started.value
return rows.length
? Math.round(rows.reduce((n, row) => n + row.totalSeconds, 0) / rows.length)
: 0
return rows.length ? Math.round(rows.reduce((n, row) => n + row.totalSeconds, 0) / rows.length) : 0
})
const openedCount = computed(() => {
const counts = new Map<number, number>()
@@ -71,28 +58,13 @@ const openedCount = computed(() => {
}
return counts
})
const lessonProblems = computed(
() => new Map((board.value?.tutorials ?? []).map((row) => [row.id, row.problems])),
)
const lessonProblems = computed(() => new Map((board.value?.tutorials ?? []).map((row) => [row.id, row.problems])))
/** 学生 → 题 → 交过的情况 */
const problemStates = computed(
() =>
new Map(
(board.value?.students ?? []).map((row) => [
row.userId,
new Map(row.problems.map((problem) => [problem.problemId, problem])),
]),
),
)
const exerciseTotal = computed(
() => new Map((board.value?.tutorials ?? []).map((row) => [row.id, row.exerciseTotal])),
)
const steps = computed(
() =>
new Map(
groups.value.flatMap((group) => group.lessons.map((lesson) => [lesson.id, lesson.step])),
),
() => new Map((board.value?.students ?? []).map((row) => [row.userId, new Map(row.problems.map((problem) => [problem.problemId, problem]))])),
)
const exerciseTotal = computed(() => new Map((board.value?.tutorials ?? []).map((row) => [row.id, row.exerciseTotal])))
const steps = computed(() => new Map(groups.value.flatMap((group) => group.lessons.map((lesson) => [lesson.id, lesson.step]))))
const maxOpened = computed(() => Math.max(1, ...openedCount.value.values()))
const lessonOptions = computed(() =>
groups.value.flatMap((group) =>
@@ -102,14 +74,10 @@ const lessonOptions = computed(() =>
})),
),
)
const lessonExercises = computed(() =>
exercises.value.filter((row) => row.tutorialId === lessonId.value),
)
const lessonExercises = computed(() => exercises.value.filter((row) => row.tutorialId === lessonId.value))
/** 读过(或做过练一练)这一课的人 */
function readersOf(id: number) {
return started.value.filter(
(row) => row.opened.includes(id) || row.lessons.some((lesson) => lesson.tutorialId === id),
)
return started.value.filter((row) => row.opened.includes(id) || row.lessons.some((lesson) => lesson.tutorialId === id))
}
const sideProblems = computed(() => {
const id = lessonId.value
@@ -135,11 +103,11 @@ function lessonOf(row: LearnBoardStudent, id: number) {
}
function cellOf(row: LearnBoardStudent, id: number) {
if (row.done.includes(id)) return "done"
if (row.done.includes(id)) return 'done'
const lesson = lessonOf(row, id)
if (lesson) return lesson.solved ? "partial" : "partial stuck"
if (row.opened.includes(id)) return "opened"
return ""
if (lesson) return lesson.solved ? 'partial' : 'partial stuck'
if (row.opened.includes(id)) return 'opened'
return ''
}
/** 做了一部分的格子:做对几成,绿就从下往上涨几成 */
@@ -147,22 +115,20 @@ function cellStyle(row: LearnBoardStudent, id: number) {
const lesson = lessonOf(row, id)
const total = exerciseTotal.value.get(id) ?? 0
if (!lesson || !total || row.done.includes(id)) return undefined
return { "--fill": `${Math.round((lesson.solved / total) * 100)}%` }
return { '--fill': `${Math.round((lesson.solved / total) * 100)}%` }
}
function cellTitle(row: LearnBoardStudent, step: number, title: string, id: number) {
const head = `第 ${step} 课 ${splitTitle(title).kp}`
const total = exerciseTotal.value.get(id) ?? 0
const lesson = lessonOf(row, id)
const wrong = lesson?.wrongAttempts ? `,错了 ${lesson.wrongAttempts} 次` : ""
const wrong = lesson?.wrongAttempts ? `,错了 ${lesson.wrongAttempts} 次` : ''
const problems = lessonProblems.value.get(id) ?? []
const states = problemStates.value.get(row.userId)
const tail = problems.length
? ` · 配套题 ${problems.filter((problem) => states?.get(problem.id)?.solved).length}/${problems.length}`
: ""
const tail = problems.length ? ` · 配套题 ${problems.filter((problem) => states?.get(problem.id)?.solved).length}/${problems.length}` : ''
if (row.done.includes(id)) return `${head}:学完了${wrong}${tail}`
if (lesson) return `${head}:练一练 ${lesson.solved}/${total}${wrong}${tail}`
if (row.opened.includes(id)) return `${head}:${total ? "打开过,练一练没做" : "打开过"}${tail}`
if (row.opened.includes(id)) return `${head}:${total ? '打开过,练一练没做' : '打开过'}${tail}`
return `${head}:没打开`
}
@@ -196,10 +162,10 @@ function openStudent(row: LearnBoardStudent) {
}
function flag(row: LearnExerciseProgress) {
if (row.triedUsers < 3) return ""
if (row.firstTryUsers === 0 && row.solvedUsers > 0) return "没人一次对"
if (row.solvedUsers / row.triedUsers < 0.5) return "多数人卡住"
return ""
if (row.triedUsers < 3) return ''
if (row.firstTryUsers === 0 && row.solvedUsers > 0) return '没人一次对'
if (row.solvedUsers / row.triedUsers < 0.5) return '多数人卡住'
return ''
}
async function load() {
@@ -210,9 +176,7 @@ async function load() {
const data = await getLearnBoard(params)
board.value = data
className.value = data.className
const ex = data.className
? await getLearnExercises({ type: type.value, className: data.className })
: { results: [] }
const ex = data.className ? await getLearnExercises({ type: type.value, className: data.className }) : { results: [] }
exercises.value = ex.results
// 练一练默认看大家打开得最多的那课
const busiest = [...openedCount.value.entries()].sort((a, b) => b[1] - a[1])[0]
@@ -239,18 +203,10 @@ onMounted(load)
<span class="title">自学情况</span>
<span class="grow" />
<div class="seg">
<button type="button" :class="{ on: type === 'python' }" @click="pickType('python')">
Python
</button>
<button type="button" :class="{ on: type === 'python' }" @click="pickType('python')">Python</button>
<button type="button" :class="{ on: type === 'c' }" @click="pickType('c')">C 语言</button>
</div>
<n-select
v-model:value="className"
:options="classOptions"
filterable
placeholder="选班级"
class="class-select"
/>
<n-select v-model:value="className" :options="classOptions" filterable placeholder="选班级" class="class-select" />
</div>
<n-spin :show="loading">
@@ -280,16 +236,9 @@ onMounted(load)
<span class="c-name strong">学到哪了</span>
<div class="cells-head">
<div v-for="group in groups" :key="group.lessons[0]!.id" class="group-head">
<span class="group-no" :title="group.project">{{
group.no || group.name
}}</span>
<span class="group-no" :title="group.project">{{ group.no || group.name }}</span>
<span class="group-steps">
<span
v-for="lesson in group.lessons"
:key="lesson.id"
class="step"
:title="splitTitle(lesson.title).kp"
>
<span v-for="lesson in group.lessons" :key="lesson.id" class="step" :title="splitTitle(lesson.title).kp">
{{ lesson.step }}
</span>
</span>
@@ -318,22 +267,18 @@ onMounted(load)
</div>
<span class="c-num num">
<template v-if="exerciseDue(row)"
>{{ row.exerciseSolved
}}<span class="muted">/{{ exerciseDue(row) }}</span></template
>{{ row.exerciseSolved }}<span class="muted">/{{ exerciseDue(row) }}</span></template
>
<template v-else>-</template>
</span>
<span class="c-num num">
<template v-if="problemCount(row).total"
>{{ problemCount(row).solved
}}<span class="muted">/{{ problemCount(row).total }}</span></template
>{{ problemCount(row).solved }}<span class="muted">/{{ problemCount(row).total }}</span></template
>
<template v-else>-</template>
</span>
<span class="c-stay num">{{ readableDuration(row.totalSeconds) }}</span>
<span class="c-last num muted">{{
row.lastViewedAt ? parseTime(row.lastViewedAt, "M月D日") : "-"
}}</span>
<span class="c-last num muted">{{ row.lastViewedAt ? parseTime(row.lastViewedAt, 'M月D日') : '-' }}</span>
</div>
<div v-if="!started.length" class="none muted">这个班还没人打开过</div>
<div v-else class="line foot">
@@ -341,7 +286,7 @@ onMounted(load)
<div class="cells bars">
<div v-for="group in groups" :key="group.lessons[0]!.id" class="group-cells">
<span v-for="lesson in group.lessons" :key="lesson.id" class="bar-col">
<span class="bar-num num">{{ openedCount.get(lesson.id) || "" }}</span>
<span class="bar-num num">{{ openedCount.get(lesson.id) || '' }}</span>
<span
class="bar"
:class="{ zero: !openedCount.get(lesson.id) }"
@@ -360,9 +305,7 @@ onMounted(load)
<span class="muted num">{{ idle.length }} 人</span>
</div>
<div class="chips">
<span v-for="row in idle" :key="row.userId" class="chip"
><UserName :username="row.username"
/></span>
<span v-for="row in idle" :key="row.userId" class="chip"><UserName :username="row.username" /></span>
</div>
</div>
</section>
@@ -370,23 +313,10 @@ onMounted(load)
<section class="card side">
<div class="side-head">
<div class="seg small">
<button
type="button"
:class="{ on: side === 'exercise' }"
@click="side = 'exercise'"
>
练一练
</button>
<button type="button" :class="{ on: side === 'problem' }" @click="side = 'problem'">
配套题
</button>
<button type="button" :class="{ on: side === 'exercise' }" @click="side = 'exercise'">练一练</button>
<button type="button" :class="{ on: side === 'problem' }" @click="side = 'problem'">配套题</button>
</div>
<n-select
v-model:value="lessonId"
:options="lessonOptions"
size="small"
class="lesson-select"
/>
<n-select v-model:value="lessonId" :options="lessonOptions" size="small" class="lesson-select" />
</div>
<template v-if="side === 'problem'">
<div v-if="!sideProblems.length" class="muted none">这课没有配套题</div>
@@ -404,15 +334,11 @@ onMounted(load)
</div>
</template>
<div v-else-if="!lessonExercises.length" class="muted none">这课没有练一练</div>
<div
v-for="row in side === 'exercise' ? lessonExercises : []"
:key="row.exerciseId"
class="ex"
>
<div v-for="row in side === 'exercise' ? lessonExercises : []" :key="row.exerciseId" class="ex">
<button type="button" class="ex-main" @click="expanded = row.exerciseId">
<span class="ex-line">
<span class="kind">{{ EXERCISE_KIND[row.type] ?? row.type }}</span>
<span class="question">{{ row.question || "(没有题干)" }}</span>
<span class="question">{{ row.question || '(没有题干)' }}</span>
<Icon icon="ph:caret-right-bold" :width="12" class="muted" />
</span>
<span class="ex-line small num">
@@ -435,11 +361,7 @@ onMounted(load)
style="width: 820px; max-width: 95vw"
@update:show="(show: boolean) => !show && (expanded = null)"
>
<ExerciseAttempts
v-if="expanded !== null"
:exercise-id="expanded"
:class-name="board?.className ?? ''"
/>
<ExerciseAttempts v-if="expanded !== null" :exercise-id="expanded" :class-name="board?.className ?? ''" />
</n-modal>
<!-- 点一道配套题:读过这课的人各自做没做对 -->
@@ -450,11 +372,7 @@ onMounted(load)
style="width: 640px; max-width: 95vw"
@update:show="(show: boolean) => !show && (problemOpen = null)"
>
<ProblemReaders
v-if="openProblem"
:display-id="openProblem.displayId"
:people="openProblem.people"
/>
<ProblemReaders v-if="openProblem" :display-id="openProblem.displayId" :people="openProblem.people" />
</n-modal>
<StudentDrawer v-model:show="showStudent" :user-id="studentId" :type="type" :steps="steps" />
@@ -639,7 +557,7 @@ onMounted(load)
background: linear-gradient(to top, #18a058 var(--fill), rgba(24, 160, 88, 0.3) var(--fill));
}
.cell.stuck {
box-shadow: inset 0 -4px 0 v-bind("theme.warningColor");
box-shadow: inset 0 -4px 0 v-bind('theme.warningColor');
}
.name-btn {
border: 0;
@@ -651,7 +569,7 @@ onMounted(load)
cursor: pointer;
}
.name-btn :deep(.name) {
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
}
.name-btn:hover :deep(.name) {
text-decoration: underline;
@@ -841,7 +759,7 @@ onMounted(load)
width: 96px;
margin-left: -16px;
padding-left: 16px;
background: v-bind("theme.bodyColor");
background: v-bind('theme.bodyColor');
}
.side {
width: auto;
+7 -7
View File
@@ -1,10 +1,10 @@
/** 练一练的题型,后台显示用的短名 */
export const EXERCISE_KIND: Record<string, string> = {
mcq: "选择",
sort: "排序",
fill: "填空",
match: "连线",
predict: "预测输出",
debug: "找错",
group: "分组",
mcq: '选择',
sort: '排序',
fill: '填空',
match: '连线',
predict: '预测输出',
debug: '找错',
group: '分组',
}
+116 -228
View File
@@ -1,45 +1,24 @@
<script setup lang="ts">
import { EditorView } from "@codemirror/view"
import { TEST_CASE_MAX_CASES } from "@oj2/contract"
import Markdown from "shared/components/Markdown.vue"
import { useThemeVars } from "naive-ui"
import PageHeader from "admin/components/PageHeader.vue"
import ProblemTypeTag from "oj/problem/components/ProblemTypeTag.vue"
import SqlProblemData from "oj/problem/components/SqlProblemData.vue"
import { getProblemTagList } from "shared/api"
import TextEditor from "shared/components/TextEditor.vue"
import { errorCode, errorMessage, isApiError } from "utils/api"
import { DIFFICULTY, STORAGE_KEY } from "utils/constants"
import { createZipBlob, getTagColor, unique } from "utils/functions"
import type { AdminProblem, BlankProblem, SqlConfig, Tag, Testcase } from "utils/types"
import PreviewStrip from "./components/PreviewStrip.vue"
import { usePreviewCollapsed } from "./components/previewCollapse"
import {
createContestProblem,
createProblem,
editProblem,
generateSQLTestcase,
getSQLTestcaseScripts,
previewSQLTestcase,
uploadTestcases,
} from "../api"
import {
cleanTags,
difficultyOptions,
isBlankHtml,
problemListRoute,
saveErrorText,
tagTooLongText,
useCreateDraft,
} from "./components/problemForm"
import {
explainSqlError,
groupSummary,
type GroupStatus,
type ScriptGroup,
} from "./components/sqlScript"
import { EditorView } from '@codemirror/view'
import { TEST_CASE_MAX_CASES } from '@oj2/contract'
import Markdown from 'shared/components/Markdown.vue'
import { useThemeVars } from 'naive-ui'
import PageHeader from 'admin/components/PageHeader.vue'
import ProblemTypeTag from 'oj/problem/components/ProblemTypeTag.vue'
import SqlProblemData from 'oj/problem/components/SqlProblemData.vue'
import { getProblemTagList } from 'shared/api'
import TextEditor from 'shared/components/TextEditor.vue'
import { errorCode, errorMessage, isApiError } from 'utils/api'
import { DIFFICULTY, STORAGE_KEY } from 'utils/constants'
import { createZipBlob, getTagColor, unique } from 'utils/functions'
import type { AdminProblem, BlankProblem, SqlConfig, Tag, Testcase } from 'utils/types'
import PreviewStrip from './components/PreviewStrip.vue'
import { usePreviewCollapsed } from './components/previewCollapse'
import { createContestProblem, createProblem, editProblem, generateSQLTestcase, getSQLTestcaseScripts, previewSQLTestcase, uploadTestcases } from '../api'
import { cleanTags, difficultyOptions, isBlankHtml, problemListRoute, saveErrorText, tagTooLongText, useCreateDraft } from './components/problemForm'
import { explainSqlError, groupSummary, type GroupStatus, type ScriptGroup } from './components/sqlScript'
const CodeEditor = defineAsyncComponent(() => import("shared/components/CodeEditor.vue"))
const CodeEditor = defineAsyncComponent(() => import('shared/components/CodeEditor.vue'))
/** 标准答案常是一长行,出题页左栏才 560 宽:折行,别横着滚。给稳定的数组,见 CodeEditor 的注释 */
const wrapLines = [EditorView.lineWrapping]
@@ -71,7 +50,7 @@ const isCreate = computed(() => !props.problemID)
interface SqlForm {
_id: string
title: string
difficulty: BlankProblem["difficulty"]
difficulty: BlankProblem['difficulty']
visible: boolean
tags: string[]
description: string
@@ -85,35 +64,35 @@ interface SqlForm {
}
const blankForm = (): SqlForm => ({
_id: "",
title: "",
difficulty: "Low",
_id: '',
title: '',
difficulty: 'Low',
visible: false,
tags: ["SQL"],
description: "",
hint: "",
source: "",
prompt: "",
tags: ['SQL'],
description: '',
hint: '',
source: '',
prompt: '',
memoryLimit: 64,
timeLimit: 1000,
sqlConfig: { mode: "query", order_sensitive: false },
answer: "",
sqlConfig: { mode: 'query', order_sensitive: false },
answer: '',
})
const form = reactive<SqlForm>(blankForm())
const testCase = reactive({ id: "", score: [] as Testcase[] })
const testCase = reactive({ id: '', score: [] as Testcase[] })
let nextKey = 0
function newGroup(sql = ""): ScriptGroup {
return { key: nextKey++, sql, ranFor: "", display: null, error: "", errorRaw: "", running: "" }
function newGroup(sql = ''): ScriptGroup {
return { key: nextKey++, sql, ranFor: '', display: null, error: '', errorRaw: '', running: '' }
}
const groups = ref<ScriptGroup[]>([])
const selected = ref(0)
/** 打开时库里那几份脚本:没改过就不用重新上传 */
let savedScripts: string[] = []
/** 已有的测试数据没读出来。空白编辑器和「本来就没有」长得一样,必须说出来 */
const loadError = ref("")
const loadError = ref('')
const showMore = ref(false)
const ready = ref(false)
@@ -122,12 +101,7 @@ const ready = ref(false)
const draft = useCreateDraft<{ form: SqlForm; scripts: string[] }>(STORAGE_KEY.ADMIN_SQL_PROBLEM, {
source: () => [form, groups.value.map((g) => g.sql)] as const,
enabled: () => ready.value && isCreate.value,
empty: () =>
!form._id &&
!form.title &&
isBlankHtml(form.description) &&
!form.answer &&
!groups.value.some((g) => g.sql),
empty: () => !form._id && !form.title && isBlankHtml(form.description) && !form.answer && !groups.value.some((g) => g.sql),
take: () => ({ form: { ...form }, scripts: groups.value.map((g) => g.sql) }),
})
@@ -142,7 +116,7 @@ async function load() {
if (isCreate.value) {
// 草稿是本机存的,形状不对(旧版本、被别的页面写坏)就当没有,别让整页起不来
const saved = draft.value
if (saved && typeof saved.form === "object" && Array.isArray(saved.scripts)) {
if (saved && typeof saved.form === 'object' && Array.isArray(saved.scripts)) {
Object.assign(form, blankForm(), saved.form)
groups.value = saved.scripts.map((sql) => newGroup(String(sql)))
} else {
@@ -161,13 +135,13 @@ async function load() {
visible: data.visible,
tags: data.tags,
description: data.description,
hint: data.hint ?? "",
source: data.source ?? "",
prompt: data.prompt ?? "",
hint: data.hint ?? '',
source: data.source ?? '',
prompt: data.prompt ?? '',
memoryLimit: data.memoryLimit,
timeLimit: data.timeLimit,
sqlConfig: data.sqlConfig ?? { mode: "query", order_sensitive: false },
answer: data.answers.find((a) => a.language === "SQL")?.code ?? "",
sqlConfig: data.sqlConfig ?? { mode: 'query', order_sensitive: false },
answer: data.answers.find((a) => a.language === 'SQL')?.code ?? '',
} satisfies SqlForm)
testCase.id = data.testCaseId
testCase.score = data.testCaseScore
@@ -178,11 +152,9 @@ async function load() {
} catch (err) {
const code = errorCode(err)
// 测试点是旧格式(不是 SQL 脚本)时后端回 not-sql-test-case,当作「还没有」就对了
if (code !== "problem-not-found" && code !== "not-sql-test-case") {
const detail = isApiError(err) && typeof err.data === "string" ? `(${err.data})` : ""
loadError.value =
`已有的测试数据没读出来${detail}。下面是空白的,不是这道题真实的测试数据 —— ` +
`直接保存会把它换掉,先排查测试点文件再改。`
if (code !== 'problem-not-found' && code !== 'not-sql-test-case') {
const detail = isApiError(err) && typeof err.data === 'string' ? `(${err.data})` : ''
loadError.value = `已有的测试数据没读出来${detail}。下面是空白的,不是这道题真实的测试数据 —— ` + `直接保存会把它换掉,先排查测试点文件再改。`
}
}
if (groups.value.length < 2) {
@@ -203,7 +175,7 @@ const tagOptions = computed(() =>
function onTagsChange(tags: string[]) {
const cleaned = cleanTags(tags)
if ("tooLong" in cleaned) message.error(tagTooLongText(cleaned.tooLong))
if ('tooLong' in cleaned) message.error(tagTooLongText(cleaned.tooLong))
else form.tags = cleaned.tags
}
@@ -213,14 +185,13 @@ function onTagsChange(tags: string[]) {
* 一组数据跑出来的结果取决于这几样,任何一样变了,原来的结果就作废。
* 排在第一也算:删掉第 1 组之后,原来的第 2 组成了题面展示的那组,增删改题得重查它改没改到行
*/
const signatureOf = (g: ScriptGroup) =>
JSON.stringify([form.answer, form.sqlConfig.mode, g.sql, groups.value[0] === g])
const signatureOf = (g: ScriptGroup) => JSON.stringify([form.answer, form.sqlConfig.mode, g.sql, groups.value[0] === g])
function statusOf(g: ScriptGroup): GroupStatus {
if (!g.sql.trim()) return "empty"
if (!form.answer.trim()) return "no-answer"
if (g.ranFor !== signatureOf(g)) return "running"
return g.error ? "error" : "ok"
if (!g.sql.trim()) return 'empty'
if (!form.answer.trim()) return 'no-answer'
if (g.ranFor !== signatureOf(g)) return 'running'
return g.error ? 'error' : 'ok'
}
async function run(g: ScriptGroup) {
@@ -228,8 +199,8 @@ async function run(g: ScriptGroup) {
if (!g.sql.trim() || !form.answer.trim()) return
if (g.ranFor === signature || g.running === signature) return
g.running = signature
let display: ScriptGroup["display"] = null
let errorRaw = ""
let display: ScriptGroup['display'] = null
let errorRaw = ''
try {
display = await previewSQLTestcase({
initSql: g.sql,
@@ -238,11 +209,10 @@ async function run(g: ScriptGroup) {
shown: groups.value[0] === g,
})
} catch (err) {
errorRaw =
isApiError(err) && typeof err.data === "string" ? err.data : errorMessage(err, "跑不起来")
errorRaw = isApiError(err) && typeof err.data === 'string' ? err.data : errorMessage(err, '跑不起来')
}
// 跑的过程中又改了:这次的结果照样记下(ranFor 说明它对应哪一版),新的那版另有一次在跑
if (g.running === signature) g.running = ""
if (g.running === signature) g.running = ''
g.ranFor = signature
g.display = display
g.error = errorRaw && explainSqlError(errorRaw)
@@ -291,7 +261,7 @@ async function generateGroup() {
selected.value = groups.value.length - 1
}
} catch (err) {
message.error(errorMessage(err, "AI 没写出来,稍后再试"))
message.error(errorMessage(err, 'AI 没写出来,稍后再试'))
} finally {
generating.value = false
}
@@ -303,13 +273,12 @@ const current = computed(() => groups.value[selected.value])
/** 为什么还不能保存。按出题的顺序查,只说第一条 */
const blocker = computed(() => {
if (!form._id.trim() || !form.title.trim()) return "编号和题目还没填"
if (isBlankHtml(form.description)) return "题目描述还没写"
if (!form.tags.length) return "至少要有一个标签"
if (!form.answer.trim()) return "标准答案还没写"
if (groups.value.length < 2) return "测试数据至少要 2 组"
if (groups.value.length > TEST_CASE_MAX_CASES)
return `测试数据最多 ${TEST_CASE_MAX_CASES} 组,删掉 ${groups.value.length - TEST_CASE_MAX_CASES} 组`
if (!form._id.trim() || !form.title.trim()) return '编号和题目还没填'
if (isBlankHtml(form.description)) return '题目描述还没写'
if (!form.tags.length) return '至少要有一个标签'
if (!form.answer.trim()) return '标准答案还没写'
if (groups.value.length < 2) return '测试数据至少要 2 组'
if (groups.value.length > TEST_CASE_MAX_CASES) return `测试数据最多 ${TEST_CASE_MAX_CASES} 组,删掉 ${groups.value.length - TEST_CASE_MAX_CASES} 组`
for (const [i, g] of groups.value.entries()) {
if (!g.sql.trim()) return `第 ${i + 1} 组还是空的,写上或删掉`
}
@@ -321,17 +290,17 @@ const blocker = computed(() => {
}
for (const [i, g] of groups.value.entries()) {
const status = statusOf(g)
if (status === "running") return "测试数据还在跑……"
if (status === "error") return `第 ${i + 1} 组还没跑通,改好或删掉才能保存`
if (status === 'running') return '测试数据还在跑……'
if (status === 'error') return `第 ${i + 1} 组还没跑通,改好或删掉才能保存`
}
return ""
return ''
})
const saving = ref(false)
async function uploadScripts(scripts: string[]) {
const blob = createZipBlob(scripts.map((content, i) => ({ name: `${i + 1}.sql`, content })))
const res = await uploadTestcases(new File([blob], "testcase.zip", { type: "application/zip" }), {
const res = await uploadTestcases(new File([blob], 'testcase.zip', { type: 'application/zip' }), {
sql: true,
})
// 分值平分,余数给最后一组;只留落库的三个键(见契约 problemTestCaseScoreSchema)
@@ -353,18 +322,15 @@ async function save() {
saving.value = true
try {
const scripts = groups.value.map((g) => g.sql)
const changed =
!testCase.id ||
scripts.length !== savedScripts.length ||
scripts.some((sql, i) => sql !== savedScripts[i])
const changed = !testCase.id || scripts.length !== savedScripts.length || scripts.some((sql, i) => sql !== savedScripts[i])
if (changed) await uploadScripts(scripts)
const body: BlankProblem = {
_id: form._id.trim(),
title: form.title.trim(),
description: form.description,
inputDescription: "",
outputDescription: "",
inputDescription: '',
outputDescription: '',
samples: [],
testCaseId: testCase.id,
testCaseScore: testCase.score,
@@ -373,16 +339,16 @@ async function save() {
difficulty: form.difficulty,
visible: form.visible,
tags: form.tags,
languages: ["SQL"],
languages: ['SQL'],
template: {},
hint: isBlankHtml(form.hint) ? "" : form.hint,
hint: isBlankHtml(form.hint) ? '' : form.hint,
source: form.source,
prompt: form.prompt,
answers: [{ language: "SQL", code: form.answer }],
answers: [{ language: 'SQL', code: form.answer }],
allowFlowchart: false,
showFlowchart: false,
mermaidCode: "",
flowchartHint: "",
mermaidCode: '',
flowchartHint: '',
astRules: null,
sqlConfig: form.sqlConfig,
sqlDisplay: null,
@@ -398,9 +364,9 @@ async function save() {
savedScripts = scripts
if (isCreate.value) {
draft.value = null
message.success("SQL 题建好了")
message.success('SQL 题建好了')
} else {
message.success("保存好了")
message.success('保存好了')
}
router.push(problemListRoute(props.contestID))
} catch (err) {
@@ -436,43 +402,20 @@ onMounted(async () => {
<section class="card">
<div class="headRow">
<n-input v-model:value="form._id" placeholder="编号" aria-label="显示编号" class="pid" />
<n-input
v-model:value="form.title"
placeholder="题目,比如:统计平均工资超过6000元的部门"
aria-label="题目"
class="grow"
/>
<n-select
v-model:value="form.difficulty"
:options="difficultyOptions"
aria-label="难度"
class="difficulty"
/>
<n-input v-model:value="form.title" placeholder="题目,比如:统计平均工资超过6000元的部门" aria-label="题目" class="grow" />
<n-select v-model:value="form.difficulty" :options="difficultyOptions" aria-label="难度" class="difficulty" />
<label class="switch">
<n-switch v-model:value="form.visible" size="small" />
<span>可见</span>
</label>
</div>
<TextEditor v-model:value="form.description" title="" simple :min-height="140" />
<n-text depth="3" class="note">
数据表和期望结果会自动接在描述后面给学生看(用第 1
组测试数据),描述里不用再抄一遍表结构。
</n-text>
<n-text depth="3" class="note"> 数据表和期望结果会自动接在描述后面给学生看(用第 1 组测试数据),描述里不用再抄一遍表结构。 </n-text>
<div class="tagRow">
<span class="label">标签</span>
<n-select
:value="form.tags"
:options="tagOptions"
multiple
filterable
tag
placeholder="选一个,或者打字建新的"
@update:value="onTagsChange"
/>
<n-select :value="form.tags" :options="tagOptions" multiple filterable tag placeholder="选一个,或者打字建新的" @update:value="onTagsChange" />
</div>
<n-button text type="primary" class="moreToggle" @click="showMore = !showMore">
提示 · 来源 · 内存限制 {{ showMore ? "▴" : "▾" }}
</n-button>
<n-button text type="primary" class="moreToggle" @click="showMore = !showMore"> 提示 · 来源 · 内存限制 {{ showMore ? '▴' : '▾' }} </n-button>
<div v-if="showMore" class="more">
<div class="label">提示(学生卡住时点开看)</div>
<TextEditor v-model:value="form.hint" title="" simple :min-height="60" />
@@ -483,13 +426,7 @@ onMounted(async () => {
</label>
<label class="field">
<span class="label">内存限制</span>
<n-input-number
v-model:value="form.memoryLimit"
:min="1"
:max="1024"
:show-button="false"
style="width: 110px"
>
<n-input-number v-model:value="form.memoryLimit" :min="1" :max="1024" :show-button="false" style="width: 110px">
<template #suffix>MB</template>
</n-input-number>
</label>
@@ -508,32 +445,15 @@ onMounted(async () => {
<n-radio-button value="query">查询 · 比结果</n-radio-button>
<n-radio-button value="modify">增删改 · 比执行完的表</n-radio-button>
</n-radio-group>
<n-checkbox
v-if="form.sqlConfig.mode === 'query'"
v-model:checked="form.sqlConfig.order_sensitive"
size="small"
>
按顺序比
</n-checkbox>
<n-checkbox v-if="form.sqlConfig.mode === 'query'" v-model:checked="form.sqlConfig.order_sensitive" size="small"> 按顺序比 </n-checkbox>
</div>
<div class="subHead">
<span class="label">标准答案</span>
<n-text depth="3" class="note">
{{
form.sqlConfig.mode === "query"
? "每组数据都拿它跑出期望结果,学生看不到"
: "执行完之后,被改过的表就是期望结果,学生看不到"
}}
{{ form.sqlConfig.mode === 'query' ? '每组数据都拿它跑出期望结果,学生看不到' : '执行完之后,被改过的表就是期望结果,学生看不到' }}
</n-text>
</div>
<CodeEditor
v-model:value="form.answer"
language="SQL"
:extra-extensions="wrapLines"
:font-size="14"
height="120px"
placeholder="SELECT ... FROM ..."
/>
<CodeEditor v-model:value="form.answer" language="SQL" :extra-extensions="wrapLines" :font-size="14" height="120px" placeholder="SELECT ... FROM ..." />
</section>
<section class="card">
@@ -556,11 +476,7 @@ onMounted(async () => {
>
AI 再写一组
</n-button>
<n-button
size="tiny"
:disabled="groupsFull"
:title="groupsFull ? `最多 ${TEST_CASE_MAX_CASES} 组,已经满了` : undefined"
@click="addGroup"
<n-button size="tiny" :disabled="groupsFull" :title="groupsFull ? `最多 ${TEST_CASE_MAX_CASES} 组,已经满了` : undefined" @click="addGroup"
>+ 加一组</n-button
>
</div>
@@ -587,17 +503,8 @@ onMounted(async () => {
<template v-else-if="g.display">{{ groupSummary(g.display) }}</template>
</span>
<span v-if="statusOf(g) === 'ok'" class="mark ok" aria-label="跑通了">✓</span>
<span v-else-if="statusOf(g) === 'error'" class="mark error" aria-label="没跑通"
>✗</span
>
<n-button
v-if="groups.length > 1"
size="tiny"
quaternary
class="remove"
:aria-label="`删掉第 ${i + 1} 组`"
@click.stop="removeGroup(i)"
>
<span v-else-if="statusOf(g) === 'error'" class="mark error" aria-label="没跑通">✗</span>
<n-button v-if="groups.length > 1" size="tiny" quaternary class="remove" :aria-label="`删掉第 ${i + 1} 组`" @click.stop="removeGroup(i)">
删掉
</n-button>
</div>
@@ -620,9 +527,7 @@ onMounted(async () => {
</section>
<div class="saveBar">
<n-button type="primary" :loading="saving" :disabled="!!blocker" @click="save">
保存
</n-button>
<n-button type="primary" :loading="saving" :disabled="!!blocker" @click="save"> 保存 </n-button>
<n-text v-if="blocker" :type="blocker.includes('没跑通') ? 'error' : 'default'" depth="2">
{{ blocker }}
</n-text>
@@ -640,14 +545,12 @@ onMounted(async () => {
第 {{ i + 1 }} 组<span v-if="statusOf(g) === 'error'" class="error"> ✗</span>
</n-radio-button>
</n-radio-group>
<n-button size="small" quaternary title="收起,专心写左边" @click="previewCollapsed = true">
收起 ›
</n-button>
<n-button size="small" quaternary title="收起,专心写左边" @click="previewCollapsed = true"> 收起 › </n-button>
</div>
<div class="page">
<div class="titleRow">
<h2>
<span v-if="form._id">{{ form._id }}</span> {{ form.title || "(题目还没起名)" }}
<span v-if="form._id">{{ form._id }}</span> {{ form.title || '(题目还没起名)' }}
</h2>
<ProblemTypeTag kind="sql" />
<n-tag size="small" :bordered="false" :type="getTagColor(form.difficulty)">
@@ -656,33 +559,18 @@ onMounted(async () => {
</div>
<h3 class="title">描述</h3>
<Markdown html :content="form.description" />
<p v-if="selected > 0" class="otherGroup">
学生看到的是第 1 组,下面是第 {{ selected + 1 }} 组跑出来的样子
</p>
<p v-if="selected > 0" class="otherGroup">学生看到的是第 1 组,下面是第 {{ selected + 1 }} 组跑出来的样子</p>
<template v-if="current">
<p v-if="statusOf(current) === 'no-answer'" class="placeholder">
写好标准答案,这里就跑出期望结果
</p>
<p v-else-if="statusOf(current) === 'empty'" class="placeholder">
第 {{ selected + 1 }} 组还没写脚本
</p>
<p v-else-if="statusOf(current) === 'running' && !current.display" class="placeholder">
在跑……
</p>
<p v-if="statusOf(current) === 'no-answer'" class="placeholder">写好标准答案,这里就跑出期望结果</p>
<p v-else-if="statusOf(current) === 'empty'" class="placeholder">第 {{ selected + 1 }} 组还没写脚本</p>
<p v-else-if="statusOf(current) === 'running' && !current.display" class="placeholder">在跑……</p>
<div v-else-if="statusOf(current) === 'error'" class="errorBox">
{{ current.error }}
<div v-if="current.error.startsWith('标准答案在这组数据上')" class="raw">
每组数据都要建齐标准答案用到的表和列。
</div>
<div v-if="current.error !== current.errorRaw" class="raw small">
原话:{{ current.errorRaw }}
</div>
<div v-if="current.error.startsWith('标准答案在这组数据上')" class="raw">每组数据都要建齐标准答案用到的表和列。</div>
<div v-if="current.error !== current.errorRaw" class="raw small">原话:{{ current.errorRaw }}</div>
</div>
<div v-else-if="current.display" :class="{ stale: statusOf(current) === 'running' }">
<SqlProblemData
:display="current.display"
:order-sensitive="form.sqlConfig.order_sensitive"
>
<SqlProblemData :display="current.display" :order-sensitive="form.sqlConfig.order_sensitive">
<template #title="{ text }">
<h3 class="title sqlTitle">{{ text }}</h3>
</template>
@@ -732,13 +620,13 @@ onMounted(async () => {
}
.card {
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 10px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.card :deep(.editorWrapper) {
@@ -794,7 +682,7 @@ onMounted(async () => {
.label {
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
flex: none;
}
@@ -848,12 +736,12 @@ onMounted(async () => {
.group.on {
background-color: rgba(24, 160, 88, 0.1);
box-shadow: inset 3px 0 0 v-bind("theme.primaryColor");
box-shadow: inset 3px 0 0 v-bind('theme.primaryColor');
}
.group.on.bad {
background-color: rgba(208, 48, 80, 0.08);
box-shadow: inset 3px 0 0 v-bind("theme.errorColor");
box-shadow: inset 3px 0 0 v-bind('theme.errorColor');
}
.groupNo {
@@ -864,7 +752,7 @@ onMounted(async () => {
.shown {
flex: none;
font-size: 12px;
color: v-bind("theme.primaryColorPressed");
color: v-bind('theme.primaryColorPressed');
}
.summary {
@@ -873,7 +761,7 @@ onMounted(async () => {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.mark {
@@ -882,15 +770,15 @@ onMounted(async () => {
}
.ok {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
}
.error {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
.summary.error {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
.remove {
@@ -912,8 +800,8 @@ onMounted(async () => {
align-items: center;
gap: 12px;
padding: 10px 0 14px;
background: v-bind("theme.bodyColor");
border-top: 1px solid v-bind("theme.borderColor");
background: v-bind('theme.bodyColor');
border-top: 1px solid v-bind('theme.borderColor');
}
.preview {
@@ -936,10 +824,10 @@ onMounted(async () => {
.page {
max-height: calc(100vh - 170px);
overflow: auto;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
padding: 18px 22px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.titleRow {
@@ -963,7 +851,7 @@ onMounted(async () => {
line-height: 1.4;
margin: 0 0 6px;
padding-left: 9px;
border-left: 3px solid v-bind("theme.primaryColor");
border-left: 3px solid v-bind('theme.primaryColor');
}
.sqlTitle {
@@ -976,12 +864,12 @@ onMounted(async () => {
border-radius: 4px;
font-size: 13px;
background-color: rgba(128, 128, 128, 0.08);
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
}
.placeholder {
margin: 14px 0 0;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.errorBox {
@@ -989,13 +877,13 @@ onMounted(async () => {
padding: 10px 12px;
border-radius: 4px;
background-color: rgba(208, 48, 80, 0.08);
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
font-size: 13px;
line-height: 1.7;
}
.errorBox .raw {
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
}
.errorBox .small {
+39 -76
View File
@@ -1,17 +1,17 @@
<script setup lang="ts">
import { useRouteQuery } from "@vueuse/router"
import { Icon } from "@iconify/vue"
import { useThemeVars } from "naive-ui"
import type { StuckProblem, StuckProblemDetail } from "utils/types"
import { getStuckProblemDetail, getStuckProblems } from "admin/api"
import { useConfigStore } from "shared/store/config"
import { groupClassOptions } from "utils/classes"
import { periodRange, type Period } from "oj/statistics/period"
import { useBackClose } from "shared/composables/backClose"
import { useBreakpoints } from "shared/composables/breakpoints"
import "oj/learn/learn.css"
import StuckDetail from "./components/StuckDetail.vue"
import { avgTries, rate } from "./components/stuckMath"
import { useRouteQuery } from '@vueuse/router'
import { Icon } from '@iconify/vue'
import { useThemeVars } from 'naive-ui'
import type { StuckProblem, StuckProblemDetail } from 'utils/types'
import { getStuckProblemDetail, getStuckProblems } from 'admin/api'
import { useConfigStore } from 'shared/store/config'
import { groupClassOptions } from 'utils/classes'
import { periodRange, type Period } from 'oj/statistics/period'
import { useBackClose } from 'shared/composables/backClose'
import { useBreakpoints } from 'shared/composables/breakpoints'
import 'oj/learn/learn.css'
import StuckDetail from './components/StuckDetail.vue'
import { avgTries, rate } from './components/stuckMath'
/**
* 卡点分析(设计稿「卡点与趋势」页的定稿 StuckFinalAll / StuckFinalClass):
@@ -27,18 +27,18 @@ const { isMobile } = useBreakpoints()
const theme = useThemeVars()
const PERIODS: { label: string; value: Period }[] = [
{ label: "这学期", value: "term" },
{ label: "最近 30 天", value: "30d" },
{ label: "最近 7 天", value: "7d" },
{ label: "全部", value: "all" },
{ label: '这学期', value: 'term' },
{ label: '最近 30 天', value: '30d' },
{ label: '最近 7 天', value: '7d' },
{ label: '全部', value: 'all' },
]
const THRESHOLDS = [5, 10, 20, 50]
const className = useRouteQuery<string>("className", "", { mode: "replace" })
const period = useRouteQuery<string>("period", "term", { mode: "replace" })
const tag = useRouteQuery<string>("tag", "", { mode: "replace" })
const picked = useRouteQuery<string>("problem", "", { mode: "replace" })
const min = useRouteQuery<string>("min", "", { mode: "replace" })
const className = useRouteQuery<string>('className', '', { mode: 'replace' })
const period = useRouteQuery<string>('period', 'term', { mode: 'replace' })
const tag = useRouteQuery<string>('tag', '', { mode: 'replace' })
const picked = useRouteQuery<string>('problem', '', { mode: 'replace' })
const min = useRouteQuery<string>('min', '', { mode: 'replace' })
const problems = ref<StuckProblem[]>([])
const detail = ref<StuckProblemDetail | null>(null)
@@ -47,9 +47,7 @@ const detailLoading = ref(false)
const classOptions = computed(() => groupClassOptions(configStore.config?.classList ?? []))
const threshold = computed(() => Number(min.value) || (className.value ? 10 : 20))
const thresholdOptions = computed(() =>
THRESHOLDS.map((n) => ({ label: `至少 ${n} 人做过`, value: n })),
)
const thresholdOptions = computed(() => THRESHOLDS.map((n) => ({ label: `至少 ${n} 人做过`, value: n })))
function firstRate(row: StuckProblem) {
return rate(row.firstTry, row.users)
@@ -73,14 +71,11 @@ const knowledge = computed(() => {
groups.set(name, group)
}
}
const all = visible.value.reduce(
(sum, row) => ({ users: sum.users + row.users, firstTry: sum.firstTry + row.firstTry }),
{ users: 0, firstTry: 0 },
)
const all = visible.value.reduce((sum, row) => ({ users: sum.users + row.users, firstTry: sum.firstTry + row.firstTry }), { users: 0, firstTry: 0 })
return [
{
name: "",
label: "全部",
name: '',
label: '全部',
problems: visible.value.length,
rate: rate(all.firstTry, all.users),
},
@@ -95,19 +90,13 @@ const knowledge = computed(() => {
]
})
const activeTag = computed(() =>
knowledge.value.some((row) => row.name === tag.value) ? tag.value : "",
)
const activeTag = computed(() => (knowledge.value.some((row) => row.name === tag.value) ? tag.value : ''))
const list = computed(() =>
visible.value
.filter((row) => !activeTag.value || row.tags.includes(activeTag.value))
.sort((a, b) => firstRate(a) - firstRate(b) || b.users - a.users),
visible.value.filter((row) => !activeTag.value || row.tags.includes(activeTag.value)).sort((a, b) => firstRate(a) - firstRate(b) || b.users - a.users),
)
const selected = computed(
() => list.value.find((row) => String(row.id) === picked.value) ?? list.value[0] ?? null,
)
const selected = computed(() => list.value.find((row) => String(row.id) === picked.value) ?? list.value[0] ?? null)
async function load() {
loading.value = true
@@ -182,13 +171,7 @@ onMounted(load)
@update:value="(value: string | null) => (className = value ?? '')"
/>
<div class="seg">
<button
v-for="option in PERIODS"
:key="option.value"
type="button"
:class="{ on: period === option.value }"
@click="period = option.value"
>
<button v-for="option in PERIODS" :key="option.value" type="button" :class="{ on: period === option.value }" @click="period = option.value">
{{ option.label }}
</button>
</div>
@@ -203,14 +186,7 @@ onMounted(load)
<span class="muted small">一次就对</span>
</div>
<div class="know-list">
<button
v-for="row in knowledge"
:key="row.name"
type="button"
class="item"
:class="{ on: row.name === activeTag }"
@click="tag = row.name"
>
<button v-for="row in knowledge" :key="row.name" type="button" class="item" :class="{ on: row.name === activeTag }" @click="tag = row.name">
<span class="line">
<span class="name">{{ row.label }}</span>
<span class="grow" />
@@ -226,7 +202,7 @@ onMounted(load)
<section class="card problems">
<div class="card-head">
<span class="strong">{{ activeTag || "全部" }}</span>
<span class="strong">{{ activeTag || '全部' }}</span>
<span class="muted small num">{{ list.length }} 道</span>
<span class="grow" />
<n-select
@@ -238,30 +214,17 @@ onMounted(load)
/>
</div>
<div class="scroll">
<div v-if="!list.length && !loading" class="none muted">
这段时间还没有 {{ threshold }} 人以上做过的题
</div>
<button
v-for="row in list"
:key="row.id"
type="button"
class="item"
:class="{ on: row.id === selected?.id }"
@click="pick(row)"
>
<div v-if="!list.length && !loading" class="none muted">这段时间还没有 {{ threshold }} 人以上做过的题</div>
<button v-for="row in list" :key="row.id" type="button" class="item" :class="{ on: row.id === selected?.id }" @click="pick(row)">
<span class="line">
<span class="pid muted num">{{ row.displayId }}</span>
<span class="ptitle">{{ row.title }}</span>
<span v-if="row.users > row.solved" class="stuck num">
{{ row.users - row.solved }} 人没对
</span>
<span v-if="row.users > row.solved" class="stuck num"> {{ row.users - row.solved }} 人没对 </span>
</span>
<span class="line indent">
<span class="track short"><span :style="{ width: `${firstRate(row)}%` }" /></span>
<span class="pct num">{{ firstRate(row) }}%</span>
<span class="muted small num nowrap">
{{ row.users }} 人 · 平均 {{ avgTries(row) }} 次
</span>
<span class="muted small num nowrap"> {{ row.users }} 人 · 平均 {{ avgTries(row) }} 次 </span>
</span>
</button>
</div>
@@ -272,7 +235,7 @@ onMounted(load)
<n-button quaternary circle @click="detailOpen = false">
<template #icon><Icon icon="ph:arrow-left" /></template>
</n-button>
<span class="strong">{{ activeTag || "全部" }}</span>
<span class="strong">{{ activeTag || '全部' }}</span>
</div>
<n-spin :show="detailLoading">
<StuckDetail v-if="detail" :detail="detail" :class-name="className" :period="period" />
@@ -526,7 +489,7 @@ onMounted(load)
border: 0;
border-radius: 0;
overflow-y: auto;
background: v-bind("theme.bodyColor");
background: v-bind('theme.bodyColor');
}
.detail-bar {
position: sticky;
@@ -538,7 +501,7 @@ onMounted(load)
height: 48px;
padding: 0 8px;
border-bottom: 1px solid var(--learn-line);
background: v-bind("theme.bodyColor");
background: v-bind('theme.bodyColor');
}
}
</style>
+26 -55
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { useRouteQuery } from "@vueuse/router"
import type { GradeTrend } from "utils/types"
import { getGradeTrend } from "admin/api"
import "oj/learn/learn.css"
import { useRouteQuery } from '@vueuse/router'
import type { GradeTrend } from 'utils/types'
import { getGradeTrend } from 'admin/api'
import 'oj/learn/learn.css'
/**
* 年度趋势(设计稿「卡点与趋势」页的 TrendB):选一届,和往届(或另一届)在两边都做过的题上
@@ -17,15 +17,15 @@ const router = useRouter()
/** 和后端的 GRADE_MIN_USERS 一致,只用在空状态的文案里 */
const MIN_USERS = 20
const SAME = 2
const PAST = "past"
const PAST = 'past'
const data = ref<GradeTrend | null>(null)
const loading = ref(false)
const grade = useRouteQuery<string>("grade", "", { mode: "replace" })
const compare = useRouteQuery<string>("compare", PAST, { mode: "replace" })
const grade = useRouteQuery<string>('grade', '', { mode: 'replace' })
const compare = useRouteQuery<string>('compare', PAST, { mode: 'replace' })
const grades = computed(() => data.value?.grades ?? [])
const selected = computed(() => data.value?.grade ?? "")
const selected = computed(() => data.value?.grade ?? '')
function rate(part: number, whole: number) {
return whole ? Math.round((part / whole) * 100) : 0
@@ -34,14 +34,12 @@ function rate(part: number, whole: number) {
const pastGrades = computed(() => grades.value.filter((g) => g < selected.value))
const pastLabel = computed(() => {
const list = pastGrades.value
if (!list.length) return "往届"
if (!list.length) return '往届'
return list.length === 1 ? `往届(${list[0]} 级)` : `往届(${list.at(-1)}–${list[0]} 级)`
})
const otherValue = computed(() => data.value?.compare ?? PAST)
const otherLabel = computed(() =>
otherValue.value === PAST ? pastLabel.value : `${otherValue.value} 级`,
)
const shortOther = computed(() => (otherValue.value === PAST ? "往届" : `${otherValue.value} 级`))
const otherLabel = computed(() => (otherValue.value === PAST ? pastLabel.value : `${otherValue.value} 级`))
const shortOther = computed(() => (otherValue.value === PAST ? '往届' : `${otherValue.value} 级`))
const gradeOptions = computed(() => grades.value.map((g) => ({ label: `${g} 级`, value: g })))
const compareOptions = computed(() => [
@@ -56,15 +54,9 @@ const rows = computed(() =>
return { row, mine: row.mine, theirs: row.theirs, now, before, delta: now - before }
}),
)
const worse = computed(() =>
rows.value.filter((item) => item.delta < -SAME).sort((a, b) => a.delta - b.delta),
)
const same = computed(() =>
rows.value.filter((item) => Math.abs(item.delta) <= SAME).sort((a, b) => a.delta - b.delta),
)
const better = computed(() =>
rows.value.filter((item) => item.delta > SAME).sort((a, b) => b.delta - a.delta),
)
const worse = computed(() => rows.value.filter((item) => item.delta < -SAME).sort((a, b) => a.delta - b.delta))
const same = computed(() => rows.value.filter((item) => Math.abs(item.delta) <= SAME).sort((a, b) => a.delta - b.delta))
const better = computed(() => rows.value.filter((item) => item.delta > SAME).sort((a, b) => b.delta - a.delta))
const summary = computed(() => {
const total = rows.value.reduce(
@@ -84,18 +76,18 @@ const summary = computed(() => {
const groups = computed(() =>
[
{ key: "worse", label: `比${shortOther.value}差`, items: worse.value },
{ key: "same", label: "差不多", items: same.value },
{ key: "better", label: `比${shortOther.value}好`, items: better.value },
{ key: 'worse', label: `比${shortOther.value}差`, items: worse.value },
{ key: 'same', label: '差不多', items: same.value },
{ key: 'better', label: `比${shortOther.value}好`, items: better.value },
].filter((group) => group.items.length),
)
function tone(delta: number) {
return delta < -SAME ? "worse" : delta > SAME ? "better" : "same"
return delta < -SAME ? 'worse' : delta > SAME ? 'better' : 'same'
}
function problemHref(displayId: string) {
return router.resolve({ name: "problem", params: { problemID: displayId } }).href
return router.resolve({ name: 'problem', params: { problemID: displayId } }).href
}
function pickGrade(value: string) {
@@ -127,19 +119,9 @@ watch([grade, compare], load, { immediate: true })
<span class="title">年度趋势</span>
<span class="grow" />
<span class="muted">比</span>
<n-select
:value="selected || null"
:options="gradeOptions"
class="grade-select"
@update:value="pickGrade"
/>
<n-select :value="selected || null" :options="gradeOptions" class="grade-select" @update:value="pickGrade" />
<span class="muted">和</span>
<n-select
:value="otherValue"
:options="compareOptions"
class="compare-select"
@update:value="(value: string) => (compare = value)"
/>
<n-select :value="otherValue" :options="compareOptions" class="compare-select" @update:value="(value: string) => (compare = value)" />
</div>
<n-spin :show="loading">
@@ -151,9 +133,7 @@ watch([grade, compare], load, { immediate: true })
</div>
<div class="stat">
<div class="label">
一次就对<template v-if="data?.days !== null">
· 各自开始做题的头 {{ data?.days }} 天</template
>
一次就对<template v-if="data?.days !== null"> · 各自开始做题的头 {{ data?.days }} 天</template>
</div>
<div class="value num">
{{ summary.now }}%<span class="unit"> / {{ shortOther }} {{ summary.before }}%</span>
@@ -165,9 +145,7 @@ watch([grade, compare], load, { immediate: true })
</div>
<div class="stat">
<div class="label">比{{ shortOther }}好</div>
<div class="value num better-text">
{{ better.length }}<span class="unit"> 道</span>
</div>
<div class="value num better-text">{{ better.length }}<span class="unit"> 道</span></div>
</div>
</div>
@@ -175,9 +153,7 @@ watch([grade, compare], load, { immediate: true })
<div class="row axis">
<span class="c-title" />
<span class="c-track ticks num">
<span v-for="tick in [0, 25, 50, 75, 100]" :key="tick" :style="{ left: `${tick}%` }"
>{{ tick }}%</span
>
<span v-for="tick in [0, 25, 50, 75, 100]" :key="tick" :style="{ left: `${tick}%` }">{{ tick }}%</span>
</span>
<span class="legend">
<span><i class="dot-now" />{{ selected }} 级</span>
@@ -210,13 +186,8 @@ watch([grade, compare], load, { immediate: true })
<b :class="`${tone(item.delta)}-text`">{{ item.now }}%</b>
<span class="muted"> / {{ item.before }}%</span>
</span>
<span class="c-delta num strong" :class="`${tone(item.delta)}-text`">
{{ item.delta > 0 ? "+" : "" }}{{ item.delta }}
</span>
<span class="c-users muted small num">
{{ selected }} 级 {{ item.mine.users }} 人 · {{ shortOther }}
{{ item.theirs.users }} 人
</span>
<span class="c-delta num strong" :class="`${tone(item.delta)}-text`"> {{ item.delta > 0 ? '+' : '' }}{{ item.delta }} </span>
<span class="c-users muted small num"> {{ selected }} 级 {{ item.mine.users }} 人 · {{ shortOther }} {{ item.theirs.users }} 人 </span>
</div>
</template>
</section>
@@ -1,8 +1,8 @@
<script lang="ts" setup>
import { errorCode, errorMessage } from "utils/api"
import { deleteContestProblem, deleteProblem, makeProblemPublic } from "admin/api"
import download from "utils/download"
import { useBreakpoints } from "shared/composables/breakpoints"
import { errorCode, errorMessage } from 'utils/api'
import { deleteContestProblem, deleteProblem, makeProblemPublic } from 'admin/api'
import download from 'utils/download'
import { useBreakpoints } from 'shared/composables/breakpoints'
/**
* 题目列表一行的操作:编辑、在前台看、下载测试数据、删除直接摆出来(用户说的:不要收进 ⋯)。
@@ -17,7 +17,7 @@ interface Props {
}
const props = defineProps<Props>()
const dialog = useDialog()
const emit = defineEmits(["updated"])
const emit = defineEmits(['updated'])
const route = useRoute()
const router = useRouter()
@@ -27,25 +27,25 @@ const message = useMessage()
// 转成公开题要想好新题号,也留给电脑,都不摆
const { isMobile } = useBreakpoints()
const isContestProblem = computed(() => route.name === "admin contest problem list")
const isContestProblem = computed(() => route.name === 'admin contest problem list')
const showMakePublicModal = ref(false)
const newDisplayID = ref("")
const newDisplayID = ref('')
async function handleDeleteProblem() {
try {
if (route.name === "admin contest problem list") {
if (route.name === 'admin contest problem list') {
await deleteContestProblem(props.problemID)
} else {
await deleteProblem(props.problemID)
}
message.success("删除成功")
emit("updated")
message.success('删除成功')
emit('updated')
} catch (err) {
if (errorCode(err) === "problem-has-submissions") {
message.error("这道题有提交之后,就不能被删除")
if (errorCode(err) === 'problem-has-submissions') {
message.error('这道题有提交之后,就不能被删除')
} else {
message.error("删除失败")
message.error('删除失败')
}
}
}
@@ -55,57 +55,57 @@ function downloads() {
}
function goEdit() {
const name = route.name!.toString().replace("list", "edit")
const name = route.name!.toString().replace('list', 'edit')
router.push({ name, params: { problemID: props.problemID } })
}
function goCheck() {
let data = router.resolve("/problem/" + props.problemDisplayID)
if (route.name === "admin contest problem list") {
let data = router.resolve('/problem/' + props.problemDisplayID)
if (route.name === 'admin contest problem list') {
data = router.resolve({
name: "contest problem",
name: 'contest problem',
params: {
contestID: route.params.contestID,
problemID: props.problemDisplayID,
},
})
}
window.open(data.href, "_blank")
window.open(data.href, '_blank')
}
function confirmDelete() {
dialog.warning({
title: `删除 ${props.problemDisplayID}?`,
content: "删掉就找不回来了。",
positiveText: "删除",
negativeText: "不删",
content: '删掉就找不回来了。',
positiveText: '删除',
negativeText: '不删',
onPositiveClick: handleDeleteProblem,
})
}
function openMakePublicModal() {
newDisplayID.value = ""
newDisplayID.value = ''
showMakePublicModal.value = true
}
async function handleMakePublic() {
if (!newDisplayID.value.trim()) {
message.error("请输入新的题目编号")
message.error('请输入新的题目编号')
return
}
try {
await makeProblemPublic(props.problemID, newDisplayID.value.trim())
message.success("已成功转为公开题目(需要手动设置可见)")
message.success('已成功转为公开题目(需要手动设置可见)')
showMakePublicModal.value = false
emit("updated") // 刷新列表
emit('updated') // 刷新列表
} catch (err) {
if (errorCode(err) === "display-id-exists") {
message.error("该题目编号已存在,请使用其他编号")
} else if (errorCode(err) === "already-public") {
message.error("该题目已经是公开题目")
if (errorCode(err) === 'display-id-exists') {
message.error('该题目编号已存在,请使用其他编号')
} else if (errorCode(err) === 'already-public') {
message.error('该题目已经是公开题目')
} else {
message.error("转换失败:" + errorMessage(err, "未知错误"))
message.error('转换失败:' + errorMessage(err, '未知错误'))
}
}
}
@@ -114,41 +114,19 @@ async function handleMakePublic() {
<n-flex :size="6" :wrap="isMobile">
<n-button size="small" @click="goEdit">编辑</n-button>
<n-button size="small" title="在前台打开这道题" @click="goCheck">前台看</n-button>
<n-button v-if="!isMobile" size="small" title="下载测试数据" @click="downloads">
测试数据
</n-button>
<n-button v-if="isContestProblem && !isMobile" size="small" @click="openMakePublicModal">
转成公开题
</n-button>
<n-button v-if="!isMobile" size="small" title="下载测试数据" @click="downloads"> 测试数据 </n-button>
<n-button v-if="isContestProblem && !isMobile" size="small" @click="openMakePublicModal"> 转成公开题 </n-button>
<span :title="props.triedUsers ? `有 ${props.triedUsers} 人交过,删不掉` : undefined">
<n-button
size="small"
quaternary
type="error"
:disabled="!!props.triedUsers"
@click="confirmDelete"
>
删除
</n-button>
<n-button size="small" quaternary type="error" :disabled="!!props.triedUsers" @click="confirmDelete"> 删除 </n-button>
</span>
</n-flex>
<n-modal
v-model:show="showMakePublicModal"
preset="card"
title="转为公开题目"
style="width: 500px"
>
<n-modal v-model:show="showMakePublicModal" preset="card" title="转为公开题目" style="width: 500px">
<n-space vertical>
<p>将竞赛题目转为公开题目后,会创建一个新的公开题目副本,原题目保持不变。</p>
<n-form>
<n-form-item label="新的题目编号" required>
<n-input
v-model:value="newDisplayID"
placeholder="例如: 1001"
clearable
@keyup.enter="handleMakePublic"
/>
<n-input v-model:value="newDisplayID" placeholder="例如: 1001" clearable @keyup.enter="handleMakePublic" />
</n-form-item>
</n-form>
<n-alert type="info" title="提示:请输入一个未被使用的题目编号"> </n-alert>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { errorCode, errorMessage } from "utils/api"
import { addProblemForContest } from "admin/api"
import { errorCode, errorMessage } from 'utils/api'
import { addProblemForContest } from 'admin/api'
interface Props {
problemID: number
@@ -8,22 +8,22 @@ interface Props {
nextDisplayId?: string
}
const props = defineProps<Props>()
const emit = defineEmits(["added"])
const emit = defineEmits(['added'])
const message = useMessage()
const displayID = ref(props.nextDisplayId || "")
const displayID = ref(props.nextDisplayId || '')
async function addProblem() {
if (!displayID.value) return
try {
await addProblemForContest(props.contestID, props.problemID, displayID.value)
emit("added")
emit('added')
} catch (err) {
if (errorCode(err) === "display-id-exists") {
message.error("显示编号重复了,请重新写一个")
} else if (errorCode(err) === "contest-ended") {
message.error("这场比赛已经结束了,不能添加题目")
if (errorCode(err) === 'display-id-exists') {
message.error('显示编号重复了,请重新写一个')
} else if (errorCode(err) === 'contest-ended') {
message.error('这场比赛已经结束了,不能添加题目')
} else {
message.error(errorMessage(err))
}
@@ -1,9 +1,9 @@
<script lang="ts" setup>
import { getLibraryProblemList } from "admin/api"
import Pagination from "shared/components/Pagination.vue"
import type { AdminProblemRow } from "utils/types"
import AddButton from "./AddButton.vue"
import { useListLoader } from "shared/composables/listLoader"
import { getLibraryProblemList } from 'admin/api'
import Pagination from 'shared/components/Pagination.vue'
import type { AdminProblemRow } from 'utils/types'
import AddButton from './AddButton.vue'
import { useListLoader } from 'shared/composables/listLoader'
interface Props {
show: boolean
@@ -12,8 +12,8 @@ interface Props {
}
const props = defineProps<Props>()
const emit = defineEmits<{
(e: "update:show", value: boolean): void
(e: "change"): void
(e: 'update:show', value: boolean): void
(e: 'change'): void
}>()
const route = useRoute()
@@ -21,23 +21,23 @@ const route = useRoute()
const query = reactive({
page: 1,
limit: 10,
keyword: "",
keyword: '',
})
const total = ref(0)
const problems = shallowRef<AdminProblemRow[]>([])
const columns: DataTableColumn<AdminProblemRow>[] = [
{ title: "编号", key: "_id", width: 80 },
{ title: "标题", key: "title" },
{ title: '编号', key: '_id', width: 80 },
{ title: '标题', key: 'title' },
{
title: "选项",
key: "add",
title: '选项',
key: 'add',
render: (row) =>
h(AddButton, {
problemID: row.id,
contestID: route.params.contestID as string,
nextDisplayId: props.nextDisplayId,
onAdded: () => emit("change"),
onAdded: () => emit('change'),
}),
width: 60,
},
@@ -68,14 +68,7 @@ watchDebounced(
)
</script>
<template>
<n-modal
:mask-closable="false"
:show="props.show"
preset="card"
style="width: 600px"
title="从题库中添加"
@close="$emit('update:show', false)"
>
<n-modal :mask-closable="false" :show="props.show" preset="card" style="width: 600px" title="从题库中添加" @close="$emit('update:show', false)">
<n-input class="search" v-model:value="query.keyword" clearable placeholder="搜索标题或编号" />
<n-data-table :loading="loading" striped :columns="columns" :data="problems" />
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
@@ -1,14 +1,10 @@
<script setup lang="ts">
import {
AST_NODE_TARGETS_BY_LANGUAGE,
AST_OPERATOR_TARGETS_BY_LANGUAGE,
AST_SUPPORTED_LANGUAGES,
} from "@oj2/contract"
import { useThemeVars } from "naive-ui"
import { errorMessage } from "utils/api"
import type { AstRule, AstRules, LANGUAGE } from "utils/types"
import { checkAstRules } from "../../api"
import type { AstCheckState } from "./editorTypes"
import { AST_NODE_TARGETS_BY_LANGUAGE, AST_OPERATOR_TARGETS_BY_LANGUAGE, AST_SUPPORTED_LANGUAGES } from '@oj2/contract'
import { useThemeVars } from 'naive-ui'
import { errorMessage } from 'utils/api'
import type { AstRule, AstRules, LANGUAGE } from 'utils/types'
import { checkAstRules } from '../../api'
import type { AstCheckState } from './editorTypes'
interface Props {
modelValue: AstRules | null
@@ -24,20 +20,16 @@ interface Props {
const props = defineProps<Props>()
const emit = defineEmits<{
(e: "update:modelValue", value: AstRules | null): void
(e: 'update:modelValue', value: AstRules | null): void
}>()
// 判题机只认 C / Python,别的语言配了规则也一条都不会跑(judge/ast.ts 的
// loadLanguage 返回 null 就直接放行)。原来这里按题目的全部语言开 tab,老师给
// C++ 配的规则存得下、题目页也照常显示成「要求」,判题却从不检查。
const supportedLanguages = computed(() =>
props.languages.filter((lang) => AST_SUPPORTED_LANGUAGES.includes(lang)),
)
const unsupportedLanguages = computed(() =>
props.languages.filter((lang) => !AST_SUPPORTED_LANGUAGES.includes(lang)),
)
const supportedLanguages = computed(() => props.languages.filter((lang) => AST_SUPPORTED_LANGUAGES.includes(lang)))
const unsupportedLanguages = computed(() => props.languages.filter((lang) => !AST_SUPPORTED_LANGUAGES.includes(lang)))
const activeTab = ref(supportedLanguages.value[0] || "Python")
const activeTab = ref(supportedLanguages.value[0] || 'Python')
const theme = useThemeVars()
@@ -47,7 +39,7 @@ const theme = useThemeVars()
* 规则配错(节点类型对不上)时完全静默:「必须使用 X」永远失败、「不能使用 X」永远通过。
* 拿标准答案先跑一遍,标准答案自己都过不了,多半是规则配错了。顺带拿到学生看到的那句话
*/
const checks = defineModel<AstCheckState>("checks", { default: () => ({}) })
const checks = defineModel<AstCheckState>('checks', { default: () => ({}) })
let generation = 0
@@ -59,12 +51,12 @@ async function runChecks() {
if (!rules.length) continue
try {
next[lang] = await checkAstRules({
language: lang as "C" | "C++" | "Python",
code: props.answers[lang] ?? "",
language: lang as 'C' | 'C++' | 'Python',
code: props.answers[lang] ?? '',
rules,
})
} catch (err) {
next[lang] = { error: errorMessage(err, "这组规则检查不了") }
next[lang] = { error: errorMessage(err, '这组规则检查不了') }
}
}
// 跑的过程中又改了:这一轮作废,新的那轮另有一次
@@ -79,7 +71,7 @@ watchDebounced(() => [props.modelValue, props.answers, supportedLanguages.value]
function checkOf(lang: string, index: number) {
const state = checks.value[lang]
if (!state || "error" in state) return null
if (!state || 'error' in state) return null
return state.rules[index] ?? null
}
@@ -89,39 +81,39 @@ function countOf(lang: string) {
const ENGINE_OPTIONS: SelectOption[] = [
{
label: "节点检查",
type: "group",
key: "node_group",
label: '节点检查',
type: 'group',
key: 'node_group',
children: [
{ label: "必须存在", value: "must_exist_node" },
{ label: "不能存在", value: "must_not_exist_node" },
{ label: "出现次数", value: "count_node" },
{ label: '必须存在', value: 'must_exist_node' },
{ label: '不能存在', value: 'must_not_exist_node' },
{ label: '出现次数', value: 'count_node' },
],
},
{
label: "函数调用",
type: "group",
key: "func_group",
label: '函数调用',
type: 'group',
key: 'func_group',
children: [
{ label: "必须调用函数", value: "must_call_function" },
{ label: "不能调用函数", value: "must_not_call_function" },
{ label: "函数调用次数", value: "count_function_call" },
{ label: '必须调用函数', value: 'must_call_function' },
{ label: '不能调用函数', value: 'must_not_call_function' },
{ label: '函数调用次数', value: 'count_function_call' },
],
},
{
label: "方法调用",
type: "group",
key: "method_group",
label: '方法调用',
type: 'group',
key: 'method_group',
children: [
{ label: "必须调用方法", value: "must_call_method" },
{ label: "不能调用方法", value: "must_not_call_method" },
{ label: '必须调用方法', value: 'must_call_method' },
{ label: '不能调用方法', value: 'must_not_call_method' },
],
},
{
label: "运算符",
type: "group",
key: "op_group",
children: [{ label: "必须使用运算符", value: "must_use_operator" }],
label: '运算符',
type: 'group',
key: 'op_group',
children: [{ label: '必须使用运算符', value: 'must_use_operator' }],
},
]
@@ -143,11 +135,11 @@ function operatorTargetOptions(lang: string): SelectOption[] {
}))
}
const NODE_ENGINES = ["must_exist_node", "must_not_exist_node", "count_node"]
const FUNCTION_ENGINES = ["must_call_function", "must_not_call_function", "count_function_call"]
const METHOD_ENGINES = ["must_call_method", "must_not_call_method"]
const OPERATOR_ENGINES = ["must_use_operator"]
const COUNT_ENGINES = ["count_node", "count_function_call"]
const NODE_ENGINES = ['must_exist_node', 'must_not_exist_node', 'count_node']
const FUNCTION_ENGINES = ['must_call_function', 'must_not_call_function', 'count_function_call']
const METHOD_ENGINES = ['must_call_method', 'must_not_call_method']
const OPERATOR_ENGINES = ['must_use_operator']
const COUNT_ENGINES = ['count_node', 'count_function_call']
function isNodeEngine(engine: string) {
return NODE_ENGINES.includes(engine)
@@ -166,18 +158,18 @@ function isCountEngine(engine: string) {
}
const COUNT_MODE_OPTIONS: SelectOption[] = [
{ label: "正好", value: "exact" },
{ label: "范围", value: "range" },
{ label: '正好', value: 'exact' },
{ label: '范围', value: 'range' },
]
function getCountMode(rule: AstRule): "exact" | "range" {
return rule.exact !== undefined ? "exact" : "range"
function getCountMode(rule: AstRule): 'exact' | 'range' {
return rule.exact !== undefined ? 'exact' : 'range'
}
function updateCountMode(lang: string, index: number, mode: "exact" | "range") {
function updateCountMode(lang: string, index: number, mode: 'exact' | 'range') {
const rules = [...getRulesForLang(lang)]
const rule = { ...rules[index] }
if (mode === "exact") {
if (mode === 'exact') {
rule.exact = rule.min ?? 1
delete rule.min
delete rule.max
@@ -222,7 +214,7 @@ function updateRules(lang: string, rules: AstRule[]) {
} else {
current[lang] = rules
}
emit("update:modelValue", Object.keys(current).length > 0 ? current : null)
emit('update:modelValue', Object.keys(current).length > 0 ? current : null)
}
function getTargetLabel(lang: string, engine: string, target: string): string | undefined {
@@ -235,10 +227,10 @@ function getTargetLabel(lang: string, engine: string, target: string): string |
function addRule(lang: string) {
const rules = [...getRulesForLang(lang)]
rules.push({
engine: "must_exist_node",
target: "for_loop",
label: getTargetLabel(lang, "must_exist_node", "for_loop"),
message: "",
engine: 'must_exist_node',
target: 'for_loop',
label: getTargetLabel(lang, 'must_exist_node', 'for_loop'),
message: '',
})
updateRules(lang, rules)
}
@@ -253,16 +245,16 @@ function updateRule(lang: string, index: number, field: string, value: any) {
const rules = [...getRulesForLang(lang)]
const rule = { ...rules[index] }
if (field === "engine") {
if (field === 'engine') {
rule.engine = value
if (isNodeEngine(value)) {
rule.target = "for_loop"
rule.label = getTargetLabel(lang, value, "for_loop")
rule.target = 'for_loop'
rule.label = getTargetLabel(lang, value, 'for_loop')
} else if (isOperatorEngine(value)) {
rule.target = "+"
rule.target = '+'
delete rule.label
} else {
rule.target = ""
rule.target = ''
delete rule.label
}
delete rule.min
@@ -270,18 +262,18 @@ function updateRule(lang: string, index: number, field: string, value: any) {
delete rule.exact
// 次数引擎不给默认值的话,存下去就是一条恒真规则
if (isCountEngine(value)) rule.exact = 1
} else if (field === "target") {
} else if (field === 'target') {
rule.target = value
const lbl = getTargetLabel(lang, rule.engine, value)
if (lbl) rule.label = lbl
else delete rule.label
} else if (field === "min") {
} else if (field === 'min') {
if (value === null || value === undefined) delete rule.min
else rule.min = value
} else if (field === "max") {
} else if (field === 'max') {
if (value === null || value === undefined) delete rule.max
else rule.max = value
} else if (field === "message") {
} else if (field === 'message') {
rule.message = value
}
@@ -299,13 +291,8 @@ watch(supportedLanguages, (langs) => {
<template>
<div class="astRules">
<div class="head">
<span class="label">{{ challenge ? "判定" : "语法要求" }}</span>
<div
v-if="supportedLanguages.length && !challenge"
class="langs"
role="tablist"
aria-label="语言"
>
<span class="label">{{ challenge ? '判定' : '语法要求' }}</span>
<div v-if="supportedLanguages.length && !challenge" class="langs" role="tablist" aria-label="语言">
<button
v-for="lang in supportedLanguages"
:key="lang"
@@ -316,7 +303,7 @@ watch(supportedLanguages, (langs) => {
:class="{ on: activeTab === lang }"
@click="activeTab = lang"
>
{{ lang }} · {{ countOf(lang) ? `${countOf(lang)} 条` : "没有" }}
{{ lang }} · {{ countOf(lang) ? `${countOf(lang)} 条` : '没有' }}
</button>
</div>
<div class="grow"></div>
@@ -324,8 +311,7 @@ watch(supportedLanguages, (langs) => {
<n-text v-else depth="3" class="note">几条都满足才算做到</n-text>
</div>
<n-text v-if="unsupportedLanguages.length" depth="3" class="note">
{{ unsupportedLanguages.join("、") }} 检查不了语法要求(判题机只认
{{ AST_SUPPORTED_LANGUAGES.join(" / ") }})
{{ unsupportedLanguages.join('、') }} 检查不了语法要求(判题机只认 {{ AST_SUPPORTED_LANGUAGES.join(' / ') }})
</n-text>
<n-text v-if="!supportedLanguages.length" depth="3" class="note">先选能交的语言</n-text>
<template v-for="lang in supportedLanguages" :key="lang">
@@ -418,31 +404,19 @@ watch(supportedLanguages, (langs) => {
size="tiny"
class="message"
:placeholder="
checkOf(lang, index)?.description
? `学生看到「${checkOf(lang, index)!.description}」,想换个说法写这里`
: '学生看到的话(不填就按规则自动写)'
checkOf(lang, index)?.description ? `学生看到「${checkOf(lang, index)!.description}」,想换个说法写这里` : '学生看到的话(不填就按规则自动写)'
"
@update:value="(v: string) => updateRule(lang, index, 'message', v)"
/>
<template v-if="challenge">
<n-text v-if="checkOf(lang, index)?.passed === true" depth="3" class="note">
标准答案这样写也满足
</n-text>
<n-text v-if="checkOf(lang, index)?.passed === true" depth="3" class="note"> 标准答案这样写也满足 </n-text>
<n-text v-else-if="checkOf(lang, index)?.passed === false" depth="3" class="note">
标准答案不是这样写的{{
checkOf(lang, index)!.actual !== undefined
? `(数到 ${checkOf(lang, index)!.actual} 次)`
: ""
}}
标准答案不是这样写的{{ checkOf(lang, index)!.actual !== undefined ? `(数到 ${checkOf(lang, index)!.actual} 次)` : '' }}
</n-text>
</template>
<span v-else-if="checkOf(lang, index)?.passed === true" class="ok">✓ 标准答案过了</span>
<span v-else-if="checkOf(lang, index)?.passed === false" class="bad">
✗ 标准答案自己没过{{
checkOf(lang, index)!.actual !== undefined
? `(数到 ${checkOf(lang, index)!.actual} 次)`
: ""
}}
✗ 标准答案自己没过{{ checkOf(lang, index)!.actual !== undefined ? `(数到 ${checkOf(lang, index)!.actual} 次)` : '' }}
</span>
<n-text v-else-if="checkOf(lang, index)" depth="3">没有 {{ lang }} 的标准答案</n-text>
</div>
@@ -472,14 +446,14 @@ watch(supportedLanguages, (langs) => {
.label {
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
width: 72px;
flex: none;
}
.langs {
display: flex;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 4px;
overflow: hidden;
}
@@ -491,17 +465,17 @@ watch(supportedLanguages, (langs) => {
background: transparent;
font: inherit;
font-size: 12px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
cursor: pointer;
}
.lang + .lang {
border-left: 1px solid v-bind("theme.borderColor");
border-left: 1px solid v-bind('theme.borderColor');
}
.lang.on {
background-color: rgba(24, 160, 88, 0.12);
color: v-bind("theme.primaryColorPressed");
color: v-bind('theme.primaryColorPressed');
font-weight: 600;
}
@@ -524,7 +498,7 @@ watch(supportedLanguages, (langs) => {
flex-direction: column;
gap: 4px;
padding: 6px 8px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
border-radius: 4px;
background-color: rgba(128, 128, 128, 0.04);
font-size: 13px;
@@ -557,17 +531,17 @@ watch(supportedLanguages, (langs) => {
}
.ok {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
white-space: nowrap;
}
.bad {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
white-space: nowrap;
}
.ruleError {
font-size: 12px;
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
</style>
@@ -1,16 +1,16 @@
<script setup lang="ts">
import type { AdminTag } from "utils/types"
import { batchTagProblems, getTagAdminList } from "admin/api"
import type { AdminTag } from 'utils/types'
import { batchTagProblems, getTagAdminList } from 'admin/api'
interface Props {
show: boolean
problemIds: number[]
action: "add" | "remove"
action: 'add' | 'remove'
}
const props = defineProps<Props>()
const emit = defineEmits<{
"update:show": [value: boolean]
'update:show': [value: boolean]
done: []
}>()
@@ -20,15 +20,11 @@ const tags = ref<AdminTag[]>([])
const selected = ref<string[]>([])
const newTags = ref<string[]>([])
const title = computed(() => (props.action === "add" ? "批量添加标签" : "批量移除标签"))
const title = computed(() => (props.action === 'add' ? '批量添加标签' : '批量移除标签'))
const selectedSet = computed(() => new Set(selected.value))
const names = computed(() =>
props.action === "add"
? Array.from(new Set([...selected.value, ...newTags.value]))
: selected.value,
)
const names = computed(() => (props.action === 'add' ? Array.from(new Set([...selected.value, ...newTags.value])) : selected.value))
function toggleTag(name: string) {
const set = new Set(selected.value)
@@ -43,19 +39,19 @@ async function listTags() {
}
function close() {
emit("update:show", false)
emit('update:show', false)
}
async function submit() {
if (!names.value.length) {
message.error("请先选择标签")
message.error('请先选择标签')
return
}
const res = await batchTagProblems(props.problemIds, names.value, props.action)
const verb = props.action === "add" ? "添加" : "移除"
const verb = props.action === 'add' ? '添加' : '移除'
message.success(`已为 ${res.problemCount} 道题${verb} ${res.tagCount} 个标签`)
close()
emit("done")
emit('done')
}
watch(
@@ -70,24 +66,11 @@ watch(
</script>
<template>
<n-modal
:show="show"
preset="card"
:title="title"
style="width: 600px"
:mask-closable="false"
@close="close"
>
<n-modal :show="show" preset="card" :title="title" style="width: 600px" :mask-closable="false" @close="close">
<n-flex vertical size="large">
<div>已选中 {{ problemIds.length }} 道题目</div>
<n-flex size="small">
<n-tag
v-for="tag in tags"
:key="tag.id"
checkable
:checked="selectedSet.has(tag.name)"
@update:checked="toggleTag(tag.name)"
>
<n-tag v-for="tag in tags" :key="tag.id" checkable :checked="selectedSet.has(tag.name)" @update:checked="toggleTag(tag.name)">
{{ tag.name }}({{ tag.problemCount }})
</n-tag>
</n-flex>
@@ -1,13 +1,13 @@
<script setup lang="ts">
import { useThemeVars } from "naive-ui"
import { useBreakpoints } from "shared/composables/breakpoints"
import { caseStatus, type AnswerSource, type CaseRow } from "./caseRows"
import { useThemeVars } from 'naive-ui'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { caseStatus, type AnswerSource, type CaseRow } from './caseRows'
/**
* 测试数据一组一行:输入 | 输出 | 当例子(设计稿「编程题出题页」B)。
* 有标准答案时输出是跑出来的、只读;没有时(老题)输出手写。
*/
const rows = defineModel<CaseRow[]>("rows", { required: true })
const rows = defineModel<CaseRow[]>('rows', { required: true })
const props = defineProps<{
source: AnswerSource | null
/** 只有例子这一列表的时候(测试数据太大、单独写例子)不显示「当例子」 */
@@ -23,14 +23,13 @@ const CLIP_LINES = 6
const expanded = ref(new Set<number>())
function lines(text: string) {
return text.split("\n")
return text.split('\n')
}
function clipped(row: CaseRow) {
const all = lines(row.output)
if (expanded.value.has(row.key) || all.length <= CLIP_LINES + 1)
return { text: row.output, rest: 0 }
return { text: all.slice(0, CLIP_LINES).join("\n"), rest: all.length - CLIP_LINES }
if (expanded.value.has(row.key) || all.length <= CLIP_LINES + 1) return { text: row.output, rest: 0 }
return { text: all.slice(0, CLIP_LINES).join('\n'), rest: all.length - CLIP_LINES }
}
function toggle(key: number) {
@@ -52,17 +51,12 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
<div class="row head">
<span></span>
<span>输入</span>
<span>{{ source ? "输出(答案跑出来的)" : "输出(手写)" }}</span>
<span>{{ source ? '输出(答案跑出来的)' : '输出(手写)' }}</span>
<span v-if="!examplesOnly">当例子</span>
<span></span>
<span></span>
</div>
<div
v-for="(row, index) in rows"
:key="row.key"
class="row"
:class="{ bad: status(row) === 'error', changed: status(row) === 'changed' }"
>
<div v-for="(row, index) in rows" :key="row.key" class="row" :class="{ bad: status(row) === 'error', changed: status(row) === 'changed' }">
<b class="no">{{ index + 1 }}</b>
<n-input
v-model:value="row.input"
@@ -86,25 +80,16 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
<div v-if="status(row) === 'error'" class="cell errorCell">{{ row.error }}</div>
<template v-else>
<pre class="cell" :class="{ stale: status(row) === 'running' }">{{
clipped(row).text || (status(row) === "running" ? "在跑……" : "(没有输出)")
clipped(row).text || (status(row) === 'running' ? '在跑……' : '(没有输出)')
}}</pre>
<button v-if="clipped(row).rest" type="button" class="more" @click="toggle(row.key)">
⋯ 还有 {{ clipped(row).rest }} 行
</button>
<button
v-else-if="expanded.has(row.key)"
type="button"
class="more"
@click="toggle(row.key)"
>
收起
</button>
<button v-if="clipped(row).rest" type="button" class="more" @click="toggle(row.key)">⋯ 还有 {{ clipped(row).rest }} 行</button>
<button v-else-if="expanded.has(row.key)" type="button" class="more" @click="toggle(row.key)">收起</button>
<div v-if="status(row) === 'changed'" class="was">
变了 · 原来存的是
<del>{{
lines(row.saved ?? "")
lines(row.saved ?? '')
.slice(0, 3)
.join(" ⏎ ") || "(空)"
.join(' ⏎ ') || '(空)'
}}</del>
</div>
</template>
@@ -123,15 +108,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
<template v-else-if="status(row) === 'error'">✗</template>
<template v-else-if="status(row) === 'changed'">●</template>
</span>
<n-button
quaternary
size="tiny"
class="remove"
:aria-label="`删掉第 ${index + 1} 组`"
@click="remove(index)"
>
删掉
</n-button>
<n-button quaternary size="tiny" class="remove" :aria-label="`删掉第 ${index + 1} 组`" @click="remove(index)"> 删掉 </n-button>
</div>
</div>
</div>
@@ -149,7 +126,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
gap: 8px;
align-items: start;
padding: 7px 4px;
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
font-size: 12px;
border-radius: 4px;
}
@@ -162,7 +139,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
border-top: 0;
padding-top: 2px;
padding-bottom: 2px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.row.changed {
@@ -176,7 +153,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
.mono :deep(textarea),
.cell {
font-family: ui-monospace, "Cascadia Mono", Consolas, "Microsoft YaHei", monospace;
font-family: ui-monospace, 'Cascadia Mono', Consolas, 'Microsoft YaHei', monospace;
font-size: 12px;
line-height: 1.5;
}
@@ -196,7 +173,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
min-height: 26px;
padding: 3px 7px;
border-radius: 3px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
background-color: rgba(128, 128, 128, 0.05);
white-space: pre;
overflow-x: auto;
@@ -209,8 +186,8 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
.errorCell {
white-space: pre-wrap;
word-break: break-all;
color: v-bind("theme.errorColor");
border-color: v-bind("theme.errorColorSuppl");
color: v-bind('theme.errorColor');
border-color: v-bind('theme.errorColorSuppl');
background-color: rgba(208, 48, 80, 0.06);
}
@@ -219,7 +196,7 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
padding: 0;
background: none;
font: inherit;
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
cursor: pointer;
}
@@ -228,11 +205,11 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
}
.was {
color: v-bind("theme.warningColorPressed");
color: v-bind('theme.warningColorPressed');
}
.was del {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.example {
@@ -245,15 +222,15 @@ const status = (row: CaseRow) => caseStatus(row, props.source)
}
.mark.ok {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
}
.mark.error {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
.mark.changed {
color: v-bind("theme.warningColor");
color: v-bind('theme.warningColor');
}
.remove {
@@ -7,11 +7,11 @@ import {
type AstRules,
type ChallengeInput,
type ChallengeSuggestionsResponse,
} from "@oj2/contract"
import { errorMessage } from "utils/api"
import type { LANGUAGE } from "utils/types"
import { getChallengeSuggestions } from "../../api"
import AstRulesEditor from "./AstRulesEditor.vue"
} from '@oj2/contract'
import { errorMessage } from 'utils/api'
import type { LANGUAGE } from 'utils/types'
import { getChallengeSuggestions } from '../../api'
import AstRulesEditor from './AstRulesEditor.vue'
/**
* 出题页的「挑战」:做对之后,同一道题加一条写法上的限制再做一遍(设计稿 StkAdmin)。
@@ -29,15 +29,13 @@ const props = defineProps<{
problemId: number | null
}>()
const emit = defineEmits<{
(e: "update:modelValue", value: Record<string, ChallengeInput[]> | null): void
(e: 'update:modelValue', value: Record<string, ChallengeInput[]> | null): void
}>()
const languages = computed(() =>
props.languages.filter((lang) => AST_SUPPORTED_LANGUAGES.includes(lang)),
)
const tab = ref<string>(languages.value[0] ?? "Python")
const languages = computed(() => props.languages.filter((lang) => AST_SUPPORTED_LANGUAGES.includes(lang)))
const tab = ref<string>(languages.value[0] ?? 'Python')
watch(languages, (list) => {
if (!list.includes(tab.value as LANGUAGE)) tab.value = list[0] ?? "Python"
if (!list.includes(tab.value as LANGUAGE)) tab.value = list[0] ?? 'Python'
})
const list = computed(() => props.modelValue?.[tab.value] ?? [])
@@ -46,7 +44,7 @@ function update(next: ChallengeInput[]) {
const value = { ...props.modelValue }
if (next.length) value[tab.value] = next
else delete value[tab.value]
emit("update:modelValue", Object.keys(value).length ? value : null)
emit('update:modelValue', Object.keys(value).length ? value : null)
}
function patch(index: number, change: Partial<ChallengeInput>) {
@@ -57,7 +55,7 @@ function remove(index: number) {
update(list.value.filter((_, i) => i !== index))
}
function add(item: ChallengeInput = { wording: "", rules: [] }) {
function add(item: ChallengeInput = { wording: '', rules: [] }) {
update([...list.value, item])
}
@@ -75,19 +73,19 @@ const full = computed(() => list.value.length >= CHALLENGES_PER_LANGUAGE_MAX)
const suggestions = ref<Record<string, ChallengeSuggestionsResponse>>({})
const loading = ref(false)
const error = ref("")
const error = ref('')
async function findSuggestions() {
if (!props.problemId) return
loading.value = true
error.value = ""
error.value = ''
try {
suggestions.value = {
...suggestions.value,
[tab.value]: await getChallengeSuggestions(props.problemId, tab.value),
}
} catch (err) {
error.value = errorMessage(err, "没找成")
error.value = errorMessage(err, '没找成')
} finally {
loading.value = false
}
@@ -98,9 +96,7 @@ const current = computed(() => suggestions.value[tab.value] ?? null)
/** 已经加上的不再列 */
const shown = computed(() => {
const taken = list.value.map((item) => JSON.stringify(item.rules))
return (current.value?.suggestions ?? []).filter(
(item) => !taken.includes(JSON.stringify(item.rules)),
)
return (current.value?.suggestions ?? []).filter((item) => !taken.includes(JSON.stringify(item.rules)))
})
</script>
@@ -108,7 +104,7 @@ const shown = computed(() => {
<div class="challenge-editor">
<n-radio-group v-if="languages.length > 1" v-model:value="tab" size="small">
<n-radio-button v-for="lang in languages" :key="lang" :value="lang">
{{ lang }}{{ modelValue?.[lang]?.length ? ` ${modelValue[lang]!.length} 条` : "" }}
{{ lang }}{{ modelValue?.[lang]?.length ? ` ${modelValue[lang]!.length} 条` : '' }}
</n-radio-button>
</n-radio-group>
@@ -133,46 +129,26 @@ const shown = computed(() => {
/>
</div>
<n-text v-if="!languages.length" depth="3" class="note">
只有 Python、C、C++ 能配挑战,先在「学生怎么写」里勾上其中一种。
</n-text>
<n-text v-if="!languages.length" depth="3" class="note"> 只有 Python、C、C++ 能配挑战,先在「学生怎么写」里勾上其中一种。 </n-text>
<template v-else>
<div class="actions">
<n-button size="small" :disabled="full" @click="add()">+ 自己写一条</n-button>
<n-button
v-if="problemId"
size="small"
:loading="loading"
:disabled="full"
@click="findSuggestions"
>
从做对的代码里找
</n-button>
<n-button v-if="problemId" size="small" :loading="loading" :disabled="full" @click="findSuggestions"> 从做对的代码里找 </n-button>
</div>
<n-text v-if="error" type="error" class="note">{{ error }}</n-text>
<div v-if="current" class="suggestions">
<n-text depth="3" class="note">
{{ current.acCount }} 个人用 {{ tab }} 做对过,下面是有一批人换了种写法也做对的地方
</n-text>
<n-text depth="3" class="note"> {{ current.acCount }} 个人用 {{ tab }} 做对过,下面是有一批人换了种写法也做对的地方 </n-text>
<n-text v-if="!shown.length" depth="3" class="note">没找到别的写法</n-text>
<div v-for="item in shown" :key="JSON.stringify(item.rules)" class="suggestion">
<div class="suggestionHead">
<div class="suggestionText">
<b>{{ item.wording }}</b>
<n-text depth="3" class="note">
{{ item.did }} 人这样做对<template v-if="item.firstShare !== null"
>,第一次做对时 {{ item.firstShare }}% 这样写</template
>
{{ item.did }} 人这样做对<template v-if="item.firstShare !== null">,第一次做对时 {{ item.firstShare }}% 这样写</template>
</n-text>
</div>
<n-button
size="small"
:disabled="full"
@click="add({ wording: item.wording, rules: item.rules })"
>
加上
</n-button>
<n-button size="small" :disabled="full" @click="add({ wording: item.wording, rules: item.rules })"> 加上 </n-button>
</div>
<pre class="example">{{ item.example }}</pre>
</div>
@@ -255,7 +231,7 @@ const shown = computed(() => {
padding: 6px 10px;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 4px;
font-family: ui-monospace, "Cascadia Mono", Consolas, "Microsoft YaHei", monospace;
font-family: ui-monospace, 'Cascadia Mono', Consolas, 'Microsoft YaHei', monospace;
font-size: 12.5px;
line-height: 1.6;
white-space: pre;
@@ -1,19 +1,17 @@
<script setup lang="ts">
import Markdown from "shared/components/Markdown.vue"
import { useThemeVars } from "naive-ui"
import { useMermaid } from "shared/composables/useMermaid"
import { DIFFICULTY, SOURCES } from "utils/constants"
import { getTagColor } from "utils/functions"
import type { AstRules, BlankProblem, LANGUAGE } from "utils/types"
import type { FlowDoc } from "shared/components/FlowchartEditor/model"
import type { AstCheckState, FlowchartMode, PreviewTab } from "./editorTypes"
import type { TemplateParts } from "./codeTemplate"
import { isBlankHtml } from "./problemForm"
import Markdown from 'shared/components/Markdown.vue'
import { useThemeVars } from 'naive-ui'
import { useMermaid } from 'shared/composables/useMermaid'
import { DIFFICULTY, SOURCES } from 'utils/constants'
import { getTagColor } from 'utils/functions'
import type { AstRules, BlankProblem, LANGUAGE } from 'utils/types'
import type { FlowDoc } from 'shared/components/FlowchartEditor/model'
import type { AstCheckState, FlowchartMode, PreviewTab } from './editorTypes'
import type { TemplateParts } from './codeTemplate'
import { isBlankHtml } from './problemForm'
const CodeEditor = defineAsyncComponent(() => import("shared/components/CodeEditor.vue"))
const FlowchartView = defineAsyncComponent(
() => import("shared/components/FlowchartEditor/FlowchartView.vue"),
)
const CodeEditor = defineAsyncComponent(() => import('shared/components/CodeEditor.vue'))
const FlowchartView = defineAsyncComponent(() => import('shared/components/FlowchartEditor/FlowchartView.vue'))
/**
* 编程题出题页的右栏:学生打开这道题看到的样子(设计稿「编程题出题页」B)。
@@ -23,7 +21,7 @@ const FlowchartView = defineAsyncComponent(
const props = defineProps<{
displayId: string
title: string
difficulty: BlankProblem["difficulty"]
difficulty: BlankProblem['difficulty']
description: string
inputDescription: string
outputDescription: string
@@ -43,38 +41,29 @@ const props = defineProps<{
flowchartDoc: FlowDoc | null
}>()
const tab = defineModel<PreviewTab>("tab", { required: true })
const tab = defineModel<PreviewTab>('tab', { required: true })
const emit = defineEmits<{ renderState: [ok: boolean]; collapse: [] }>()
const theme = useThemeVars()
// ---------------------------------------------------------------- 语法要求
const KIND_TAG_TYPE = { require: "success", forbid: "error", count: "info" } as const
const KIND_TAG_TYPE = { require: 'success', forbid: 'error', count: 'info' } as const
function requirementsOf(lang: string) {
const rules = props.astRules?.[lang] ?? []
const state = props.astChecks[lang]
return rules.map((rule, i) => ({
text:
rule.message ||
(state && !("error" in state) ? state.rules[i]?.description : "") ||
"(规则还没写完)",
kind: rule.engine.startsWith("must_not")
? ("forbid" as const)
: rule.engine.startsWith("count")
? ("count" as const)
: ("require" as const),
text: rule.message || (state && !('error' in state) ? state.rules[i]?.description : '') || '(规则还没写完)',
kind: rule.engine.startsWith('must_not') ? ('forbid' as const) : rule.engine.startsWith('count') ? ('count' as const) : ('require' as const),
}))
}
const requirementLanguages = computed(() =>
props.languages.filter((lang) => (props.astRules?.[lang]?.length ?? 0) > 0),
)
const requirementLanguages = computed(() => props.languages.filter((lang) => (props.astRules?.[lang]?.length ?? 0) > 0))
// ---------------------------------------------------------------- 编辑器
const editorLanguage = ref<LANGUAGE>(props.languages[0] ?? "Python")
const editorLanguage = ref<LANGUAGE>(props.languages[0] ?? 'Python')
watch(
() => props.languages,
(langs) => {
@@ -92,18 +81,18 @@ const editorCode = computed(() => {
const referenceDoc = computed(() => (props.flowchartDoc?.steps.length ? props.flowchartDoc : null))
const container = useTemplateRef<HTMLElement>("chart")
const container = useTemplateRef<HTMLElement>('chart')
const { renderFlowchart, renderError, renderSuccess } = useMermaid()
async function render() {
await renderFlowchart(container.value, props.mermaidCode)
emit("renderState", renderSuccess.value)
emit('renderState', renderSuccess.value)
}
// 改了先报「没验证」,防抖之后的渲染跑完再报结果(和 MermaidEditor 同一个理由)
watch(
() => props.mermaidCode,
() => emit("renderState", false),
() => emit('renderState', false),
)
watchDebounced(() => props.mermaidCode, render, { debounce: 300, maxWait: 1000 })
onMounted(() => nextTick(render))
@@ -117,20 +106,16 @@ onMounted(() => nextTick(render))
<n-radio-group v-model:value="tab" size="small">
<n-radio-button value="statement">题面</n-radio-button>
<n-radio-button value="editor">编辑器</n-radio-button>
<n-radio-button value="flowchart" :class="{ dim: flowchartMode === 'none' }">
流程图
</n-radio-button>
<n-radio-button value="flowchart" :class="{ dim: flowchartMode === 'none' }"> 流程图 </n-radio-button>
</n-radio-group>
<n-button size="small" quaternary title="收起,专心写左边" @click="emit('collapse')">
收起 ›
</n-button>
<n-button size="small" quaternary title="收起,专心写左边" @click="emit('collapse')"> 收起 › </n-button>
</div>
<!-- 题面 -->
<div v-show="tab === 'statement'" class="page">
<div class="titleRow">
<span v-if="displayId" class="pid">{{ displayId }}</span>
<h2>{{ title || "(题目还没起名)" }}</h2>
<h2>{{ title || '(题目还没起名)' }}</h2>
</div>
<div class="meta">
<n-tag size="small" :bordered="false" :type="getTagColor(difficulty)">
@@ -144,13 +129,7 @@ onMounted(() => nextTick(render))
<span v-if="requirementLanguages.length > 1 || languages.length > 1" class="langLabel">
{{ lang }}
</span>
<n-tag
v-for="(rule, i) in requirementsOf(lang)"
:key="`${lang}-${i}`"
:type="KIND_TAG_TYPE[rule.kind]"
size="small"
:bordered="false"
>
<n-tag v-for="(rule, i) in requirementsOf(lang)" :key="`${lang}-${i}`" :type="KIND_TAG_TYPE[rule.kind]" size="small" :bordered="false">
{{ rule.text }}
</n-tag>
</template>
@@ -188,7 +167,7 @@ onMounted(() => nextTick(render))
</template>
</div>
<p v-else class="placeholder">
{{ bigData ? "在左边加一个例子" : "在左边的测试数据里勾几组「当例子」" }}
{{ bigData ? '在左边加一个例子' : '在左边的测试数据里勾几组「当例子」' }}
</p>
<template v-if="flowchartMode === 'show'">
@@ -217,40 +196,23 @@ onMounted(() => nextTick(render))
</div>
<div v-if="(astRules?.[editorLanguage]?.length ?? 0) > 0" class="requirements">
<span class="requirementsHead">语法要求</span>
<n-tag
v-for="(rule, i) in requirementsOf(editorLanguage)"
:key="i"
:type="KIND_TAG_TYPE[rule.kind]"
size="small"
:bordered="false"
>
<n-tag v-for="(rule, i) in requirementsOf(editorLanguage)" :key="i" :type="KIND_TAG_TYPE[rule.kind]" size="small" :bordered="false">
{{ rule.text }}
</n-tag>
</div>
<p class="muted small">
{{
editorParts?.template.trim()
? "学生打开编辑器时里面已经有这些:"
? '学生打开编辑器时里面已经有这些:'
: SOURCES[editorLanguage]
? `没写 ${editorLanguage} 的预制代码,学生打开是全站默认的:`
: `没写 ${editorLanguage} 的预制代码,学生打开是空白的`
}}
</p>
<CodeEditor
v-if="editorCode"
:value="editorCode"
:language="editorLanguage"
:font-size="14"
height="320px"
readonly
/>
<CodeEditor v-if="editorCode" :value="editorCode" :language="editorLanguage" :font-size="14" height="320px" readonly />
<p v-if="editorParts?.prepend.trim() || editorParts?.append.trim()" class="muted small">
提交时,学生的代码{{
editorParts?.prepend.trim() && editorParts?.append.trim()
? "前后"
: editorParts?.prepend.trim()
? "前面"
: "后面"
editorParts?.prepend.trim() && editorParts?.append.trim() ? '前后' : editorParts?.prepend.trim() ? '前面' : '后面'
}}还会拼上你藏起来的代码。
</p>
</div>
@@ -258,9 +220,7 @@ onMounted(() => nextTick(render))
<!-- 流程图:一直挂着,改了图的代码随时知道画不画得出来 -->
<div v-show="tab === 'flowchart'" class="page">
<p v-if="flowchartMode === 'none'" class="placeholder">这道题不用流程图</p>
<p v-else-if="flowchartMode === 'draw'" class="placeholder">
学生在题目页右边自己画,交上去按例子和测试数据评
</p>
<p v-else-if="flowchartMode === 'draw'" class="placeholder">学生在题目页右边自己画,交上去按例子和测试数据评</p>
<template v-else>
<p class="muted small">学生在题面例子下面看到的是:</p>
<div v-if="referenceDoc" class="reference">
@@ -304,10 +264,10 @@ onMounted(() => nextTick(render))
.page {
max-height: calc(100vh - 150px);
overflow: auto;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
padding: 18px 22px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
display: flex;
flex-direction: column;
gap: 10px;
@@ -326,7 +286,7 @@ onMounted(() => nextTick(render))
}
.pid {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
/* 和题目页的小节标题一个样子(oj/problem/components/ProblemContent.vue) */
@@ -336,7 +296,7 @@ onMounted(() => nextTick(render))
line-height: 1.4;
margin: 6px 0 0;
padding-left: 9px;
border-left: 3px solid v-bind("theme.primaryColor");
border-left: 3px solid v-bind('theme.primaryColor');
}
.io {
@@ -363,7 +323,7 @@ onMounted(() => nextTick(render))
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
font-size: 12px;
}
@@ -374,7 +334,7 @@ onMounted(() => nextTick(render))
.placeholder {
margin: 0;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
/* 参考流程图:和学生题面(ProblemContent.vue)同一种浅灰底 */
@@ -398,7 +358,7 @@ onMounted(() => nextTick(render))
.sampleLabel,
.sampleNo {
font-size: 12px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.sampleNo {
@@ -412,7 +372,7 @@ onMounted(() => nextTick(render))
padding: 4px 10px;
border-radius: 6px;
background-color: rgba(128, 128, 128, 0.08);
font-family: ui-monospace, "Cascadia Mono", Consolas, "Microsoft YaHei", monospace;
font-family: ui-monospace, 'Cascadia Mono', Consolas, 'Microsoft YaHei', monospace;
font-size: 13px;
line-height: 1.55;
white-space: pre;
@@ -432,7 +392,7 @@ onMounted(() => nextTick(render))
padding: 8px 10px;
border-radius: 4px;
font-size: 13px;
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
background-color: rgba(208, 48, 80, 0.08);
word-break: break-all;
}
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { Icon } from '@iconify/vue'
/**
* 「新建题目」先选题型:编程题和 SQL 题是两张不同的出题页,测试数据的格式也不一样,
@@ -7,39 +7,33 @@ import { Icon } from "@iconify/vue"
* 每项要两行(名字 + 一句话),n-dropdown 的选项是固定行高,放不下,所以自己画
*/
defineProps<{ label: string; primary?: boolean }>()
const emit = defineEmits<{ select: [kind: "code" | "sql"] }>()
const emit = defineEmits<{ select: [kind: 'code' | 'sql'] }>()
const show = ref(false)
const OPTIONS = [
{
kind: "code",
icon: "ph:code-bold",
title: "编程题",
note: "C / C++ / Python,有输入输出说明和样例,也能挂流程图、语法要求",
kind: 'code',
icon: 'ph:code-bold',
title: '编程题',
note: 'C / C++ / Python,有输入输出说明和样例,也能挂流程图、语法要求',
},
{
kind: "sql",
icon: "ph:database-bold",
title: "SQL 题",
note: "学生写 SQL 查数据库;给几组建表脚本和一条标准答案就行",
kind: 'sql',
icon: 'ph:database-bold',
title: 'SQL 题',
note: '学生写 SQL 查数据库;给几组建表脚本和一条标准答案就行',
},
] as const
function pick(kind: "code" | "sql") {
function pick(kind: 'code' | 'sql') {
show.value = false
emit("select", kind)
emit('select', kind)
}
</script>
<template>
<n-popover
v-model:show="show"
trigger="click"
placement="bottom-end"
:show-arrow="false"
style="padding: 6px; width: 340px"
>
<n-popover v-model:show="show" trigger="click" placement="bottom-end" :show-arrow="false" style="padding: 6px; width: 340px">
<template #trigger>
<n-button :type="primary ? 'primary' : 'default'" icon-placement="right">
{{ label }}
@@ -47,13 +41,7 @@ function pick(kind: "code" | "sql") {
</n-button>
</template>
<div class="menu">
<button
v-for="option in OPTIONS"
:key="option.kind"
type="button"
class="option"
@click="pick(option.kind)"
>
<button v-for="option in OPTIONS" :key="option.kind" type="button" class="option" @click="pick(option.kind)">
<Icon :icon="option.icon" :width="20" class="icon" :class="option.kind" />
<span class="text">
<b>{{ option.title }}</b>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { useThemeVars } from "naive-ui"
import { useThemeVars } from 'naive-ui'
/**
* 出题页右栏「学生看到的样子」收起来之后剩下的那一条:竖着贴在右边,点一下展开。
@@ -27,18 +27,18 @@ const theme = useThemeVars()
flex-direction: column;
align-items: center;
gap: 8px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
background: v-bind("theme.cardColor");
color: v-bind("theme.textColor2");
background: v-bind('theme.cardColor');
color: v-bind('theme.textColor2');
font: inherit;
font-size: 13px;
cursor: pointer;
}
.strip:hover {
color: v-bind("theme.primaryColor");
border-color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
border-color: v-bind('theme.primaryColor');
}
.arrow {
@@ -1,10 +1,10 @@
<script setup lang="ts">
import { zonedParts } from "utils/functions"
import type { StuckProblemDetail, StuckStudent } from "utils/types"
import UserName from "shared/components/UserName.vue"
import { classLabel } from "utils/classes"
import { resultName, useResultColor } from "oj/statistics/results"
import { avgTries, rate } from "./stuckMath"
import { zonedParts } from 'utils/functions'
import type { StuckProblemDetail, StuckStudent } from 'utils/types'
import UserName from 'shared/components/UserName.vue'
import { classLabel } from 'utils/classes'
import { resultName, useResultColor } from 'oj/statistics/results'
import { avgTries, rate } from './stuckMath'
/**
* 卡点分析右栏:一道题的详情(做过几人、一次就对、错在哪、各班、交了几次才对、历年、
@@ -34,14 +34,12 @@ const summary = computed(() => {
}
})
const errorTotal = computed(() =>
(props.detail.errors ?? []).reduce((sum, row) => sum + row.count, 0),
)
const errorTotal = computed(() => (props.detail.errors ?? []).reduce((sum, row) => sum + row.count, 0))
const byClass = computed(() => {
const groups = new Map<string, StuckStudent[]>()
for (const row of students.value) {
const key = row.className ?? ""
const key = row.className ?? ''
groups.set(key, [...(groups.get(key) ?? []), row])
}
return [...groups]
@@ -62,11 +60,11 @@ const byClass = computed(() => {
})
const BUCKETS = [
{ label: "1 次", min: 1, max: 1 },
{ label: "2 次", min: 2, max: 2 },
{ label: "3 次", min: 3, max: 3 },
{ label: "4–5 次", min: 4, max: 5 },
{ label: "6 次以上", min: 6, max: Infinity },
{ label: '1 次', min: 1, max: 1 },
{ label: '2 次', min: 2, max: 2 },
{ label: '3 次', min: 3, max: 3 },
{ label: '4–5 次', min: 4, max: 5 },
{ label: '6 次以上', min: 6, max: Infinity },
]
const distribution = computed(() => {
const solved = students.value.filter((row) => row.solved)
@@ -85,9 +83,7 @@ const mostTries = computed(() =>
.slice(0, 6),
)
const stuckStudents = computed(() =>
students.value.filter((row) => !row.solved).sort((a, b) => b.tries - a.tries),
)
const stuckStudents = computed(() => students.value.filter((row) => !row.solved).sort((a, b) => b.tries - a.tries))
const currentYear = (() => {
const now = zonedParts(new Date())!
@@ -103,8 +99,8 @@ const history = computed(() =>
)
function gap(minutes: number | null) {
if (minutes === null) return ""
if (minutes < 1) return "不到 1 分钟"
if (minutes === null) return ''
if (minutes < 1) return '不到 1 分钟'
if (minutes < 60) return `${minutes} 分钟`
if (minutes < 1440) return `${Math.round(minutes / 60)} 小时`
return `隔了 ${Math.round(minutes / 1440)} 天`
@@ -119,12 +115,12 @@ const links = computed(() => {
if (!row) return null
const scope = props.className ? { className: props.className } : {}
return {
problem: href({ name: "problem", params: { problemID: row.displayId } }),
problem: href({ name: 'problem', params: { problemID: row.displayId } }),
statistics: href({
name: "statistics",
name: 'statistics',
query: { problem: row.displayId, period: props.period, ...scope },
}),
submissions: href({ name: "submissions", query: { problem: row.displayId, ...scope } }),
submissions: href({ name: 'submissions', query: { problem: row.displayId, ...scope } }),
}
})
</script>
@@ -156,9 +152,7 @@ const links = computed(() => {
</div>
<div>
<div class="muted small">还没做对</div>
<div class="big num" :class="{ red: summary.stuck }">
{{ summary.stuck }}<span class="unit"> 人</span>
</div>
<div class="big num" :class="{ red: summary.stuck }">{{ summary.stuck }}<span class="unit"> 人</span></div>
</div>
</div>
@@ -202,11 +196,7 @@ const links = computed(() => {
<div class="dist">
<div v-for="row in distribution" :key="row.label" class="dcol">
<span class="small num strong">{{ row.count }} 人</span>
<span
class="dbar"
:class="{ first: row.min === 1, many: row.min === 6 }"
:style="{ height: `${row.height}px` }"
/>
<span class="dbar" :class="{ first: row.min === 1, many: row.min === 6 }" :style="{ height: `${row.height}px` }" />
<span class="muted small">{{ row.label }}</span>
</div>
</div>
@@ -236,14 +226,10 @@ const links = computed(() => {
</template>
<div v-if="history.length" class="block">
<div class="muted small">历年一次就对{{ className ? "(全站)" : "" }}</div>
<div class="muted small">历年一次就对{{ className ? '(全站)' : '' }}</div>
<div v-for="row in history" :key="row.label" class="hrow num">
<span class="hlabel" :class="{ muted: !row.current }">
{{ row.label }}{{ row.current ? " 这学年" : "" }}
</span>
<span class="track mid" :class="{ past: !row.current }"
><span :style="{ width: `${row.rate}%` }"
/></span>
<span class="hlabel" :class="{ muted: !row.current }"> {{ row.label }}{{ row.current ? ' 这学年' : '' }} </span>
<span class="track mid" :class="{ past: !row.current }"><span :style="{ width: `${row.rate}%` }" /></span>
<span class="pct" :class="{ strong: row.current }">{{ row.rate }}%</span>
<span class="muted small">{{ row.users }} 人</span>
</div>
@@ -260,17 +246,10 @@ const links = computed(() => {
<UserName :username="row.username" class="uname" />
<span class="muted num ntries">交了 {{ row.tries }} 次</span>
<span class="legend" :style="{ color: resultColor(row.lastResult) }">
<i :style="{ background: resultColor(row.lastResult) }" />{{
resultName(row.lastResult)
}}
<i :style="{ background: resultColor(row.lastResult) }" />{{ resultName(row.lastResult) }}
</span>
<span class="grow" />
<a
:href="href({ path: `/submission/${row.lastSubmissionId}` })"
target="_blank"
class="link small"
>看代码</a
>
<a :href="href({ path: `/submission/${row.lastSubmissionId}` })" target="_blank" class="link small">看代码</a>
</div>
</div>
</div>
@@ -1,10 +1,10 @@
<script setup lang="ts">
import { NButton, NTag } from "naive-ui"
import Pagination from "shared/components/Pagination.vue"
import type { AdminProblemRow } from "utils/types"
import { batchTagProblems, getProblemList } from "admin/api"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import { NButton, NTag } from 'naive-ui'
import Pagination from 'shared/components/Pagination.vue'
import type { AdminProblemRow } from 'utils/types'
import { batchTagProblems, getProblemList } from 'admin/api'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
interface Props {
show: boolean
@@ -14,7 +14,7 @@ interface Props {
const props = defineProps<Props>()
const emit = defineEmits<{
"update:show": [value: boolean]
'update:show': [value: boolean]
changed: []
}>()
@@ -25,34 +25,29 @@ const problems = ref<AdminProblemRow[]>([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const keyword = ref("")
const keyword = ref('')
const { isMobile } = useBreakpoints()
const allColumns: DataTableColumn<AdminProblemRow>[] = [
{ title: "题号", key: "_id", width: 90 },
{ title: '题号', key: '_id', width: 90 },
{
title: "题目",
key: "title",
title: '题目',
key: 'title',
minWidth: 200,
render: (row) =>
h(NButton, { text: true, type: "primary", onClick: () => goEdit(row) }, () => row.title),
render: (row) => h(NButton, { text: true, type: 'primary', onClick: () => goEdit(row) }, () => row.title),
},
{
title: "学生看得到",
key: "visible",
title: '学生看得到',
key: 'visible',
width: 100,
render: (row) =>
h(NTag, { size: "small", bordered: false, type: row.visible ? "success" : "default" }, () =>
row.visible ? "看得到" : "藏着",
),
render: (row) => h(NTag, { size: 'small', bordered: false, type: row.visible ? 'success' : 'default' }, () => (row.visible ? '看得到' : '藏着')),
},
{
title: "",
key: "actions",
title: '',
key: 'actions',
width: 90,
render: (row) =>
h(NButton, { size: "small", quaternary: true, onClick: () => removeTag(row) }, () => "摘掉"),
render: (row) => h(NButton, { size: 'small', quaternary: true, onClick: () => removeTag(row) }, () => '摘掉'),
},
]
@@ -69,27 +64,25 @@ const { loading, track } = useListLoader()
async function listProblems() {
if (page.value < 1) page.value = 1
const offset = (page.value - 1) * limit.value
const res = await track(
getProblemList(offset, limit.value, keyword.value, "", undefined, props.tagId),
)
const res = await track(getProblemList(offset, limit.value, keyword.value, '', undefined, props.tagId))
if (!res) return
problems.value = res.results
total.value = res.total
}
function close() {
emit("update:show", false)
emit('update:show', false)
}
function goEdit(row: AdminProblemRow) {
close()
router.push({ name: "admin problem edit", params: { problemID: row.id } })
router.push({ name: 'admin problem edit', params: { problemID: row.id } })
}
async function removeTag(row: AdminProblemRow) {
await batchTagProblems([row.id], [props.tagName], "remove")
await batchTagProblems([row.id], [props.tagName], 'remove')
message.success(`已移除「${row.title}」的标签`)
emit("changed")
emit('changed')
// 移掉本页最后一条时退回上一页,交给下面的 watcher 重新拉取
if (problems.value.length === 1 && page.value > 1) {
page.value -= 1
@@ -107,7 +100,7 @@ watch(
(show) => {
if (!show) return
page.value = 1
keyword.value = ""
keyword.value = ''
},
)
@@ -123,22 +116,11 @@ watchDebounced(
</script>
<template>
<n-modal
:show="show"
preset="card"
:title="`标签「${tagName}」下的题目`"
style="width: 720px"
@close="close"
>
<n-modal :show="show" preset="card" :title="`标签「${tagName}」下的题目`" style="width: 720px" @close="close">
<n-flex vertical size="large">
<n-flex justify="space-between" align="center">
<span>共 {{ total }} 道题</span>
<n-input
v-model:value="keyword"
:style="{ width: isMobile ? '160px' : '220px' }"
placeholder="题号或题目名"
clearable
/>
<n-input v-model:value="keyword" :style="{ width: isMobile ? '160px' : '220px' }" placeholder="题号或题目名" clearable />
</n-flex>
<n-data-table :loading="loading" striped :columns="columns" :data="problems" />
<Pagination :total="total" v-model:limit="limit" v-model:page="page" />
@@ -1,14 +1,10 @@
import {
TEST_CASE_EDIT_MAX_CASES,
TEST_CASE_EDIT_MAX_FILE_BYTES,
TEST_CASE_MAX_CASES,
} from "@oj2/contract"
import type { RunnableLanguage } from "@oj2/contract"
import { strFromU8, unzipSync } from "fflate"
import type { Ref } from "vue"
import { errorMessage } from "utils/api"
import { JUDGE_STATUS, SubmissionStatus } from "utils/constants"
import { trialRun } from "utils/judge"
import { TEST_CASE_EDIT_MAX_CASES, TEST_CASE_EDIT_MAX_FILE_BYTES, TEST_CASE_MAX_CASES } from '@oj2/contract'
import type { RunnableLanguage } from '@oj2/contract'
import { strFromU8, unzipSync } from 'fflate'
import type { Ref } from 'vue'
import { errorMessage } from 'utils/api'
import { JUDGE_STATUS, SubmissionStatus } from 'utils/constants'
import { trialRun } from 'utils/judge'
/**
* 编程题出题页的测试数据(设计稿「编程题出题页」B):一组一行,输出由标准答案在判题机上
@@ -37,19 +33,19 @@ export interface AnswerSource {
code: string
}
export type CaseStatus = "manual" | "empty" | "running" | "error" | "changed" | "ok"
export type CaseStatus = 'manual' | 'empty' | 'running' | 'error' | 'changed' | 'ok'
let nextKey = 0
export function newRow(input = "", output = "", example = false, saved: string | null = null) {
export function newRow(input = '', output = '', example = false, saved: string | null = null) {
return {
key: nextKey++,
input,
output,
example,
saved,
ranFor: "",
error: "",
ranFor: '',
error: '',
} satisfies CaseRow
}
@@ -59,32 +55,31 @@ export function newRow(input = "", output = "", example = false, saved: string |
*/
export function normalizeCase(input: string, output: string) {
return {
input: input.replace(/\r\n/g, "\n").replace(/\n$/, ""),
output: output.replace(/\r\n/g, "\n").trimEnd(),
input: input.replace(/\r\n/g, '\n').replace(/\n$/, ''),
output: output.replace(/\r\n/g, '\n').trimEnd(),
}
}
/** 判题机比对时去掉的是整段输出末尾的空白(见 services/test-case.ts 的 rstrip),这里同一个口径 */
export function sameOutput(a: string, b: string) {
return a.replace(/\r\n/g, "\n").trimEnd() === b.replace(/\r\n/g, "\n").trimEnd()
return a.replace(/\r\n/g, '\n').trimEnd() === b.replace(/\r\n/g, '\n').trimEnd()
}
const signatureOf = (source: AnswerSource, row: CaseRow) =>
JSON.stringify([source.language, source.code, row.input])
const signatureOf = (source: AnswerSource, row: CaseRow) => JSON.stringify([source.language, source.code, row.input])
export function caseStatus(row: CaseRow, source: AnswerSource | null): CaseStatus {
if (!source) return "manual"
if (row.ranFor !== signatureOf(source, row)) return "running"
if (row.error) return "error"
if (row.saved !== null && !sameOutput(row.saved, row.output)) return "changed"
return "ok"
if (!source) return 'manual'
if (row.ranFor !== signatureOf(source, row)) return 'running'
if (row.error) return 'error'
if (row.saved !== null && !sameOutput(row.saved, row.output)) return 'changed'
return 'ok'
}
/** 答案报错时给老师看的一句话:状态 + 输出的最后一行(Python 的异常原文就在那) */
function describeFailure(result: SubmissionStatus, output: string, line?: number | null) {
const name = JUDGE_STATUS[result]?.name ?? "没跑通"
const last = output.trimEnd().split("\n").at(-1)?.trim()
const where = line ? `(第 ${line} 行)` : ""
const name = JUDGE_STATUS[result]?.name ?? '没跑通'
const last = output.trimEnd().split('\n').at(-1)?.trim()
const where = line ? `(第 ${line} 行)` : ''
return last ? `${name}:${last}${where}` : `${name}${where}`
}
@@ -118,26 +113,26 @@ export function useCaseRunner(rows: Ref<CaseRow[]>, source: Ref<AnswerSource | n
})
batch.forEach((row, i) => {
row.ranFor = signatures[i]!
if (response.status === "compile-error") {
row.output = ""
row.error = `标准答案编译不过:${response.message.trim().split("\n").at(-1) ?? ""}`
} else if (response.status === "too-much-output") {
row.output = ""
row.error = "输出太多(多半是死循环在不停打印)"
if (response.status === 'compile-error') {
row.output = ''
row.error = `标准答案编译不过:${response.message.trim().split('\n').at(-1) ?? ''}`
} else if (response.status === 'too-much-output') {
row.output = ''
row.error = '输出太多(多半是死循环在不停打印)'
} else {
const run = response.cases[i]!
if (run.result === SubmissionStatus.accepted) {
row.output = run.output.trimEnd()
row.error = ""
row.error = ''
} else {
row.output = ""
row.output = ''
row.error = describeFailure(run.result, run.output, run.runtimeError?.line)
}
}
})
} catch (err) {
// 判题机忙、连不上:这一批记成没跑通,别无限重试;老师点「重跑」再来
const reason = errorMessage(err, "判题机暂时连不上")
const reason = errorMessage(err, '判题机暂时连不上')
batch.forEach((row, i) => {
row.ranFor = signatures[i]!
row.error = reason
@@ -156,7 +151,7 @@ export function useCaseRunner(rows: Ref<CaseRow[]>, source: Ref<AnswerSource | n
/** 「重跑」:把没跑通的几组作废重来 */
function rerunFailed() {
rows.value.forEach((row) => {
if (row.error) row.ranFor = ""
if (row.error) row.ranFor = ''
})
void runAll()
}
@@ -168,44 +163,37 @@ export function useCaseRunner(rows: Ref<CaseRow[]>, source: Ref<AnswerSource | n
* 导入 zip:在浏览器里拆成一组组。和后端 collectPairs 同一个规矩 —— 从 1.in / 1.out
* 开始连续编号,断了就停。太大(见契约 TEST_CASE_EDIT_*)就不拆,交给调用方直接上传。
*/
export function readCaseZip(
archive: Uint8Array,
): { ok: true; cases: { input: string; output: string }[] } | { ok: false; reason: string } {
export function readCaseZip(archive: Uint8Array): { ok: true; cases: { input: string; output: string }[] } | { ok: false; reason: string } {
let files: Record<string, Uint8Array>
try {
files = unzipSync(archive, { filter: (file) => /^\d+\.(in|out)$/.test(file.name) })
} catch {
return { ok: false, reason: "压缩包损坏,或者不是 zip" }
return { ok: false, reason: '压缩包损坏,或者不是 zip' }
}
const cases: { input: string; output: string }[] = []
for (let i = 1; files[`${i}.in`] && files[`${i}.out`]; i += 1) {
const input = files[`${i}.in`]!
const output = files[`${i}.out`]!
if (
input.length > TEST_CASE_EDIT_MAX_FILE_BYTES ||
output.length > TEST_CASE_EDIT_MAX_FILE_BYTES
)
return { ok: false, reason: "too-large" }
if (input.length > TEST_CASE_EDIT_MAX_FILE_BYTES || output.length > TEST_CASE_EDIT_MAX_FILE_BYTES) return { ok: false, reason: 'too-large' }
cases.push(normalizeCase(strFromU8(input), strFromU8(output)))
}
if (!cases.length)
return { ok: false, reason: "压缩包里没有从 1.in / 1.out 开始连续编号的测试点" }
if (!cases.length) return { ok: false, reason: '压缩包里没有从 1.in / 1.out 开始连续编号的测试点' }
if (cases.length > TEST_CASE_MAX_CASES)
return {
ok: false,
reason: `测试数据最多 ${TEST_CASE_MAX_CASES} 组,这个压缩包里有 ${cases.length} 组,挑有代表性的留下`,
}
if (cases.length > TEST_CASE_EDIT_MAX_CASES) return { ok: false, reason: "too-large" }
if (cases.length > TEST_CASE_EDIT_MAX_CASES) return { ok: false, reason: 'too-large' }
return { ok: true, cases }
}
/** 打包上传前的文件内容:CRLF 统一成 LF,非空输入补结尾换行(C 的 scanf / gets 读最后一行更稳) */
export function caseFiles(rows: { input: string; output: string }[]) {
const lf = (text: string) => text.replace(/\r\n/g, "\n")
const lf = (text: string) => text.replace(/\r\n/g, '\n')
return rows.flatMap((row, i) => {
const input = lf(row.input)
return [
{ name: `${i + 1}.in`, content: input && !input.endsWith("\n") ? `${input}\n` : input },
{ name: `${i + 1}.in`, content: input && !input.endsWith('\n') ? `${input}\n` : input },
{ name: `${i + 1}.out`, content: lf(row.output) },
]
})
@@ -14,18 +14,17 @@ export interface TemplateParts {
append: string
}
const section = (raw: string, name: string) =>
raw.match(new RegExp(`//${name} BEGIN\\n([\\s\\S]+?)//${name} END`))?.[1] ?? ""
const section = (raw: string, name: string) => raw.match(new RegExp(`//${name} BEGIN\\n([\\s\\S]+?)//${name} END`))?.[1] ?? ''
/** 段落末尾那个换行是标记格式要的,不是内容,显示时去掉 */
const strip = (text: string) => text.replace(/\n$/, "")
const strip = (text: string) => text.replace(/\n$/, '')
export function parseTemplate(raw: string | undefined): TemplateParts {
if (!raw) return { prepend: "", template: "", append: "" }
if (!raw) return { prepend: '', template: '', append: '' }
return {
prepend: strip(section(raw, "PREPEND")),
template: strip(section(raw, "TEMPLATE")),
append: strip(section(raw, "APPEND")),
prepend: strip(section(raw, 'PREPEND')),
template: strip(section(raw, 'TEMPLATE')),
append: strip(section(raw, 'APPEND')),
}
}
@@ -40,7 +39,7 @@ export function buildTemplate(parts: TemplateParts): string | null {
`//PREPEND BEGIN\n${body(parts.prepend)}//PREPEND END`,
`//TEMPLATE BEGIN\n${body(parts.template)}//TEMPLATE END`,
`//APPEND BEGIN\n${body(parts.append)}//APPEND END`,
].join("\n\n")
].join('\n\n')
}
/** 跑标准答案时套上前后两段,和判题时(routes/trial-run.ts、judgeSubmission)一个拼法 */
@@ -51,5 +50,5 @@ export function wrapWithTemplate(code: string, parts: TemplateParts) {
/** 一段内容:非空时统一以一个换行结尾 */
function body(text: string) {
return text.trim() ? `${text.replace(/\n*$/, "")}\n` : ""
return text.trim() ? `${text.replace(/\n*$/, '')}\n` : ''
}
@@ -1,13 +1,13 @@
import type { AstCheckResponse } from "@oj2/contract"
import type { AstCheckResponse } from '@oj2/contract'
/**
* 出题页里每种语言的语法要求自测结果:每条规则学生看到的那句话 + 标准答案过不过。
* 规则本身配得不对(后端 astRulesError)时是一句错误。右边预览和保存前的检查都看它
*/
export type AstCheckState = Record<string, { rules: AstCheckResponse["rules"] } | { error: string }>
export type AstCheckState = Record<string, { rules: AstCheckResponse['rules'] } | { error: string }>
/** 右栏「学生看到的样子」开着哪一页 */
export type PreviewTab = "statement" | "editor" | "flowchart"
export type PreviewTab = 'statement' | 'editor' | 'flowchart'
/** 流程图三选一:不用 / 给学生看参考图(showFlowchart)/ 让学生自己画、按这张图打分(allowFlowchart) */
export type FlowchartMode = "none" | "show" | "draw"
export type FlowchartMode = 'none' | 'show' | 'draw'
@@ -3,5 +3,5 @@
* 记在本机:老师想专心写的时候收起来,下次打开还是收着的
*/
export function usePreviewCollapsed() {
return useStorage("oj2:admin-problem-preview-collapsed", false)
return useStorage('oj2:admin-problem-preview-collapsed', false)
}
@@ -1,9 +1,9 @@
import { PROBLEM_TAG_MAX_LENGTH } from "@oj2/contract"
import { StorageSerializers, useLocalStorage, watchDebounced } from "@vueuse/core"
import type { WatchSource } from "vue"
import { errorCode, errorMessage } from "utils/api"
import { DIFFICULTY } from "utils/constants"
import { unique } from "utils/functions"
import { PROBLEM_TAG_MAX_LENGTH } from '@oj2/contract'
import { StorageSerializers, useLocalStorage, watchDebounced } from '@vueuse/core'
import type { WatchSource } from 'vue'
import { errorCode, errorMessage } from 'utils/api'
import { DIFFICULTY } from 'utils/constants'
import { unique } from 'utils/functions'
/**
* 编程题(detail.vue)、SQL 题(SqlDetail.vue)两个出题页共用的零件。两页要填的东西几乎
@@ -11,23 +11,21 @@ import { unique } from "utils/functions"
*/
/** 富文本编辑器清空之后留下的是一个空段落,不是空串 */
export const isBlankHtml = (html: string) => !html.trim() || html === "<p><br></p>"
export const isBlankHtml = (html: string) => !html.trim() || html === '<p><br></p>'
export const difficultyOptions = (["Low", "Mid", "High"] as const).map((value) => ({
export const difficultyOptions = (['Low', 'Mid', 'High'] as const).map((value) => ({
label: DIFFICULTY[value],
value,
}))
/** 出题页的「返回」:比赛题回这场比赛的题目列表,公开题回题库 */
export function problemListRoute(contestID: string | undefined) {
return contestID
? { name: "admin contest problem list", params: { contestID } }
: { name: "admin problem list" }
return contestID ? { name: 'admin contest problem list', params: { contestID } } : { name: 'admin problem list' }
}
/** 保存失败给老师看的话。编号撞了是最常见的一种,单独说清楚 */
export function saveErrorText(err: unknown) {
return errorCode(err) === "display-id-exists" ? "显示编号重复了,换一个" : errorMessage(err)
return errorCode(err) === 'display-id-exists' ? '显示编号重复了,换一个' : errorMessage(err)
}
/**
@@ -48,10 +46,7 @@ export const tagTooLongText = (tag: string) => `标签最多 ${PROBLEM_TAG_MAX_L
*
* `enabled` 在页面数据摆好之前要返回 false,不然加载时那一下会把空表单存进去。
*/
export function useCreateDraft<T>(
key: string,
options: { source: WatchSource; enabled: () => boolean; empty: () => boolean; take: () => T },
) {
export function useCreateDraft<T>(key: string, options: { source: WatchSource; enabled: () => boolean; empty: () => boolean; take: () => T }) {
// 初值是 null 时 VueUse 推不出类型,会拿 String() 存成 "[object Object]",得显式指定
const draft = useLocalStorage<T | null>(key, null, { serializer: StorageSerializers.object })
watchDebounced(
@@ -1,5 +1,5 @@
import type { SqlDisplay } from "utils/types"
import { changedRowCount, tableChanges } from "oj/problem/utils/sqlChanges"
import type { SqlDisplay } from 'utils/types'
import { changedRowCount, tableChanges } from 'oj/problem/utils/sqlChanges'
/** 出题页的一组测试数据:一份建表 + 插数据的脚本,和它跑出来的样子 */
export interface ScriptGroup {
@@ -16,7 +16,7 @@ export interface ScriptGroup {
running: string
}
export type GroupStatus = "empty" | "no-answer" | "running" | "ok" | "error"
export type GroupStatus = 'empty' | 'no-answer' | 'running' | 'ok' | 'error'
/**
* SQLite 的报错是英文,出题的老师未必看得懂。常见的几种翻成一句中文,
@@ -28,17 +28,17 @@ export function explainSqlError(message: string) {
[/no such column: (\S+)/, (m) => `没有 ${m[1]} 这一列`],
[/table (\S+) already exists/, (m) => `${m[1]} 这张表建了两次`],
[/near "([^"]*)": syntax error/, (m) => `语法有错,在「${m[1]}」附近`],
[/incomplete input/, () => "语句没写完(少了右括号或分号?)"],
[/incomplete input/, () => '语句没写完(少了右括号或分号?)'],
[/UNIQUE constraint failed: (\S+)/, (m) => `${m[1]} 有重复的值`],
[/(\d+) values for (\d+) columns/, (m) => `一行给了 ${m[1]} 个值,但表有 ${m[2]} 列`],
]
if (message.includes("标准答案未修改任何表数据")) {
return "标准答案在这组数据上一行都没改:第 1 组是题面上给学生看的,里面要有会被改到的行"
if (message.includes('标准答案未修改任何表数据')) {
return '标准答案在这组数据上一行都没改:第 1 组是题面上给学生看的,里面要有会被改到的行'
}
for (const [pattern, say] of rules) {
const match = message.match(pattern)
if (match) {
const where = message.startsWith("标准答案") ? "标准答案在这组数据上" : "这组的脚本"
const where = message.startsWith('标准答案') ? '标准答案在这组数据上' : '这组的脚本'
return `${where}跑不起来:${say(match)}`
}
}
@@ -47,9 +47,9 @@ export function explainSqlError(message: string) {
/** 列表里那一行的小结:几张表各几行 → 期望几行 / 改了几行 */
export function groupSummary(display: SqlDisplay) {
const rows = display.tables.map((t) => t.total_rows).join(" + ")
const rows = display.tables.map((t) => t.total_rows).join(' + ')
const expected = display.expected
if ("columns" in expected) return `${rows} 行 → 期望 ${expected.total_rows} 行`
if ('columns' in expected) return `${rows} 行 → 期望 ${expected.total_rows} 行`
const changed = expected.changed_tables.reduce((sum, table) => {
if (table.dropped) return sum + 1
const changes = tableChanges(
@@ -7,5 +7,5 @@ export function rate(part: number, whole: number) {
/** 做对的人平均交了几次(只数做对那次及之前的) */
export function avgTries(row: { solved: number; solvedTries: number }) {
return row.solved ? (row.solvedTries / row.solved).toFixed(1) : "-"
return row.solved ? (row.solvedTries / row.solved).toFixed(1) : '-'
}
File diff suppressed because it is too large. Load diff
+12 -28
View File
@@ -1,9 +1,9 @@
<script setup lang="ts">
import { isSqlProblem } from "@oj2/contract"
import type { AdminProblem } from "utils/types"
import { getProblem } from "../api"
import ProblemDetail from "./detail.vue"
import SqlDetail from "./SqlDetail.vue"
import { isSqlProblem } from '@oj2/contract'
import type { AdminProblem } from 'utils/types'
import { getProblem } from '../api'
import ProblemDetail from './detail.vue'
import SqlDetail from './SqlDetail.vue'
/**
* 出题 / 改题的入口:编程题和 SQL 题是两张不同的页。
@@ -20,25 +20,21 @@ const router = useRouter()
const message = useMessage()
const loaded = shallowRef<AdminProblem | null>(null)
const kind = ref<"code" | "sql" | null>(null)
const kind = ref<'code' | 'sql' | null>(null)
async function resolve() {
kind.value = null
loaded.value = null
if (!props.problemID) {
kind.value = route.query.type === "sql" ? "sql" : "code"
kind.value = route.query.type === 'sql' ? 'sql' : 'code'
return
}
try {
loaded.value = await getProblem(props.problemID)
kind.value = isSqlProblem(loaded.value) ? "sql" : "code"
kind.value = isSqlProblem(loaded.value) ? 'sql' : 'code'
} catch {
message.error("获取题目失败")
router.push(
props.contestID
? { name: "admin contest problem list", params: { contestID: props.contestID } }
: { name: "admin problem list" },
)
message.error('获取题目失败')
router.push(props.contestID ? { name: 'admin contest problem list', params: { contestID: props.contestID } } : { name: 'admin problem list' })
}
}
@@ -46,18 +42,6 @@ watch(() => [props.problemID, route.query.type], resolve, { immediate: true })
</script>
<template>
<SqlDetail
v-if="kind === 'sql'"
:key="`sql-${problemID ?? 'new'}`"
:problem-i-d="problemID"
:contest-i-d="contestID"
:initial="loaded"
/>
<ProblemDetail
v-else-if="kind === 'code'"
:key="`code-${problemID ?? 'new'}`"
:problem-i-d="problemID"
:contest-i-d="contestID"
:initial="loaded"
/>
<SqlDetail v-if="kind === 'sql'" :key="`sql-${problemID ?? 'new'}`" :problem-i-d="problemID" :contest-i-d="contestID" :initial="loaded" />
<ProblemDetail v-else-if="kind === 'code'" :key="`code-${problemID ?? 'new'}`" :problem-i-d="problemID" :contest-i-d="contestID" :initial="loaded" />
</template>
+95 -142
View File
@@ -1,22 +1,22 @@
<script setup lang="ts">
import { NSwitch, useThemeVars } from "naive-ui"
import Pagination from "shared/components/Pagination.vue"
import { usePagination } from "shared/composables/pagination"
import { parseTime } from "utils/functions"
import type { AdminProblemRow } from "utils/types"
import { errorMessage } from "utils/api"
import { batchSetProblemVisible, getProblemList, toggleProblemVisible } from "../api"
import Actions from "./components/Actions.vue"
import AddFromLibraryModal from "./components/AddFromLibraryModal.vue"
import { useRouteQuery } from "@vueuse/router"
import AuthorSelect from "admin/components/AuthorSelect.vue"
import type { DataTableRowKey } from "naive-ui"
import BatchTagModal from "./components/BatchTagModal.vue"
import CreateProblemMenu from "./components/CreateProblemMenu.vue"
import PageHeader from "admin/components/PageHeader.vue"
import ProblemTypeTag from "oj/problem/components/ProblemTypeTag.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import { NSwitch, useThemeVars } from 'naive-ui'
import Pagination from 'shared/components/Pagination.vue'
import { usePagination } from 'shared/composables/pagination'
import { parseTime } from 'utils/functions'
import type { AdminProblemRow } from 'utils/types'
import { errorMessage } from 'utils/api'
import { batchSetProblemVisible, getProblemList, toggleProblemVisible } from '../api'
import Actions from './components/Actions.vue'
import AddFromLibraryModal from './components/AddFromLibraryModal.vue'
import { useRouteQuery } from '@vueuse/router'
import AuthorSelect from 'admin/components/AuthorSelect.vue'
import type { DataTableRowKey } from 'naive-ui'
import BatchTagModal from './components/BatchTagModal.vue'
import CreateProblemMenu from './components/CreateProblemMenu.vue'
import PageHeader from 'admin/components/PageHeader.vue'
import ProblemTypeTag from 'oj/problem/components/ProblemTypeTag.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
/**
* 后台题目列表(设计稿「后台题目列表」PlA / PlB)。一行一道题:题号、题目(点了就是编辑)、
@@ -39,11 +39,11 @@ const { isMobile } = useBreakpoints()
const title = computed(
() =>
({
"admin problem list": "题目列表",
"admin contest problem list": "比赛题目列表",
'admin problem list': '题目列表',
'admin contest problem list': '比赛题目列表',
})[route.name as string],
)
const isContestProblemList = computed(() => route.name === "admin contest problem list")
const isContestProblemList = computed(() => route.name === 'admin contest problem list')
const [show, toggleShow] = useToggle()
const { count, inc } = useCounter(0)
@@ -51,7 +51,7 @@ const total = ref(0)
const problems = ref<AdminProblemRow[]>([])
const selectedRowKeys = ref<DataTableRowKey[]>([])
const batchTagAction = ref<"add" | "remove">("add")
const batchTagAction = ref<'add' | 'remove'>('add')
const [showBatchTag, toggleBatchTag] = useToggle(false)
const selectedProblemIds = computed(() => selectedRowKeys.value.map((key) => Number(key)))
@@ -62,7 +62,7 @@ function chooseProblems(rowKeys: DataTableRowKey[]) {
selectedRowKeys.value = rowKeys
}
function openBatchTag(action: "add" | "remove") {
function openBatchTag(action: 'add' | 'remove') {
batchTagAction.value = action
toggleBatchTag(true)
}
@@ -73,38 +73,38 @@ function onBatchTagDone() {
}
const nextDisplayID = computed(() => {
if (!isContestProblemList.value) return ""
if (problems.value.length === 0) return "1"
if (!isContestProblemList.value) return ''
if (problems.value.length === 0) return '1'
const ids = problems.value.map((p) => p._id)
if (ids.every((id) => /^\d+$/.test(id))) {
return String(Math.max(...ids.map((id) => parseInt(id))) + 1)
}
return ""
return ''
})
interface ProblemQuery {
keyword: string
author: string
kind: "" | "code" | "sql"
kind: '' | 'code' | 'sql'
/** 1 = 学生看得到的,0 = 藏着的 */
visible: "" | "1" | "0"
visible: '' | '1' | '0'
}
// 使用分页 composable
const { query, clearQuery } = usePagination<ProblemQuery>({
keyword: useRouteQuery("keyword", "").value,
author: useRouteQuery("author", "").value,
kind: useRouteQuery<ProblemQuery["kind"]>("kind", "").value,
visible: useRouteQuery<ProblemQuery["visible"]>("visible", "").value,
keyword: useRouteQuery('keyword', '').value,
author: useRouteQuery('author', '').value,
kind: useRouteQuery<ProblemQuery['kind']>('kind', '').value,
visible: useRouteQuery<ProblemQuery['visible']>('visible', '').value,
})
const counts = ref<{ all: number; visible: number; hidden: number } | null>(null)
// 手机上三个按钮放不下、「藏着的」被切掉:换小号,再不够就横着滑
const narrow = useMediaQuery("(max-width: 640px)")
const narrow = useMediaQuery('(max-width: 640px)')
const visibleTabs = computed(() => [
{ value: "" as const, label: "全部", count: counts.value?.all },
{ value: "1" as const, label: "学生看得到", count: counts.value?.visible },
{ value: "0" as const, label: "藏着的", count: counts.value?.hidden },
{ value: '' as const, label: '全部', count: counts.value?.all },
{ value: '1' as const, label: '学生看得到', count: counts.value?.visible },
{ value: '0' as const, label: '藏着的', count: counts.value?.hidden },
])
/**
@@ -112,27 +112,25 @@ const visibleTabs = computed(() => [
* 列宽只放得下两个,摆两个再加 +N 的话 +N 会被截掉
*/
function renderTags(tags: string[]) {
if (!tags.length) return h("span", { class: "muted" }, "—")
if (!tags.length) return h('span', { class: 'muted' }, '—')
const shown = tags.length > 2 ? tags.slice(0, 1) : tags
return h("span", { class: "tags", title: tags.join("、") }, [
...shown.map((tag) => h("span", { class: "tag", key: tag }, tag)),
tags.length > shown.length
? h("span", { class: "muted more" }, `+${tags.length - shown.length}`)
: null,
return h('span', { class: 'tags', title: tags.join('、') }, [
...shown.map((tag) => h('span', { class: 'tag', key: tag }, tag)),
tags.length > shown.length ? h('span', { class: 'muted more' }, `+${tags.length - shown.length}`) : null,
])
}
function renderTitle(row: AdminProblemRow) {
const kinds = [
row.isSql ? h(ProblemTypeTag, { kind: "sql" }) : null,
row.allowFlowchart ? h(ProblemTypeTag, { kind: "flowchart" }) : null,
row.hasAstRules ? h(ProblemTypeTag, { kind: "ast" }) : null,
row.isSql ? h(ProblemTypeTag, { kind: 'sql' }) : null,
row.allowFlowchart ? h(ProblemTypeTag, { kind: 'flowchart' }) : null,
row.hasAstRules ? h(ProblemTypeTag, { kind: 'ast' }) : null,
]
return h("span", { class: "title-cell" }, [
return h('span', { class: 'title-cell' }, [
h(
"a",
'a',
{
class: "title-link",
class: 'title-link',
href: router.resolve(editRoute(row.id)).href,
onClick: (event: MouseEvent) => {
if (event.ctrlKey || event.metaKey || event.shiftKey) return
@@ -148,56 +146,53 @@ function renderTitle(row: AdminProblemRow) {
function editRoute(problemID: number) {
return {
name: isContestProblemList.value ? "admin contest problem edit" : "admin problem edit",
name: isContestProblemList.value ? 'admin contest problem edit' : 'admin problem edit',
params: isContestProblemList.value ? { contestID: props.contestID, problemID } : { problemID },
}
}
const baseColumns: DataTableColumn<AdminProblemRow>[] = [
{
title: "题号",
key: "_id",
title: '题号',
key: '_id',
width: 70,
render: (row) => h("span", { class: "did", title: `内部编号 ${row.id}` }, row._id),
render: (row) => h('span', { class: 'did', title: `内部编号 ${row.id}` }, row._id),
},
// 题目定宽:p90 也就 12 个字加一两个类型标签。原来 minWidth 让它吃掉整行剩余空间(用户嫌空太多),
// 剩下的宽度给最后的操作列
{ title: "题目", key: "title", width: 196, ellipsis: false, render: renderTitle },
{ title: "知识点", key: "tags", width: 158, render: (row) => renderTags(row.tags) },
{ title: '题目', key: 'title', width: 196, ellipsis: false, render: renderTitle },
{ title: '知识点', key: 'tags', width: 158, render: (row) => renderTags(row.tags) },
{
title: "做对 / 做过",
key: "users",
title: '做对 / 做过',
key: 'users',
width: 96,
render: (row) =>
row.triedUsers
? h("span", { class: "num" }, [
String(row.solvedUsers),
h("span", { class: "muted" }, ` / ${row.triedUsers}`),
])
: h("span", { class: "muted" }, "没人做过"),
? h('span', { class: 'num' }, [String(row.solvedUsers), h('span', { class: 'muted' }, ` / ${row.triedUsers}`)])
: h('span', { class: 'muted' }, '没人做过'),
},
{ title: "出题人", key: "username", width: 86, ellipsis: { tooltip: true } },
{ title: '出题人', key: 'username', width: 86, ellipsis: { tooltip: true } },
{
title: "创建",
key: "create_time",
title: '创建',
key: 'create_time',
width: 100,
render: (row) => h("span", { class: "num muted" }, parseTime(row.createTime, "YYYY-MM-DD")),
render: (row) => h('span', { class: 'num muted' }, parseTime(row.createTime, 'YYYY-MM-DD')),
},
{
title: "学生看得到",
key: "visible",
title: '学生看得到',
key: 'visible',
width: 96,
render: (row) =>
h(NSwitch, {
value: row.visible,
size: "small",
size: 'small',
rubberBand: false,
onUpdateValue: () => toggleVisible(row.id),
}),
},
{
title: "",
key: "actions",
title: '',
key: 'actions',
minWidth: 240,
render: (row) =>
h(Actions, {
@@ -215,24 +210,18 @@ const baseColumns: DataTableColumn<AdminProblemRow>[] = [
*/
function renderMobileCard(row: AdminProblemRow) {
const meta = [
row.tags.length
? row.tags.slice(0, 2).join("、") + (row.tags.length > 2 ? ` +${row.tags.length - 2}` : "")
: null,
isContestProblemList.value
? null
: row.triedUsers
? `做对 ${row.solvedUsers} / ${row.triedUsers}`
: "没人做过",
row.tags.length ? row.tags.slice(0, 2).join('、') + (row.tags.length > 2 ? ` +${row.tags.length - 2}` : '') : null,
isContestProblemList.value ? null : row.triedUsers ? `做对 ${row.solvedUsers} / ${row.triedUsers}` : '没人做过',
row.username,
parseTime(row.createTime, "YYYY-MM-DD"),
parseTime(row.createTime, 'YYYY-MM-DD'),
].filter((it): it is string => !!it)
return h("div", { class: "m-card" }, [
h("div", { class: "m-head" }, [h("span", { class: "did" }, row._id), renderTitle(row)]),
return h('div', { class: 'm-card' }, [
h('div', { class: 'm-head' }, [h('span', { class: 'did' }, row._id), renderTitle(row)]),
// 每一项自己不断开(「做对 8 / 14」折成两半看不懂),放不下整项换行
h(
"div",
{ class: "m-meta muted" },
meta.map((text, i) => h("span", { class: "m-item", key: i }, i ? ` · ${text}` : text)),
'div',
{ class: 'm-meta muted' },
meta.map((text, i) => h('span', { class: 'm-item', key: i }, i ? ` · ${text}` : text)),
),
h(Actions, {
problemID: row.id,
@@ -244,12 +233,12 @@ function renderMobileCard(row: AdminProblemRow) {
}
const mobileColumns: DataTableColumn<AdminProblemRow>[] = [
{ title: "题目", key: "title", render: renderMobileCard },
{ title: '题目', key: 'title', render: renderMobileCard },
{
title: "看得到",
key: "visible",
title: '看得到',
key: 'visible',
width: 72,
align: "center",
align: 'center',
render: (row) =>
h(NSwitch, {
value: row.visible,
@@ -261,9 +250,7 @@ const mobileColumns: DataTableColumn<AdminProblemRow>[] = [
const columns = computed<DataTableColumn<AdminProblemRow>[]>(() => {
const cols = isMobile.value ? mobileColumns : baseColumns
return isContestProblemList.value
? cols.filter((it) => !("key" in it) || it.key !== "users")
: [{ type: "selection" }, ...cols]
return isContestProblemList.value ? cols.filter((it) => !('key' in it) || it.key !== 'users') : [{ type: 'selection' }, ...cols]
})
const { loading, track } = useListLoader()
@@ -271,16 +258,7 @@ async function listProblems() {
if (query.page < 1) query.page = 1
const offset = (query.page - 1) * query.limit
const res = await track(
getProblemList(
offset,
query.limit,
query.keyword,
query.author,
props.contestID,
undefined,
query.kind,
props.contestID ? "" : query.visible,
),
getProblemList(offset, query.limit, query.keyword, query.author, props.contestID, undefined, query.kind, props.contestID ? '' : query.visible),
)
if (!res) return
total.value = res.total
@@ -293,7 +271,7 @@ const message = useMessage()
async function batchVisible(visible: boolean) {
try {
const { problemCount } = await batchSetProblemVisible(selectedProblemIds.value, visible)
message.success(`${problemCount} 道题${visible ? "学生看得到了" : "藏起来了"}`)
message.success(`${problemCount} 道题${visible ? '学生看得到了' : '藏起来了'}`)
selectedRowKeys.value = []
listProblems()
} catch (error) {
@@ -321,16 +299,16 @@ async function toggleVisible(problemID: number) {
}
const kindOptions = [
{ label: "全部题型", value: "" },
{ label: "编程题", value: "code" },
{ label: "SQL 题", value: "sql" },
{ label: '全部题型', value: '' },
{ label: '编程题', value: 'code' },
{ label: 'SQL 题', value: 'sql' },
]
function createProblem(kind: string) {
router.push({
name: isContestProblemList.value ? "admin contest problem create" : "admin problem create",
name: isContestProblemList.value ? 'admin contest problem create' : 'admin problem create',
params: isContestProblemList.value ? { contestID: props.contestID } : {},
query: kind === "sql" ? { type: "sql" } : {},
query: kind === 'sql' ? { type: 'sql' } : {},
})
}
@@ -352,10 +330,7 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
</script>
<template>
<PageHeader
:title="title ?? '题目列表'"
:back="isContestProblemList ? { name: 'admin contest list' } : undefined"
>
<PageHeader :title="title ?? '题目列表'" :back="isContestProblemList ? { name: 'admin contest list' } : undefined">
<template #actions>
<template v-if="!isContestProblemList">
<CreateProblemMenu label="新建题目" primary @select="createProblem" />
@@ -366,20 +341,8 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
</template>
</template>
<template #filters>
<n-input
v-model:value="query.keyword"
placeholder="题号或题目名"
clearable
:style="{ width: isMobile ? '100%' : '220px' }"
@clear="clearQuery"
/>
<n-select
v-if="!props.contestID"
v-model:value="query.kind"
:options="kindOptions"
aria-label="题型"
style="width: 120px"
/>
<n-input v-model:value="query.keyword" placeholder="题号或题目名" clearable :style="{ width: isMobile ? '100%' : '220px' }" @clear="clearQuery" />
<n-select v-if="!props.contestID" v-model:value="query.kind" :options="kindOptions" aria-label="题型" style="width: 120px" />
<n-flex v-if="!props.contestID" align="center" :size="8">
<n-text depth="3">出题人</n-text>
<AuthorSelect v-model:value="query.author" all />
@@ -419,18 +382,8 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
@update:checked-row-keys="chooseProblems"
/>
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
<AddFromLibraryModal
v-model:show="show"
:count="count"
:next-display-id="nextDisplayID"
@change="listProblems"
/>
<BatchTagModal
v-model:show="showBatchTag"
:problem-ids="selectedProblemIds"
:action="batchTagAction"
@done="onBatchTagDone"
/>
<AddFromLibraryModal v-model:show="show" :count="count" :next-display-id="nextDisplayID" @change="listProblems" />
<BatchTagModal v-model:show="showBatchTag" :problem-ids="selectedProblemIds" :action="batchTagAction" @done="onBatchTagDone" />
</template>
<style scoped>
@@ -441,8 +394,8 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
margin-bottom: 12px;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid v-bind("theme.successColorSuppl");
background: v-bind("theme.hoverColor");
border: 1px solid v-bind('theme.successColorSuppl');
background: v-bind('theme.hoverColor');
white-space: nowrap;
flex-wrap: wrap;
}
@@ -481,7 +434,7 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
}
.problem-table :deep(.title-link) {
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
font-weight: 500;
text-decoration: none;
}
@@ -504,12 +457,12 @@ watch(() => [query.page, query.limit, query.author, query.kind, query.visible],
height: 22px;
padding: 0 7px;
border-radius: 3px;
background: v-bind("theme.actionColor");
background: v-bind('theme.actionColor');
font-size: 12px;
}
.problem-table :deep(.muted) {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.problem-table :deep(.more) {
+33 -55
View File
@@ -1,22 +1,22 @@
<script setup lang="ts">
import PageHeader from "admin/components/PageHeader.vue"
import { useThemeVars } from "naive-ui"
import type { AdminTag, TagCategory } from "utils/types"
import { deleteTag, getTagAdminList, renameTag, setTagCategory } from "../api"
import TagProblemsModal from "./components/TagProblemsModal.vue"
import PageHeader from 'admin/components/PageHeader.vue'
import { useThemeVars } from 'naive-ui'
import type { AdminTag, TagCategory } from 'utils/types'
import { deleteTag, getTagAdminList, renameTag, setTagCategory } from '../api'
import TagProblemsModal from './components/TagProblemsModal.vue'
const message = useMessage()
const dialog = useDialog()
const theme = useThemeVars()
const tags = ref<AdminTag[]>([])
const keyword = ref("")
const keyword = ref('')
// 搜索在后端做(getTagAdminList 带 keyword),这里只是一份引用,两栏和待归类都从它分
const visibleTags = computed(() => tags.value)
const editingId = ref<number | null>(null)
const editingName = ref("")
const editingName = ref('')
const activeTag = ref<AdminTag | null>(null)
const [showTagProblems, toggleTagProblems] = useToggle(false)
@@ -36,11 +36,11 @@ const columnsOf = computed(() => {
const confirmed = visibleTags.value.filter((t) => t.categoryConfirmed)
return [
{
key: "knowledge" as const,
title: "知识点",
tags: confirmed.filter((t) => t.category === "knowledge"),
key: 'knowledge' as const,
title: '知识点',
tags: confirmed.filter((t) => t.category === 'knowledge'),
},
{ key: "theme" as const, title: "主题", tags: confirmed.filter((t) => t.category === "theme") },
{ key: 'theme' as const, title: '主题', tags: confirmed.filter((t) => t.category === 'theme') },
].map((col) => ({
...col,
tags: [...col.tags].sort((a, b) => b.problemCount - a.problemCount),
@@ -61,13 +61,13 @@ function startEdit(tag: AdminTag) {
function cancelEdit() {
editingId.value = null
editingName.value = ""
editingName.value = ''
}
async function saveTag(tag: AdminTag) {
const name = editingName.value.trim()
if (!name) {
message.error("标签名不能为空")
message.error('标签名不能为空')
return
}
if (name === tag.name) {
@@ -78,7 +78,7 @@ async function saveTag(tag: AdminTag) {
if (res.merged) {
message.success(`已合并到「${res.name}」,影响 ${res.affectedCount} 道题`)
} else {
message.success("已重命名")
message.success('已重命名')
}
cancelEdit()
listTags()
@@ -88,20 +88,18 @@ async function changeCategory(tag: AdminTag, category: TagCategory) {
await setTagCategory(tag.id, category)
tag.category = category
tag.categoryConfirmed = true
message.success(`「${tag.name}」已归到${category === "theme" ? "主题" : "知识点"}`)
message.success(`「${tag.name}」已归到${category === 'theme' ? '主题' : '知识点'}`)
}
function confirmDelete(tag: AdminTag) {
dialog.warning({
title: `删除「${tag.name}」?`,
content: tag.problemCount
? `${tag.problemCount} 道题会摘掉这个标签,题目本身不动。`
: "没有题目挂着它。",
positiveText: "删除",
negativeText: "取消",
content: tag.problemCount ? `${tag.problemCount} 道题会摘掉这个标签,题目本身不动。` : '没有题目挂着它。',
positiveText: '删除',
negativeText: '取消',
onPositiveClick: async () => {
await deleteTag(tag.id)
message.success("已删除")
message.success('已删除')
listTags()
},
})
@@ -139,14 +137,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
<n-empty v-if="!col.tags.length" size="small" description="没有" class="empty" />
<div v-for="tag in col.tags" :key="tag.id" class="row">
<template v-if="editingId === tag.id">
<n-input
v-model:value="editingName"
size="small"
autofocus
class="rename"
@keyup.enter="saveTag(tag)"
@keyup.esc="cancelEdit"
/>
<n-input v-model:value="editingName" size="small" autofocus class="rename" @keyup.enter="saveTag(tag)" @keyup.esc="cancelEdit" />
<n-button size="small" type="primary" @click="saveTag(tag)">保存</n-button>
<n-button size="small" @click="cancelEdit">取消</n-button>
</template>
@@ -154,33 +145,20 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
<button type="button" class="name" :title="tag.name" @click="openTagProblems(tag)">
{{ tag.name }}
</button>
<span class="bar"
><i :style="{ width: `${(tag.problemCount / col.max) * 100}%` }"></i
></span>
<span class="bar"><i :style="{ width: `${(tag.problemCount / col.max) * 100}%` }"></i></span>
<span class="count">{{ tag.problemCount }} 道</span>
<n-button size="tiny" quaternary @click="startEdit(tag)">改名</n-button>
<n-button
size="tiny"
quaternary
@click="changeCategory(tag, tag.category === 'theme' ? 'knowledge' : 'theme')"
>
{{ tag.category === "theme" ? "改成知识点" : "改成主题" }}
<n-button size="tiny" quaternary @click="changeCategory(tag, tag.category === 'theme' ? 'knowledge' : 'theme')">
{{ tag.category === 'theme' ? '改成知识点' : '改成主题' }}
</n-button>
<n-button size="tiny" quaternary type="error" @click="confirmDelete(tag)"
>删除</n-button
>
<n-button size="tiny" quaternary type="error" @click="confirmDelete(tag)">删除</n-button>
</template>
</div>
</div>
</section>
</div>
<TagProblemsModal
v-model:show="showTagProblems"
:tag-id="activeTag?.id ?? 0"
:tag-name="activeTag?.name ?? ''"
@changed="listTags"
/>
<TagProblemsModal v-model:show="showTagProblems" :tag-id="activeTag?.id ?? 0" :tag-name="activeTag?.name ?? ''" @changed="listTags" />
</template>
<style scoped>
@@ -222,7 +200,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
}
.list {
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
border-radius: 8px;
padding: 2px 6px;
}
@@ -233,7 +211,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
gap: 10px;
height: 40px;
padding: 0 4px 0 8px;
border-bottom: 1px solid v-bind("theme.dividerColor");
border-bottom: 1px solid v-bind('theme.dividerColor');
}
.row:last-child {
@@ -242,7 +220,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
/* 斑马底纹,和后台其它列表一样(用户要的) */
.row:nth-child(even) {
background: v-bind("theme.tableColorStriped");
background: v-bind('theme.tableColorStriped');
}
.name {
@@ -257,7 +235,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
font: inherit;
font-size: 15px;
text-align: left;
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
cursor: pointer;
}
@@ -269,7 +247,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
flex: 1 1 auto;
height: 6px;
border-radius: 3px;
background: v-bind("theme.actionColor");
background: v-bind('theme.actionColor');
overflow: hidden;
}
@@ -277,7 +255,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
display: block;
height: 6px;
border-radius: 3px;
background: v-bind("theme.successColorSuppl");
background: v-bind('theme.successColorSuppl');
}
.count {
@@ -285,7 +263,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
text-align: right;
font-size: 13px;
font-variant-numeric: tabular-nums;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.rename {
@@ -294,7 +272,7 @@ watchDebounced(keyword, listTags, { debounce: 500, maxWait: 1000 })
.muted {
font-size: 13px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.empty {
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { useThemeVars } from "naive-ui"
import type { BadgeBody } from "admin/api"
import type { AdminProblemSetBadge } from "utils/types"
import { useThemeVars } from 'naive-ui'
import type { BadgeBody } from 'admin/api'
import type { AdminProblemSetBadge } from 'utils/types'
/**
* 加奖章 / 改奖章共用一个弹窗:传了 badge 就是改,null 就是加。
@@ -9,17 +9,17 @@ import type { AdminProblemSetBadge } from "utils/types"
* 「做对 N 道」数的是做对的全部题(含选做),和后端 eligibleForBadge 同一个口径。
*/
const props = defineProps<{ badge: AdminProblemSetBadge | null; problemsCount: number }>()
const show = defineModel<boolean>("show", { required: true })
const show = defineModel<boolean>('show', { required: true })
const emit = defineEmits<{ save: [data: BadgeBody] }>()
const theme = useThemeVars()
const ICONS = [1, 2, 3, 4, 5, 6].map((i) => `/badge-${i}.png`)
const form = reactive<BadgeBody>({
name: "",
description: "",
name: '',
description: '',
icon: ICONS[0]!,
conditionType: "problem_count",
conditionType: 'problem_count',
conditionValue: 1,
})
@@ -27,50 +27,33 @@ const form = reactive<BadgeBody>({
watch(show, (open) => {
if (!open) return
Object.assign(form, {
name: props.badge?.name ?? "",
description: props.badge?.description ?? "",
name: props.badge?.name ?? '',
description: props.badge?.description ?? '',
icon: props.badge?.icon || ICONS[0]!,
conditionType: props.badge?.conditionType ?? "problem_count",
conditionType: props.badge?.conditionType ?? 'problem_count',
conditionValue: props.badge?.conditionValue || 1,
})
})
const valid = computed(
() =>
form.name.trim().length > 0 &&
(form.conditionType === "all_problems" || form.conditionValue >= 1),
)
const valid = computed(() => form.name.trim().length > 0 && (form.conditionType === 'all_problems' || form.conditionValue >= 1))
function save() {
if (!valid.value) return
emit("save", {
emit('save', {
...form,
name: form.name.trim(),
conditionValue: form.conditionType === "all_problems" ? 0 : form.conditionValue,
conditionValue: form.conditionType === 'all_problems' ? 0 : form.conditionValue,
})
}
</script>
<template>
<n-modal
v-model:show="show"
preset="card"
:title="badge ? '改奖章' : '加奖章'"
style="width: 460px"
:mask-closable="false"
>
<n-modal v-model:show="show" preset="card" :title="badge ? '改奖章' : '加奖章'" style="width: 460px" :mask-closable="false">
<div class="form">
<div class="field">
<span class="label">图标</span>
<div class="icons">
<button
v-for="icon in ICONS"
:key="icon"
class="icon"
:class="{ on: form.icon === icon }"
:aria-label="`选这个图标`"
@click="form.icon = icon"
>
<button v-for="icon in ICONS" :key="icon" class="icon" :class="{ on: form.icon === icon }" :aria-label="`选这个图标`" @click="form.icon = icon">
<img :src="icon" alt="" />
</button>
</div>
@@ -100,11 +83,7 @@ function save() {
</n-input-number>
</div>
<span class="hint">
{{
form.conditionType === "all_problems"
? "必做题全部做对就发。"
: "做对的题(选做也算)够这个数就发。"
}}改了条件会按大家现在的进度重新发、收。
{{ form.conditionType === 'all_problems' ? '必做题全部做对就发。' : '做对的题(选做也算)够这个数就发。' }}改了条件会按大家现在的进度重新发、收。
</span>
</div>
<template #footer>
@@ -133,7 +112,7 @@ function save() {
width: 36px;
flex-shrink: 0;
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
}
.icons {
@@ -152,7 +131,7 @@ function save() {
}
.icon.on {
border-color: v-bind("theme.primaryColor");
border-color: v-bind('theme.primaryColor');
}
.icon img {
@@ -163,6 +142,6 @@ function save() {
.hint {
font-size: 12px;
line-height: 1.6;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
</style>
+80 -125
View File
@@ -1,9 +1,9 @@
<script setup lang="ts">
import { useThemeVars } from "naive-ui"
import PageHeader from "admin/components/PageHeader.vue"
import { errorMessage } from "utils/api"
import { fromPickerValue, parseTime, toPickerValue, zonedParts } from "utils/functions"
import type { AdminProblemRow, AdminProblemSet, AdminProblemSetBadge } from "utils/types"
import { useThemeVars } from 'naive-ui'
import PageHeader from 'admin/components/PageHeader.vue'
import { errorMessage } from 'utils/api'
import { fromPickerValue, parseTime, toPickerValue, zonedParts } from 'utils/functions'
import type { AdminProblemRow, AdminProblemSet, AdminProblemSetBadge } from 'utils/types'
import {
addProblemsToSet,
createProblemSet,
@@ -20,8 +20,8 @@ import {
reorderProblemSetProblems,
setProblemRequired,
type BadgeBody,
} from "../api"
import BadgeModal from "./components/BadgeModal.vue"
} from '../api'
import BadgeModal from './components/BadgeModal.vue'
/**
* 新建 / 编辑题单,一屏做完(设计稿「题单重设计」后台那块):左边名字、说明、布置期、公开;
@@ -43,18 +43,18 @@ const ready = ref(false)
const saving = ref(false)
const current = ref<AdminProblemSet | null>(null)
const form = reactive({ title: "", description: "", visible: true })
const form = reactive({ title: '', description: '', visible: true })
// ---------------------------------------------------------------- 布置期
const DAY = 86_400_000
const OFFSET = 8 * 3_600_000
const CHOICES = [
{ days: 7, label: "一周" },
{ days: 14, label: "两周" },
{ days: 28, label: "四周" },
{ days: 7, label: '一周' },
{ days: 14, label: '两周' },
{ days: 28, label: '四周' },
]
const WEEKDAYS = ["日", "一", "二", "三", "四", "五", "六"]
const WEEKDAYS = ['日', '一', '二', '三', '四', '五', '六']
/** 东八区某一天结束的时刻(23:59:59.999) */
function endOfDay(ms: number) {
@@ -63,36 +63,32 @@ function endOfDay(ms: number) {
}
/** "none" 不布置 / 天数 / "pick" 自己选日期 */
const choice = ref<"none" | "pick" | number>(14)
const choice = ref<'none' | 'pick' | number>(14)
const picked = ref(toPickerValue(Date.now() + 14 * DAY))
const untilMs = computed(() => {
if (choice.value === "none") return null
if (choice.value === "pick") return endOfDay(fromPickerValue(picked.value))
if (choice.value === 'none') return null
if (choice.value === 'pick') return endOfDay(fromPickerValue(picked.value))
return endOfDay(Date.now() + choice.value * DAY)
})
function dayText(ms: number) {
const iso = new Date(ms).toISOString()
return `${parseTime(iso, "M月D日")} 周${WEEKDAYS[new Date(ms + OFFSET).getUTCDay()]}`
return `${parseTime(iso, 'M月D日')} 周${WEEKDAYS[new Date(ms + OFFSET).getUTCDay()]}`
}
const running = computed(() => !!current.value?.assigning)
const expired = computed(
() => !!current.value && !current.value.assigning && !!current.value.assignedUntil,
)
const expired = computed(() => !!current.value && !current.value.assigning && !!current.value.assignedUntil)
const assignHint = computed(() => {
if (untilMs.value === null) {
return running.value
? "保存后马上结束布置,以前的代码都放出来。"
: "不布置:学生照样能加入、做题,只是不藏以前的代码。"
return running.value ? '保存后马上结束布置,以前的代码都放出来。' : '不布置:学生照样能加入、做题,只是不藏以前的代码。'
}
if (untilMs.value <= Date.now()) return "这一天已经过了,选个以后的日子。"
if (untilMs.value <= Date.now()) return '这一天已经过了,选个以后的日子。'
const head = `布置到 ${dayText(untilMs.value)}。`
return running.value
? `${head}这一轮从 ${parseTime(current.value!.assignedAt!, "M月D日")} 开始,改日期只是延长或提前结束。`
: `${head}${expired.value ? "上一轮已经结束,保存就是再布置一次。" : ""}`
? `${head}这一轮从 ${parseTime(current.value!.assignedAt!, 'M月D日')} 开始,改日期只是延长或提前结束。`
: `${head}${expired.value ? '上一轮已经结束,保存就是再布置一次。' : ''}`
})
const disabledDate = (ts: number) => fromPickerValue(ts) + DAY <= Date.now()
@@ -112,7 +108,7 @@ async function loadProblems() {
}))
}
const keyword = ref("")
const keyword = ref('')
const results = ref<AdminProblemRow[]>([])
const searching = ref(false)
@@ -142,8 +138,7 @@ watchDebounced(
{ debounce: 300 },
)
const added = (displayId: string) =>
items.value.some((item) => item.displayId.toLowerCase() === displayId.toLowerCase())
const added = (displayId: string) => items.value.some((item) => item.displayId.toLowerCase() === displayId.toLowerCase())
async function addMany(displayIds: string[], titles = new Map<string, string>()) {
if (!editing.value) {
@@ -153,9 +148,7 @@ async function addMany(displayIds: string[], titles = new Map<string, string>())
let displayId = typed
let title = titles.get(typed)
if (!title) {
const found = (await getLibraryProblemList(0, 5, typed)).results.find(
(row) => row._id.toLowerCase() === typed.toLowerCase(),
)
const found = (await getLibraryProblemList(0, 5, typed)).results.find((row) => row._id.toLowerCase() === typed.toLowerCase())
if (!found) {
message.warning(`题号 ${typed} 找不到(或者没公开)`)
continue
@@ -165,17 +158,17 @@ async function addMany(displayIds: string[], titles = new Map<string, string>())
}
items.value.push({ id: 0, displayId, title, isRequired: true })
}
keyword.value = ""
keyword.value = ''
return
}
try {
const res = await addProblemsToSet(id.value, displayIds)
const notes = []
if (res.missing.length) notes.push(`找不到:${res.missing.join("、")}`)
if (res.duplicate.length) notes.push(`已经在里面:${res.duplicate.join("、")}`)
if (notes.length) message.warning(notes.join(";"))
if (res.missing.length) notes.push(`找不到:${res.missing.join('、')}`)
if (res.duplicate.length) notes.push(`已经在里面:${res.duplicate.join('、')}`)
if (notes.length) message.warning(notes.join(';'))
else message.success(`加了 ${res.added.length} 道`)
keyword.value = ""
keyword.value = ''
await Promise.all([loadProblems(), reloadSet()])
} catch (err) {
message.error(errorMessage(err))
@@ -203,10 +196,10 @@ function remove(item: Item) {
return
}
dialog.warning({
title: "从题单里拿掉这道题?",
title: '从题单里拿掉这道题?',
content: `「${item.title}」。已经加入的 ${current.value?.participantCount ?? 0} 个人的进度会重算,题目本身不受影响。`,
positiveText: "拿掉",
negativeText: "不拿",
positiveText: '拿掉',
negativeText: '不拿',
onPositiveClick: async () => {
try {
await removeProblemFromSet(id.value, item.id)
@@ -256,7 +249,7 @@ const badgeModal = ref(false)
const editingBadge = ref<AdminProblemSetBadge | null>(null)
function badgeCondition(badge: AdminProblemSetBadge) {
return badge.conditionType === "all_problems" ? "全部做完" : `做对 ${badge.conditionValue} 道`
return badge.conditionType === 'all_problems' ? '全部做完' : `做对 ${badge.conditionValue} 道`
}
function openBadge(badge: AdminProblemSetBadge | null) {
@@ -278,11 +271,9 @@ async function saveBadge(data: BadgeBody) {
function removeBadge(badge: AdminProblemSetBadge) {
dialog.warning({
title: `删掉奖章「${badge.name}」?`,
content: badge.earnedCount
? `已经拿到它的 ${badge.earnedCount} 个人也会一起被收回。`
: "还没有人拿到它。",
positiveText: "删掉",
negativeText: "不删",
content: badge.earnedCount ? `已经拿到它的 ${badge.earnedCount} 个人也会一起被收回。` : '还没有人拿到它。',
positiveText: '删掉',
negativeText: '不删',
onPositiveClick: async () => {
try {
await deleteProblemSetBadge(id.value, badge.id)
@@ -301,7 +292,7 @@ async function reloadSet() {
}
async function load() {
keyword.value = ""
keyword.value = ''
if (!editing.value) {
ready.value = true
return
@@ -310,10 +301,10 @@ async function load() {
const set = current.value!
Object.assign(form, { title: set.title, description: set.description, visible: set.visible })
if (set.assigning) {
choice.value = "pick"
choice.value = 'pick'
picked.value = toPickerValue(Date.parse(set.assignedUntil!))
} else {
choice.value = "none"
choice.value = 'none'
}
await Promise.all([loadProblems(), getProblemSetBadges(id.value).then((b) => (badges.value = b))])
ready.value = true
@@ -321,11 +312,11 @@ async function load() {
async function submit() {
if (!form.title.trim()) {
message.error("题单还没起名字")
message.error('题单还没起名字')
return
}
if (untilMs.value !== null && untilMs.value <= Date.now()) {
message.error("布置到的日期已经过了")
message.error('布置到的日期已经过了')
return
}
const body = {
@@ -338,7 +329,7 @@ async function submit() {
try {
if (editing.value) {
current.value = await editProblemSet(id.value, body)
message.success("改好了")
message.success('改好了')
return
}
const created = await createProblemSet(body)
@@ -355,10 +346,8 @@ async function submit() {
}
}
}
message.success(
items.value.length ? `题单建好了,${items.value.length} 道题都加进去了` : "题单建好了",
)
router.replace({ name: "admin problemset edit", params: { problemSetId: created.id } })
message.success(items.value.length ? `题单建好了,${items.value.length} 道题都加进去了` : '题单建好了')
router.replace({ name: 'admin problemset edit', params: { problemSetId: created.id } })
} catch (err) {
message.error(errorMessage(err))
} finally {
@@ -372,13 +361,13 @@ function removeSet() {
title: `删除题单「${set.title}」?`,
content: set.participantCount
? `${set.participantCount} 个人的进度和他们拿到的奖章会一起删掉,找不回来。只是不想让学生看到的话,关掉「公开」就行。`
: "还没有人加入。删掉找不回来。",
positiveText: "删除",
negativeText: "不删",
: '还没有人加入。删掉找不回来。',
positiveText: '删除',
negativeText: '不删',
onPositiveClick: async () => {
try {
await deleteProblemSet(set.id)
router.replace({ name: "admin problemset list" })
router.replace({ name: 'admin problemset list' })
} catch (err) {
message.error(errorMessage(err))
}
@@ -393,9 +382,7 @@ onMounted(load)
<template>
<PageHeader :title="editing ? '编辑题单' : '新建题单'" :back="{ name: 'admin problemset list' }">
<template v-if="editing" #actions>
<n-button tag="a" :href="`/problemset/${problemSetId}`" target="_blank">
到前台看这个题单
</n-button>
<n-button tag="a" :href="`/problemset/${problemSetId}`" target="_blank"> 到前台看这个题单 </n-button>
</template>
</PageHeader>
@@ -414,28 +401,12 @@ onMounted(load)
<span class="label">布置</span>
<div class="stack">
<n-flex :size="6" align="center">
<button class="chip" :class="{ on: choice === 'none' }" @click="choice = 'none'">
不布置
</button>
<button
v-for="c in CHOICES"
:key="c.days"
class="chip"
:class="{ on: choice === c.days }"
@click="choice = c.days"
>
<button class="chip" :class="{ on: choice === 'none' }" @click="choice = 'none'">不布置</button>
<button v-for="c in CHOICES" :key="c.days" class="chip" :class="{ on: choice === c.days }" @click="choice = c.days">
{{ c.label }}
</button>
<button class="chip" :class="{ on: choice === 'pick' }" @click="choice = 'pick'">
选日期…
</button>
<n-date-picker
v-if="choice === 'pick'"
v-model:value="picked"
type="date"
:is-date-disabled="disabledDate"
style="width: 150px"
/>
<button class="chip" :class="{ on: choice === 'pick' }" @click="choice = 'pick'">选日期…</button>
<n-date-picker v-if="choice === 'pick'" v-model:value="picked" type="date" :is-date-disabled="disabledDate" style="width: 150px" />
</n-flex>
<span class="hint">{{ assignHint }}</span>
<span class="hint">
@@ -447,9 +418,7 @@ onMounted(load)
<div class="field">
<span class="label">公开</span>
<n-switch v-model:value="form.visible" />
<span class="hint">{{
form.visible ? "学生能在题单列表里看到" : "藏起来,学生看不到也进不去"
}}</span>
<span class="hint">{{ form.visible ? '学生能在题单列表里看到' : '藏起来,学生看不到也进不去' }}</span>
</div>
<div v-if="current" class="stats">
@@ -461,8 +430,7 @@ onMounted(load)
<div class="save">
<n-button type="primary" :loading="saving" @click="submit">保存</n-button>
<span class="hint"
>{{ items.length }} 道题<template v-if="optionalCount">
· {{ optionalCount }} 道选做</template
>{{ items.length }} 道题<template v-if="optionalCount"> · {{ optionalCount }} 道选做</template
><template v-if="editing"> · {{ badges.length }} 个奖章</template></span
>
<div class="spacer"></div>
@@ -485,7 +453,7 @@ onMounted(load)
/>
<div v-if="pasted.length" class="results">
<div class="result">
<span class="grow">粘贴了 {{ pasted.length }} 个题号:{{ pasted.join("、") }}</span>
<span class="grow">粘贴了 {{ pasted.length }} 个题号:{{ pasted.join('、') }}</span>
<n-button size="small" type="primary" @click="addMany(pasted)">全部加进来</n-button>
</div>
</div>
@@ -520,11 +488,9 @@ onMounted(load)
:title="item.isRequired ? '点一下改成选做' : '点一下改回必做'"
@click="toggleRequired(item)"
>
{{ item.isRequired ? "必做" : "选做" }}
{{ item.isRequired ? '必做' : '选做' }}
</button>
<n-button size="small" text :aria-label="`拿掉 ${item.title}`" @click="remove(item)"
>✕</n-button
>
<n-button size="small" text :aria-label="`拿掉 ${item.title}`" @click="remove(item)">✕</n-button>
</div>
</div>
<div v-else class="empty hint">还没加题。在上面输入题号,比如 3065</div>
@@ -546,13 +512,7 @@ onMounted(load)
<span class="muted ell grow tiny">{{ badge.description }}</span>
<span class="muted num tiny">{{ badge.earnedCount }} 人拿到</span>
<n-button size="small" text type="primary" @click="openBadge(badge)">改</n-button>
<n-button
size="small"
text
:aria-label="`删掉 ${badge.name}`"
@click="removeBadge(badge)"
>✕</n-button
>
<n-button size="small" text :aria-label="`删掉 ${badge.name}`" @click="removeBadge(badge)">✕</n-button>
</div>
</div>
<div v-else class="empty hint">还没有奖章。比如「做对 3 道」发一个、「全部做完」发一个</div>
@@ -560,12 +520,7 @@ onMounted(load)
</div>
</div>
<BadgeModal
v-model:show="badgeModal"
:badge="editingBadge"
:problems-count="items.length"
@save="saveBadge"
/>
<BadgeModal v-model:show="badgeModal" :badge="editingBadge" :problems-count="items.length" @save="saveBadge" />
</template>
<style scoped>
@@ -582,9 +537,9 @@ onMounted(load)
display: flex;
flex-direction: column;
gap: 16px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.form {
@@ -632,7 +587,7 @@ onMounted(load)
width: 40px;
flex-shrink: 0;
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
}
.stack {
@@ -654,11 +609,11 @@ onMounted(load)
.hint {
font-size: 12px;
line-height: 1.6;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.tiny {
@@ -680,18 +635,18 @@ onMounted(load)
height: 28px;
padding: 0 12px;
border-radius: 14px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
background: transparent;
font: inherit;
font-size: 13px;
color: v-bind("theme.textColor2");
color: v-bind('theme.textColor2');
cursor: pointer;
white-space: nowrap;
}
.chip.on {
border-color: v-bind("theme.primaryColor");
color: v-bind("theme.primaryColor");
border-color: v-bind('theme.primaryColor');
color: v-bind('theme.primaryColor');
font-weight: 600;
}
@@ -704,7 +659,7 @@ onMounted(load)
.chip.dashed {
border-style: dashed;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.chip.static {
@@ -716,14 +671,14 @@ onMounted(load)
align-items: center;
box-sizing: border-box;
padding: 10px 12px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
font-size: 13px;
background: v-bind("theme.actionColor");
background: v-bind('theme.actionColor');
}
.stats a {
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
text-decoration: none;
}
@@ -732,12 +687,12 @@ onMounted(load)
align-items: center;
gap: 10px;
padding-top: 12px;
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
}
.results {
margin-top: -4px;
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
overflow: hidden;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
@@ -754,11 +709,11 @@ onMounted(load)
}
.result + .result {
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
}
.list {
border: 1px solid v-bind("theme.borderColor");
border: 1px solid v-bind('theme.borderColor');
border-radius: 6px;
overflow: hidden;
}
@@ -771,11 +726,11 @@ onMounted(load)
align-items: center;
gap: 10px;
font-size: 14px;
background: v-bind("theme.cardColor");
background: v-bind('theme.cardColor');
}
.item + .item {
border-top: 1px solid v-bind("theme.dividerColor");
border-top: 1px solid v-bind('theme.dividerColor');
}
.item.dragging {
@@ -788,7 +743,7 @@ onMounted(load)
.grip {
cursor: grab;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
letter-spacing: -3px;
user-select: none;
}
+42 -66
View File
@@ -1,13 +1,13 @@
<script setup lang="ts">
import PageHeader from "admin/components/PageHeader.vue"
import Pagination from "shared/components/Pagination.vue"
import { usePagination } from "shared/composables/pagination"
import { parseTime } from "utils/functions"
import type { AdminProblemSet } from "utils/types"
import { getProblemSetList, toggleProblemSetVisible } from "../api"
import { NButton, NSwitch, NTag, useThemeVars } from "naive-ui"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import PageHeader from 'admin/components/PageHeader.vue'
import Pagination from 'shared/components/Pagination.vue'
import { usePagination } from 'shared/composables/pagination'
import { parseTime } from 'utils/functions'
import type { AdminProblemSet } from 'utils/types'
import { getProblemSetList, toggleProblemSetVisible } from '../api'
import { NButton, NSwitch, NTag, useThemeVars } from 'naive-ui'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
/**
* 后台题单列表。难度、状态两列和筛选拿掉了(线上全是简单 / 活跃,「状态 + 可见」合成了「公开」),
@@ -19,34 +19,24 @@ const { isMobile } = useBreakpoints()
const total = ref(0)
const problemSets = ref<AdminProblemSet[]>([])
const { query, clearQuery } = usePagination<{ keyword: string }>({ keyword: "" })
const { query, clearQuery } = usePagination<{ keyword: string }>({ keyword: '' })
function edit(row: AdminProblemSet) {
router.push({ name: "admin problemset edit", params: { problemSetId: row.id } })
router.push({ name: 'admin problemset edit', params: { problemSetId: row.id } })
}
function renderTitle(row: AdminProblemSet) {
return h(
NButton,
{ text: true, type: "primary", onClick: () => edit(row) },
{ default: () => row.title },
)
return h(NButton, { text: true, type: 'primary', onClick: () => edit(row) }, { default: () => row.title })
}
function renderAssigned(row: AdminProblemSet) {
return row.assigning
? h(
NTag,
{ type: "info", size: "small", bordered: false },
{ default: () => `到 ${parseTime(row.assignedUntil!, "M月D日")}` },
)
: "—"
return row.assigning ? h(NTag, { type: 'info', size: 'small', bordered: false }, { default: () => `到 ${parseTime(row.assignedUntil!, 'M月D日')}` }) : '—'
}
function renderVisible(row: AdminProblemSet) {
return h(NSwitch, {
value: row.visible,
size: isMobile.value ? "medium" : "small",
size: isMobile.value ? 'medium' : 'small',
rubberBand: false,
onUpdateValue: () => toggleVisible(row.id),
})
@@ -59,60 +49,60 @@ function renderMobileCard(row: AdminProblemSet) {
`${row.participantCount} 人加入 · ${row.completedCount} 人做完`,
row.badgeCount ? `${row.badgeCount} 个奖章` : null,
row.createdBy.username,
parseTime(row.createTime, "YYYY-MM-DD"),
parseTime(row.createTime, 'YYYY-MM-DD'),
].filter((it): it is string => !!it)
return h("div", { class: "m-card" }, [
h("div", { class: "m-head" }, [renderTitle(row), row.assigning ? renderAssigned(row) : null]),
return h('div', { class: 'm-card' }, [
h('div', { class: 'm-head' }, [renderTitle(row), row.assigning ? renderAssigned(row) : null]),
h(
"div",
{ class: "m-meta" },
items.map((text, i) => h("span", { class: "m-item", key: i }, i ? ` · ${text}` : text)),
'div',
{ class: 'm-meta' },
items.map((text, i) => h('span', { class: 'm-item', key: i }, i ? ` · ${text}` : text)),
),
])
}
const mobileColumns: DataTableColumn<AdminProblemSet>[] = [
{ title: "题单", key: "title", render: renderMobileCard },
{ title: "公开", key: "visible", width: 72, align: "center", render: renderVisible },
{ title: '题单', key: 'title', render: renderMobileCard },
{ title: '公开', key: 'visible', width: 72, align: 'center', render: renderVisible },
]
const desktopColumns: DataTableColumn<AdminProblemSet>[] = [
{ title: "ID", key: "id", width: 70 },
{ title: 'ID', key: 'id', width: 70 },
{
title: "题单",
key: "title",
title: '题单',
key: 'title',
minWidth: 200,
render: renderTitle,
},
{ title: "题数", key: "problemsCount", width: 70 },
{ title: '题数', key: 'problemsCount', width: 70 },
{
title: "加入 / 做完",
key: "participantCount",
title: '加入 / 做完',
key: 'participantCount',
width: 110,
render: (row) => `${row.participantCount} / ${row.completedCount}`,
},
{ title: "奖章", key: "badgeCount", width: 70 },
{ title: '奖章', key: 'badgeCount', width: 70 },
{
title: "布置",
key: "assignedUntil",
title: '布置',
key: 'assignedUntil',
width: 130,
render: renderAssigned,
},
{
title: "创建者",
key: "createdBy",
title: '创建者',
key: 'createdBy',
width: 110,
render: (row) => row.createdBy.username,
},
{
title: "创建时间",
key: "createTime",
title: '创建时间',
key: 'createTime',
width: 120,
render: (row) => parseTime(row.createTime, "YYYY-MM-DD"),
render: (row) => parseTime(row.createTime, 'YYYY-MM-DD'),
},
{
title: "公开",
key: "visible",
title: '公开',
key: 'visible',
width: 80,
render: renderVisible,
},
@@ -143,27 +133,13 @@ watch(() => [query.page, query.limit], listProblemSets)
<template>
<PageHeader title="题单列表">
<template #actions>
<n-button type="primary" @click="router.push({ name: 'admin problemset create' })">
新建题单
</n-button>
<n-button type="primary" @click="router.push({ name: 'admin problemset create' })"> 新建题单 </n-button>
</template>
<template #filters>
<n-input
v-model:value="query.keyword"
placeholder="搜题单名字"
clearable
@clear="clearQuery"
:style="{ width: isMobile ? '100%' : '220px' }"
/>
<n-input v-model:value="query.keyword" placeholder="搜题单名字" clearable @clear="clearQuery" :style="{ width: isMobile ? '100%' : '220px' }" />
</template>
</PageHeader>
<n-data-table
:loading="loading"
striped
class="set-table"
:columns="columns"
:data="problemSets"
/>
<n-data-table :loading="loading" striped class="set-table" :columns="columns" :data="problemSets" />
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
</template>
@@ -186,7 +162,7 @@ watch(() => [query.page, query.limit], listProblemSets)
.set-table :deep(.m-meta) {
font-size: 13px;
line-height: 1.5;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.set-table :deep(.m-item) {
+57 -109
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import PageHeader from "admin/components/PageHeader.vue"
import { useThemeVars } from "naive-ui"
import { classLabel } from "utils/classes"
import { errorMessage } from "utils/api"
import { CLASS_NAME_MAX_DIGITS, CLASS_NAME_MIN_DIGITS, CLASS_NAME_RE } from "utils/constants"
import { copyToClipboard, parseTime } from "utils/functions"
import type { OrphanImage, OrphanTestCase, Server, WebsiteConfig } from "utils/types"
import { useConfigStore } from "shared/store/config"
import PageHeader from 'admin/components/PageHeader.vue'
import { useThemeVars } from 'naive-ui'
import { classLabel } from 'utils/classes'
import { errorMessage } from 'utils/api'
import { CLASS_NAME_MAX_DIGITS, CLASS_NAME_MIN_DIGITS, CLASS_NAME_RE } from 'utils/constants'
import { copyToClipboard, parseTime } from 'utils/functions'
import type { OrphanImage, OrphanTestCase, Server, WebsiteConfig } from 'utils/types'
import { useConfigStore } from 'shared/store/config'
import {
deleteJudgeServer,
editWebsite,
@@ -16,7 +16,7 @@ import {
listOrphanImages,
pruneInvalidTestcases,
pruneOrphanImages,
} from "../api"
} from '../api'
/**
* 后台设置(设计稿「后台首页」页的 ConfAdmin):网站 / 班级 / 开关 / 判题机,有无效测试用例时
@@ -32,7 +32,7 @@ const theme = useThemeVars()
const configStore = useConfigStore()
const websiteConfig = reactive<WebsiteConfig>({
websiteName: "判题狗",
websiteName: '判题狗',
allowRegister: false,
submissionListShowAll: true,
classList: [],
@@ -42,8 +42,8 @@ const websiteConfig = reactive<WebsiteConfig>({
* 上一次存进去(或刚读回来)的内容。和它一样就不存 —— 读回配置本身也是一次改动,
* 只看「读完没有」的话,那次改动的延迟保存会在读完之后照样发出去
*/
let savedSnapshot = ""
const saveState = ref<"idle" | "saving" | "saved" | "failed">("idle")
let savedSnapshot = ''
const saveState = ref<'idle' | 'saving' | 'saved' | 'failed'>('idle')
async function getWebsiteConfig() {
const res = await getWebsite()
@@ -65,29 +65,27 @@ watchDebounced(
async function saveWebsiteConfig() {
if (!websiteConfig.websiteName.trim()) {
saveState.value = "failed"
message.error("网站名不能空着")
saveState.value = 'failed'
message.error('网站名不能空着')
return
}
// 班级号要和用户名里 ks 后面那段对得上,位数不对登录页会查不到该班学生。后端也会拦
const invalid = websiteConfig.classList.filter((c) => !CLASS_NAME_RE.test(c))
if (invalid.length) {
message.error(
`班级号 ${invalid.join("、")} 必须是 ${CLASS_NAME_MIN_DIGITS}~${CLASS_NAME_MAX_DIGITS} 位数字`,
)
message.error(`班级号 ${invalid.join('、')} 必须是 ${CLASS_NAME_MIN_DIGITS}~${CLASS_NAME_MAX_DIGITS} 位数字`)
return
}
saveState.value = "saving"
saveState.value = 'saving'
const snapshot = JSON.stringify(websiteConfig)
try {
await editWebsite(websiteConfig)
savedSnapshot = snapshot
} catch (err) {
saveState.value = "failed"
message.error("没保存上:" + errorMessage(err))
saveState.value = 'failed'
message.error('没保存上:' + errorMessage(err))
return
}
saveState.value = "saved"
saveState.value = 'saved'
// 广播由后端在 POST /admin/website 里做,开着页面的人不用刷新
configStore.getConfig()
}
@@ -98,18 +96,18 @@ async function saveWebsiteConfig() {
const classGroups = computed(() => {
const groups = new Map<string, string[]>()
for (const name of websiteConfig.classList) {
const grade = /^\d{3,}$/.test(name) ? name.slice(0, 2) : "其他"
const grade = /^\d{3,}$/.test(name) ? name.slice(0, 2) : '其他'
groups.set(grade, [...(groups.get(grade) ?? []), name])
}
return [...groups.entries()]
.sort(([a], [b]) => b.localeCompare(a))
.map(([grade, list]) => ({
grade,
list: [...list].sort((a, b) => a.localeCompare(b, "zh-CN", { numeric: true })),
list: [...list].sort((a, b) => a.localeCompare(b, 'zh-CN', { numeric: true })),
}))
})
const newClass = ref("")
const newClass = ref('')
function addClass() {
const value = newClass.value.trim()
if (!value) return
@@ -122,7 +120,7 @@ function addClass() {
return
}
websiteConfig.classList = [...websiteConfig.classList, value]
newClass.value = ""
newClass.value = ''
}
function removeClass(name: string) {
@@ -131,10 +129,10 @@ function removeClass(name: string) {
// ---------------------------------------------------------------- 判题机
const token = ref("")
const token = ref('')
const tokenShown = ref(false)
const servers = ref<Server[]>([])
const abnormalServers = computed(() => servers.value.filter((item) => item.status === "abnormal"))
const abnormalServers = computed(() => servers.value.filter((item) => item.status === 'abnormal'))
async function getJudgeServerData() {
const res = await getJudgeServer()
@@ -145,7 +143,7 @@ async function getJudgeServerData() {
/** 上一次心跳:一分钟内写「刚刚还在」,否则「N 分钟 / 小时 / 天没动静了」 */
function heartbeatText(server: Server) {
const seconds = Math.max(0, (Date.now() - Date.parse(server.lastHeartbeat)) / 1000)
if (seconds < 60) return "刚刚还在"
if (seconds < 60) return '刚刚还在'
if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟没动静了`
if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时没动静了`
return `${Math.floor(seconds / 86400)} 天没动静了`
@@ -153,18 +151,18 @@ function heartbeatText(server: Server) {
async function delJudgeServer(hostname: string) {
await deleteJudgeServer(hostname)
message.success("删掉了")
message.success('删掉了')
getJudgeServerData()
}
async function deleteAbnormalServers() {
await Promise.all(abnormalServers.value.map((item) => deleteJudgeServer(item.hostname)))
message.success("删掉了")
message.success('删掉了')
getJudgeServerData()
}
async function copyToken() {
if (await copyToClipboard(token.value)) message.success("复制好了")
if (await copyToClipboard(token.value)) message.success('复制好了')
}
// ---------------------------------------------------------------- 无效的测试用例
@@ -177,7 +175,7 @@ async function getTestcases() {
async function deleteTestcase(id?: string) {
await pruneInvalidTestcases(id)
message.success("删掉了")
message.success('删掉了')
getTestcases()
}
@@ -191,8 +189,8 @@ const orphanImages = ref<OrphanImage[] | null>(null)
const scanningImages = ref(false)
const IMAGE_GROUPS = [
{ folder: "upload", label: "编辑器里删掉的图" },
{ folder: "avatar", label: "换下来的头像" },
{ folder: 'upload', label: '编辑器里删掉的图' },
{ folder: 'avatar', label: '换下来的头像' },
] as const
const imageGroups = computed(() =>
@@ -249,11 +247,7 @@ onMounted(() => {
<h3>网站</h3>
<div class="field">
<label for="site-name" class="field-label">网站名</label>
<n-input
v-model:value="websiteConfig.websiteName"
:input-props="{ id: 'site-name' }"
style="width: 240px"
/>
<n-input v-model:value="websiteConfig.websiteName" :input-props="{ id: 'site-name' }" style="width: 240px" />
<n-text depth="3" class="hint">顶栏左上角和浏览器标签页上显示的名字</n-text>
</div>
</section>
@@ -263,27 +257,16 @@ onMounted(() => {
班级 <span class="count">{{ websiteConfig.classList.length }} 个</span>
</h3>
<div v-for="group in classGroups" :key="group.grade" class="grade listed">
<span class="grade-label">{{ group.grade === "其他" ? "其他" : `${group.grade} 级` }}</span>
<span class="grade-label">{{ group.grade === '其他' ? '其他' : `${group.grade} 级` }}</span>
<div class="chips">
<n-tag
v-for="name in group.list"
:key="name"
closable
:bordered="false"
@close="removeClass(name)"
>
<n-tag v-for="name in group.list" :key="name" closable :bordered="false" @close="removeClass(name)">
{{ classLabel(name) }}
</n-tag>
</div>
</div>
<div class="grade">
<span class="grade-label"></span>
<n-input
v-model:value="newClass"
placeholder="加一个班,如 2613"
style="width: 180px"
@keyup.enter="addClass"
/>
<n-input v-model:value="newClass" placeholder="加一个班,如 2613" style="width: 180px" @keyup.enter="addClass" />
<n-button @click="addClass">加</n-button>
<n-text depth="3" class="hint">批量建号时新班级会自动加进来,这里主要是删掉毕业的班</n-text>
</div>
@@ -304,14 +287,7 @@ onMounted(() => {
<section class="block">
<h3>
判题机
<n-button
v-if="abnormalServers.length > 1"
size="small"
style="margin-left: 8px"
@click="deleteAbnormalServers"
>
把断了的都删掉
</n-button>
<n-button v-if="abnormalServers.length > 1" size="small" style="margin-left: 8px" @click="deleteAbnormalServers"> 把断了的都删掉 </n-button>
</h3>
<n-empty v-if="!servers.length" description="一台都没有连上" />
<div v-for="server in servers" :key="server.hostname" class="server">
@@ -321,25 +297,16 @@ onMounted(() => {
{{ server.cpuCore }} 核 · CPU {{ server.cpuUsage }}% · 内存 {{ server.memoryUsage }}% · 版本
{{ server.judgerVersion }}
</span>
<span
:class="server.status === 'normal' ? 'ok-text' : 'bad-text'"
:title="parseTime(server.lastHeartbeat, 'YYYY-MM-DD HH:mm:ss')"
>
<span :class="server.status === 'normal' ? 'ok-text' : 'bad-text'" :title="parseTime(server.lastHeartbeat, 'YYYY-MM-DD HH:mm:ss')">
{{ heartbeatText(server) }}
</span>
<n-button
v-if="server.status !== 'normal'"
size="small"
@click="delJudgeServer(server.hostname)"
>
删掉
</n-button>
<n-button v-if="server.status !== 'normal'" size="small" @click="delJudgeServer(server.hostname)"> 删掉 </n-button>
</div>
<div class="server token">
<span class="muted">接口凭证</span>
<span class="mono">{{ tokenShown ? token : "••••••••••••" }}</span>
<span class="mono">{{ tokenShown ? token : '••••••••••••' }}</span>
<n-button size="small" @click="tokenShown = !tokenShown">
{{ tokenShown ? "藏起来" : "显示" }}
{{ tokenShown ? '藏起来' : '显示' }}
</n-button>
<n-button size="small" @click="copyToken">复制</n-button>
</div>
@@ -349,12 +316,10 @@ onMounted(() => {
<h3>
没人用的图片
<n-button size="small" style="margin-left: 8px" :loading="scanningImages" @click="scanImages">
{{ orphanImages ? "再查一遍" : "查一下" }}
{{ orphanImages ? '再查一遍' : '查一下' }}
</n-button>
</h3>
<n-text v-if="orphanImages && !imageGroups.length" depth="3" class="hint">
都有地方在用
</n-text>
<n-text v-if="orphanImages && !imageGroups.length" depth="3" class="hint"> 都有地方在用 </n-text>
<div v-for="group in imageGroups" :key="group.folder" class="image-group">
<div class="image-group-head">
{{ group.label }}
@@ -368,21 +333,10 @@ onMounted(() => {
</div>
<div class="thumbs">
<div v-for="image in group.images" :key="image.name" class="thumb">
<a
:href="image.url"
target="_blank"
:title="`${image.name} · ${parseTime(new Date(image.createTime * 1000), 'YYYY-MM-DD')}`"
>
<a :href="image.url" target="_blank" :title="`${image.name} · ${parseTime(new Date(image.createTime * 1000), 'YYYY-MM-DD')}`">
<img :src="image.url" alt="" loading="lazy" />
</a>
<button
type="button"
class="thumb-delete"
title="删掉"
@click="deleteImages({ folder: image.folder, name: image.name })"
>
×
</button>
<button type="button" class="thumb-delete" title="删掉" @click="deleteImages({ folder: image.folder, name: image.name })">×</button>
</div>
</div>
</div>
@@ -395,13 +349,7 @@ onMounted(() => {
</h3>
<n-text depth="3" class="hint">删题时测试数据留在了磁盘上(故意的,删错了还能捞回来)</n-text>
<div class="chips">
<n-tag
v-for="item in testcases"
:key="item.id"
closable
:bordered="false"
@close="deleteTestcase(item.id)"
>
<n-tag v-for="item in testcases" :key="item.id" closable :bordered="false" @close="deleteTestcase(item.id)">
{{ item.id }}
</n-tag>
</div>
@@ -416,7 +364,7 @@ onMounted(() => {
margin-bottom: 16px;
padding: 16px 18px;
border-radius: 10px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
}
h3 {
@@ -430,7 +378,7 @@ h3 {
margin-left: 8px;
font-size: 13px;
font-weight: 400;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.field,
@@ -445,7 +393,7 @@ h3 {
.field-label {
width: 60px;
font-size: 14px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.hint {
@@ -456,7 +404,7 @@ h3 {
width: 50px;
flex: none;
font-size: 13px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.chips {
@@ -489,8 +437,8 @@ h3 {
height: 72px;
border-radius: 6px;
overflow: hidden;
border: 1px solid v-bind("theme.dividerColor");
background: v-bind("theme.actionColor");
border: 1px solid v-bind('theme.dividerColor');
background: v-bind('theme.actionColor');
}
.thumb img {
@@ -535,23 +483,23 @@ h3 {
}
.dot.ok {
background: v-bind("theme.successColor");
background: v-bind('theme.successColor');
}
.dot.bad {
background: v-bind("theme.errorColor");
background: v-bind('theme.errorColor');
}
.ok-text {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
}
.bad-text {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
.muted {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.token {
+44 -64
View File
@@ -1,16 +1,16 @@
<script setup lang="ts">
import type { DashboardInfo } from "@oj2/contract"
import { BarElement, CategoryScale, Chart as ChartJS, LinearScale, Tooltip } from "chart.js"
import { useThemeVars } from "naive-ui"
import { Bar } from "vue-chartjs"
import { useChartTheme } from "shared/composables/chartTheme"
import { rgba } from "shared/composables/tone"
import PageHeader from "admin/components/PageHeader.vue"
import { classLabel, groupClassOptions } from "utils/classes"
import { useConfigStore } from "shared/store/config"
import { useUserStore } from "shared/store/user"
import { SubmissionStatus } from "utils/constants"
import { getBaseInfo, randomUser10 } from "../api"
import type { DashboardInfo } from '@oj2/contract'
import { BarElement, CategoryScale, Chart as ChartJS, LinearScale, Tooltip } from 'chart.js'
import { useThemeVars } from 'naive-ui'
import { Bar } from 'vue-chartjs'
import { useChartTheme } from 'shared/composables/chartTheme'
import { rgba } from 'shared/composables/tone'
import PageHeader from 'admin/components/PageHeader.vue'
import { classLabel, groupClassOptions } from 'utils/classes'
import { useConfigStore } from 'shared/store/config'
import { useUserStore } from 'shared/store/user'
import { SubmissionStatus } from 'utils/constants'
import { getBaseInfo, randomUser10 } from '../api'
/**
* 后台首页(设计稿「后台首页」AdminHome):一块看板。上面一排看「现在」—— 判题机在不在、
@@ -39,20 +39,20 @@ onMounted(async () => {
const siteTiles = computed(() => {
const site = info.value?.site
if (!site) return []
const n = (value: number) => value.toLocaleString("zh-CN")
const n = (value: number) => value.toLocaleString('zh-CN')
return [
{ label: "学生", value: n(site.students), note: `老师 ${site.teachers} 人` },
{ label: '学生', value: n(site.students), note: `老师 ${site.teachers} 人` },
{
label: "题目",
label: '题目',
value: n(site.problems),
note: `学生看得到 ${n(site.visibleProblems)} 道`,
to: "/admin/problem/list",
to: '/admin/problem/list',
},
{ label: "提交", value: n(site.submissions), note: `这学期 ${n(site.termSubmissions)} 次` },
{ label: "这周做题的人", value: n(site.weekActive), note: "周一起交过题的" },
{ label: "比赛", value: n(site.contests), note: "", to: "/admin/contest/list" },
{ label: "题单", value: n(site.problemSets), note: "", to: "/admin/problemset/list" },
{ label: "自学", value: n(site.tutorials), note: "课", to: "/admin/tutorial/list" },
{ label: '提交', value: n(site.submissions), note: `这学期 ${n(site.termSubmissions)} 次` },
{ label: '这周做题的人', value: n(site.weekActive), note: '周一起交过题的' },
{ label: '比赛', value: n(site.contests), note: '', to: '/admin/contest/list' },
{ label: '题单', value: n(site.problemSets), note: '', to: '/admin/problemset/list' },
{ label: '自学', value: n(site.tutorials), note: '课', to: '/admin/tutorial/list' },
]
})
@@ -64,9 +64,7 @@ const dailyData = computed(() => {
datasets: [
{
data: daily.map((d) => d.count),
backgroundColor: daily.map((_, i) =>
i === daily.length - 1 ? theme.value.primaryColor : rgba(theme.value.primaryColor, 0.4),
),
backgroundColor: daily.map((_, i) => (i === daily.length - 1 ? theme.value.primaryColor : rgba(theme.value.primaryColor, 0.4))),
borderRadius: 3,
maxBarThickness: 22,
},
@@ -89,21 +87,21 @@ const dailyOptions = {
}
function openSystemErrors() {
router.push({ name: "submissions", query: { result: String(SubmissionStatus.system_error) } })
router.push({ name: 'submissions', query: { result: String(SubmissionStatus.system_error) } })
}
const shortcuts = [
{ label: "新建题目", to: "/admin/problem/create" },
{ label: "新建比赛", to: "/admin/contest/create" },
{ label: "批量建号", to: "/admin/user/generate" },
{ label: "课堂看板", to: "/classroom" },
{ label: '新建题目', to: '/admin/problem/create' },
{ label: '新建比赛', to: '/admin/contest/create' },
{ label: '批量建号', to: '/admin/user/generate' },
{ label: '课堂看板', to: '/classroom' },
]
// ---------------------------------------------------------------- 抽一个人
const classOptions = computed(() => groupClassOptions(configStore.config?.classList ?? []))
const luckyClass = ref<string | null>(null)
const luckyGuy = ref("")
const luckyGuy = ref('')
const isRolling = ref(false)
const pulseKey = ref(0)
let rollingTimer: ReturnType<typeof setInterval> | null = null
@@ -123,7 +121,7 @@ async function draw() {
const prefix = `ks${luckyClass.value}`
const names = (await randomUser10(prefix)).map((name) => name.slice(prefix.length) || name)
if (!names.length) {
luckyGuy.value = "这个班没有人"
luckyGuy.value = '这个班没有人'
return
}
stopRolling()
@@ -142,7 +140,7 @@ async function draw() {
watch(luckyClass, () => {
stopRolling()
luckyGuy.value = ""
luckyGuy.value = ''
})
onUnmounted(stopRolling)
</script>
@@ -159,12 +157,7 @@ onUnmounted(stopRolling)
<div class="tile">
<span class="label">今天提交</span>
<b>{{ info.todaySubmissionCount }} 次</b>
<button
v-if="info.todaySystemErrorCount"
type="button"
class="link bad-note"
@click="openSystemErrors"
>
<button v-if="info.todaySystemErrorCount" type="button" class="link bad-note" @click="openSystemErrors">
系统错误 {{ info.todaySystemErrorCount }} 次 →
</button>
<span v-else class="note">系统错误 0 次</span>
@@ -176,14 +169,8 @@ onUnmounted(stopRolling)
</div>
<div class="tile">
<span class="label">正在上课</span>
<b>{{ info.activeClass ? classLabel(info.activeClass) : "没有" }}</b>
<router-link
v-if="info.activeClass"
class="link"
:to="{ name: 'classroom board', query: { className: info.activeClass } }"
>
去课堂看板 →
</router-link>
<b>{{ info.activeClass ? classLabel(info.activeClass) : '没有' }}</b>
<router-link v-if="info.activeClass" class="link" :to="{ name: 'classroom board', query: { className: info.activeClass } }"> 去课堂看板 → </router-link>
<span v-else class="note">最近两小时没有哪个班在交题</span>
</div>
</div>
@@ -220,19 +207,12 @@ onUnmounted(stopRolling)
<div class="lucky">
<b class="lucky-title">抽一个人</b>
<n-select
v-model:value="luckyClass"
:options="classOptions"
filterable
placeholder="选班级"
aria-label="班级"
class="lucky-select"
/>
<n-select v-model:value="luckyClass" :options="classOptions" filterable placeholder="选班级" aria-label="班级" class="lucky-select" />
<span :key="pulseKey" class="lucky-name" :class="{ pulse: !isRolling && luckyGuy }">
{{ luckyGuy }}
</span>
<n-button type="primary" :disabled="!luckyClass || isRolling" @click="draw">
{{ luckyGuy ? "再抽一个" : "抽" }}
{{ luckyGuy ? '再抽一个' : '抽' }}
</n-button>
</div>
</template>
@@ -251,13 +231,13 @@ onUnmounted(stopRolling)
gap: 4px;
padding: 14px 16px;
border-radius: 10px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
}
.label,
.note {
font-size: 13px;
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.tile b {
@@ -266,12 +246,12 @@ onUnmounted(stopRolling)
}
.tile b.ok {
color: v-bind("theme.successColor");
color: v-bind('theme.successColor');
}
.tile b.bad,
.bad-note {
color: v-bind("theme.errorColor");
color: v-bind('theme.errorColor');
}
.bad-note {
@@ -285,7 +265,7 @@ onUnmounted(stopRolling)
background: none;
font: inherit;
font-size: 13px;
color: v-bind("theme.primaryColor");
color: v-bind('theme.primaryColor');
text-decoration: none;
cursor: pointer;
}
@@ -307,7 +287,7 @@ onUnmounted(stopRolling)
gap: 2px;
padding: 12px 14px;
border-radius: 10px;
background: v-bind("theme.actionColor");
background: v-bind('theme.actionColor');
color: inherit;
text-decoration: none;
}
@@ -318,14 +298,14 @@ onUnmounted(stopRolling)
}
.site-tile.clickable:hover {
background: v-bind("theme.hoverColor");
background: v-bind('theme.hoverColor');
}
.chart-card {
margin-bottom: 18px;
padding: 14px 16px;
border-radius: 10px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
}
.chart-head {
@@ -350,7 +330,7 @@ onUnmounted(stopRolling)
gap: 14px;
padding: 16px 18px;
border-radius: 10px;
border: 1px solid v-bind("theme.dividerColor");
border: 1px solid v-bind('theme.dividerColor');
}
.lucky-select {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AdminProblemRow, AdminProblemListItem } from "utils/types"
import type { AdminProblemRow, AdminProblemListItem } from 'utils/types'
// 把后端的列表项塑形成管理端列表行,与请求逻辑解耦。
export function toAdminProblemRow(result: AdminProblemListItem): AdminProblemRow {
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { errorMessage } from "utils/api"
import { Icon } from '@iconify/vue'
import { errorMessage } from 'utils/api'
import type {
Exercise,
ExerciseType,
@@ -11,8 +11,8 @@ import type {
ExercisePredictData,
ExerciseDebugData,
ExerciseGroupData,
} from "utils/types"
import { getAdminExercises, createExercise, updateExercise, deleteExercise } from "admin/api"
} from 'utils/types'
import { getAdminExercises, createExercise, updateExercise, deleteExercise } from 'admin/api'
/**
* 编辑页右栏的「练一练」:一道一行,写着它在正文的哪一节;新建的直接插到正文光标处,
@@ -34,85 +34,85 @@ const editingId = ref<number | null>(null)
/** 编辑的这道有几个人做过;为 0 时不问要不要清空 */
const editingAttempts = ref(0)
const resetAttempts = ref(false)
const formType = ref<ExerciseType>("mcq")
const formType = ref<ExerciseType>('mcq')
const formOrder = ref(0)
const mcqQuestion = ref("")
const mcqOptions = ref(["", ""])
const mcqQuestion = ref('')
const mcqOptions = ref(['', ''])
const mcqAnswer = ref<number[]>([])
const sortQuestion = ref("")
const sortCode = ref("")
const sortQuestion = ref('')
const sortCode = ref('')
const fillQuestion = ref("")
const fillCode = ref("")
const fillQuestion = ref('')
const fillCode = ref('')
const matchQuestion = ref("")
const matchLeft = ref("")
const matchRight = ref("")
const matchQuestion = ref('')
const matchLeft = ref('')
const matchRight = ref('')
const predictQuestion = ref("")
const predictCode = ref("")
const predictAnswer = ref("")
const predictQuestion = ref('')
const predictCode = ref('')
const predictAnswer = ref('')
const debugQuestion = ref("")
const debugCode = ref("")
const debugQuestion = ref('')
const debugCode = ref('')
const debugAnswer = ref<number[]>([])
const debugExplanation = ref("")
const debugExplanation = ref('')
const groupQuestion = ref("")
const groupBuckets = ref("")
const groupItems = ref("")
const groupQuestion = ref('')
const groupBuckets = ref('')
const groupItems = ref('')
const debugLines = computed(() => (debugCode.value === "" ? [] : debugCode.value.split("\n")))
const debugLines = computed(() => (debugCode.value === '' ? [] : debugCode.value.split('\n')))
async function load() {
exercises.value = await getAdminExercises(props.tutorialId)
emit("change", exercises.value)
emit('change', exercises.value)
}
/** 这道题在正文的哪一节:占位符前面最近的二级标题;没放进正文就是 null */
function placeOf(id: number) {
const at = props.content.indexOf(`[[exercise:${id}]]`)
if (at < 0) return null
const before = props.content.slice(0, at).split("\n")
const before = props.content.slice(0, at).split('\n')
for (let i = before.length - 1; i >= 0; i--) {
const heading = before[i]!.match(/^##\s+(.+)$/)
if (heading) return heading[1]!.trim()
}
return "开头"
return '开头'
}
onMounted(load)
function resetForms() {
mcqQuestion.value = ""
mcqOptions.value = ["", ""]
mcqQuestion.value = ''
mcqOptions.value = ['', '']
mcqAnswer.value = []
sortQuestion.value = ""
sortCode.value = ""
fillQuestion.value = ""
fillCode.value = ""
matchQuestion.value = ""
matchLeft.value = ""
matchRight.value = ""
predictQuestion.value = ""
predictCode.value = ""
predictAnswer.value = ""
debugQuestion.value = ""
debugCode.value = ""
sortQuestion.value = ''
sortCode.value = ''
fillQuestion.value = ''
fillCode.value = ''
matchQuestion.value = ''
matchLeft.value = ''
matchRight.value = ''
predictQuestion.value = ''
predictCode.value = ''
predictAnswer.value = ''
debugQuestion.value = ''
debugCode.value = ''
debugAnswer.value = []
debugExplanation.value = ""
groupQuestion.value = ""
groupBuckets.value = ""
groupItems.value = ""
debugExplanation.value = ''
groupQuestion.value = ''
groupBuckets.value = ''
groupItems.value = ''
}
function openCreate() {
editingId.value = null
editingAttempts.value = 0
resetAttempts.value = false
formType.value = "mcq"
formType.value = 'mcq'
formOrder.value = exercises.value.length
resetForms()
showForm.value = true
@@ -125,41 +125,41 @@ function openEdit(ex: Exercise) {
formType.value = ex.type
formOrder.value = ex.order
resetForms()
if (ex.type === "mcq") {
if (ex.type === 'mcq') {
const d = ex.data as ExerciseMcqData
mcqQuestion.value = d.question
mcqOptions.value = [...d.options]
mcqAnswer.value = [...d.answer]
} else if (ex.type === "sort") {
} else if (ex.type === 'sort') {
const d = ex.data as ExerciseSortData
sortQuestion.value = d.question
sortCode.value = d.lines.join("\n")
} else if (ex.type === "fill") {
sortCode.value = d.lines.join('\n')
} else if (ex.type === 'fill') {
const d = ex.data as ExerciseFillData
fillQuestion.value = d.question
fillCode.value = d.code
} else if (ex.type === "match") {
} else if (ex.type === 'match') {
const d = ex.data as ExerciseMatchData
matchQuestion.value = d.question
matchLeft.value = d.left.join("\n")
matchLeft.value = d.left.join('\n')
// 按答案顺序还原右列,重存时识别答案保持为顺序对应
matchRight.value = d.answer.map((a) => d.right[a]).join("\n")
} else if (ex.type === "predict") {
matchRight.value = d.answer.map((a) => d.right[a]).join('\n')
} else if (ex.type === 'predict') {
const d = ex.data as ExercisePredictData
predictQuestion.value = d.question
predictCode.value = d.code
predictAnswer.value = d.answer.join("\n===\n")
} else if (ex.type === "debug") {
predictAnswer.value = d.answer.join('\n===\n')
} else if (ex.type === 'debug') {
const d = ex.data as ExerciseDebugData
debugQuestion.value = d.question
debugCode.value = d.lines.join("\n")
debugCode.value = d.lines.join('\n')
debugAnswer.value = [...d.answer]
debugExplanation.value = d.explanation ?? ""
} else if (ex.type === "group") {
debugExplanation.value = d.explanation ?? ''
} else if (ex.type === 'group') {
const d = ex.data as ExerciseGroupData
groupQuestion.value = d.question
groupBuckets.value = d.buckets.join("\n")
groupItems.value = d.items.map((it, i) => `${it} => ${d.buckets[d.answer[i]]}`).join("\n")
groupBuckets.value = d.buckets.join('\n')
groupItems.value = d.items.map((it, i) => `${it} => ${d.buckets[d.answer[i]]}`).join('\n')
}
showForm.value = true
}
@@ -178,102 +178,102 @@ function toggleDebug(i: number) {
function splitLines(text: string): string[] {
return text
.split("\n")
.split('\n')
.map((l) => l.trim())
.filter((l) => l !== "")
.filter((l) => l !== '')
}
function buildData(): Record<string, unknown> | null {
if (formType.value === "mcq") {
if (formType.value === 'mcq') {
// 后端 exerciseDataError 也卡这三条,先在这儿报,省一次往返
if (mcqOptions.value.length < 2) {
message.error("选择题至少要有 2 个选项")
message.error('选择题至少要有 2 个选项')
return null
}
if (mcqOptions.value.some((option) => !option.trim())) {
message.error("选项不能留空")
message.error('选项不能留空')
return null
}
if (mcqAnswer.value.length === 0) {
message.error("请至少勾选一个正确答案")
message.error('请至少勾选一个正确答案')
return null
}
return {
question: mcqQuestion.value || "下面选项中正确是哪个?",
question: mcqQuestion.value || '下面选项中正确是哪个?',
options: mcqOptions.value,
answer: mcqAnswer.value,
}
}
if (formType.value === "sort") {
const lines = sortCode.value.split("\n").filter((l) => l.trim() !== "")
if (formType.value === 'sort') {
const lines = sortCode.value.split('\n').filter((l) => l.trim() !== '')
if (lines.length < 2) {
message.error("排序题至少要有 2 行代码")
message.error('排序题至少要有 2 行代码')
return null
}
return {
question: sortQuestion.value || "将下列代码行排列为正确顺序",
question: sortQuestion.value || '将下列代码行排列为正确顺序',
lines,
}
}
if (formType.value === "fill") {
if (formType.value === 'fill') {
if (!fillCode.value.trim()) {
message.error("请填写含空位的代码")
message.error('请填写含空位的代码')
return null
}
// 学生端按 {{...}} 抠空位,没有标记就是一段谁也做不了的代码,
// 而老师这边看不出任何异样 —— 这是这个编辑器以前唯一完全不校验的题型
if (!/\{\{[^}]+\}\}/.test(fillCode.value)) {
message.error("代码里没有空位,用 {{答案}} 标记,多个合法答案用 | 分隔")
message.error('代码里没有空位,用 {{答案}} 标记,多个合法答案用 | 分隔')
return null
}
return { question: fillQuestion.value, code: fillCode.value }
}
if (formType.value === "match") {
if (formType.value === 'match') {
const left = splitLines(matchLeft.value)
const right = splitLines(matchRight.value)
if (left.length < 2 || left.length !== right.length) {
message.error("左右两列需各至少 2 项且行数相等(按行一一对应)")
message.error('左右两列需各至少 2 项且行数相等(按行一一对应)')
return null
}
return {
question: matchQuestion.value || "把左右两列正确连线",
question: matchQuestion.value || '把左右两列正确连线',
left,
right,
answer: left.map((_, i) => i),
}
}
if (formType.value === "predict") {
if (predictCode.value.trim() === "") {
message.error("请填写代码")
if (formType.value === 'predict') {
if (predictCode.value.trim() === '') {
message.error('请填写代码')
return null
}
const answer = predictAnswer.value
.split(/\n===\n/)
.map((a) => a.replace(/\s+$/, ""))
.filter((a) => a.trim() !== "")
.map((a) => a.replace(/\s+$/, ''))
.filter((a) => a.trim() !== '')
if (answer.length === 0) {
message.error("请填写至少一个正确输出")
message.error('请填写至少一个正确输出')
return null
}
return {
question: predictQuestion.value || "这段代码会输出什么?",
question: predictQuestion.value || '这段代码会输出什么?',
code: predictCode.value,
answer,
}
}
if (formType.value === "debug") {
const lines = debugCode.value.split("\n")
if (formType.value === 'debug') {
const lines = debugCode.value.split('\n')
const answer = debugAnswer.value.filter((i) => i < lines.length).sort((a, b) => a - b)
if (lines.length === 0 || answer.length === 0) {
message.error("请填写代码并勾选至少一行错误")
message.error('请填写代码并勾选至少一行错误')
return null
}
const data: Record<string, unknown> = {
question: debugQuestion.value || "下面代码哪几行有错?",
question: debugQuestion.value || '下面代码哪几行有错?',
lines,
answer,
}
if (debugExplanation.value.trim() !== "") {
if (debugExplanation.value.trim() !== '') {
data.explanation = debugExplanation.value.trim()
}
return data
@@ -281,21 +281,21 @@ function buildData(): Record<string, unknown> | null {
// group
const buckets = splitLines(groupBuckets.value)
if (buckets.length < 2) {
message.error("请至少填写 2 个分组")
message.error('请至少填写 2 个分组')
return null
}
const items: string[] = []
const answer: number[] = []
for (const line of groupItems.value.split("\n")) {
if (line.trim() === "") continue
const parts = line.split("=>")
for (const line of groupItems.value.split('\n')) {
if (line.trim() === '') continue
const parts = line.split('=>')
if (parts.length !== 2) {
message.error(`项目格式应为「项目 => 分组名」:${line}`)
return null
}
const item = parts[0].trim()
const bucket = buckets.indexOf(parts[1].trim())
if (item === "" || bucket === -1) {
if (item === '' || bucket === -1) {
message.error(`项目或分组名无效:${line}`)
return null
}
@@ -303,11 +303,11 @@ function buildData(): Record<string, unknown> | null {
answer.push(bucket)
}
if (items.length === 0) {
message.error("请至少填写一个项目")
message.error('请至少填写一个项目')
return null
}
return {
question: groupQuestion.value || "把下列项目归类到正确的分组",
question: groupQuestion.value || '把下列项目归类到正确的分组',
buckets,
items,
answer,
@@ -327,7 +327,7 @@ async function save() {
order: formOrder.value,
resetAttempts: resetAttempts.value,
})
message.success(resetAttempts.value ? "练习题已更新,学生的作答已清空" : "练习题已更新")
message.success(resetAttempts.value ? '练习题已更新,学生的作答已清空' : '练习题已更新')
} else {
const created = await createExercise({
tutorialId: props.tutorialId,
@@ -335,37 +335,37 @@ async function save() {
data,
order: formOrder.value,
})
message.success("已新建,插到了正文光标处")
emit("insert", created.id)
message.success('已新建,插到了正文光标处')
emit('insert', created.id)
}
showForm.value = false
await load()
} catch (e) {
message.error(errorMessage(e, "保存失败"))
message.error(errorMessage(e, '保存失败'))
}
}
function confirmDelete(id: number) {
dialog.warning({
title: "删除练习题",
content: "此操作不可撤销",
positiveText: "删除",
title: '删除练习题',
content: '此操作不可撤销',
positiveText: '删除',
onPositiveClick: async () => {
await deleteExercise(id)
message.success("已删除")
message.success('已删除')
await load()
},
})
}
const TYPE_NAMES: Record<ExerciseType, string> = {
mcq: "选择",
sort: "排序",
fill: "填空",
match: "连线",
predict: "预测输出",
debug: "找错",
group: "分组",
mcq: '选择',
sort: '排序',
fill: '填空',
match: '连线',
predict: '预测输出',
debug: '找错',
group: '分组',
}
function typeName(type: ExerciseType) {
@@ -403,12 +403,7 @@ function typeName(type: ExerciseType) {
</div>
</div>
<n-modal
v-model:show="showForm"
:title="editingId ? '编辑练习题' : '新建练习题'"
preset="card"
style="width: 560px"
>
<n-modal v-model:show="showForm" :title="editingId ? '编辑练习题' : '新建练习题'" preset="card" style="width: 560px">
<n-form label-placement="top">
<n-form-item label="题型">
<n-radio-group v-model:value="formType" :disabled="!!editingId">
@@ -428,22 +423,13 @@ function typeName(type: ExerciseType) {
<template v-if="formType === 'mcq'">
<n-form-item label="题目">
<n-input
v-model:value="mcqQuestion"
type="textarea"
:rows="2"
placeholder="下面选项中正确是哪个?"
/>
<n-input v-model:value="mcqQuestion" type="textarea" :rows="2" placeholder="下面选项中正确是哪个?" />
</n-form-item>
<n-form-item label="选项(勾选所有正确答案)">
<n-space vertical style="width: 100%">
<n-flex v-for="(_opt, i) in mcqOptions" :key="i" align="center" :size="8">
<n-checkbox :checked="mcqAnswer.includes(i)" @update:checked="toggleAnswer(i)" />
<n-input
v-model:value="mcqOptions[i]"
:placeholder="`选项 ${String.fromCharCode(65 + i)}`"
style="flex: 1"
/>
<n-input v-model:value="mcqOptions[i]" :placeholder="`选项 ${String.fromCharCode(65 + i)}`" style="flex: 1" />
<n-button
size="small"
:disabled="mcqOptions.length <= 2"
@@ -464,12 +450,7 @@ function typeName(type: ExerciseType) {
<template v-else-if="formType === 'sort'">
<n-form-item label="题目">
<n-input
v-model:value="sortQuestion"
type="textarea"
:rows="2"
placeholder="将下列代码行排列为正确顺序"
/>
<n-input v-model:value="sortQuestion" type="textarea" :rows="2" placeholder="将下列代码行排列为正确顺序" />
</n-form-item>
<n-form-item label="正确代码(每行将自动成为一道排序项)">
<n-input
@@ -477,19 +458,14 @@ function typeName(type: ExerciseType) {
type="textarea"
:rows="10"
placeholder="在此粘贴正确的代码,保存后将自动按行拆分并乱序"
style="font-family: &quot;Monaco&quot;"
style="font-family: 'Monaco'"
/>
</n-form-item>
</template>
<template v-else-if="formType === 'fill'">
<n-form-item label="题目说明">
<n-input
v-model:value="fillQuestion"
type="textarea"
:rows="2"
placeholder="例:补全下面的循环语句"
/>
<n-input v-model:value="fillQuestion" type="textarea" :rows="2" placeholder="例:补全下面的循环语句" />
</n-form-item>
<n-form-item label="含空位的代码">
<n-input
@@ -497,122 +473,62 @@ function typeName(type: ExerciseType) {
type="textarea"
:rows="10"
placeholder="用 {{答案}} 标记空位,多个合法答案用 | 分隔,例如:for {{i|idx}} in range(10):"
style="font-family: &quot;Monaco&quot;"
style="font-family: 'Monaco'"
/>
</n-form-item>
</template>
<template v-else-if="formType === 'match'">
<n-form-item label="题目说明">
<n-input
v-model:value="matchQuestion"
type="textarea"
:rows="2"
placeholder="例:把函数和它的功能连起来"
/>
<n-input v-model:value="matchQuestion" type="textarea" :rows="2" placeholder="例:把函数和它的功能连起来" />
</n-form-item>
<n-form-item label="左列(每行一项)">
<n-input
v-model:value="matchLeft"
type="textarea"
:rows="6"
placeholder="print&#10;len&#10;type"
/>
<n-input v-model:value="matchLeft" type="textarea" :rows="6" placeholder="print&#10;len&#10;type" />
</n-form-item>
<n-form-item label="右列(与左列按行一一对应,保存后右列自动乱序)">
<n-input
v-model:value="matchRight"
type="textarea"
:rows="6"
placeholder="输出内容&#10;返回长度&#10;返回类型"
/>
<n-input v-model:value="matchRight" type="textarea" :rows="6" placeholder="输出内容&#10;返回长度&#10;返回类型" />
</n-form-item>
</template>
<template v-else-if="formType === 'predict'">
<n-form-item label="题目说明">
<n-input
v-model:value="predictQuestion"
type="textarea"
:rows="2"
placeholder="例:这段代码会输出什么?"
/>
<n-input v-model:value="predictQuestion" type="textarea" :rows="2" placeholder="例:这段代码会输出什么?" />
</n-form-item>
<n-form-item label="代码">
<n-input
v-model:value="predictCode"
type="textarea"
:rows="8"
placeholder="print(1 + 2)"
style="font-family: &quot;Monaco&quot;"
/>
<n-input v-model:value="predictCode" type="textarea" :rows="8" placeholder="print(1 + 2)" style="font-family: 'Monaco'" />
</n-form-item>
<n-form-item label="正确输出(多个可接受答案之间用单独一行 === 分隔)">
<n-input
v-model:value="predictAnswer"
type="textarea"
:rows="4"
placeholder="3"
style="font-family: &quot;Monaco&quot;"
/>
<n-input v-model:value="predictAnswer" type="textarea" :rows="4" placeholder="3" style="font-family: 'Monaco'" />
</n-form-item>
</template>
<template v-else-if="formType === 'debug'">
<n-form-item label="题目说明">
<n-input
v-model:value="debugQuestion"
type="textarea"
:rows="2"
placeholder="例:下面代码哪几行有错?"
/>
<n-input v-model:value="debugQuestion" type="textarea" :rows="2" placeholder="例:下面代码哪几行有错?" />
</n-form-item>
<n-form-item label="代码(每行一项)">
<n-input
v-model:value="debugCode"
type="textarea"
:rows="8"
placeholder="在此粘贴含错误的代码"
style="font-family: &quot;Monaco&quot;"
/>
<n-input v-model:value="debugCode" type="textarea" :rows="8" placeholder="在此粘贴含错误的代码" style="font-family: 'Monaco'" />
</n-form-item>
<n-form-item label="勾选错误行">
<n-space vertical style="width: 100%">
<n-empty v-if="debugLines.length === 0" description="先填写代码" size="small" />
<n-flex v-for="(line, i) in debugLines" :key="i" align="center" :size="8">
<n-checkbox :checked="debugAnswer.includes(i)" @update:checked="toggleDebug(i)" />
<n-text style="font-family: Monaco; white-space: pre">
{{ i + 1 }}. {{ line }}
</n-text>
<n-text style="font-family: Monaco; white-space: pre"> {{ i + 1 }}. {{ line }} </n-text>
</n-flex>
</n-space>
</n-form-item>
<n-form-item label="错误说明(可选,提交后展示)">
<n-input
v-model:value="debugExplanation"
type="textarea"
:rows="2"
placeholder="例:第 2 行少了冒号"
/>
<n-input v-model:value="debugExplanation" type="textarea" :rows="2" placeholder="例:第 2 行少了冒号" />
</n-form-item>
</template>
<template v-else-if="formType === 'group'">
<n-form-item label="题目说明">
<n-input
v-model:value="groupQuestion"
type="textarea"
:rows="2"
placeholder="例:把下面的值归类到正确的类型"
/>
<n-input v-model:value="groupQuestion" type="textarea" :rows="2" placeholder="例:把下面的值归类到正确的类型" />
</n-form-item>
<n-form-item label="分组(每行一个分组名)">
<n-input
v-model:value="groupBuckets"
type="textarea"
:rows="4"
placeholder="int&#10;float&#10;str"
/>
<n-input v-model:value="groupBuckets" type="textarea" :rows="4" placeholder="int&#10;float&#10;str" />
</n-form-item>
<n-form-item label="项目(每行「项目 => 分组名」)">
<n-input
@@ -620,7 +536,7 @@ function typeName(type: ExerciseType) {
type="textarea"
:rows="6"
placeholder="3 => int&#10;3.14 => float&#10;hello => str"
style="font-family: &quot;Monaco&quot;"
style="font-family: 'Monaco'"
/>
</n-form-item>
</template>
@@ -629,9 +545,7 @@ function typeName(type: ExerciseType) {
<template #footer>
<n-flex align="center" :size="8">
<!-- 改了答案或选项时勾上:按旧答案做对的人不该还算做对 -->
<n-checkbox v-if="editingId && editingAttempts" v-model:checked="resetAttempts">
同时清空学生的作答({{ editingAttempts }} 人做过)
</n-checkbox>
<n-checkbox v-if="editingId && editingAttempts" v-model:checked="resetAttempts"> 同时清空学生的作答({{ editingAttempts }} 人做过) </n-checkbox>
<span style="flex: 1" />
<n-button @click="showForm = false">取消</n-button>
<n-button type="primary" @click="save">保存</n-button>
@@ -1,12 +1,8 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import {
TUTORIAL_PROBLEM_MAX,
type AdminTutorialProblem,
type TutorialProblemCandidate,
} from "@oj2/contract"
import { errorMessage } from "utils/api"
import { getTutorialProblemCandidates, setTutorialProblems } from "admin/api"
import { Icon } from '@iconify/vue'
import { TUTORIAL_PROBLEM_MAX, type AdminTutorialProblem, type TutorialProblemCandidate } from '@oj2/contract'
import { errorMessage } from 'utils/api'
import { getTutorialProblemCandidates, setTutorialProblems } from 'admin/api'
/**
* 一课结尾「去做几道题」挑哪几道(设计稿「后台 · 编辑一课」右栏)。
@@ -16,7 +12,7 @@ const props = defineProps<{ tutorialId: number; problems: AdminTutorialProblem[]
const emit = defineEmits<{ update: [problems: AdminTutorialProblem[]] }>()
const message = useMessage()
const keyword = ref("")
const keyword = ref('')
const candidates = ref<TutorialProblemCandidate[]>([])
const dragIndex = ref<number | null>(null)
@@ -38,14 +34,14 @@ onMounted(search)
async function save(next: AdminTutorialProblem[]) {
const before = props.problems
emit("update", next)
emit('update', next)
try {
await setTutorialProblems(
props.tutorialId,
next.map((item) => item.id),
)
} catch (err) {
emit("update", before)
emit('update', before)
message.error(errorMessage(err))
}
}
@@ -89,9 +85,7 @@ function drop(target: number) {
@dragover.prevent
@drop="drop(index)"
>
<span class="handle" aria-hidden="true"
><Icon icon="ph:dots-six-vertical-bold" :width="14"
/></span>
<span class="handle" aria-hidden="true"><Icon icon="ph:dots-six-vertical-bold" :width="14" /></span>
<span class="pid">{{ problem.displayId }}</span>
<span class="name">{{ problem.title }}</span>
<span v-if="problem.mustDo" class="must">必会</span>
@@ -107,7 +101,7 @@ function drop(target: number) {
<span class="pid">{{ item.displayId }}</span>
<span class="name">{{ item.title }}</span>
<span v-if="item.mustDo" class="must">必会</span>
<span v-else class="tags">{{ item.tags.join(" · ") }}</span>
<span v-else class="tags">{{ item.tags.join(' · ') }}</span>
<n-button size="tiny" @click="add(item)">
<template #icon><Icon icon="ph:plus" /></template>
加
+38 -70
View File
@@ -1,23 +1,17 @@
<script lang="ts" setup>
import { Icon } from "@iconify/vue"
import type { AdminTutorialProblem } from "@oj2/contract"
import { errorMessage } from "utils/api"
import MarkdownEditor from "shared/components/MarkdownEditor.vue"
import type { Exercise, TutorialEdit, TutorialListItem } from "utils/types"
import { parseLesson } from "oj/learn/composables/useLessonParse"
import { joinTitle, lessonPath, splitTitle } from "oj/learn/lesson"
import LessonBody from "oj/learn/components/LessonBody.vue"
import "oj/learn/learn.css"
import {
createTutorial,
deleteTutorial,
getTutorial,
getTutorialList,
updateTutorial,
} from "../api"
import ExerciseManager from "./components/ExerciseManager.vue"
import RelatedProblems from "./components/RelatedProblems.vue"
import { useBreakpoints } from "shared/composables/breakpoints"
import { Icon } from '@iconify/vue'
import type { AdminTutorialProblem } from '@oj2/contract'
import { errorMessage } from 'utils/api'
import MarkdownEditor from 'shared/components/MarkdownEditor.vue'
import type { Exercise, TutorialEdit, TutorialListItem } from 'utils/types'
import { parseLesson } from 'oj/learn/composables/useLessonParse'
import { joinTitle, lessonPath, splitTitle } from 'oj/learn/lesson'
import LessonBody from 'oj/learn/components/LessonBody.vue'
import 'oj/learn/learn.css'
import { createTutorial, deleteTutorial, getTutorial, getTutorialList, updateTutorial } from '../api'
import ExerciseManager from './components/ExerciseManager.vue'
import RelatedProblems from './components/RelatedProblems.vue'
import { useBreakpoints } from 'shared/composables/breakpoints'
/**
* 编辑一课(设计稿「后台 · 编辑一课」):知识点 / 情境 / 项目三个字段,正文左边写、
@@ -30,32 +24,32 @@ const route = useRoute()
const router = useRouter()
const message = useMessage()
const isCreate = computed(() => route.name === "admin tutorial create")
const isCreate = computed(() => route.name === 'admin tutorial create')
// 手机上左右分栏各剩一百多像素,改成正文「写 / 预览」切着看
const { isMobile } = useBreakpoints()
const pane = ref<"source" | "preview">("source")
const pane = ref<'source' | 'preview'>('source')
const tutorial = reactive<TutorialEdit>({
id: 0,
title: "",
content: "",
project: typeof route.query.project === "string" ? route.query.project : "",
title: '',
content: '',
project: typeof route.query.project === 'string' ? route.query.project : '',
isPublic: false,
order: 0,
type: route.query.type === "c" ? "c" : "python",
type: route.query.type === 'c' ? 'c' : 'python',
})
const kp = ref("")
const scene = ref("")
const kp = ref('')
const scene = ref('')
const problems = ref<AdminTutorialProblem[]>([])
const exercises = ref<Exercise[]>([])
const allTutorials = ref<{ [key: string]: TutorialListItem[] }>({ python: [], c: [] })
const saving = ref(false)
const editor = useTemplateRef<InstanceType<typeof MarkdownEditor>>("editor")
const editor = useTemplateRef<InstanceType<typeof MarkdownEditor>>('editor')
const typeOptions = [
{ label: "Python", value: "python" },
{ label: "C 语言", value: "c" },
{ label: 'Python', value: 'python' },
{ label: 'C 语言', value: 'c' },
]
const siblings = computed(() => allTutorials.value[tutorial.type] ?? [])
@@ -71,8 +65,8 @@ const step = computed(() => {
return index >= 0 ? index + 1 : null
})
const heading = computed(() => {
if (isCreate.value) return "新建一课"
const label = tutorial.type === "c" ? "C 语言" : "Python"
if (isCreate.value) return '新建一课'
const label = tutorial.type === 'c' ? 'C 语言' : 'Python'
return step.value ? `${label} 第 ${step.value} 课` : `${label} · 没公开`
})
const preview = computed(() => parseLesson(tutorial.content, exercises.value))
@@ -101,18 +95,18 @@ async function init() {
async function submit() {
tutorial.title = joinTitle(kp.value, scene.value)
if (!kp.value.trim() || !tutorial.content.trim()) {
message.error("知识点和正文必填")
message.error('知识点和正文必填')
return
}
saving.value = true
try {
if (isCreate.value) {
const created = await createTutorial(tutorial)
message.success("已新建,接着可以加练一练和相关题")
router.replace({ name: "admin tutorial edit", params: { tutorialID: created.id } })
message.success('已新建,接着可以加练一练和相关题')
router.replace({ name: 'admin tutorial edit', params: { tutorialID: created.id } })
} else {
await updateTutorial(tutorial)
message.success("已保存")
message.success('已保存')
allTutorials.value = await getTutorialList().catch(() => allTutorials.value)
}
} catch (err) {
@@ -125,8 +119,8 @@ async function submit() {
async function remove() {
try {
await deleteTutorial(tutorial.id)
message.success("已删除")
router.push({ name: "admin tutorial list" })
message.success('已删除')
router.push({ name: 'admin tutorial list' })
} catch (err) {
message.error(errorMessage(err))
}
@@ -137,7 +131,7 @@ function insertExercise(id: number) {
}
function openStudentView() {
if (step.value) window.open(router.resolve(lessonPath(tutorial.type, step.value)).href, "_blank")
if (step.value) window.open(router.resolve(lessonPath(tutorial.type, step.value)).href, '_blank')
}
watch(() => props.tutorialID, init)
@@ -147,9 +141,7 @@ onMounted(init)
<template>
<div class="page">
<div class="top">
<router-link :to="{ name: 'admin tutorial list' }" class="back">
<Icon icon="ph:caret-left-bold" :width="13" />教程
</router-link>
<router-link :to="{ name: 'admin tutorial list' }" class="back"> <Icon icon="ph:caret-left-bold" :width="13" />教程 </router-link>
<span class="slash">/</span>
<span class="heading">{{ heading }}</span>
<span class="grow" />
@@ -181,15 +173,7 @@ onMounted(init)
</label>
<label class="field">
<span>项目</span>
<n-select
v-model:value="tutorial.project"
:options="projectOptions"
filterable
tag
clearable
placeholder="选一个,或者打字新建"
style="width: 250px"
/>
<n-select v-model:value="tutorial.project" :options="projectOptions" filterable tag clearable placeholder="选一个,或者打字新建" style="width: 250px" />
</label>
<label v-if="isCreate" class="field">
<span>语言</span>
@@ -212,12 +196,7 @@ onMounted(init)
</div>
<div class="split" :class="isMobile ? `only-${pane}` : ''">
<div class="source">
<MarkdownEditor
ref="editor"
v-model:value="tutorial.content"
:code-lang="tutorial.type"
height="100%"
/>
<MarkdownEditor ref="editor" v-model:value="tutorial.content" :code-lang="tutorial.type" height="100%" />
</div>
<div class="preview">
<LessonBody
@@ -233,22 +212,11 @@ onMounted(init)
<aside class="side">
<section class="card pad">
<ExerciseManager
v-if="tutorial.id"
:tutorial-id="tutorial.id"
:content="tutorial.content"
@insert="insertExercise"
@change="exercises = $event"
/>
<ExerciseManager v-if="tutorial.id" :tutorial-id="tutorial.id" :content="tutorial.content" @insert="insertExercise" @change="exercises = $event" />
<div v-else class="muted">保存之后就能加练一练</div>
</section>
<section class="card pad">
<RelatedProblems
v-if="tutorial.id"
:tutorial-id="tutorial.id"
:problems="problems"
@update="problems = $event"
/>
<RelatedProblems v-if="tutorial.id" :tutorial-id="tutorial.id" :problems="problems" @update="problems = $event" />
<div v-else class="muted">保存之后就能挑相关题</div>
</section>
</aside>
+27 -73
View File
@@ -1,16 +1,11 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import { errorMessage } from "utils/api"
import type { TutorialListItem } from "utils/types"
import { groupByProject, splitTitle, type TutorialType } from "oj/learn/lesson"
import ProjectTile from "oj/learn/components/ProjectTile.vue"
import "oj/learn/learn.css"
import {
getTutorialList,
renameTutorialProject,
reorderTutorials,
setTutorialVisibility,
} from "../api"
import { Icon } from '@iconify/vue'
import { errorMessage } from 'utils/api'
import type { TutorialListItem } from 'utils/types'
import { groupByProject, splitTitle, type TutorialType } from 'oj/learn/lesson'
import ProjectTile from 'oj/learn/components/ProjectTile.vue'
import 'oj/learn/learn.css'
import { getTutorialList, renameTutorialProject, reorderTutorials, setTutorialVisibility } from '../api'
/**
* 教程列表(设计稿「后台 · 教程列表」):按项目分组,拖动排序;每课看得到几道练一练、
@@ -20,14 +15,14 @@ const router = useRouter()
const route = useRoute()
const message = useMessage()
const type = ref<TutorialType>(route.query.type === "c" ? "c" : "python")
const type = ref<TutorialType>(route.query.type === 'c' ? 'c' : 'python')
const all = ref<{ [key: string]: TutorialListItem[] }>({ python: [], c: [] })
const collapsed = ref(new Set<string>())
const renaming = ref<string | null>(null)
const renameTo = ref("")
const renameTo = ref('')
const dragId = ref<number | null>(null)
const showNewProject = ref(false)
const newProject = ref("")
const newProject = ref('')
const list = computed(() => all.value[type.value] ?? [])
const groups = computed(() =>
@@ -54,9 +49,7 @@ const publicStep = computed(() => {
async function load() {
all.value = await getTutorialList()
// 整组没公开又没项目的(老教程)默认收起
collapsed.value = new Set(
groups.value.filter((group) => group.hidden && !group.project).map((group) => group.key),
)
collapsed.value = new Set(groups.value.filter((group) => group.hidden && !group.project).map((group) => group.key))
}
function pickType(value: TutorialType) {
@@ -106,7 +99,7 @@ async function drop(target: TutorialListItem) {
dragId.value = null
if (!from || from.id === target.id) return
if (from.project !== target.project) {
message.warning("只能在同一个项目里拖,换项目请到编辑页里改")
message.warning('只能在同一个项目里拖,换项目请到编辑页里改')
return
}
const ids = list.value.map((item) => item.id).filter((id) => id !== from.id)
@@ -129,14 +122,14 @@ async function drop(target: TutorialListItem) {
}
function createIn(project: string) {
router.push({ name: "admin tutorial create", query: { type: type.value, project } })
router.push({ name: 'admin tutorial create', query: { type: type.value, project } })
}
function confirmNewProject() {
const name = newProject.value.trim()
if (!name) return
showNewProject.value = false
newProject.value = ""
newProject.value = ''
createIn(name)
}
@@ -148,9 +141,7 @@ onMounted(load)
<div class="top">
<span class="title">教程</span>
<div class="seg">
<button type="button" :class="{ on: type === 'python' }" @click="pickType('python')">
Python
</button>
<button type="button" :class="{ on: type === 'python' }" @click="pickType('python')">Python</button>
<button type="button" :class="{ on: type === 'c' }" @click="pickType('c')">C 语言</button>
</div>
<span class="grow" />
@@ -178,37 +169,19 @@ onMounted(load)
<template v-for="group in groups" :key="group.key">
<!-- 整行都能点开合;行里的改名、加一课自己拦住,不顺带开合 -->
<div class="row grouprow" @click="toggle(group.key)">
<button
type="button"
class="fold"
:aria-label="collapsed.has(group.key) ? '展开' : '收起'"
>
<Icon
:icon="collapsed.has(group.key) ? 'ph:caret-right-bold' : 'ph:caret-down-bold'"
:width="13"
/>
<button type="button" class="fold" :aria-label="collapsed.has(group.key) ? '展开' : '收起'">
<Icon :icon="collapsed.has(group.key) ? 'ph:caret-right-bold' : 'ph:caret-down-bold'" :width="13" />
</button>
<ProjectTile :icon="group.icon" :tone="group.tone" :size="26" />
<span v-if="renaming === group.project && group.project" class="rename" @click.stop>
<n-input
v-model:value="renameTo"
size="small"
style="width: 280px"
autofocus
@keyup.enter="saveRename"
@keyup.esc="renaming = null"
/>
<n-input v-model:value="renameTo" size="small" style="width: 280px" autofocus @keyup.enter="saveRename" @keyup.esc="renaming = null" />
<n-button size="small" type="primary" @click="saveRename">保存</n-button>
<n-button size="small" quaternary @click="renaming = null">取消</n-button>
</span>
<template v-else>
<span class="group-name">{{
group.project || (group.hidden ? "没公开" : "没有项目")
}}</span>
<span class="group-name">{{ group.project || (group.hidden ? '没公开' : '没有项目') }}</span>
<span class="muted">{{ group.items.length }} 课</span>
<a v-if="group.project" href="#" @click.stop.prevent="startRename(group.project)"
>改名</a
>
<a v-if="group.project" href="#" @click.stop.prevent="startRename(group.project)">改名</a>
<a href="#" @click.stop.prevent="createIn(group.project)">加一课</a>
</template>
</div>
@@ -224,52 +197,33 @@ onMounted(load)
@dragover.prevent
@drop="drop(item)"
>
<span class="c-drag handle" aria-hidden="true"
><Icon icon="ph:dots-six-vertical-bold" :width="16"
/></span>
<span class="c-no num muted">{{ publicStep.get(item.id) ?? "—" }}</span>
<span class="c-drag handle" aria-hidden="true"><Icon icon="ph:dots-six-vertical-bold" :width="16" /></span>
<span class="c-no num muted">{{ publicStep.get(item.id) ?? '—' }}</span>
<span class="c-title">
<span class="kp">{{ splitTitle(item.title).kp }}</span>
<span class="scene">{{ splitTitle(item.title).scene }}</span>
</span>
<span class="c-num c-ex num">{{ item.exerciseCount || "-" }}</span>
<span class="c-num c-ex num">{{ item.exerciseCount || '-' }}</span>
<span class="c-num num">
<template v-if="item.problemCount">{{ item.problemCount }}</template>
<span v-else class="warn">还没挑</span>
</span>
<span class="c-num wide num">{{ item.readers }}</span>
<span class="c-switch">
<n-switch
:value="item.isPublic"
size="small"
:rubber-band="false"
@update:value="toggleVisible(item)"
/>
<n-switch :value="item.isPublic" size="small" :rubber-band="false" @update:value="toggleVisible(item)" />
</span>
<router-link
:to="{ name: 'admin tutorial edit', params: { tutorialID: item.id } }"
class="c-edit"
>
编辑
</router-link>
<router-link :to="{ name: 'admin tutorial edit', params: { tutorialID: item.id } }" class="c-edit"> 编辑 </router-link>
</div>
</template>
</template>
</section>
<n-modal v-model:show="showNewProject" preset="card" title="新建项目" style="width: 420px">
<n-input
v-model:value="newProject"
placeholder="项目五 · 智慧物流·仓储管理"
maxlength="64"
@keyup.enter="confirmNewProject"
/>
<n-input v-model:value="newProject" placeholder="项目五 · 智慧物流·仓储管理" maxlength="64" @keyup.enter="confirmNewProject" />
<template #footer>
<n-flex justify="end">
<n-button @click="showNewProject = false">取消</n-button>
<n-button type="primary" :disabled="!newProject.trim()" @click="confirmNewProject">
接着写第一课
</n-button>
<n-button type="primary" :disabled="!newProject.trim()" @click="confirmNewProject"> 接着写第一课 </n-button>
</n-flex>
</template>
</n-modal>
+4 -8
View File
@@ -2,15 +2,11 @@
* 账号名单下成表格:用户名、密码两列。批量建号建完下名单、用户列表按班下名单共用这一份。
* 开头带 BOM,Excel 打开中文才不乱码
*/
export function downloadAccountsCsv(
rows: { username: string; password: string }[],
filename: string,
) {
export function downloadAccountsCsv(rows: { username: string; password: string }[], filename: string) {
const cell = (text: string) => (/[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text)
const csv =
"用户名,密码\n" + rows.map((it) => `${cell(it.username)},${cell(it.password)}`).join("\n")
const link = document.createElement("a")
link.href = URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8" }))
const csv = '用户名,密码\n' + rows.map((it) => `${cell(it.username)},${cell(it.password)}`).join('\n')
const link = document.createElement('a')
link.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))
link.download = `${filename}.csv`
link.click()
URL.revokeObjectURL(link.href)
+13 -13
View File
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import { editUser } from "admin/api"
import type { AdminUserForm } from "utils/types"
import { useBreakpoints } from "shared/composables/breakpoints"
import { editUser } from 'admin/api'
import type { AdminUserForm } from 'utils/types'
import { useBreakpoints } from 'shared/composables/breakpoints'
/**
* 用户列表一行的操作:重置密码、编辑、禁用、删除直接摆出来(用户说的:不要收进 ⋯)。
@@ -12,10 +12,10 @@ interface Props {
}
const props = defineProps<Props>()
const emit = defineEmits<{
(e: "deleteUser", value: number[]): void
(e: "userBanned", value: AdminUserForm): void
(e: "openEditModal", value: AdminUserForm): void
(e: "resetPassword", value: AdminUserForm): void
(e: 'deleteUser', value: number[]): void
(e: 'userBanned', value: AdminUserForm): void
(e: 'openEditModal', value: AdminUserForm): void
(e: 'resetPassword', value: AdminUserForm): void
}>()
const dialog = useDialog()
@@ -25,16 +25,16 @@ const { isMobile } = useBreakpoints()
async function banUser() {
props.user.isDisabled = !props.user.isDisabled
await editUser(props.user)
emit("userBanned", props.user)
emit('userBanned', props.user)
}
function confirmDelete() {
dialog.warning({
title: `删除 ${props.user.username}?`,
content: "删掉就找不回来了。交过题的账号删不掉,那种请改为禁用。",
positiveText: "删除",
negativeText: "不删",
onPositiveClick: () => emit("deleteUser", [props.user.id]),
content: '删掉就找不回来了。交过题的账号删不掉,那种请改为禁用。',
positiveText: '删除',
negativeText: '不删',
onPositiveClick: () => emit('deleteUser', [props.user.id]),
})
}
</script>
@@ -43,7 +43,7 @@ function confirmDelete() {
<n-button size="small" @click="emit('resetPassword', props.user)">重置密码</n-button>
<n-button size="small" @click="emit('openEditModal', props.user)">编辑</n-button>
<n-button size="small" @click="banUser">
{{ props.user.isDisabled ? "解除禁用" : "禁用" }}
{{ props.user.isDisabled ? '解除禁用' : '禁用' }}
</n-button>
<n-button size="small" quaternary type="error" @click="confirmDelete">删除</n-button>
</n-flex>
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import TextCopy from "shared/components/TextCopy.vue"
import { USER_TYPE } from "utils/constants"
import type { AdminUserForm } from "utils/types"
import TextCopy from 'shared/components/TextCopy.vue'
import { USER_TYPE } from 'utils/constants'
import type { AdminUserForm } from 'utils/types'
interface Props {
user: AdminUserForm
@@ -9,7 +9,7 @@ interface Props {
}
const props = defineProps<Props>()
defineEmits<{
(e: "toggle", value: number): void
(e: 'toggle', value: number): void
}>()
/**
@@ -21,9 +21,7 @@ defineEmits<{
* `rawPassword` 为空时不打码:给一个点了什么也不显示的按钮没有意义,直接走原来的
* TextCopy(渲染成空)。
*/
const maskable = computed(
() => props.user.adminType !== USER_TYPE.REGULAR_USER && !!props.user.rawPassword,
)
const maskable = computed(() => props.user.adminType !== USER_TYPE.REGULAR_USER && !!props.user.rawPassword)
</script>
<template>
<!-- 显示出来之后要能再收回去:看一眼就该关掉,不然一整页管理员密码就那么摊着,
@@ -32,7 +30,7 @@ const maskable = computed(
<span v-if="!props.revealed" class="dots">••••••</span>
<TextCopy v-else>{{ props.user.rawPassword }}</TextCopy>
<n-button size="tiny" secondary @click="$emit('toggle', props.user.id)">
{{ props.revealed ? "隐藏" : "显示" }}
{{ props.revealed ? '隐藏' : '显示' }}
</n-button>
</n-flex>
<TextCopy v-else>{{ props.user.rawPassword }}</TextCopy>
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { PROBLEM_PERMISSION, USER_TYPE } from "utils/constants"
import { getUserRole } from "utils/functions"
import type { AdminUserForm } from "utils/types"
import TextCopy from "shared/components/TextCopy.vue"
import { PROBLEM_PERMISSION, USER_TYPE } from 'utils/constants'
import { getUserRole } from 'utils/functions'
import type { AdminUserForm } from 'utils/types'
import TextCopy from 'shared/components/TextCopy.vue'
interface Props {
user: AdminUserForm
@@ -15,23 +15,11 @@ const hasRoleTag = computed(() => props.user.adminType !== USER_TYPE.REGULAR_USE
<n-flex align="center" :size="6" :wrap="false">
<TextCopy>{{ props.user.username }}</TextCopy>
<n-tag v-if="props.user.isDisabled" type="error" size="small" :bordered="false"> 已禁用 </n-tag>
<n-tag
v-if="hasRoleTag"
:type="getUserRole(props.user.adminType).type"
size="small"
:bordered="false"
>
<n-tag v-if="hasRoleTag" :type="getUserRole(props.user.adminType).type" size="small" :bordered="false">
{{ getUserRole(props.user.adminType).label }}
</n-tag>
<n-tag
v-if="
props.user.adminType === USER_TYPE.STUDENT_ADMIN ||
props.user.adminType === USER_TYPE.TEACHER_ADMIN
"
size="small"
:bordered="false"
>
{{ props.user.problemPermission === PROBLEM_PERMISSION.ALL ? "全部题目" : "自己的题" }}
<n-tag v-if="props.user.adminType === USER_TYPE.STUDENT_ADMIN || props.user.adminType === USER_TYPE.TEACHER_ADMIN" size="small" :bordered="false">
{{ props.user.problemPermission === PROBLEM_PERMISSION.ALL ? '全部题目' : '自己的题' }}
</n-tag>
</n-flex>
</template>
+44 -98
View File
@@ -1,19 +1,14 @@
<script setup lang="ts">
import type { ImportUsersRequest } from "@oj2/contract"
import { downloadAccountsCsv } from "./accountsCsv"
import PageHeader from "admin/components/PageHeader.vue"
import { classLabel } from "utils/classes"
import UserName from "shared/components/UserName.vue"
import { errorMessage } from "utils/api"
import {
CLASS_NAME_MAX_DIGITS,
CLASS_NAME_MAX_VALUE,
CLASS_NAME_MIN_DIGITS,
CLASS_NAME_MIN_VALUE,
} from "utils/constants"
import { parseTime } from "utils/functions"
import { checkUsernames, importUsers } from "../api"
import { useBreakpoints } from "shared/composables/breakpoints"
import type { ImportUsersRequest } from '@oj2/contract'
import { downloadAccountsCsv } from './accountsCsv'
import PageHeader from 'admin/components/PageHeader.vue'
import { classLabel } from 'utils/classes'
import UserName from 'shared/components/UserName.vue'
import { errorMessage } from 'utils/api'
import { CLASS_NAME_MAX_DIGITS, CLASS_NAME_MAX_VALUE, CLASS_NAME_MIN_DIGITS, CLASS_NAME_MIN_VALUE } from 'utils/constants'
import { parseTime } from 'utils/functions'
import { checkUsernames, importUsers } from '../api'
import { useBreakpoints } from 'shared/composables/breakpoints'
/**
* 批量建号(设计稿「后台用户与批量建号」UsGen / UsGenIssue / UsDone)。
@@ -27,25 +22,25 @@ const message = useMessage()
// 手机上左右两栏改成上下:先填班级和名单,预览排在下面
const { isMobile } = useBreakpoints()
const classNo = ref("")
const rawInput = ref("")
const classNo = ref('')
const rawInput = ref('')
const classError = computed(() => {
const value = classNo.value.trim()
if (!value) return ""
if (!value) return ''
const n = Number(value)
if (!/^\d+$/.test(value) || n < CLASS_NAME_MIN_VALUE || n > CLASS_NAME_MAX_VALUE) {
return `班级号要是 ${CLASS_NAME_MIN_DIGITS}~${CLASS_NAME_MAX_DIGITS} 位数字`
}
return ""
return ''
})
const prefix = computed(() => (classNo.value.trim() ? `ks${classNo.value.trim()}` : ""))
const prefix = computed(() => (classNo.value.trim() ? `ks${classNo.value.trim()}` : ''))
/** 名单:一行一个,前后和中间的空格都去掉(从表格里复制常带空格),空行不算 */
const names = computed(() =>
rawInput.value
.split("\n")
.map((line) => line.replace(/\s+/g, ""))
.split('\n')
.map((line) => line.replace(/\s+/g, ''))
.filter(Boolean),
)
@@ -54,8 +49,8 @@ const passwords = new Map<string, string>()
function passwordOf(name: string) {
let value = passwords.get(name)
if (!value) {
value = ""
for (let j = 0; j < 6; j++) value += "123456789".charAt(Math.floor(Math.random() * 9))
value = ''
for (let j = 0; j < 6; j++) value += '123456789'.charAt(Math.floor(Math.random() * 9))
passwords.set(name, value)
}
return value
@@ -86,7 +81,7 @@ const duplicates = computed(() => {
const existing = ref<{ username: string; createTime: string | null }[]>([])
const checking = ref(false)
watchDebounced(
() => rows.value.map((row) => row.username).join("\n"),
() => rows.value.map((row) => row.username).join('\n'),
async () => {
const usernames = [...new Set(rows.value.map((row) => row.username))]
if (!usernames.length || classError.value || usernames.length > 500) {
@@ -106,16 +101,8 @@ watchDebounced(
)
const tooMany = computed(() => rows.value.length > 500)
const issueCount = computed(
() =>
(classError.value ? 1 : 0) +
duplicates.value.length +
existing.value.length +
(tooMany.value ? 1 : 0),
)
const canSubmit = computed(
() => rows.value.length > 0 && !issueCount.value && !checking.value && !!prefix.value,
)
const issueCount = computed(() => (classError.value ? 1 : 0) + duplicates.value.length + existing.value.length + (tooMany.value ? 1 : 0))
const canSubmit = computed(() => rows.value.length > 0 && !issueCount.value && !checking.value && !!prefix.value)
// ---------------------------------------------------------------- 建号
@@ -128,10 +115,10 @@ async function submit() {
// 占位邮箱必须全站唯一:注册、编辑用户、导入三条路都查重。每批一段随机后缀错开,
// 同一个班分两批导也不会撞。这个地址不发给任何人,纯占位
const batch = Math.random().toString(36).slice(2, 8)
const payload: ImportUsersRequest["users"] = rows.value.map((row, i) => [
const payload: ImportUsersRequest['users'] = rows.value.map((row, i) => [
row.username,
row.password,
`${prefix.value || "user"}.${batch}.${i + 1}@example.com`,
`${prefix.value || 'user'}.${batch}.${i + 1}@example.com`,
row.name,
])
saving.value = true
@@ -140,7 +127,7 @@ async function submit() {
addedClasses.value = res.addedClasses ?? []
done.value = rows.value.map(({ username, password }) => ({ username, password }))
} catch (err) {
message.error("没建成:" + errorMessage(err))
message.error('没建成:' + errorMessage(err))
} finally {
saving.value = false
}
@@ -148,37 +135,30 @@ async function submit() {
function again() {
done.value = null
rawInput.value = ""
rawInput.value = ''
addedClasses.value = []
passwords.clear()
}
function download() {
if (!done.value) return
downloadAccountsCsv(done.value, prefix.value || "账号")
downloadAccountsCsv(done.value, prefix.value || '账号')
}
/** 打印账号条:一人一张,一页四列,打出来剪开发下去 */
function printSlips() {
if (!done.value) return
const escape = (text: string) =>
text.replace(
/[&<>"]/g,
(ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[ch]!,
)
const escape = (text: string) => text.replace(/[&<>"]/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[ch]!)
const slips = done.value
.map(
(it) =>
`<div class="slip"><div class="u">${escape(it.username)}</div><div class="p">密码 ${escape(it.password)}</div></div>`,
)
.join("")
const win = window.open("", "_blank")
.map((it) => `<div class="slip"><div class="u">${escape(it.username)}</div><div class="p">密码 ${escape(it.password)}</div></div>`)
.join('')
const win = window.open('', '_blank')
if (!win) {
message.warning("浏览器拦住了新窗口,允许弹出窗口后再点一次")
message.warning('浏览器拦住了新窗口,允许弹出窗口后再点一次')
return
}
win.document.write(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>${escape(
classLabel(classNo.value.trim()) || "账号条",
classLabel(classNo.value.trim()) || '账号条',
)}</title><style>
body{margin:12mm;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:0}
@@ -198,9 +178,7 @@ body{margin:12mm;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
<div v-if="done" class="done">
<div class="done-bar">
<b>建好了 {{ done.length }} 个账号</b>
<n-text v-if="addedClasses.length" depth="3">
{{ addedClasses.map((name) => classLabel(name)).join("、") }}已加进班级列表
</n-text>
<n-text v-if="addedClasses.length" depth="3"> {{ addedClasses.map((name) => classLabel(name)).join('、') }}已加进班级列表 </n-text>
<div class="spacer"></div>
<n-button @click="download">下载名单(表格)</n-button>
<n-button type="primary" @click="printSlips">打印账号条</n-button>
@@ -219,51 +197,31 @@ body{margin:12mm;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
<label class="label" for="class-no">班级号</label>
<div class="class-row">
<span class="ks">ks</span>
<n-input
v-model:value="classNo"
:input-props="{ id: 'class-no', inputmode: 'numeric' }"
placeholder="如 2612"
style="width: 120px"
/>
<n-input v-model:value="classNo" :input-props="{ id: 'class-no', inputmode: 'numeric' }" placeholder="如 2612" style="width: 120px" />
<span v-if="classNo.trim() && !classError" class="class-name">
{{ classLabel(classNo.trim()) }}
</span>
</div>
<label class="label" for="names">
名单 <n-text depth="3" class="hint">从表格里整列复制过来,一行一个</n-text>
</label>
<n-input
v-model:value="rawInput"
type="textarea"
:input-props="{ id: 'names' }"
:rows="isMobile ? 8 : 20"
placeholder="一行一个名字"
/>
<label class="label" for="names"> 名单 <n-text depth="3" class="hint">从表格里整列复制过来,一行一个</n-text> </label>
<n-input v-model:value="rawInput" type="textarea" :input-props="{ id: 'names' }" :rows="isMobile ? 8 : 20" placeholder="一行一个名字" />
</div>
<div class="right">
<template v-if="rows.length">
<div class="head">
<b>会建这 {{ rows.length }} 个账号</b>
<n-tag v-if="!issueCount && !checking && prefix" type="success" :bordered="false" round>
没有重名
</n-tag>
<n-tag v-if="issueCount" type="warning" :bordered="false" round>
有 {{ issueCount }} 处要先改
</n-tag>
<n-tag v-if="!issueCount && !checking && prefix" type="success" :bordered="false" round> 没有重名 </n-tag>
<n-tag v-if="issueCount" type="warning" :bordered="false" round> 有 {{ issueCount }} 处要先改 </n-tag>
</div>
<div v-if="issueCount" class="issues">
<div v-if="classError">{{ classError }}</div>
<div v-if="tooMany">一次最多 500 个,分两批建</div>
<div v-for="dup in duplicates" :key="dup.line">
第 {{ dup.line }} 行「{{ dup.name }}」和第 {{ dup.firstLine }} 行重名 ——
同班同名的,名字后面加个 1、2 区分
第 {{ dup.line }} 行「{{ dup.name }}」和第 {{ dup.firstLine }} 行重名 —— 同班同名的,名字后面加个 1、2 区分
</div>
<div v-for="it in existing" :key="it.username">
{{ it.username }} 已经有这个账号了<template v-if="it.createTime"
>({{ parseTime(it.createTime, "YYYY-MM-DD") }} 建的)</template
>
{{ it.username }} 已经有这个账号了<template v-if="it.createTime">({{ parseTime(it.createTime, 'YYYY-MM-DD') }} 建的)</template>
—— 删掉这一行,或者换个名字
</div>
</div>
@@ -288,25 +246,13 @@ body{margin:12mm;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
</div>
<div>
<n-button
type="primary"
size="large"
:disabled="!canSubmit"
:loading="saving || checking"
@click="submit"
>
<n-button type="primary" size="large" :disabled="!canSubmit" :loading="saving || checking" @click="submit">
建好这 {{ rows.length }} 个账号
</n-button>
<n-text v-if="!prefix" depth="3" class="hint" style="margin-left: 12px">
先填班级号
</n-text>
<n-text v-if="!prefix" depth="3" class="hint" style="margin-left: 12px"> 先填班级号 </n-text>
</div>
</template>
<n-empty
v-else
:description="`${isMobile ? '上面' : '左边'}粘进名单,这里就列出会建成的账号`"
:style="{ marginTop: isMobile ? '24px' : '80px' }"
/>
<n-empty v-else :description="`${isMobile ? '上面' : '左边'}粘进名单,这里就列出会建成的账号`" :style="{ marginTop: isMobile ? '24px' : '80px' }" />
</div>
</div>
</template>
+100 -171
View File
@@ -1,24 +1,24 @@
<script setup lang="ts">
import { Icon } from "@iconify/vue"
import PageHeader from "admin/components/PageHeader.vue"
import { errorMessage } from "utils/api"
import { DataTableRowKey, SelectOption, useThemeVars } from "naive-ui"
import Pagination from "shared/components/Pagination.vue"
import { usePagination } from "shared/composables/pagination"
import { parseTime } from "utils/functions"
import type { AdminUserForm } from "utils/types"
import { deleteUsers, editUser, getUserList, importUsers, resetPassword } from "../api"
import Actions from "./components/Actions.vue"
import UserNameCell from "./components/UserNameCell.vue"
import PasswordCell from "./components/PasswordCell.vue"
import { PROBLEM_PERMISSION, USER_TYPE } from "utils/constants"
import { useRouteQuery } from "@vueuse/router"
import { NO_CLASS, STUDENT_ROLES, type ImportUsersRequest } from "@oj2/contract"
import { downloadAccountsCsv } from "./accountsCsv"
import { classLabel, groupClassOptions } from "utils/classes"
import { useConfigStore } from "shared/store/config"
import { useBreakpoints } from "shared/composables/breakpoints"
import { useListLoader } from "shared/composables/listLoader"
import { Icon } from '@iconify/vue'
import PageHeader from 'admin/components/PageHeader.vue'
import { errorMessage } from 'utils/api'
import { DataTableRowKey, SelectOption, useThemeVars } from 'naive-ui'
import Pagination from 'shared/components/Pagination.vue'
import { usePagination } from 'shared/composables/pagination'
import { parseTime } from 'utils/functions'
import type { AdminUserForm } from 'utils/types'
import { deleteUsers, editUser, getUserList, importUsers, resetPassword } from '../api'
import Actions from './components/Actions.vue'
import UserNameCell from './components/UserNameCell.vue'
import PasswordCell from './components/PasswordCell.vue'
import { PROBLEM_PERMISSION, USER_TYPE } from 'utils/constants'
import { useRouteQuery } from '@vueuse/router'
import { NO_CLASS, STUDENT_ROLES, type ImportUsersRequest } from '@oj2/contract'
import { downloadAccountsCsv } from './accountsCsv'
import { classLabel, groupClassOptions } from 'utils/classes'
import { useConfigStore } from 'shared/store/config'
import { useBreakpoints } from 'shared/composables/breakpoints'
import { useListLoader } from 'shared/composables/listLoader'
/**
* 后台用户列表(设计稿「后台用户与批量建号」UsList)。老师进来多半是三件事:学生忘了密码、
@@ -39,14 +39,14 @@ interface UserQuery {
// 使用分页 composable
const { query, clearQuery } = usePagination<UserQuery>({
keyword: useRouteQuery("keyword", "").value,
type: useRouteQuery("type", "").value,
orderBy: useRouteQuery("orderBy", "").value,
className: useRouteQuery("className", "").value,
keyword: useRouteQuery('keyword', '').value,
type: useRouteQuery('type', '').value,
orderBy: useRouteQuery('orderBy', '').value,
className: useRouteQuery('className', '').value,
})
const classOptions = computed(() => [
{ label: "全部班级", value: "" },
{ label: '全部班级', value: '' },
...groupClassOptions(configStore.config?.classList ?? []),
{ label: classLabel(NO_CLASS), value: NO_CLASS },
])
@@ -57,21 +57,21 @@ const users = ref<AdminUserForm[]>([])
const userEditing = ref<AdminUserForm | null>(null)
const adminOptions = [
{ label: "全部角色", value: "" },
{ label: "学生", value: USER_TYPE.REGULAR_USER },
{ label: "学生管理员", value: USER_TYPE.STUDENT_ADMIN },
{ label: "教师管理员", value: USER_TYPE.TEACHER_ADMIN },
{ label: "超级管理员", value: USER_TYPE.SUPER_ADMIN },
{ label: '全部角色', value: '' },
{ label: '学生', value: USER_TYPE.REGULAR_USER },
{ label: '学生管理员', value: USER_TYPE.STUDENT_ADMIN },
{ label: '教师管理员', value: USER_TYPE.TEACHER_ADMIN },
{ label: '超级管理员', value: USER_TYPE.SUPER_ADMIN },
]
const sortOptions = [
{ label: "最近建号", value: "" },
{ label: "按用户名", value: "username" },
{ label: "最近登录", value: "-last_login" },
{ label: "在线优先", value: "-online" },
{ label: '最近建号', value: '' },
{ label: '按用户名', value: 'username' },
{ label: '最近登录', value: '-last_login' },
{ label: '在线优先', value: '-online' },
]
const [create, toggleCreate] = useToggle(false)
const password = ref("")
const password = ref('')
// 已经点开的管理员密码,按 user id 记。同一个按钮再点一下收回去;listUsers() 里清空,
// 所以翻页/搜索/换筛选之后也一律回到打码状态 —— 不做定时自动隐藏,也不记进 localStorage。
const revealedPasswords = ref(new Set<number>())
@@ -81,17 +81,13 @@ const rowKey = (row: AdminUserForm) => row.id
/** 上次登录:今天的写「今天 13:02」,在线的前面一个绿点;今年的写到月日;从没登录的写出来 */
function lastLoginText(row: AdminUserForm) {
if (!row.lastLogin) return h("span", { class: "muted" }, "从没登录")
const day = parseTime(row.lastLogin, "YYYY-MM-DD")
const today = parseTime(new Date().toISOString(), "YYYY-MM-DD")
if (!row.lastLogin) return h('span', { class: 'muted' }, '从没登录')
const day = parseTime(row.lastLogin, 'YYYY-MM-DD')
const today = parseTime(new Date().toISOString(), 'YYYY-MM-DD')
const text =
day === today
? `今天 ${parseTime(row.lastLogin, "HH:mm")}`
: day.slice(0, 4) === today.slice(0, 4)
? parseTime(row.lastLogin, "MM-DD HH:mm")
: day
return h("span", { class: "num", title: parseTime(row.lastLogin, "YYYY-MM-DD HH:mm:ss") }, [
row.isOnline ? h("span", { class: "online", title: "在线" }) : null,
day === today ? `今天 ${parseTime(row.lastLogin, 'HH:mm')}` : day.slice(0, 4) === today.slice(0, 4) ? parseTime(row.lastLogin, 'MM-DD HH:mm') : day
return h('span', { class: 'num', title: parseTime(row.lastLogin, 'YYYY-MM-DD HH:mm:ss') }, [
row.isOnline ? h('span', { class: 'online', title: '在线' }) : null,
text,
])
}
@@ -121,67 +117,52 @@ function renderActions(row: AdminUserForm) {
* 密码单独一行(学生忘了密码是最常见的事,要一眼找到),操作按钮放不下就折行
*/
function renderMobileCard(row: AdminUserForm) {
return h("div", { class: "m-card" }, [
return h('div', { class: 'm-card' }, [
h(UserNameCell, { user: row }),
h("div", { class: "m-meta muted" }, [
h("span", { class: "m-item" }, row.className ? classLabel(row.className) : "没填班级"),
h("span", { class: "m-item" }, [" · ", lastLoginText(row)]),
row.createTime
? h("span", { class: "m-item" }, ` · 建号 ${parseTime(row.createTime, "YYYY-MM-DD")}`)
: null,
h('div', { class: 'm-meta muted' }, [
h('span', { class: 'm-item' }, row.className ? classLabel(row.className) : '没填班级'),
h('span', { class: 'm-item' }, [' · ', lastLoginText(row)]),
row.createTime ? h('span', { class: 'm-item' }, ` · 建号 ${parseTime(row.createTime, 'YYYY-MM-DD')}`) : null,
]),
row.rawPassword
? h("div", { class: "m-password" }, [
h("span", { class: "muted" }, "密码"),
renderPassword(row),
])
: null,
row.rawPassword ? h('div', { class: 'm-password' }, [h('span', { class: 'muted' }, '密码'), renderPassword(row)]) : null,
renderActions(row),
])
}
const mobileColumns: DataTableColumn<AdminUserForm>[] = [
{ type: "selection" },
{ title: "用户", key: "username", render: renderMobileCard },
]
const mobileColumns: DataTableColumn<AdminUserForm>[] = [{ type: 'selection' }, { title: '用户', key: 'username', render: renderMobileCard }]
const desktopColumns: DataTableColumn<AdminUserForm>[] = [
{ type: "selection" },
{ type: 'selection' },
{
title: "用户名",
key: "username",
title: '用户名',
key: 'username',
// 定宽:用户名一般就 ks + 班号 + 两三个字,原来 minWidth 让它把整行剩下的空都吃掉了(用户嫌空太多)。
// 剩下的宽度给最后的操作列,操作直接摆出来
width: 230,
render: (row) => h(UserNameCell, { user: row }),
},
{
title: "班级",
key: "className",
title: '班级',
key: 'className',
width: 130,
render: (row) => h("span", { class: "muted" }, row.className ? classLabel(row.className) : "—"),
render: (row) => h('span', { class: 'muted' }, row.className ? classLabel(row.className) : '—'),
},
{
title: "密码",
key: "raw_password",
title: '密码',
key: 'raw_password',
width: 150,
render: renderPassword,
},
{ title: "上次登录", key: "last_login", width: 150, render: lastLoginText },
{ title: '上次登录', key: 'last_login', width: 150, render: lastLoginText },
{
title: "建号",
key: "create_time",
title: '建号',
key: 'create_time',
width: 110,
render: (row) =>
h(
"span",
{ class: "num muted" },
row.createTime ? parseTime(row.createTime, "YYYY-MM-DD") : "",
),
render: (row) => h('span', { class: 'num muted' }, row.createTime ? parseTime(row.createTime, 'YYYY-MM-DD') : ''),
},
{
key: "actions",
title: "",
key: 'actions',
title: '',
minWidth: 300,
render: renderActions,
},
@@ -190,16 +171,16 @@ const desktopColumns: DataTableColumn<AdminUserForm>[] = [
const columns = computed(() => (isMobile.value ? mobileColumns : desktopColumns))
const options: SelectOption[] = [
{ label: "普通", value: USER_TYPE.REGULAR_USER },
{ label: "学生管理员", value: USER_TYPE.STUDENT_ADMIN },
{ label: "教师管理员", value: USER_TYPE.TEACHER_ADMIN },
{ label: "超级管理员", value: USER_TYPE.SUPER_ADMIN },
{ label: '普通', value: USER_TYPE.REGULAR_USER },
{ label: '学生管理员', value: USER_TYPE.STUDENT_ADMIN },
{ label: '教师管理员', value: USER_TYPE.TEACHER_ADMIN },
{ label: '超级管理员', value: USER_TYPE.SUPER_ADMIN },
]
const problemPermissionOptions: SelectOption[] = [
{ label: "无权限", value: PROBLEM_PERMISSION.NONE },
{ label: "仅管理自己创建", value: PROBLEM_PERMISSION.OWN },
{ label: "管理全部题目", value: PROBLEM_PERMISSION.ALL },
{ label: '无权限', value: PROBLEM_PERMISSION.NONE },
{ label: '仅管理自己创建', value: PROBLEM_PERMISSION.OWN },
{ label: '管理全部题目', value: PROBLEM_PERMISSION.ALL },
]
// 老师不给「无权限」:比赛题的接口要出题权限,设了就是比赛题目页全报权限不足,后端也会兜成「仅自己」
const teacherPermissionOptions = problemPermissionOptions.slice(1)
@@ -208,9 +189,7 @@ const { loading, track } = useListLoader()
async function listUsers() {
if (query.page < 1) query.page = 1
const offset = (query.page - 1) * query.limit
const res = await track(
getUserList(offset, query.limit, query.type, query.keyword, query.orderBy, query.className),
)
const res = await track(getUserList(offset, query.limit, query.type, query.keyword, query.orderBy, query.className))
if (!res) return
total.value = res.total
neverLoggedIn.value = res.neverLoggedIn
@@ -229,19 +208,17 @@ async function downloadClassAccounts() {
try {
const rows: AdminUserForm[] = []
for (let offset = 0; ; offset += 250) {
const res = await getUserList(offset, 250, "", "", "username", className)
const res = await getUserList(offset, 250, '', '', 'username', className)
rows.push(...res.results)
if (!res.results.length || rows.length >= res.total) break
}
const students = rows.filter((it) =>
(STUDENT_ROLES as readonly string[]).includes(it.adminType),
)
const students = rows.filter((it) => (STUDENT_ROLES as readonly string[]).includes(it.adminType))
if (!students.length) {
message.warning("这个班没有学生")
message.warning('这个班没有学生')
return
}
downloadAccountsCsv(
students.map((it) => ({ username: it.username, password: it.rawPassword ?? "" })),
students.map((it) => ({ username: it.username, password: it.rawPassword ?? '' })),
`${classLabel(className)}账号`,
)
} catch (err) {
@@ -258,7 +235,7 @@ function chooseUsers(rowKeys: DataTableRowKey[]) {
async function onDeleteUsers(ids: DataTableRowKey[] | Ref<number[]>) {
try {
await deleteUsers(toRaw(ids) as number[])
message.success("删掉了")
message.success('删掉了')
userIDs.value = []
} catch (err) {
message.error(errorMessage(err))
@@ -290,34 +267,34 @@ function createNewUser() {
toggleCreate(true)
userEditing.value = {
id: 0,
username: "",
realName: "",
username: '',
realName: '',
// 预填一个唯一的占位邮箱:这条路走的是导入接口,后端要求邮箱合法且不重复,
// 留空会直接被打回。想填真邮箱就改掉它
email: `user.${Math.random().toString(36).slice(2, 10)}@example.com`,
// 导入接口写死建成普通用户(后端 POST /admin/users),这里不摆一个建不出来的
// 角色。要给管理员权限,建完再用「编辑」改
adminType: "Regular User",
problemPermission: "None",
adminType: 'Regular User',
problemPermission: 'None',
createTime: null,
lastLogin: null,
isDisabled: false,
isOnline: false,
rawPassword: null,
className: null,
password: "",
password: '',
}
password.value = ""
password.value = ''
}
function onOpenEditModal(user: AdminUserForm) {
userEditing.value = user
password.value = ""
password.value = ''
}
function onCloseEditModal() {
userEditing.value = null
password.value = ""
password.value = ''
toggleCreate(false)
}
@@ -325,24 +302,19 @@ async function handleEditUser() {
if (!userEditing.value) return
// 新建走的是导入接口,密码是必填的(后端 min(1)),留空只会换来一句 400
if (create.value && !password.value) {
message.error("新建用户必须填写密码")
message.error('新建用户必须填写密码')
return
}
if (password.value && password.value.length < 6) {
message.error("密码长度不得小于 6")
message.error('密码长度不得小于 6')
return
}
// http 拦截器只对 login-required / permission-denied 自动弹提示,
// 其余业务错误(比如班级号位数不对)不接住就什么都不显示
try {
if (create.value) {
const newUser: ImportUsersRequest["users"] = [
[
userEditing.value.username,
password.value,
userEditing.value.email ?? "",
userEditing.value.realName ?? "",
],
const newUser: ImportUsersRequest['users'] = [
[userEditing.value.username, password.value, userEditing.value.email ?? '', userEditing.value.realName ?? ''],
]
await importUsers(newUser)
listUsers()
@@ -353,11 +325,11 @@ async function handleEditUser() {
await editUser(user)
}
} catch (err) {
message.error("保存失败:" + errorMessage(err))
message.error('保存失败:' + errorMessage(err))
return
}
userEditing.value = null
password.value = ""
password.value = ''
toggleCreate(false)
}
@@ -380,45 +352,17 @@ watch(() => [query.page, query.limit, query.type, query.orderBy, query.className
删掉就找不回来了。交过题的账号删不掉,那种请改为禁用。
</n-popconfirm>
<n-button @click="createNewUser">新建一个</n-button>
<n-button type="primary" @click="$router.push({ name: 'admin user generate' })">
批量建号
</n-button>
<n-button type="primary" @click="$router.push({ name: 'admin user generate' })"> 批量建号 </n-button>
</template>
<template #filters>
<n-input
:style="{ width: isMobile ? '100%' : '220px' }"
v-model:value="query.keyword"
placeholder="用户名或名字"
clearable
@clear="clearQuery"
/>
<n-select
v-model:value="query.className"
:options="classOptions"
filterable
aria-label="班级"
style="width: 150px"
/>
<n-button
v-if="query.className && query.className !== NO_CLASS"
:loading="downloadingClass"
@click="downloadClassAccounts"
>
<n-input :style="{ width: isMobile ? '100%' : '220px' }" v-model:value="query.keyword" placeholder="用户名或名字" clearable @clear="clearQuery" />
<n-select v-model:value="query.className" :options="classOptions" filterable aria-label="班级" style="width: 150px" />
<n-button v-if="query.className && query.className !== NO_CLASS" :loading="downloadingClass" @click="downloadClassAccounts">
<template #icon><Icon icon="ph:download-simple" /></template>
下载这个班的账号
</n-button>
<n-select
v-model:value="query.type"
:options="adminOptions"
aria-label="角色"
style="width: 120px"
/>
<n-select
v-model:value="query.orderBy"
:options="sortOptions"
aria-label="排序"
style="width: 120px"
/>
<n-select v-model:value="query.type" :options="adminOptions" aria-label="角色" style="width: 120px" />
<n-select v-model:value="query.orderBy" :options="sortOptions" aria-label="排序" style="width: 120px" />
<n-text depth="3">
{{ total }} 人<template v-if="neverLoggedIn"> · {{ neverLoggedIn }} 人从没登录</template>
</n-text>
@@ -435,14 +379,7 @@ watch(() => [query.page, query.limit, query.type, query.orderBy, query.className
@update:checked-row-keys="chooseUsers"
/>
<Pagination :total="total" v-model:limit="query.limit" v-model:page="query.page" />
<n-modal
:mask-closable="false"
:show="!!userEditing"
preset="card"
:title="create ? '新建用户' : '编辑用户'"
style="width: 700px"
@close="onCloseEditModal"
>
<n-modal :mask-closable="false" :show="!!userEditing" preset="card" :title="create ? '新建用户' : '编辑用户'" style="width: 700px" @close="onCloseEditModal">
<n-form label-placement="left" v-if="userEditing">
<n-grid :cols="isMobile ? 1 : 2" :x-gap="16">
<n-form-item-gi :span="1" label="用户">
@@ -466,21 +403,13 @@ watch(() => [query.page, query.limit, query.type, query.orderBy, query.className
<n-input v-model:value="password" />
</n-form-item-gi>
<n-form-item-gi
v-if="
!create &&
(userEditing.adminType === USER_TYPE.STUDENT_ADMIN ||
userEditing.adminType === USER_TYPE.TEACHER_ADMIN)
"
v-if="!create && (userEditing.adminType === USER_TYPE.STUDENT_ADMIN || userEditing.adminType === USER_TYPE.TEACHER_ADMIN)"
:span="1"
label="出题权限"
>
<n-select
v-model:value="userEditing.problemPermission"
:options="
userEditing.adminType === USER_TYPE.TEACHER_ADMIN
? teacherPermissionOptions
: problemPermissionOptions
"
:options="userEditing.adminType === USER_TYPE.TEACHER_ADMIN ? teacherPermissionOptions : problemPermissionOptions"
/>
</n-form-item-gi>
@@ -498,7 +427,7 @@ watch(() => [query.page, query.limit, query.type, query.orderBy, query.className
<style scoped>
.user-table :deep(.muted) {
color: v-bind("theme.textColor3");
color: v-bind('theme.textColor3');
}
.user-table :deep(.m-card) {
@@ -535,7 +464,7 @@ watch(() => [query.page, query.limit, query.type, query.orderBy, query.className
height: 7px;
margin-right: 6px;
border-radius: 50%;
background: v-bind("theme.successColor");
background: v-bind('theme.successColor');
vertical-align: 1px;
}
</style>