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
+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;