mirror of
https://github.com/SECTL/SecScore.git
synced 2026-07-19 19:04:23 +08:00
feat: 新增自动加分规则管理页
This commit is contained in:
@@ -0,0 +1,432 @@
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
Form,
|
||||
Input,
|
||||
Pagination,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Table,
|
||||
Tag,
|
||||
message,
|
||||
} from "antd"
|
||||
import { Utils as QbUtils, type ImmutableTree } from "@react-awesome-query-builder/antd"
|
||||
import type { ColumnsType } from "antd/es/table"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { ActionEditor } from "./AutoScoreManagerPage/ActionEditor"
|
||||
import { TriggerRuleBuilder } from "./AutoScoreManagerPage/TriggerRuleBuilder"
|
||||
import {
|
||||
actionDraftsToPayload,
|
||||
actionsToDrafts,
|
||||
createDefaultActionDraft,
|
||||
createEmptyTriggerTree,
|
||||
createTriggerQueryConfig,
|
||||
hasUnsupportedTriggerLogic,
|
||||
queryTreeToTriggers,
|
||||
triggersToQueryTree,
|
||||
type ActionDraft,
|
||||
type AutoScoreRule,
|
||||
} from "./AutoScoreManagerPage/AutoScoreUtils"
|
||||
|
||||
interface StudentItem {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
interface RuleFormValues {
|
||||
name?: string
|
||||
studentNames?: string[]
|
||||
}
|
||||
|
||||
interface AutoScoreManagerProps {
|
||||
canEdit: boolean
|
||||
}
|
||||
|
||||
function AutoScoreManager({ canEdit }: AutoScoreManagerProps): React.JSX.Element {
|
||||
const { t, i18n } = useTranslation()
|
||||
const [form] = Form.useForm<RuleFormValues>()
|
||||
const [messageApi, contextHolder] = message.useMessage()
|
||||
|
||||
const triggerConfig = useMemo(
|
||||
() => createTriggerQueryConfig(t),
|
||||
[i18n.resolvedLanguage, i18n.language]
|
||||
)
|
||||
const [triggerTree, setTriggerTree] = useState<ImmutableTree>(() =>
|
||||
createEmptyTriggerTree(triggerConfig)
|
||||
)
|
||||
const [actionDrafts, setActionDrafts] = useState<ActionDraft[]>([createDefaultActionDraft()])
|
||||
const [students, setStudents] = useState<StudentItem[]>([])
|
||||
const [rules, setRules] = useState<AutoScoreRule[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editingRuleId, setEditingRuleId] = useState<number | null>(null)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
|
||||
useEffect(() => {
|
||||
setTriggerTree((prevTree) => QbUtils.checkTree(prevTree, triggerConfig))
|
||||
}, [triggerConfig])
|
||||
|
||||
useEffect(() => {
|
||||
const maxPage = Math.max(1, Math.ceil(rules.length / pageSize))
|
||||
if (currentPage > maxPage) {
|
||||
setCurrentPage(maxPage)
|
||||
}
|
||||
}, [currentPage, pageSize, rules.length])
|
||||
|
||||
const resetEditor = () => {
|
||||
setEditingRuleId(null)
|
||||
form.setFieldsValue({ name: "", studentNames: [] })
|
||||
setTriggerTree(createEmptyTriggerTree(triggerConfig))
|
||||
setActionDrafts([createDefaultActionDraft()])
|
||||
}
|
||||
|
||||
const emitDataUpdated = () => {
|
||||
window.dispatchEvent(new CustomEvent("ss:data-updated", { detail: { category: "all" } }))
|
||||
}
|
||||
|
||||
const fetchStudents = async () => {
|
||||
const api = (window as any).api
|
||||
if (!api || !canEdit) return
|
||||
|
||||
try {
|
||||
const res = await api.queryStudents({})
|
||||
if (res.success && Array.isArray(res.data)) {
|
||||
setStudents(res.data)
|
||||
}
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
}
|
||||
|
||||
const fetchRules = async () => {
|
||||
const api = (window as any).api
|
||||
if (!api || !canEdit) return
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.autoScoreGetRules()
|
||||
if (res.success && Array.isArray(res.data)) {
|
||||
setRules(res.data)
|
||||
} else {
|
||||
messageApi.error(res.message || t("autoScore.fetchFailed"))
|
||||
}
|
||||
} catch {
|
||||
messageApi.error(t("autoScore.fetchFailed"))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!canEdit) return
|
||||
fetchStudents().catch(() => void 0)
|
||||
fetchRules().catch(() => void 0)
|
||||
}, [canEdit])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
const api = (window as any).api
|
||||
if (!api) return
|
||||
if (!canEdit) {
|
||||
messageApi.error(t("common.readOnly"))
|
||||
return
|
||||
}
|
||||
|
||||
const values = await form.validateFields()
|
||||
const name = String(values.name || "").trim()
|
||||
const studentNames = Array.isArray(values.studentNames) ? values.studentNames : []
|
||||
|
||||
if (!name) {
|
||||
messageApi.warning(t("autoScore.nameRequired"))
|
||||
return
|
||||
}
|
||||
|
||||
if (hasUnsupportedTriggerLogic(triggerTree, triggerConfig)) {
|
||||
messageApi.warning(t("autoScore.unsupportedLogic"))
|
||||
return
|
||||
}
|
||||
|
||||
const triggers = queryTreeToTriggers(triggerTree, triggerConfig)
|
||||
if (triggers.length === 0) {
|
||||
messageApi.warning(t("autoScore.triggerRequired"))
|
||||
return
|
||||
}
|
||||
|
||||
const actionPayload = actionDraftsToPayload(actionDrafts)
|
||||
if (actionPayload.error === "score_required") {
|
||||
messageApi.warning(t("autoScore.scorePlaceholder"))
|
||||
return
|
||||
}
|
||||
if (actionPayload.error === "tag_required") {
|
||||
messageApi.warning(t("autoScore.tagNamePlaceholder"))
|
||||
return
|
||||
}
|
||||
if (actionPayload.actions.length === 0) {
|
||||
messageApi.warning(t("autoScore.actionRequired"))
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const payload = {
|
||||
name,
|
||||
enabled: true,
|
||||
studentNames,
|
||||
triggers,
|
||||
actions: actionPayload.actions,
|
||||
}
|
||||
const res =
|
||||
editingRuleId === null
|
||||
? await api.autoScoreAddRule(payload)
|
||||
: await api.autoScoreUpdateRule({ ...payload, id: editingRuleId })
|
||||
|
||||
if (res.success) {
|
||||
messageApi.success(
|
||||
editingRuleId === null ? t("autoScore.createSuccess") : t("autoScore.updateSuccess")
|
||||
)
|
||||
resetEditor()
|
||||
await fetchRules()
|
||||
emitDataUpdated()
|
||||
} else {
|
||||
messageApi.error(
|
||||
res.message ||
|
||||
(editingRuleId === null ? t("autoScore.createFailed") : t("autoScore.updateFailed"))
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
messageApi.error(
|
||||
editingRuleId === null ? t("autoScore.createFailed") : t("autoScore.updateFailed")
|
||||
)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (rule: AutoScoreRule) => {
|
||||
setEditingRuleId(rule.id)
|
||||
form.setFieldsValue({
|
||||
name: rule.name,
|
||||
studentNames: rule.studentNames || [],
|
||||
})
|
||||
setTriggerTree(triggersToQueryTree(triggerConfig, rule.triggers || []))
|
||||
setActionDrafts(actionsToDrafts(rule.actions || []))
|
||||
}
|
||||
|
||||
const handleDelete = async (ruleId: number) => {
|
||||
const api = (window as any).api
|
||||
if (!api) return
|
||||
if (!canEdit) {
|
||||
messageApi.error(t("common.readOnly"))
|
||||
return
|
||||
}
|
||||
|
||||
const res = await api.autoScoreDeleteRule(ruleId)
|
||||
if (res.success) {
|
||||
messageApi.success(t("autoScore.deleteSuccess"))
|
||||
if (editingRuleId === ruleId) {
|
||||
resetEditor()
|
||||
}
|
||||
await fetchRules()
|
||||
emitDataUpdated()
|
||||
} else {
|
||||
messageApi.error(res.message || t("autoScore.deleteFailed"))
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggle = async (ruleId: number, enabled: boolean) => {
|
||||
const api = (window as any).api
|
||||
if (!api) return
|
||||
if (!canEdit) {
|
||||
messageApi.error(t("common.readOnly"))
|
||||
return
|
||||
}
|
||||
|
||||
const res = await api.autoScoreToggleRule({ ruleId, enabled })
|
||||
if (res.success) {
|
||||
setRules((prevRules) =>
|
||||
prevRules.map((rule) => (rule.id === ruleId ? { ...rule, enabled } : rule))
|
||||
)
|
||||
messageApi.success(enabled ? t("autoScore.enabled") : t("autoScore.disabled"))
|
||||
emitDataUpdated()
|
||||
} else {
|
||||
messageApi.error(
|
||||
res.message || (enabled ? t("autoScore.enableFailed") : t("autoScore.disableFailed"))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const formatLastExecuted = (value?: string | null) => {
|
||||
if (!value) return t("autoScore.notExecuted")
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return t("autoScore.invalidTime")
|
||||
return date.toLocaleString()
|
||||
}
|
||||
|
||||
const columns: ColumnsType<AutoScoreRule> = [
|
||||
{
|
||||
title: t("autoScore.name"),
|
||||
dataIndex: "name",
|
||||
key: "name",
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: t("autoScore.status"),
|
||||
key: "status",
|
||||
width: 120,
|
||||
render: (_, row) => (
|
||||
<Switch
|
||||
checked={row.enabled}
|
||||
disabled={!canEdit}
|
||||
onChange={(checked) => {
|
||||
handleToggle(row.id, checked).catch(() => void 0)
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("autoScore.applicableStudents"),
|
||||
key: "studentNames",
|
||||
width: 220,
|
||||
render: (_, row) =>
|
||||
row.studentNames.length > 0 ? (
|
||||
<Tag>{t("autoScore.studentCount", { count: row.studentNames.length })}</Tag>
|
||||
) : (
|
||||
<Tag>{t("autoScore.allStudents")}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("autoScore.triggers"),
|
||||
key: "triggers",
|
||||
width: 150,
|
||||
render: (_, row) => <Tag>{t("autoScore.triggerCount", { count: row.triggers.length })}</Tag>,
|
||||
},
|
||||
{
|
||||
title: t("autoScore.actions"),
|
||||
key: "actions",
|
||||
width: 140,
|
||||
render: (_, row) => <Tag>{t("autoScore.actionCount", { count: row.actions.length })}</Tag>,
|
||||
},
|
||||
{
|
||||
title: t("autoScore.lastExecuted"),
|
||||
dataIndex: "lastExecuted",
|
||||
key: "lastExecuted",
|
||||
width: 180,
|
||||
render: (value: string | null | undefined) => formatLastExecuted(value),
|
||||
},
|
||||
{
|
||||
title: t("common.operation"),
|
||||
key: "operation",
|
||||
width: 160,
|
||||
render: (_, row) => (
|
||||
<Space size={4}>
|
||||
<Button type="link" disabled={!canEdit} onClick={() => handleEdit(row)}>
|
||||
{t("common.edit")}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={t("autoScore.deleteConfirm")}
|
||||
onConfirm={() => {
|
||||
handleDelete(row.id).catch(() => void 0)
|
||||
}}
|
||||
>
|
||||
<Button type="link" danger disabled={!canEdit}>
|
||||
{t("common.delete")}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
const pagedRules = rules.slice((currentPage - 1) * pageSize, currentPage * pageSize)
|
||||
|
||||
return (
|
||||
<div style={{ padding: "24px" }}>
|
||||
{contextHolder}
|
||||
<h2 style={{ marginBottom: "24px", color: "var(--ss-text-main)" }}>{t("autoScore.title")}</h2>
|
||||
|
||||
{!canEdit && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
style={{ marginBottom: "16px" }}
|
||||
message={t("autoScore.adminRequired")}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Card style={{ marginBottom: "24px", backgroundColor: "var(--ss-card-bg)" }}>
|
||||
<Form form={form} layout="vertical">
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "24px" }}>
|
||||
<Form.Item
|
||||
label={t("autoScore.name")}
|
||||
name="name"
|
||||
rules={[{ required: true, message: t("autoScore.nameRequired") }]}
|
||||
>
|
||||
<Input placeholder={t("autoScore.namePlaceholder")} disabled={!canEdit} />
|
||||
</Form.Item>
|
||||
<Form.Item label={t("autoScore.applicableStudents")} name="studentNames">
|
||||
<Select
|
||||
mode="multiple"
|
||||
showSearch
|
||||
disabled={!canEdit}
|
||||
placeholder={t("autoScore.studentPlaceholder")}
|
||||
options={students.map((student) => ({
|
||||
label: student.name,
|
||||
value: student.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<TriggerRuleBuilder
|
||||
config={triggerConfig}
|
||||
value={triggerTree}
|
||||
canEdit={canEdit}
|
||||
onChange={(nextTree, config) => setTriggerTree(QbUtils.checkTree(nextTree, config))}
|
||||
/>
|
||||
|
||||
<ActionEditor value={actionDrafts} canEdit={canEdit} onChange={setActionDrafts} />
|
||||
|
||||
<div style={{ marginBottom: "24px", display: "flex", gap: "12px" }}>
|
||||
<Button type="primary" loading={saving} disabled={!canEdit} onClick={() => handleSubmit().catch(() => void 0)}>
|
||||
{editingRuleId === null ? t("autoScore.addAutomation") : t("autoScore.updateAutomation")}
|
||||
</Button>
|
||||
<Button disabled={!canEdit || saving} onClick={resetEditor}>
|
||||
{editingRuleId === null ? t("autoScore.resetForm") : t("autoScore.cancelEdit")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card style={{ marginBottom: "24px", backgroundColor: "var(--ss-card-bg)" }}>
|
||||
<Table
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={pagedRules}
|
||||
pagination={false}
|
||||
style={{ color: "var(--ss-text-main)" }}
|
||||
/>
|
||||
<div style={{ marginTop: 16, textAlign: "right" }}>
|
||||
<Pagination
|
||||
current={currentPage}
|
||||
pageSize={pageSize}
|
||||
total={rules.length}
|
||||
showSizeChanger
|
||||
showTotal={(total) => t("common.total", { count: total })}
|
||||
onChange={(page, size) => {
|
||||
setCurrentPage(page)
|
||||
setPageSize(size)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { AutoScoreManager }
|
||||
export default AutoScoreManager
|
||||
@@ -0,0 +1,97 @@
|
||||
import React, { useMemo } from "react"
|
||||
import { Button, Card, Input, InputNumber, Select, Space } from "antd"
|
||||
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import type { ActionDraft, ActionEvent } from "./AutoScoreUtils"
|
||||
import { createDefaultActionDraft } from "./AutoScoreUtils"
|
||||
|
||||
interface ActionEditorProps {
|
||||
value: ActionDraft[]
|
||||
canEdit: boolean
|
||||
onChange: (nextDrafts: ActionDraft[]) => void
|
||||
}
|
||||
|
||||
export const ActionEditor: React.FC<ActionEditorProps> = ({ value, canEdit, onChange }) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const actionOptions = useMemo(
|
||||
() => [
|
||||
{ value: "add_score", label: t("autoScore.actionAddScore") },
|
||||
{ value: "add_tag", label: t("autoScore.actionAddTag") },
|
||||
],
|
||||
[t]
|
||||
)
|
||||
|
||||
const updateAction = (id: string, patch: Partial<Omit<ActionDraft, "id">>) => {
|
||||
onChange(value.map((item) => (item.id === id ? { ...item, ...patch } : item)))
|
||||
}
|
||||
|
||||
const handleAddAction = () => {
|
||||
onChange([...value, createDefaultActionDraft()])
|
||||
}
|
||||
|
||||
const handleRemoveAction = (id: string) => {
|
||||
if (value.length <= 1) return
|
||||
onChange(value.filter((item) => item.id !== id))
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
style={{ marginBottom: "24px", backgroundColor: "var(--ss-card-bg)" }}
|
||||
title={t("autoScore.triggeredActions")}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: "100%" }} size={12}>
|
||||
{value.map((action) => (
|
||||
<div key={action.id} style={{ display: "flex", gap: "8px", alignItems: "center" }}>
|
||||
<Select
|
||||
style={{ minWidth: 180 }}
|
||||
value={action.event}
|
||||
disabled={!canEdit}
|
||||
options={actionOptions}
|
||||
onChange={(event: ActionEvent) =>
|
||||
updateAction(action.id, {
|
||||
event,
|
||||
value: event === "add_score" ? "1" : "",
|
||||
})
|
||||
}
|
||||
/>
|
||||
{action.event === "add_score" ? (
|
||||
<InputNumber
|
||||
style={{ width: 180 }}
|
||||
placeholder={t("autoScore.scorePlaceholder")}
|
||||
value={action.value ? Number(action.value) : undefined}
|
||||
disabled={!canEdit}
|
||||
onChange={(nextValue) =>
|
||||
updateAction(action.id, { value: nextValue === null ? "" : String(nextValue) })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
style={{ minWidth: 220 }}
|
||||
placeholder={t("autoScore.tagNamePlaceholder")}
|
||||
value={action.value}
|
||||
disabled={!canEdit}
|
||||
onChange={(event) => updateAction(action.id, { value: event.target.value })}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
disabled={!canEdit || value.length <= 1}
|
||||
onClick={() => handleRemoveAction(action.id)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="dashed"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={!canEdit}
|
||||
onClick={handleAddAction}
|
||||
style={{ fontWeight: "bolder", fontSize: 15 }}
|
||||
>
|
||||
{t("autoScore.addAction")}
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
AntdConfig,
|
||||
Utils as QbUtils,
|
||||
type Config,
|
||||
type ImmutableTree,
|
||||
type JsonGroup,
|
||||
type JsonItem,
|
||||
type JsonRule,
|
||||
} from "@react-awesome-query-builder/antd"
|
||||
import type { TFunction } from "i18next"
|
||||
|
||||
export interface AutoScoreTrigger {
|
||||
event: string
|
||||
value?: string | null
|
||||
}
|
||||
|
||||
export interface AutoScoreAction {
|
||||
event: string
|
||||
value?: string | null
|
||||
}
|
||||
|
||||
export interface AutoScoreRule {
|
||||
id: number
|
||||
name: string
|
||||
enabled: boolean
|
||||
studentNames: string[]
|
||||
triggers: AutoScoreTrigger[]
|
||||
actions: AutoScoreAction[]
|
||||
lastExecuted?: string | null
|
||||
}
|
||||
|
||||
export type ActionEvent = "add_score" | "add_tag"
|
||||
|
||||
export interface ActionDraft {
|
||||
id: string
|
||||
event: ActionEvent
|
||||
value: string
|
||||
}
|
||||
|
||||
export type ActionDraftError = "score_required" | "tag_required" | null
|
||||
|
||||
const TRIGGER_FIELD_INTERVAL = "interval_minutes"
|
||||
const TRIGGER_FIELD_TAG = "student_tag"
|
||||
const OP_EQUAL = "equal"
|
||||
|
||||
const buildEmptyGroup = (): JsonGroup => ({
|
||||
id: QbUtils.uuid(),
|
||||
type: "group",
|
||||
properties: {
|
||||
conjunction: "AND",
|
||||
},
|
||||
children1: [],
|
||||
})
|
||||
|
||||
const toFiniteNumber = (value: unknown): number | null => {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number(value)
|
||||
if (Number.isFinite(parsed)) return parsed
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const toStringValue = (value: unknown): string => {
|
||||
if (value === null || value === undefined) return ""
|
||||
return String(value)
|
||||
}
|
||||
|
||||
const ruleFromTrigger = (trigger: AutoScoreTrigger): JsonRule | null => {
|
||||
if (trigger.event === "interval_time_passed") {
|
||||
const minutes = toFiniteNumber(trigger.value)
|
||||
if (!minutes || minutes <= 0) return null
|
||||
return {
|
||||
id: QbUtils.uuid(),
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: TRIGGER_FIELD_INTERVAL,
|
||||
operator: OP_EQUAL,
|
||||
value: [Math.floor(minutes)],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (trigger.event === "student_has_tag") {
|
||||
const tagName = toStringValue(trigger.value).trim()
|
||||
if (!tagName) return null
|
||||
return {
|
||||
id: QbUtils.uuid(),
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: TRIGGER_FIELD_TAG,
|
||||
operator: OP_EQUAL,
|
||||
value: [tagName],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const triggerFromRule = (rule: JsonRule): AutoScoreTrigger | null => {
|
||||
const field = typeof rule.properties?.field === "string" ? rule.properties.field : ""
|
||||
const value = Array.isArray(rule.properties?.value) ? rule.properties.value[0] : undefined
|
||||
|
||||
if (field === TRIGGER_FIELD_INTERVAL) {
|
||||
const minutes = toFiniteNumber(value)
|
||||
if (!minutes || minutes <= 0) return null
|
||||
return {
|
||||
event: "interval_time_passed",
|
||||
value: String(Math.floor(minutes)),
|
||||
}
|
||||
}
|
||||
|
||||
if (field === TRIGGER_FIELD_TAG) {
|
||||
const tagName = toStringValue(value).trim()
|
||||
if (!tagName) return null
|
||||
return {
|
||||
event: "student_has_tag",
|
||||
value: tagName,
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const collectTriggersFromItems = (items: JsonItem[] | undefined): AutoScoreTrigger[] => {
|
||||
if (!Array.isArray(items)) return []
|
||||
const collected: AutoScoreTrigger[] = []
|
||||
for (const item of items) {
|
||||
if (item.type === "rule") {
|
||||
const trigger = triggerFromRule(item)
|
||||
if (trigger) collected.push(trigger)
|
||||
continue
|
||||
}
|
||||
if (item.type === "group") {
|
||||
collected.push(...collectTriggersFromItems(item.children1))
|
||||
}
|
||||
}
|
||||
return collected
|
||||
}
|
||||
|
||||
export const createTriggerQueryConfig = (t: TFunction): Config =>
|
||||
({
|
||||
...AntdConfig,
|
||||
fields: {
|
||||
[TRIGGER_FIELD_INTERVAL]: {
|
||||
label: t("autoScore.triggerIntervalTime"),
|
||||
type: "number",
|
||||
operators: [OP_EQUAL],
|
||||
valueSources: ["value"],
|
||||
preferWidgets: ["number"],
|
||||
fieldSettings: { min: 1 },
|
||||
},
|
||||
[TRIGGER_FIELD_TAG]: {
|
||||
label: t("autoScore.triggerStudentTag"),
|
||||
type: "text",
|
||||
operators: [OP_EQUAL],
|
||||
valueSources: ["value"],
|
||||
preferWidgets: ["text"],
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
...AntdConfig.settings,
|
||||
liteMode: false,
|
||||
compactMode: false,
|
||||
renderSize: "medium",
|
||||
showNot: true,
|
||||
forceShowConj: true,
|
||||
canLeaveEmptyGroup: false,
|
||||
canReorder: true,
|
||||
canRegroup: true,
|
||||
},
|
||||
}) as Config
|
||||
|
||||
export const createEmptyTriggerTree = (config: Config): ImmutableTree =>
|
||||
QbUtils.checkTree(QbUtils.loadTree(buildEmptyGroup()), config)
|
||||
|
||||
export const triggersToQueryTree = (config: Config, triggers: AutoScoreTrigger[]): ImmutableTree => {
|
||||
const children = triggers.map(ruleFromTrigger).filter((item): item is JsonRule => Boolean(item))
|
||||
const group: JsonGroup = {
|
||||
...buildEmptyGroup(),
|
||||
children1: children,
|
||||
}
|
||||
return QbUtils.checkTree(QbUtils.loadTree(group), config)
|
||||
}
|
||||
|
||||
export const queryTreeToTriggers = (tree: ImmutableTree, config: Config): AutoScoreTrigger[] => {
|
||||
const checkedTree = QbUtils.checkTree(tree, config)
|
||||
const jsonTree = QbUtils.getTree(checkedTree, false, true)
|
||||
if (!jsonTree || jsonTree.type !== "group") return []
|
||||
return collectTriggersFromItems(jsonTree.children1)
|
||||
}
|
||||
|
||||
const hasUnsupportedLogicInGroup = (group: JsonGroup): boolean => {
|
||||
const conjunction = typeof group.properties?.conjunction === "string" ? group.properties.conjunction : "AND"
|
||||
const not = Boolean(group.properties?.not)
|
||||
|
||||
if (conjunction !== "AND" || not) {
|
||||
return true
|
||||
}
|
||||
|
||||
const children = Array.isArray(group.children1) ? group.children1 : []
|
||||
for (const child of children) {
|
||||
if (child.type === "group" && hasUnsupportedLogicInGroup(child)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export const hasUnsupportedTriggerLogic = (tree: ImmutableTree, config: Config): boolean => {
|
||||
const checkedTree = QbUtils.checkTree(tree, config)
|
||||
const jsonTree = QbUtils.getTree(checkedTree, false, true)
|
||||
if (!jsonTree || jsonTree.type !== "group") return false
|
||||
return hasUnsupportedLogicInGroup(jsonTree)
|
||||
}
|
||||
|
||||
export const createDefaultActionDraft = (): ActionDraft => ({
|
||||
id: QbUtils.uuid(),
|
||||
event: "add_score",
|
||||
value: "1",
|
||||
})
|
||||
|
||||
export const actionsToDrafts = (actions: AutoScoreAction[]): ActionDraft[] => {
|
||||
const mapped = actions
|
||||
.map((action) => {
|
||||
if (action.event !== "add_score" && action.event !== "add_tag") return null
|
||||
return {
|
||||
id: QbUtils.uuid(),
|
||||
event: action.event,
|
||||
value: toStringValue(action.value),
|
||||
} satisfies ActionDraft
|
||||
})
|
||||
.filter((item): item is ActionDraft => Boolean(item))
|
||||
|
||||
return mapped.length > 0 ? mapped : [createDefaultActionDraft()]
|
||||
}
|
||||
|
||||
export const actionDraftsToPayload = (
|
||||
drafts: ActionDraft[]
|
||||
): { actions: AutoScoreAction[]; error: ActionDraftError } => {
|
||||
const actions: AutoScoreAction[] = []
|
||||
for (const draft of drafts) {
|
||||
if (draft.event === "add_score") {
|
||||
const score = toFiniteNumber(draft.value)
|
||||
if (!score || score === 0) {
|
||||
return { actions: [], error: "score_required" }
|
||||
}
|
||||
actions.push({ event: draft.event, value: String(score) })
|
||||
continue
|
||||
}
|
||||
|
||||
const tagName = draft.value.trim()
|
||||
if (!tagName) {
|
||||
return { actions: [], error: "tag_required" }
|
||||
}
|
||||
actions.push({ event: draft.event, value: tagName })
|
||||
}
|
||||
|
||||
return { actions, error: null }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import React, { useMemo } from "react"
|
||||
import { Card } from "antd"
|
||||
import {
|
||||
Builder,
|
||||
Query,
|
||||
type BuilderProps,
|
||||
type Config,
|
||||
type ImmutableTree,
|
||||
} from "@react-awesome-query-builder/antd"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import "@react-awesome-query-builder/antd/css/styles.css"
|
||||
|
||||
interface TriggerRuleBuilderProps {
|
||||
config: Config
|
||||
value: ImmutableTree
|
||||
canEdit: boolean
|
||||
onChange: (nextTree: ImmutableTree, config: Config) => void
|
||||
}
|
||||
|
||||
export const TriggerRuleBuilder: React.FC<TriggerRuleBuilderProps> = ({
|
||||
config,
|
||||
value,
|
||||
canEdit,
|
||||
onChange,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const queryConfig = useMemo<Config>(() => {
|
||||
if (canEdit) return config
|
||||
return {
|
||||
...config,
|
||||
settings: {
|
||||
...config.settings,
|
||||
canReorder: false,
|
||||
canRegroup: false,
|
||||
immutableGroupsMode: true,
|
||||
immutableFieldsMode: true,
|
||||
immutableOpsMode: true,
|
||||
immutableValuesMode: true,
|
||||
},
|
||||
} as Config
|
||||
}, [config, canEdit])
|
||||
|
||||
return (
|
||||
<Card
|
||||
style={{ marginBottom: "24px", backgroundColor: "var(--ss-card-bg)" }}
|
||||
title={t("autoScore.whenTriggered")}
|
||||
>
|
||||
<div
|
||||
className="query-builder-container"
|
||||
style={{ overflowX: "auto", pointerEvents: canEdit ? "auto" : "none", opacity: canEdit ? 1 : 0.7 }}
|
||||
>
|
||||
<Query
|
||||
{...queryConfig}
|
||||
value={value}
|
||||
onChange={(immutableTree, config) => onChange(immutableTree, config)}
|
||||
renderBuilder={(props: BuilderProps) => (
|
||||
<div className="query-builder" style={{ minWidth: 680 }}>
|
||||
<Builder {...props} />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ const loadStudentManager = () => import("./StudentManager")
|
||||
const loadSettings = () => import("./Settings")
|
||||
const loadReasonManager = () => import("./ReasonManager")
|
||||
const loadScoreManager = () => import("./ScoreManager")
|
||||
const loadAutoScoreManager = () => import("./AutoScoreManager")
|
||||
const loadLeaderboard = () => import("./Leaderboard")
|
||||
const loadSettlementHistory = () => import("./SettlementHistory")
|
||||
const loadRewardSettings = () => import("./RewardSettings")
|
||||
@@ -27,6 +28,7 @@ const StudentManager = lazy(() => loadStudentManager().then((m) => ({ default: m
|
||||
const Settings = lazy(() => loadSettings().then((m) => ({ default: m.Settings })))
|
||||
const ReasonManager = lazy(() => loadReasonManager().then((m) => ({ default: m.ReasonManager })))
|
||||
const ScoreManager = lazy(() => loadScoreManager().then((m) => ({ default: m.ScoreManager })))
|
||||
const AutoScoreManager = lazy(loadAutoScoreManager)
|
||||
const Leaderboard = lazy(() => loadLeaderboard().then((m) => ({ default: m.Leaderboard })))
|
||||
const SettlementHistory = lazy(() =>
|
||||
loadSettlementHistory().then((m) => ({ default: m.SettlementHistory }))
|
||||
@@ -41,6 +43,7 @@ const warmupRouteChunks = () =>
|
||||
loadSettings(),
|
||||
loadReasonManager(),
|
||||
loadScoreManager(),
|
||||
loadAutoScoreManager(),
|
||||
loadLeaderboard(),
|
||||
loadSettlementHistory(),
|
||||
loadRewardSettings(),
|
||||
@@ -101,6 +104,7 @@ export function ContentArea({
|
||||
if (normalizedPath.startsWith("/home")) return t("sidebar.home")
|
||||
if (normalizedPath.startsWith("/students")) return t("sidebar.students")
|
||||
if (normalizedPath.startsWith("/score")) return t("sidebar.score")
|
||||
if (normalizedPath.startsWith("/auto-score")) return t("sidebar.autoScore")
|
||||
if (normalizedPath.startsWith("/boards")) return t("sidebar.boards")
|
||||
if (normalizedPath.startsWith("/leaderboard")) return t("sidebar.leaderboard")
|
||||
if (normalizedPath.startsWith("/settlements")) return t("sidebar.settlements")
|
||||
@@ -364,6 +368,10 @@ export function ContentArea({
|
||||
<ScoreManager canEdit={permission === "admin" || permission === "points"} />
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/auto-score"
|
||||
element={<AutoScoreManager canEdit={permission === "admin"} />}
|
||||
/>
|
||||
<Route path="/boards" element={<BoardManager canManage={permission === "admin"} />} />
|
||||
<Route path="/leaderboard" element={<Leaderboard />} />
|
||||
<Route path="/settlements" element={<SettlementHistory />} />
|
||||
|
||||
@@ -163,6 +163,12 @@ export function Sidebar({
|
||||
icon: <HistoryOutlined />,
|
||||
label: t("sidebar.score"),
|
||||
},
|
||||
{
|
||||
key: "auto-score",
|
||||
icon: <SyncOutlined />,
|
||||
label: t("sidebar.autoScore"),
|
||||
disabled: permission !== "admin",
|
||||
},
|
||||
{
|
||||
key: "reward-settings",
|
||||
icon: <AppstoreAddOutlined />,
|
||||
|
||||
@@ -770,6 +770,7 @@
|
||||
"adminDeleteRequired": "Admin permission required to delete auto score automation",
|
||||
"adminToggleRequired": "Admin permission required to enable/disable auto score automation",
|
||||
"fetchFailed": "Failed to get automation",
|
||||
"unsupportedLogic": "Saving currently supports AND-only conditions. OR / NOT logic is not wired to backend persistence yet",
|
||||
"triggerRequired": "Please add at least one trigger",
|
||||
"actionRequired": "Please add at least one action",
|
||||
"createSuccess": "Automation created successfully",
|
||||
|
||||
@@ -770,6 +770,7 @@
|
||||
"adminDeleteRequired": "需要管理员权限以删除自动加分自动化",
|
||||
"adminToggleRequired": "需要管理员权限以启用/禁用自动加分自动化",
|
||||
"fetchFailed": "获取自动化失败",
|
||||
"unsupportedLogic": "当前版本保存规则时仅支持 AND 条件,OR / NOT 逻辑暂未接入后端存储",
|
||||
"triggerRequired": "请至少添加一个触发器",
|
||||
"actionRequired": "请至少添加一个行动",
|
||||
"createSuccess": "自动化创建成功",
|
||||
|
||||
+65
-1
@@ -22,6 +22,26 @@ export interface dataUpdatedEvent {
|
||||
source?: string
|
||||
}
|
||||
|
||||
export interface autoScoreTrigger {
|
||||
event: string
|
||||
value?: string | null
|
||||
}
|
||||
|
||||
export interface autoScoreAction {
|
||||
event: string
|
||||
value?: string | null
|
||||
}
|
||||
|
||||
export interface autoScoreRule {
|
||||
id: number
|
||||
name: string
|
||||
enabled: boolean
|
||||
studentNames: string[]
|
||||
triggers: autoScoreTrigger[]
|
||||
actions: autoScoreAction[]
|
||||
lastExecuted?: string | null
|
||||
}
|
||||
|
||||
export type settingsKey =
|
||||
| "is_wizard_completed"
|
||||
| "log_level"
|
||||
@@ -29,6 +49,8 @@ export type settingsKey =
|
||||
| "search_keyboard_layout"
|
||||
| "disable_search_keyboard"
|
||||
| "themes_custom"
|
||||
| "auto_score_enabled"
|
||||
| "auto_score_rules"
|
||||
| "current_theme_id"
|
||||
| "dashboards_config"
|
||||
| "pg_connection_string"
|
||||
@@ -42,6 +64,8 @@ export interface settingsSpec {
|
||||
search_keyboard_layout: "t9" | "qwerty26"
|
||||
disable_search_keyboard: boolean
|
||||
themes_custom: themeConfig[]
|
||||
auto_score_enabled: boolean
|
||||
auto_score_rules: autoScoreRule[]
|
||||
current_theme_id: string
|
||||
dashboards_config: any[]
|
||||
pg_connection_string: string
|
||||
@@ -235,6 +259,46 @@ const api = {
|
||||
settlementId: number
|
||||
}): Promise<{ success: boolean; data: any }> => invoke("db_settlement_leaderboard", { params }),
|
||||
|
||||
// Auto Score
|
||||
autoScoreGetRules: (): Promise<{
|
||||
success: boolean
|
||||
data?: autoScoreRule[]
|
||||
message?: string
|
||||
}> => invoke("auto_score_get_rules"),
|
||||
autoScoreAddRule: (rule: {
|
||||
name: string
|
||||
enabled: boolean
|
||||
studentNames: string[]
|
||||
triggers: autoScoreTrigger[]
|
||||
actions: autoScoreAction[]
|
||||
}): Promise<{ success: boolean; data?: number; message?: string }> =>
|
||||
invoke("auto_score_add_rule", { rule }),
|
||||
autoScoreUpdateRule: (rule: {
|
||||
id: number
|
||||
name: string
|
||||
enabled: boolean
|
||||
studentNames: string[]
|
||||
triggers: autoScoreTrigger[]
|
||||
actions: autoScoreAction[]
|
||||
}): Promise<{ success: boolean; data?: boolean; message?: string }> =>
|
||||
invoke("auto_score_update_rule", { rule }),
|
||||
autoScoreDeleteRule: (ruleId: number): Promise<{ success: boolean; data?: boolean; message?: string }> =>
|
||||
invoke("auto_score_delete_rule", { ruleId }),
|
||||
autoScoreToggleRule: (params: {
|
||||
ruleId: number
|
||||
enabled: boolean
|
||||
}): Promise<{ success: boolean; data?: boolean; message?: string }> =>
|
||||
invoke("auto_score_toggle_rule", { params }),
|
||||
autoScoreGetStatus: (): Promise<{
|
||||
success: boolean
|
||||
data?: {
|
||||
enabled: boolean
|
||||
}
|
||||
message?: string
|
||||
}> => invoke("auto_score_get_status"),
|
||||
autoScoreSortRules: (ruleIds: number[]): Promise<{ success: boolean; data?: boolean; message?: string }> =>
|
||||
invoke("auto_score_sort_rules", { ruleIds }),
|
||||
|
||||
// Settings & Sync
|
||||
getAllSettings: (): Promise<{ success: boolean; data: settingsSpec }> =>
|
||||
invoke("settings_get_all"),
|
||||
@@ -442,7 +506,7 @@ const api = {
|
||||
appRestart: (): Promise<void> => invoke("app_restart"),
|
||||
|
||||
// Generic invoke wrapper for backward compatibility with callers using `api.invoke`
|
||||
invoke: async (channel: string, ...args: any[]): Promise<any> => {
|
||||
invoke: async (channel: string, ..._args: any[]): Promise<any> => {
|
||||
switch (channel) {
|
||||
default:
|
||||
throw new Error(`Unsupported legacy invoke channel: ${channel}`)
|
||||
|
||||
@@ -2,6 +2,7 @@ export const MOBILE_NAV_ALL_KEYS = [
|
||||
"home",
|
||||
"students",
|
||||
"score",
|
||||
"auto-score",
|
||||
"reward-settings",
|
||||
"boards",
|
||||
"leaderboard",
|
||||
@@ -23,6 +24,7 @@ export const MOBILE_NAV_ITEMS: MobileNavItemConfig[] = [
|
||||
{ key: "home", path: "/home", labelKey: "sidebar.home" },
|
||||
{ key: "students", path: "/students", labelKey: "sidebar.students", adminOnly: true },
|
||||
{ key: "score", path: "/score", labelKey: "sidebar.score" },
|
||||
{ key: "auto-score", path: "/auto-score", labelKey: "sidebar.autoScore", adminOnly: true },
|
||||
{
|
||||
key: "reward-settings",
|
||||
path: "/reward-settings",
|
||||
|
||||
Reference in New Issue
Block a user