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,
@@ -0,0 +1 @@
DROP TABLE IF EXISTS clazz_audit_log;
@@ -0,0 +1,13 @@
CREATE TABLE clazz_audit_log (
id VARCHAR PRIMARY KEY,
clazz_id VARCHAR NOT NULL,
action VARCHAR NOT NULL,
operator_hty_id VARCHAR NOT NULL,
operator_name VARCHAR,
changes JSONB,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
org_id VARCHAR
);
CREATE INDEX idx_clazz_audit_log_clazz_id ON clazz_audit_log (clazz_id);
CREATE INDEX idx_clazz_audit_log_created_at ON clazz_audit_log (created_at);
+168
View File
@@ -1255,6 +1255,124 @@ pub struct TeacherHourStatsRow {
pub total_hours: f64,
}
#[derive(QueryableByName, Serialize, Deserialize, Debug, Clone)]
pub struct StudentLessonRow {
#[diesel(sql_type = diesel::sql_types::Varchar)]
pub clazz_id: String,
#[diesel(sql_type = diesel::sql_types::Varchar)]
pub clazz_name: String,
#[diesel(sql_type = diesel::sql_types::Timestamp)]
pub start_from: NaiveDateTime,
#[diesel(sql_type = diesel::sql_types::Timestamp)]
pub end_by: NaiveDateTime,
#[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Varchar>)]
pub teacher_names: Option<String>,
#[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Varchar>)]
pub attendance_status: Option<String>,
#[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Double>)]
pub deducted_hours: Option<f64>,
#[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Varchar>)]
pub leave_status: Option<String>,
}
#[derive(QueryableByName, Serialize, Deserialize, Debug, Clone)]
pub struct TeacherDetailStatsRow {
#[diesel(sql_type = diesel::sql_types::Varchar)]
pub student_id: String,
#[diesel(sql_type = diesel::sql_types::Nullable<diesel::sql_types::Varchar>)]
pub student_name: Option<String>,
#[diesel(sql_type = diesel::sql_types::BigInt)]
pub total_classes: i64,
#[diesel(sql_type = diesel::sql_types::BigInt)]
pub attended: i64,
#[diesel(sql_type = diesel::sql_types::BigInt)]
pub absent: i64,
#[diesel(sql_type = diesel::sql_types::Double)]
pub total_hours: f64,
#[diesel(sql_type = diesel::sql_types::BigInt)]
pub leave_count: i64,
}
impl Clazz {
pub fn student_lesson_stats_by_org_and_date_range(
org: &String,
start_date: &String,
end_date: &String,
student_id: &String,
conn: &mut PgConnection,
) -> anyhow::Result<Vec<StudentLessonRow>> {
let query_text = format!(
"select c.id as clazz_id,
c.clazz_name,
c.start_from,
c.end_by,
(select string_agg(elem->>'real_name', ', ')
from jsonb_array_elements(c.teachers#>'{{val,users,vals}}') elem) as teacher_names,
a.status as attendance_status,
a.deducted_hours,
lr.request_status as leave_status
from clazz c
left join clazz_attendance a on c.id = a.clazz_id and a.student_id = '{sid}' and (a.is_delete is null or a.is_delete = false)
left join clazz_leave_request lr on c.id = lr.clazz_id and lr.student_id = '{sid}'
where c.org_id = '{org}'
and c.start_from >= '{start}'
and c.end_by <= '{end}'
and (c.is_delete is null or c.is_delete = false)
and c.students @> '{{\"val\": {{\"users\": {{\"vals\": [{{\"user_id\": \"{sid}\"}}]}}}}}}'::jsonb
order by c.start_from desc",
sid = student_id,
org = org,
start = start_date,
end = end_date,
);
sql_query(query_text)
.load::<StudentLessonRow>(conn)
.map_err(|e| anyhow!(HtyErr {
code: HtyErrCode::DbErr,
reason: Some(e.to_string()),
}))
}
pub fn teacher_detail_stats_by_org_and_date_range(
org: &String,
start_date: &String,
end_date: &String,
teacher_id: &String,
conn: &mut PgConnection,
) -> anyhow::Result<Vec<TeacherDetailStatsRow>> {
let query_text = format!(
"select s_el->>'user_id' as student_id,
s_el->>'real_name' as student_name,
count(distinct c.id)::bigint as total_classes,
count(distinct a.id) filter (where a.status = 'NORMAL')::bigint as attended,
count(distinct a.id) filter (where a.status = 'ABSENT')::bigint as absent,
coalesce(sum(a.deducted_hours), 0)::double precision as total_hours,
count(distinct lr.id)::bigint as leave_count
from clazz c
cross join lateral jsonb_array_elements(c.students#>'{{val,users,vals}}') s_el
left join clazz_attendance a on c.id = a.clazz_id and a.student_id = s_el->>'user_id' and (a.is_delete is null or a.is_delete = false)
left join clazz_leave_request lr on c.id = lr.clazz_id and lr.student_id = s_el->>'user_id'
where c.org_id = '{org}'
and c.start_from >= '{start}'
and c.end_by <= '{end}'
and (c.is_delete is null or c.is_delete = false)
and c.created_by = '{tid}'
group by s_el->>'user_id', s_el->>'real_name'
order by student_name",
org = org,
start = start_date,
end = end_date,
tid = teacher_id,
);
sql_query(query_text)
.load::<TeacherDetailStatsRow>(conn)
.map_err(|e| anyhow!(HtyErr {
code: HtyErrCode::DbErr,
reason: Some(e.to_string()),
}))
}
}
impl ClazzLeaveRequest {
pub fn create(
payload: &ClazzLeaveRequest,
@@ -1434,3 +1552,53 @@ impl ClazzAttendance {
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Queryable, Insertable, PartialEq)]
#[diesel(table_name = clazz_audit_log)]
pub struct ClazzAuditLog {
pub id: String,
pub clazz_id: String,
pub action: String,
pub operator_hty_id: String,
pub operator_name: Option<String>,
pub changes: Option<serde_json::Value>,
pub created_at: NaiveDateTime,
pub org_id: Option<String>,
}
#[derive(Insertable)]
#[diesel(table_name = clazz_audit_log)]
pub struct NewClazzAuditLog {
pub id: String,
pub clazz_id: String,
pub action: String,
pub operator_hty_id: String,
pub operator_name: Option<String>,
pub changes: Option<serde_json::Value>,
pub created_at: NaiveDateTime,
pub org_id: Option<String>,
}
impl ClazzAuditLog {
pub fn insert(
log: &NewClazzAuditLog,
conn: &mut PgConnection,
) -> anyhow::Result<()> {
use crate::schema::clazz_audit_log::dsl::*;
insert_into(clazz_audit_log)
.values(log)
.execute(conn)?;
Ok(())
}
pub fn list_by_clazz_id(
clazz_id_in: &String,
conn: &mut PgConnection,
) -> anyhow::Result<Vec<ClazzAuditLog>> {
use crate::schema::clazz_audit_log::dsl::*;
Ok(clazz_audit_log
.filter(clazz_id.eq(clazz_id_in))
.order(created_at.desc())
.load::<ClazzAuditLog>(conn)?)
}
}
+14
View File
@@ -44,6 +44,19 @@ diesel::table! {
}
}
diesel::table! {
clazz_audit_log (id) {
id -> Varchar,
clazz_id -> Varchar,
action -> Varchar,
operator_hty_id -> Varchar,
operator_name -> Nullable<Varchar>,
changes -> Nullable<Jsonb>,
created_at -> Timestamp,
org_id -> Nullable<Varchar>,
}
}
diesel::table! {
clazz_leave_request (id) {
id -> Varchar,
@@ -155,6 +168,7 @@ diesel::joinable!(hour_transaction -> course_hour_package (package_id));
diesel::allow_tables_to_appear_in_same_query!(
clazz,
clazz_attendance,
clazz_audit_log,
clazz_leave_request,
clazz_repeat,
course_hour_package,