feat: add audit logging and lesson statistics for clazz

- Add clazz_audit_log table with diesel migration for CRUD audit trail
- Add audit log backend: model, queries, handler, route
- Add audit log viewer in clazz detail modal (操作记录)
- Add student_lesson_stats API (GET /api/v1/clazz/stats/my-lessons)
- Add teacher_detail_stats API (GET /api/v1/clazz/stats/teacher-detail)
- Register all new routes in lib.rs

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-01 19:45:56 +08:00
parent 723787a8ea
commit 5bf43143ea
7 changed files with 348 additions and 5 deletions
+5 -2
View File
@@ -30,8 +30,8 @@ use crate::ws_course_package::{
};
use crate::ws_xiaoke::{batch_save_clazz_attendance, find_clazz_attendance_by_clazz_id};
use crate::ws_xiaoke::{
approve_clazz_leave, create_clazz_leave, list_clazz_leave, supervisor_teacher_stats,
teacher_hour_stats,
approve_clazz_leave, create_clazz_leave, list_clazz_leave, student_lesson_stats,
supervisor_teacher_stats, teacher_detail_stats, teacher_hour_stats,
};
#[debug_handler]
@@ -102,9 +102,12 @@ pub fn clazz_router(db_url: &str) -> Router {
)
.route("/api/v1/clazz/stats/my-hours", get(teacher_hour_stats))
.route("/api/v1/clazz/stats/org-teachers", get(supervisor_teacher_stats))
.route("/api/v1/clazz/stats/my-lessons", get(student_lesson_stats))
.route("/api/v1/clazz/stats/teacher-detail", get(teacher_detail_stats))
.route("/api/v1/clazz/leave/create", post(create_clazz_leave))
.route("/api/v1/clazz/leave/approve", post(approve_clazz_leave))
.route("/api/v1/clazz/leave/list", get(list_clazz_leave))
.route("/api/v1/clazz/audit-log/list", get(list_clazz_audit_log))
// 课包(course_package
.route("/api/v1/clazz/course-package/create", post(create_course_package))
.route("/api/v1/clazz/course-package/update", post(update_course_package))
+87 -2
View File
@@ -14,7 +14,7 @@ use htycommons::web::{
HtySudoerTokenHeader,
};
use htykc_models::models::{
Clazz, ClazzRepeat, ReqClazz, ReqClazzRepeat, ReqClazzWithRepeat,
Clazz, ClazzAuditLog, ClazzRepeat, NewClazzAuditLog, ReqClazz, ReqClazzRepeat, ReqClazzWithRepeat,
};
use std::collections::HashMap;
use std::ops::DerefMut;
@@ -27,6 +27,37 @@ fn current_org_id_from_auth(token: &AuthorizationHeader) -> Option<String> {
.and_then(|decoded| decoded.current_org_id)
}
fn hty_id_from_auth(token: &AuthorizationHeader) -> Option<String> {
jwt_decode_token(&(*token).clone())
.ok()
.and_then(|decoded| decoded.hty_id)
}
fn write_clazz_audit_log(
db_pool: &Arc<DbState>,
clazz_id: &str,
action: &str,
operator_hty_id: &str,
changes: Option<serde_json::Value>,
org_id: Option<String>,
) {
if let Ok(conn) = fetch_db_conn(db_pool) {
let _ = ClazzAuditLog::insert(
&NewClazzAuditLog {
id: uuid(),
clazz_id: clazz_id.to_string(),
action: action.to_string(),
operator_hty_id: operator_hty_id.to_string(),
operator_name: None,
changes,
created_at: current_local_datetime(),
org_id,
},
extract_conn(conn).deref_mut(),
);
}
}
pub async fn find_all_non_repeatable_within_date_range(
sudoer: HtySudoerTokenHeader,
host: HtyHostHeader,
@@ -666,6 +697,23 @@ async fn raw_update_clazz(
extract_conn(fetch_db_conn(&db_pool)?).deref_mut(),
)?;
// Audit log
let operator_id = hty_id_from_auth(&token).unwrap_or_default();
let action = if in_kecheng.is_delete == Some(true) { "DELETE" } else { "UPDATE" };
write_clazz_audit_log(
&db_pool,
&id_kecheng,
action,
&operator_id,
Some(serde_json::json!({
"is_delete": in_kecheng.is_delete,
"clazz_name": in_kecheng.clazz_name,
"start_from": in_kecheng.start_from,
"end_by": in_kecheng.end_by,
})),
current_org_id,
);
Ok(())
}
@@ -848,11 +896,24 @@ async fn raw_create_clazz_with_repeat(
(to_create_kecheng, to_create_kecheng_repeat),
);
let out_result = raw_create_clazz_with_repeat_tx(params, db_pool);
let out_result = raw_create_clazz_with_repeat_tx(params, db_pool.clone());
match out_result {
Ok(out) => {
debug!("created_kecheng: {:?}", out);
write_clazz_audit_log(
&db_pool,
&new_clazz_id,
"CREATE",
&id_user,
Some(serde_json::json!({
"clazz_name": in_kecheng.clazz_name,
"start_from": in_kecheng.start_from,
"end_by": in_kecheng.end_by,
"is_repeat": in_kecheng.is_repeat,
})),
current_org_id.clone(),
);
Ok(out)
}
Err(e) => Err(anyhow!(HtyErr {
@@ -862,6 +923,30 @@ async fn raw_create_clazz_with_repeat(
}
}
pub async fn list_clazz_audit_log(
_sudoer: HtySudoerTokenHeader,
_host: HtyHostHeader,
_auth: AuthorizationHeader,
State(db_pool): State<Arc<DbState>>,
Query(params): Query<HashMap<String, String>>,
) -> Json<HtyResponse<Vec<ClazzAuditLog>>> {
let result = (|| -> anyhow::Result<Vec<ClazzAuditLog>> {
let clazz_id = get_some_from_query_params::<String>("clazz_id", &params)
.ok_or_else(|| anyhow!("clazz_id is required"))?;
ClazzAuditLog::list_by_clazz_id(
&clazz_id,
extract_conn(fetch_db_conn(&db_pool)?).deref_mut(),
)
})();
match result {
Ok(ok) => wrap_json_ok_resp(ok),
Err(e) => {
error!("list_clazz_audit_log -> failed, e: {}", e);
wrap_json_anyhow_err(e)
}
}
}
#[cfg(test)]
mod tests {
use htycommons::common::current_local_datetime;
+60 -1
View File
@@ -10,7 +10,8 @@ use htycommons::web::{
HtySudoerTokenHeader,
};
use htykc_models::models::{
Clazz, ClazzAttendance, ClazzLeaveRequest, ReqBatchClazzAttendance, ReqClazzLeaveRequest, TeacherHourStatsRow,
Clazz, ClazzAttendance, ClazzLeaveRequest, ReqBatchClazzAttendance, ReqClazzLeaveRequest,
StudentLessonRow, TeacherDetailStatsRow, TeacherHourStatsRow,
};
use htycommons::uuid;
use std::collections::HashMap;
@@ -175,6 +176,64 @@ pub async fn supervisor_teacher_stats(
}
}
pub async fn student_lesson_stats(
_sudoer: HtySudoerTokenHeader,
_host: HtyHostHeader,
auth: AuthorizationHeader,
State(db_pool): State<Arc<DbState>>,
Query(params): Query<HashMap<String, String>>,
) -> Json<HtyResponse<Vec<StudentLessonRow>>> {
let result = (|| -> anyhow::Result<Vec<StudentLessonRow>> {
let token = jwt_decode_token(&(*auth).clone())?;
let student_id = token.hty_id.ok_or_else(|| anyhow!("hty_id is required"))?;
let org_id = required_org_id_from_auth(&auth)?;
let start_date = get_some_from_query_params::<String>("start_date", &params)
.unwrap_or_else(|| "1970-01-01 00:00:00".to_string());
let end_date = get_some_from_query_params::<String>("end_date", &params)
.unwrap_or_else(|| "2999-12-31 23:59:59".to_string());
Clazz::student_lesson_stats_by_org_and_date_range(
&org_id,
&start_date,
&end_date,
&student_id,
extract_conn(fetch_db_conn(&db_pool)?).deref_mut(),
)
})();
match result {
Ok(ok) => wrap_json_ok_resp(ok),
Err(e) => wrap_json_anyhow_err(e),
}
}
pub async fn teacher_detail_stats(
_sudoer: HtySudoerTokenHeader,
_host: HtyHostHeader,
auth: AuthorizationHeader,
State(db_pool): State<Arc<DbState>>,
Query(params): Query<HashMap<String, String>>,
) -> Json<HtyResponse<Vec<TeacherDetailStatsRow>>> {
let result = (|| -> anyhow::Result<Vec<TeacherDetailStatsRow>> {
let token = jwt_decode_token(&(*auth).clone())?;
let teacher_id = token.hty_id.ok_or_else(|| anyhow!("hty_id is required"))?;
let org_id = required_org_id_from_auth(&auth)?;
let start_date = get_some_from_query_params::<String>("start_date", &params)
.unwrap_or_else(|| "1970-01-01 00:00:00".to_string());
let end_date = get_some_from_query_params::<String>("end_date", &params)
.unwrap_or_else(|| "2999-12-31 23:59:59".to_string());
Clazz::teacher_detail_stats_by_org_and_date_range(
&org_id,
&start_date,
&end_date,
&teacher_id,
extract_conn(fetch_db_conn(&db_pool)?).deref_mut(),
)
})();
match result {
Ok(ok) => wrap_json_ok_resp(ok),
Err(e) => wrap_json_anyhow_err(e),
}
}
pub async fn create_clazz_leave(
_sudoer: HtySudoerTokenHeader,
_host: HtyHostHeader,