This commit is contained in:
Yukino_fox
2026-03-29 19:36:39 +08:00
21 changed files with 1425 additions and 548 deletions
+7 -505
View File
@@ -8,13 +8,16 @@ target/
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Environment variables
.env
.env.local
*.env.*
# Editor/IDE
# Editor / IDE
.vscode/
.idea/
*.swp
@@ -39,28 +42,9 @@ pip-delete-this-directory.txt
nosetests.xml
coverage.xml
*.cover
*.db
*.log
*.pot
*.pyc
*.pyo
*.pyd
.MF
.TemporaryItems
.deps
.nfs*
.pytest_cache/
.mypy_cache/
# Node.js
npm-debug.log*
yarn-debug.log*
yarn-error.log*
node_modules/
jspm_packages/
*.min.js
*.min.css
# OS generated files
.DS_Store
.DS_Store?
@@ -71,488 +55,6 @@ ehthumbs.db
Thumbs.db
desktop.ini
# Compiled and binary files
*.exe
*.dll
*.so
*.a
*.o
*.out
*.class
*.jar
*.war
*.ear
*.zip
*.tar
*.gz
*.tgz
*.bz2
*.xz
*.7z
*.rar
*.zst
*.lz4
*.lzh
*.cab
*.arj
*.rpm
*.deb
*.Z
*.lz
*.lzo
*.tar.gz
*.tar.bz2
*.tar.xz
*.tar.zst
# Go
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.prof
coverage.out
vendor/
# Java
*.class
*.jar
*.war
*.ear
*.zip
hs_err_pid*
replay_pid*
# C/C++
*.o
*.a
*.so
*.obj
*.exe
*.dll
*.lib
*.so*
*.dylib*
*.plist
*.swp
*~
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
desktop.ini
# Ruby
*.gem
*.rbc
.bundle/
.config/byebug_history
.yardoc/
_yardoc/
doc/
.rdoc
.coveralls.yml
.travis.yml
.circleci/
.semaphore/
appveyor.yml
.codeclimate.yml
.codacy-coverage.yml
.codacy.yml
.lgtm.yml
.reviewdog.yml
.sider.yml
.styleci.yml
.php_cs
.php_cs.dist
.php-cs-fixer.dist.php
.php-cs-fixer.php
.editorconfig
.eslintrc
.jshintrc
.jscsrc
.babelrc
.postcssrc
.prettierrc
.stylelint
.stylelintrc
.hintrc
.remarkrc
.gitattributes
.gitignore
.pre-commit-config.yaml
.mdlrc
.rubocop.yml
.slim-lint.yml
.rubocop_todo.yml
.slim-lint-report.json
.scss-lint.yml
.scss-lint-report.json
.jshintignore
.eslintignore
.babelignore
.prettierignore
.stylelintignore
.stylelintrcignore
.hintignore
.remarkignore
.gitmodules
.gitreview
.gitlab-ci.yml
.drone.yml
.direnv
.envrc
.secrets.baseline
.checkov.yaml
.tflint.hcl
.kitchen.local.yml
.kitchen.yml
.kitchen/
.vagrant/
.terraform/
.terragrunt-cache/
.chef/knife.rb
.chef/config.rb
.chef/environment/
.chef/role/
.chef/data_bags/
.chef/cookbooks/
.chef/site-cookbooks/
.chef/environments/
.chef/roles/
.chef/data_bags/
.chef/encrypted_data_bag_secret
.chef/trusted_certs/
.chef/clients/
.chef/nodes/
.chef/users/
.chef/validation.pem
.chef/client.pem
.chef/server.pem
.chef/webui_priv.pem
.chef/webui_pub.pem
.chef/private-chef-secrets.json
.chef/local-mode-cache/
chefignore
Berksfile.lock
Berksfile
Policyfile.rb
Policyfile.lock.json
Guardfile
Capfile
Rakefile
Vagrantfile
Gemfile
Gemfile.lock
Puppetfile
Puppetfile.lock
.gitlab/issue_templates/
.gitlab/mr_templates/
.gitlab-ci/
.gitlab/ci/
.gitlab/merge_request_templates/
.gitlab/issue_templates/
.gitlab-feature-flag/
.gitlab-feature-flag.yml
.gitlab-feature-flag.yaml
.gitlab-feature-flag.json
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go
.gitlab-feature-flag.java
.gitlab-feature-flag.cpp
.gitlab-feature-flag.c
.gitlab-feature-flag.h
.gitlab-feature-flag.hpp
.gitlab-feature-flag.cc
.gitlab-feature-flag.hxx
.gitlab-feature-flag.cs
.gitlab-feature-flag.fs
.gitlab-feature-flag.fsi
.gitlab-feature-flag.fsx
.gitlab-feature-flag.fsscript
.gitlab-feature-flag.vb
.gitlab-feature-flag.vbs
.gitlab-feature-flag.asp
.gitlab-feature-flag.aspx
.gitlab-feature-flag.html
.gitlab-feature-flag.htm
.gitlab-feature-flag.xhtml
.gitlab-feature-flag.css
.gitlab-feature-flag.scss
.gitlab-feature-flag.sass
.gitlab-feature-flag.less
.gitlab-feature-flag.styl
.gitlab-feature-flag.json
.gitlab-feature-flag.yaml
.gitlab-feature-flag.yml
.gitlab-feature-flag.toml
.gitlab-feature-flag.ini
.gitlab-feature-flag.cfg
.gitlab-feature-flag.conf
.gitlab-feature-flag.properties
.gitlab-feature-flag.xml
.gitlab-feature-flag.csv
.gitlab-feature-flag.tsv
.gitlab-feature-flag.sql
.gitlab-feature-flag.sh
.gitlab-feature-flag.bat
.gitlab-feature-flag.cmd
.gitlab-feature-flag.ps1
.gitlab-feature-flag.pl
.gitlab-feature-flag.rb
.gitlab-feature-flag.py
.gitlab-feature-flag.js
.gitlab-feature-flag.ts
.gitlab-feature-flag.go......
# Tauri local/generated artifacts
src-tauri/data.sql
src-tauri/gen/
File diff suppressed because one or more lines are too long
+5 -2
View File
@@ -1,6 +1,6 @@
use parking_lot::RwLock;
use serde::Deserialize;
use sea_orm::{ConnectionTrait, DatabaseConnection, Statement};
use serde::Deserialize;
use serde_json::{Map, Value as JsonValue};
use sqlx::{Column, Row, SqlitePool};
use std::collections::HashSet;
@@ -155,7 +155,10 @@ async fn get_board_configs_raw(conn: &DatabaseConnection) -> Result<Option<Strin
}
}
async fn upsert_board_configs_raw(conn: &DatabaseConnection, config_json: &str) -> Result<(), String> {
async fn upsert_board_configs_raw(
conn: &DatabaseConnection,
config_json: &str,
) -> Result<(), String> {
let config_escaped = escape_sql(config_json);
let now_escaped = escape_sql(&now_iso());
let sql = format!(
+5 -4
View File
@@ -1150,7 +1150,10 @@ pub async fn db_switch_connection(
let logger = state_guard.logger.read();
logger.log(
LogLevel::Info,
&format!("Database switch requested, connection_string length: {}", connection_string.len()),
&format!(
"Database switch requested, connection_string length: {}",
connection_string.len()
),
Some("database"),
None,
);
@@ -1225,9 +1228,7 @@ pub async fn db_switch_connection(
connection_string
};
let conn = create_sqlite_connection(&path)
.await
.map_err(|e| {
let conn = create_sqlite_connection(&path).await.map_err(|e| {
logger.log(
LogLevel::Error,
&format!("SQLite connection failed: {}", e),
+15 -4
View File
@@ -313,7 +313,9 @@ async fn post_banyou_action<T: DeserializeOwned>(
params: serde_json::Value,
) -> Result<T, String> {
let timestamp = chrono::Utc::now().timestamp_millis();
let url = format!("https://care.seewo.com/app/apis.json?action={action}&timestamp={timestamp}&isAjax=1");
let url = format!(
"https://care.seewo.com/app/apis.json?action={action}&timestamp={timestamp}&isAjax=1"
);
let payload = serde_json::json!({
"action": action,
"params": params,
@@ -371,7 +373,11 @@ async fn post_banyou_action<T: DeserializeOwned>(
"body_preview": first_n_chars(&body, 500),
})),
);
return Err(format!("班优接口请求失败({} HTTP {}", action, status.as_u16()));
return Err(format!(
"班优接口请求失败({} HTTP {}",
action,
status.as_u16()
));
}
let parsed: BanYouApiResponse<T> = serde_json::from_str(&body).map_err(|e| {
@@ -993,7 +999,9 @@ pub async fn student_fetch_banyou_classroom_detail(
(Vec::new(), None)
};
let final_team_plan_id = params.team_plan_id.or_else(|| team_plans.first().map(|p| p.team_plan_id));
let final_team_plan_id = params
.team_plan_id
.or_else(|| team_plans.first().map(|p| p.team_plan_id));
let group_data = if let Some(team_plan_id) = final_team_plan_id {
match post_banyou_action::<BanYouGroupFetchData>(
@@ -1032,7 +1040,10 @@ pub async fn student_fetch_banyou_classroom_detail(
let detail = BanYouClassroomDetailData {
medals,
students: students_data.students,
teams: group_data.as_ref().map(|d| d.teams.clone()).unwrap_or_default(),
teams: group_data
.as_ref()
.map(|d| d.teams.clone())
.unwrap_or_default(),
ungrouped_students: group_data
.as_ref()
.map(|d| d.students.clone())
+4 -3
View File
@@ -318,9 +318,10 @@ fn setup_database(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
*db_guard = Some(active_conn);
}
state_guard.initialize().await.map_err(|e| {
format!("Failed to initialize app state: {}", e)
})?;
state_guard
.initialize()
.await
.map_err(|e| format!("Failed to initialize app state: {}", e))?;
Ok::<_, Box<dyn std::error::Error>>(())
});
+62 -14
View File
@@ -1,4 +1,4 @@
use chrono::{DateTime, Utc};
use chrono::{DateTime, Months, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tauri::{AppHandle, Emitter};
@@ -15,6 +15,20 @@ pub struct AutoScoreAction {
pub value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum IntervalUnit {
Minute,
Day,
Month,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct IntervalTriggerValue {
amount: i64,
unit: IntervalUnit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoScoreRule {
pub id: i32,
@@ -171,25 +185,19 @@ impl AutoScoreService {
for trigger in &rule.triggers {
if trigger.event == "interval_time_passed" {
let minutes = trigger
.value
let interval = parse_interval_trigger_value(trigger.value.as_ref());
let base_time = rule
.last_executed
.as_ref()
.and_then(|v| v.parse::<i64>().ok())
.unwrap_or(30);
let interval_ms = minutes * 60 * 1000;
.and_then(|value| DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&Utc))
.unwrap_or(now);
if let Some(last_executed_str) = &rule.last_executed {
if let Ok(last_executed) = DateTime::parse_from_rfc3339(last_executed_str) {
let last_executed_utc: DateTime<Utc> = last_executed.with_timezone(&Utc);
let next_execute_time =
last_executed_utc + chrono::Duration::milliseconds(interval_ms);
let next_execute_time = add_interval_to_time(base_time, &interval)?;
let delay_ms = (next_execute_time - now).num_milliseconds();
return Some(delay_ms.max(0));
}
}
return Some(interval_ms);
}
}
None
}
@@ -197,3 +205,43 @@ impl AutoScoreService {
let _ = app_handle.emit("auto-score:rulesChanged", &self.rules);
}
}
fn parse_interval_trigger_value(value: Option<&String>) -> IntervalTriggerValue {
if let Some(raw_value) = value {
if let Ok(minutes) = raw_value.parse::<i64>() {
if minutes > 0 {
return IntervalTriggerValue {
amount: minutes,
unit: IntervalUnit::Minute,
};
}
}
if let Ok(parsed_value) = serde_json::from_str::<IntervalTriggerValue>(raw_value) {
if parsed_value.amount > 0 {
return parsed_value;
}
}
}
IntervalTriggerValue {
amount: 30,
unit: IntervalUnit::Minute,
}
}
fn add_interval_to_time(
base_time: DateTime<Utc>,
interval: &IntervalTriggerValue,
) -> Option<DateTime<Utc>> {
match interval.unit {
IntervalUnit::Minute => {
base_time.checked_add_signed(chrono::Duration::minutes(interval.amount))
}
IntervalUnit::Day => base_time.checked_add_signed(chrono::Duration::days(interval.amount)),
IntervalUnit::Month => {
let months = u32::try_from(interval.amount).ok()?;
base_time.checked_add_months(Months::new(months))
}
}
}
+1 -3
View File
@@ -431,9 +431,7 @@ impl SettingsService {
"settings",
];
return items.iter().all(|item| {
item.as_str()
.map(|s| allowed.contains(&s))
.unwrap_or(false)
item.as_str().map(|s| allowed.contains(&s)).unwrap_or(false)
});
}
false
+8
View File
@@ -92,6 +92,9 @@ select {
.ss-sidebar .ant-menu-item {
color: var(--ss-sidebar-text, var(--ss-text-main));
height: 40px !important;
line-height: 42px !important;
border-radius: 6px !important;
}
.ss-sidebar .ant-menu-item-selected {
@@ -318,6 +321,11 @@ html.platform-macos #root {
min-height: 100%;
}
.ss-route-page.is-board-page {
height: 100%;
overflow: hidden;
}
.ss-route-page.is-subpage-enter {
animation: ss-subpage-enter 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
+464
View File
@@ -0,0 +1,464 @@
import React, { useEffect, useMemo, useState } from "react"
import {
Alert,
Button,
Card,
Form,
Input,
Pagination,
Popconfirm,
Select,
Space,
Switch,
Table,
Tag,
message,
} from "antd"
import { type ImmutableTree } from "@react-awesome-query-builder/antd"
import type { ColumnsType } from "antd/es/table"
import { useTranslation } from "react-i18next"
import { fetchAllTags } from "./TagEditorDialog"
import { ActionEditor } from "./AutoScoreManagerPage/ActionEditor"
import { TriggerRuleBuilder } from "./AutoScoreManagerPage/TriggerRuleBuilder"
import {
actionDraftsToPayload,
actionsToDrafts,
createDefaultActionDraft,
createEmptyTriggerTree,
createTriggerQueryConfig,
hasUnsupportedTriggerLogic,
queryTreeToTriggers,
triggersToQueryTree,
type ActionDraft,
type AutoScoreRule,
type AutoScoreTagOption,
} from "./AutoScoreManagerPage/AutoScoreUtils"
interface StudentItem {
id: number
name: string
}
interface TagItem {
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 [tags, setTags] = useState<TagItem[]>([])
const tagOptions = useMemo<AutoScoreTagOption[]>(
() =>
tags.map((tag) => ({
label: tag.name,
value: tag.name,
})),
[tags]
)
const triggerConfig = useMemo(
() => createTriggerQueryConfig(t, tagOptions),
[i18n.resolvedLanguage, i18n.language, tagOptions]
)
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(() => {
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 fetchTags = async () => {
if (!canEdit) return
try {
const tagList = await fetchAllTags()
if (Array.isArray(tagList)) {
setTags(tagList)
}
} 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
fetchTags().catch(() => void 0)
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) => setTriggerTree(nextTree)}
/>
<ActionEditor
value={actionDrafts}
tagOptions={tagOptions}
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,128 @@
import React, { useMemo } from "react"
import { Button, Card, InputNumber, Select, Space } from "antd"
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import { useTranslation } from "react-i18next"
import type { ActionDraft, ActionEvent, AutoScoreTagOption } from "./AutoScoreUtils"
import { createDefaultActionDraft } from "./AutoScoreUtils"
interface ActionEditorProps {
value: ActionDraft[]
tagOptions: AutoScoreTagOption[]
canEdit: boolean
onChange: (nextDrafts: ActionDraft[]) => void
}
export const ActionEditor: React.FC<ActionEditorProps> = ({
value,
tagOptions,
canEdit,
onChange,
}) => {
const { t } = useTranslation()
const actionOptions = useMemo(
() => [
{ value: "add_score", label: t("autoScore.actionAddScore") },
{ value: "add_tag", label: t("autoScore.actionAddTag") },
],
[t]
)
const mergedTagOptions = useMemo(() => {
const optionMap = new Map(tagOptions.map((option) => [option.value, option]))
for (const action of value) {
if (action.event !== "add_tag") continue
const tagValues = Array.isArray(action.value)
? action.value
: action.value
? [action.value]
: []
for (const tagValue of tagValues) {
if (!optionMap.has(tagValue)) {
optionMap.set(tagValue, { label: tagValue, value: tagValue })
}
}
}
return Array.from(optionMap.values())
}, [tagOptions, value])
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) })
}
/>
) : (
<Select
mode="multiple"
showSearch
allowClear
style={{ minWidth: 260 }}
placeholder={t("autoScore.tagNamePlaceholder")}
value={Array.isArray(action.value) ? action.value : action.value ? [action.value] : []}
disabled={!canEdit}
options={mergedTagOptions}
onChange={(nextValue) => updateAction(action.id, { value: nextValue })}
/>
)}
<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,353 @@
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"
import { IntervalValueWidget, parseIntervalTriggerValue, stringifyIntervalTriggerValue } from "./IntervalValueWidget"
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 AutoScoreTagOption {
label: string
value: string
}
export interface ActionDraft {
id: string
event: ActionEvent
value: string | string[]
}
export type ActionDraftError = "score_required" | "tag_required" | null
const TRIGGER_FIELD_INTERVAL = "interval_minutes"
const TRIGGER_FIELD_TAG = "student_tag"
const TRIGGER_TYPE_INTERVAL = "interval_duration"
const TRIGGER_WIDGET_INTERVAL = "interval_duration"
const OP_EQUAL = "equal"
const OP_MULTISELECT_CONTAINS = "multiselect_contains"
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 normalizeTagValues = (values: unknown[]): string[] => {
const normalized = values
.map((value) => toStringValue(value).trim())
.filter(Boolean)
return Array.from(new Set(normalized))
}
const parseTagValues = (value: unknown): string[] => {
if (Array.isArray(value)) {
return normalizeTagValues(value)
}
const text = toStringValue(value).trim()
if (!text) return []
if (text.startsWith("[")) {
try {
const parsed = JSON.parse(text)
if (Array.isArray(parsed)) {
return normalizeTagValues(parsed)
}
} catch {
void 0
}
}
return [text]
}
const stringifyTagValues = (values: string[]): string | null => {
const normalized = normalizeTagValues(values)
if (normalized.length === 0) return null
if (normalized.length === 1) return normalized[0]
return JSON.stringify(normalized)
}
const ruleFromTrigger = (trigger: AutoScoreTrigger): JsonRule | null => {
if (trigger.event === "interval_time_passed") {
const intervalValue = parseIntervalTriggerValue(trigger.value)
const serializedIntervalValue = intervalValue
? stringifyIntervalTriggerValue(intervalValue)
: null
if (!serializedIntervalValue) return null
return {
id: QbUtils.uuid(),
type: "rule",
properties: {
field: TRIGGER_FIELD_INTERVAL,
operator: OP_EQUAL,
value: [serializedIntervalValue],
},
}
}
if (trigger.event === "student_has_tag") {
const tagNames = parseTagValues(trigger.value)
if (tagNames.length === 0) return null
return {
id: QbUtils.uuid(),
type: "rule",
properties: {
field: TRIGGER_FIELD_TAG,
operator: OP_MULTISELECT_CONTAINS,
value: [tagNames],
},
}
}
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 intervalValue = parseIntervalTriggerValue(value)
const serializedIntervalValue = intervalValue
? stringifyIntervalTriggerValue(intervalValue)
: null
if (!serializedIntervalValue) return null
return {
event: "interval_time_passed",
value: serializedIntervalValue,
}
}
if (field === TRIGGER_FIELD_TAG) {
const tagNames = parseTagValues(value)
const serializedValue = stringifyTagValues(tagNames)
if (!serializedValue) return null
return {
event: "student_has_tag",
value: serializedValue,
}
}
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, tagOptions: AutoScoreTagOption[]): Config =>
({
...AntdConfig,
widgets: {
...AntdConfig.widgets,
[TRIGGER_WIDGET_INTERVAL]: {
...AntdConfig.widgets.text,
type: "text",
jsType: "string",
hideOperator: true,
factory: IntervalValueWidget,
valuePlaceholder: t("autoScore.intervalAmountPlaceholder"),
validateValue: (value) => {
const rawValue = toStringValue(value).trim()
if (!rawValue) return true
return parseIntervalTriggerValue(rawValue) !== null
},
},
},
types: {
...AntdConfig.types,
[TRIGGER_TYPE_INTERVAL]: {
...AntdConfig.types.text,
defaultOperator: OP_EQUAL,
mainWidget: TRIGGER_WIDGET_INTERVAL,
widgets: {
[TRIGGER_WIDGET_INTERVAL]: {
operators: [OP_EQUAL],
},
},
},
},
fields: {
[TRIGGER_FIELD_INTERVAL]: {
label: t("autoScore.triggerIntervalTime"),
type: TRIGGER_TYPE_INTERVAL,
operators: [OP_EQUAL],
valueSources: ["value"],
preferWidgets: [TRIGGER_WIDGET_INTERVAL],
},
[TRIGGER_FIELD_TAG]: {
label: t("autoScore.triggerStudentTag"),
type: "multiselect",
defaultOperator: OP_MULTISELECT_CONTAINS,
operators: [OP_MULTISELECT_CONTAINS],
valueSources: ["value"],
preferWidgets: ["multiselect"],
fieldSettings: {
listValues: tagOptions.map((tag) => ({
value: tag.value,
title: tag.label,
})),
allowCustomValues: true,
showSearch: true,
},
},
},
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:
action.event === "add_tag" ? parseTagValues(action.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 = Array.isArray(draft.value) ? null : toFiniteNumber(draft.value)
if (!score || score === 0) {
return { actions: [], error: "score_required" }
}
actions.push({ event: draft.event, value: String(score) })
continue
}
const serializedTagValue = stringifyTagValues(parseTagValues(draft.value))
if (!serializedTagValue) {
return { actions: [], error: "tag_required" }
}
actions.push({ event: draft.event, value: serializedTagValue })
}
return { actions, error: null }
}
@@ -0,0 +1,79 @@
export type IntervalUnit = "minute" | "day" | "month"
export interface IntervalValue {
amount: number
unit: IntervalUnit
}
export const DEFAULT_INTERVAL_UNIT: IntervalUnit = "day"
const normalizePositiveInteger = (value: unknown): number | null => {
if (typeof value === "number" && Number.isFinite(value)) {
const normalized = Math.floor(value)
return normalized > 0 ? normalized : null
}
if (typeof value === "string" && value.trim()) {
const parsed = Number(value)
if (Number.isFinite(parsed)) {
const normalized = Math.floor(parsed)
return normalized > 0 ? normalized : null
}
}
return null
}
const isIntervalUnit = (value: unknown): value is IntervalUnit =>
value === "minute" || value === "day" || value === "month"
export const getDefaultIntervalValue = (): IntervalValue => ({
amount: 1,
unit: DEFAULT_INTERVAL_UNIT,
})
export const parseIntervalTriggerValue = (value: unknown): IntervalValue | null => {
if (typeof value === "object" && value !== null) {
const amount = normalizePositiveInteger((value as IntervalValue).amount)
const unit = (value as IntervalValue).unit
if (amount && isIntervalUnit(unit)) {
return { amount, unit }
}
}
const text = value === null || value === undefined ? "" : String(value).trim()
if (!text) return null
const legacyMinutes = normalizePositiveInteger(text)
if (legacyMinutes !== null && !text.startsWith("{")) {
return { amount: legacyMinutes, unit: "minute" }
}
try {
const parsed = JSON.parse(text) as Partial<IntervalValue>
const amount = normalizePositiveInteger(parsed.amount)
if (amount && isIntervalUnit(parsed.unit)) {
return { amount, unit: parsed.unit }
}
} catch {
void 0
}
return null
}
export const stringifyIntervalTriggerValue = (value: IntervalValue): string | null => {
const amount = normalizePositiveInteger(value.amount)
if (!amount || !isIntervalUnit(value.unit)) {
return null
}
if (value.unit === "minute") {
return String(amount)
}
return JSON.stringify({
amount,
unit: value.unit,
})
}
@@ -0,0 +1,118 @@
import React, { useMemo } from "react"
import { InputNumber, Select } from "antd"
import type { WidgetProps } from "@react-awesome-query-builder/antd"
import { useTranslation } from "react-i18next"
export type IntervalUnit = "month" | "day" | "minute"
export interface IntervalValue {
amount: number
unit: IntervalUnit
}
export const DEFAULT_INTERVAL_UNIT: IntervalUnit = "day"
export const getDefaultIntervalValue = (): IntervalValue => ({
amount: 1,
unit: DEFAULT_INTERVAL_UNIT,
})
export const parseIntervalTriggerValue = (value: unknown): IntervalValue | null => {
if (value === null || value === undefined) return null
const str = String(value).trim()
if (!str) return null
try {
const parsed = JSON.parse(str)
if (
typeof parsed === "object" &&
parsed !== null &&
typeof parsed.amount === "number" &&
typeof parsed.unit === "string"
) {
const validUnits: IntervalUnit[] = ["month", "day", "minute"]
if (validUnits.includes(parsed.unit as IntervalUnit)) {
return {
amount: Math.max(1, Math.floor(parsed.amount)),
unit: parsed.unit as IntervalUnit,
}
}
}
} catch {
void 0
}
return null
}
export const stringifyIntervalTriggerValue = (value: IntervalValue): string => {
return JSON.stringify({
amount: value.amount,
unit: value.unit,
})
}
export const IntervalValueWidget: React.FC<WidgetProps> = ({
value,
setValue,
readonly,
placeholder,
}) => {
const { t } = useTranslation()
const parsedValue = parseIntervalTriggerValue(value)
const unitOptions = useMemo(
() => [
{ label: t("autoScore.intervalUnitMonth"), value: "month" },
{ label: t("autoScore.intervalUnitDay"), value: "day" },
{ label: t("autoScore.intervalUnitMinute"), value: "minute" },
],
[t]
)
const handleAmountChange = (nextAmount: number | null) => {
if (nextAmount === null) {
setValue(null)
return
}
const serializedValue = stringifyIntervalTriggerValue({
amount: nextAmount,
unit: parsedValue?.unit ?? DEFAULT_INTERVAL_UNIT,
})
setValue(serializedValue)
}
const handleUnitChange = (nextUnit: IntervalUnit) => {
const baseValue = parsedValue ?? getDefaultIntervalValue()
const serializedValue = stringifyIntervalTriggerValue({
amount: baseValue.amount,
unit: nextUnit,
})
setValue(serializedValue)
}
return (
<div style={{ display: "flex", gap: 8, minWidth: 280 }}>
<InputNumber
min={1}
precision={0}
disabled={readonly}
value={parsedValue?.amount}
placeholder={placeholder || t("autoScore.intervalAmountPlaceholder")}
onChange={handleAmountChange}
style={{ width: 130 }}
/>
<Select
disabled={readonly}
value={parsedValue?.unit ?? DEFAULT_INTERVAL_UNIT}
options={unitOptions}
onChange={handleUnitChange}
style={{ width: 140 }}
/>
</div>
)
}
export default IntervalValueWidget
@@ -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>
)
}
+11 -2
View File
@@ -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(),
@@ -92,6 +95,7 @@ export function ContentArea({
const isSubPage = location.pathname !== "/" && !location.pathname.startsWith("/home")
const shouldAnimateSubPage = isPortraitMode && isSubPage
const normalizedPath = location.pathname === "/" ? "/home" : location.pathname
const isBoardPage = normalizedPath.startsWith("/boards")
const isMobileHeaderMode = isPortraitMode && isMobileDevice && !immersiveMode
const isPrimaryMobilePage =
normalizedPath.startsWith("/home") || normalizedPath.startsWith("/settings")
@@ -100,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")
@@ -317,7 +322,7 @@ export function ContentArea({
<Content
style={{
flex: 1,
overflowY: "auto",
overflowY: isBoardPage ? "hidden" : "auto",
overflowX: "hidden",
paddingBottom: bottomInset ? `${bottomInset}px` : 0,
}}
@@ -340,7 +345,7 @@ export function ContentArea({
>
<div
key={location.pathname}
className={`ss-route-page${shouldAnimateSubPage ? " is-subpage-enter" : ""}`}
className={`ss-route-page${shouldAnimateSubPage ? " is-subpage-enter" : ""}${isBoardPage ? " is-board-page" : ""}`}
>
<Routes>
<Route
@@ -363,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 />} />
+6
View File
@@ -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 />,
+5
View File
@@ -781,6 +781,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",
@@ -813,6 +814,10 @@
"triggerStudentTag": "Student Tag",
"actionAddScore": "Add Score",
"actionAddTag": "Add Tag",
"intervalAmountPlaceholder": "Enter interval amount",
"intervalUnitMonth": "month(s) later",
"intervalUnitDay": "day(s) later",
"intervalUnitMinute": "minute(s) later",
"minutesPlaceholder": "Enter minutes",
"minutes": "minutes",
"tagsPlaceholder": "Enter tag name",
+5
View File
@@ -781,6 +781,7 @@
"adminDeleteRequired": "需要管理员权限以删除自动加分自动化",
"adminToggleRequired": "需要管理员权限以启用/禁用自动加分自动化",
"fetchFailed": "获取自动化失败",
"unsupportedLogic": "当前版本保存规则时仅支持 AND 条件,OR / NOT 逻辑暂未接入后端存储",
"triggerRequired": "请至少添加一个触发器",
"actionRequired": "请至少添加一个行动",
"createSuccess": "自动化创建成功",
@@ -811,6 +812,10 @@
"triggerStudentTag": "学生标签",
"actionAddScore": "加分",
"actionAddTag": "添加标签",
"intervalAmountPlaceholder": "请输入间隔数量",
"intervalUnitMonth": "个月后",
"intervalUnitDay": "天后",
"intervalUnitMinute": "分钟后",
"minutesPlaceholder": "请输入分钟数",
"minutes": "分钟",
"tagsPlaceholder": "请输入标签名称",
+65 -1
View File
@@ -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
@@ -237,6 +261,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"),
@@ -493,7 +557,7 @@ const api = {
appRestart: (): Promise<void> => invoke("app_restart"),
// Generic invoke wrapper for backward compatibility with callers using `api.invoke`
invoke: async (channel: string): Promise<any> => {
invoke: async (channel: string, ..._args: any[]): Promise<any> => {
switch (channel) {
default:
throw new Error(`Unsupported legacy invoke channel: ${channel}`)
+1
View File
@@ -24,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",