forge
Explore
Log in

Don't you dare go Hollow

Weighted mark reports per course and overall

Browse files at this commit

ebc1bd2c1681800e36cde8434a314efc5f9bfb8dAhmet Kaan GümüşParent: cd56c5b
  • feat
    • weighted mark reports per course and overall
Show full message
✨ feat(marks): weighted mark reports per course and overall

GET /marks/me gives any authenticated user their own report; GET
/marks/{user} (teacher+) reads anyone's, 404 for unknown users. For
each enrolled course the report joins the course's exams with the
user's graded results: per-exam entries (title, kind, weight, mark,
grader), a Σ(mark×weight)/Σ(weight) course average, and a plain mean
of course averages overall. Ungraded exams don't appear, averages stay
null until something is graded, and unenrolling hides a course's block
without deleting result rows.

ExamResult::list_for_user_in_course supplies the raw rows behind each
course block.
src/domain/exam_result.rsmodified+21 -0
@@ -1,6 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::database::{Database, EXAM_RESULT_TABLE};3 use crate::database::{Database, EXAM_RESULT_TABLE};
4+use crate::domain::course::CourseId;
4 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
5 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
6 use crate::error::{AppError, ValidationError};7 use crate::error::{AppError, ValidationError};
@@ -124,6 +125,26 @@ impl ExamResult {
124 saved.ok_or_else(|| AppError::Internal("failed to record exam result".into()))125 saved.ok_or_else(|| AppError::Internal("failed to record exam result".into()))
125 }126 }
126 127
128+ /// The user's graded results restricted to one course's exams — the raw
129+ /// rows behind the per-course block of the marks report.
130+ pub async fn list_for_user_in_course(
131+ course: &CourseId,
132+ user: &UserId,
133+ db: &Database,
134+ ) -> Result<Vec<ExamResult>, AppError> {
135+ let mut result = db
136+ .query(
137+ "SELECT * FROM exam_result WHERE user = $usr
138+ AND exam IN (SELECT VALUE id FROM exam WHERE course = $course)
139+ ORDER BY id DESC",
140+ )
141+ .bind(("usr", user.record()))
142+ .bind(("course", course.record()))
143+ .await?
144+ .check()?;
145+ Ok(result.take::<Vec<ExamResult>>(0)?)
146+ }
147+
127 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {148 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {
128 let mut result = db149 let mut result = db
129 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")150 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")
src/lib.rsmodified+3 -1
@@ -32,7 +32,7 @@ use crate::state::AppState;
32 info(32 info(
33 title = "Hezarfen Backend API",33 title = "Hezarfen Backend API",
34 version = env!("CARGO_PKG_VERSION"),34 version = env!("CARGO_PKG_VERSION"),
35- description = "Notes, events, attendance, and exams behind cookie-session auth.",35+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth.",
36 ),36 ),
37 modifiers(&SecurityAddon),37 modifiers(&SecurityAddon),
38 tags(38 tags(
@@ -43,6 +43,7 @@ use crate::state::AppState;
43 (name = "events", description = "Events and attendance"),43 (name = "events", description = "Events and attendance"),
44 (name = "courses", description = "Courses, enrollment, and course exams"),44 (name = "courses", description = "Courses, enrollment, and course exams"),
45 (name = "exams", description = "Exams (per course, weighted) and student results"),45 (name = "exams", description = "Exams (per course, weighted) and student results"),
46+ (name = "marks", description = "Weighted mark reports per course and overall"),
46 ),47 ),
47 )]48 )]
48 struct ApiDoc;49 struct ApiDoc;
@@ -76,6 +77,7 @@ pub fn build_router(state: AppState) -> Router {
76 .nest("/events", web::events::routes())77 .nest("/events", web::events::routes())
77 .nest("/courses", web::courses::routes())78 .nest("/courses", web::courses::routes())
78 .nest("/exams", web::exams::routes())79 .nest("/exams", web::exams::routes())
80+ .nest("/marks", web::marks::routes())
79 .split_for_parts();81 .split_for_parts();
80 82
81 // Catch-all per-IP limit over every route (Swagger included). Kept inside83 // Catch-all per-IP limit over every route (Swagger included). Kept inside
src/web/marks.rsadded+176 -0
@@ -0,0 +1,176 @@
1+use std::collections::HashMap;
2+
3+use axum::Json;
4+use axum::extract::{Path, State};
5+use serde::Serialize;
6+use utoipa::ToSchema;
7+use utoipa_axum::router::OpenApiRouter;
8+use utoipa_axum::routes;
9+
10+use crate::database::Database;
11+use crate::domain::course::Course;
12+use crate::domain::exam::Exam;
13+use crate::domain::exam_result::ExamResult;
14+use crate::domain::user::{User, UserId};
15+use crate::error::{AppError, ErrorResponse};
16+use crate::state::AppState;
17+
18+use super::{CourseResponse, CurrentUser, RequireTeacher};
19+
20+pub fn routes() -> OpenApiRouter<AppState> {
21+ OpenApiRouter::new()
22+ .routes(routes!(my_marks))
23+ .routes(routes!(user_marks))
24+}
25+
26+/// One graded exam inside a course block of the report.
27+#[derive(Serialize, ToSchema)]
28+struct MarkEntry {
29+ /// Exam id.
30+ exam: String,
31+ title: String,
32+ kind: String,
33+ weight: i64,
34+ mark: i64,
35+ graded_by: String,
36+}
37+
38+/// A student's marks in one enrolled course.
39+#[derive(Serialize, ToSchema)]
40+struct CourseMarks {
41+ course: CourseResponse,
42+ /// Graded results only — ungraded exams don't appear.
43+ results: Vec<MarkEntry>,
44+ /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while
45+ /// nothing is graded.
46+ average: Option<f64>,
47+}
48+
49+/// A student's full mark report across their enrolled courses.
50+#[derive(Serialize, ToSchema)]
51+struct MarksReport {
52+ /// The student's user id.
53+ user: String,
54+ courses: Vec<CourseMarks>,
55+ /// Plain mean of the non-null course averages; `null` while no course has
56+ /// a graded exam.
57+ overall_average: Option<f64>,
58+}
59+
60+/// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The
61+/// zero-denominator guard is structural — `ExamWeight` already forbids 0.
62+fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {
63+ let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum();
64+ if total_weight == 0 {
65+ return None;
66+ }
67+ let total: i64 = pairs.iter().map(|(mark, weight)| mark * weight).sum();
68+ Some(total as f64 / total_weight as f64)
69+}
70+
71+/// Assemble the report: for each enrolled course, join the course's exams
72+/// (weights) with the user's graded results, then average.
73+async fn build_report(user: &UserId, db: &Database) -> Result<MarksReport, AppError> {
74+ let courses = Course::list_enrolled(user, db).await?;
75+
76+ let mut blocks = Vec::with_capacity(courses.len());
77+ for course in &courses {
78+ let exams = Exam::list_for_course(course.get_id(), db).await?;
79+ let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();
80+
81+ let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?;
82+ let mut entries = Vec::with_capacity(results.len());
83+ let mut pairs = Vec::with_capacity(results.len());
84+ for result in &results {
85+ // A result whose exam is gone cannot happen given the delete
86+ // cascade — skip defensively rather than corrupt the average.
87+ let Some(exam) = by_key.get(result.get_exam().key()) else {
88+ continue;
89+ };
90+ entries.push(MarkEntry {
91+ exam: exam.get_id().key().to_string(),
92+ title: exam.get_title().as_str().to_string(),
93+ kind: exam.get_kind().as_str().to_string(),
94+ weight: exam.get_weight().as_i64(),
95+ mark: result.get_mark().as_i64(),
96+ graded_by: result.get_graded_by().key().to_string(),
97+ });
98+ pairs.push((result.get_mark().as_i64(), exam.get_weight().as_i64()));
99+ }
100+
101+ blocks.push(CourseMarks {
102+ course: CourseResponse::new(course),
103+ average: weighted_average(&pairs),
104+ results: entries,
105+ });
106+ }
107+
108+ let averages: Vec<f64> = blocks.iter().filter_map(|block| block.average).collect();
109+ let overall_average =
110+ (!averages.is_empty()).then(|| averages.iter().sum::<f64>() / averages.len() as f64);
111+
112+ Ok(MarksReport {
113+ user: user.key().to_string(),
114+ courses: blocks,
115+ overall_average,
116+ })
117+}
118+
119+/// The current user's mark report: every enrolled course with its graded
120+/// exams, weighted course averages, and the overall average.
121+#[utoipa::path(
122+ get,
123+ path = "/me",
124+ tag = "marks",
125+ security(("session_cookie" = [])),
126+ responses(
127+ (status = 200, description = "The caller's mark report", body = MarksReport),
128+ (status = 401, description = "Not authenticated", body = ErrorResponse),
129+ ),
130+)]
131+async fn my_marks(
132+ State(st): State<AppState>,
133+ CurrentUser(user): CurrentUser,
134+) -> Result<Json<MarksReport>, AppError> {
135+ Ok(Json(build_report(user.get_id(), &st.db).await?))
136+}
137+
138+/// Any user's mark report. Requires teacher+.
139+#[utoipa::path(
140+ get,
141+ path = "/{user}",
142+ tag = "marks",
143+ security(("session_cookie" = [])),
144+ params(("user" = String, Path, description = "User id")),
145+ responses(
146+ (status = 200, description = "The user's mark report", body = MarksReport),
147+ (status = 401, description = "Not authenticated", body = ErrorResponse),
148+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
149+ (status = 404, description = "User not found", body = ErrorResponse),
150+ ),
151+)]
152+async fn user_marks(
153+ State(st): State<AppState>,
154+ _teacher: RequireTeacher,
155+ Path(user): Path<String>,
156+) -> Result<Json<MarksReport>, AppError> {
157+ let target = UserId::from_key(&user);
158+ // User must exist — a missing user is a 404, not an empty report.
159+ User::read(&target, &st.db)
160+ .await?
161+ .ok_or(AppError::NotFound)?;
162+ Ok(Json(build_report(&target, &st.db).await?))
163+}
164+
165+#[cfg(test)]
166+mod tests {
167+ use super::*;
168+
169+ #[tokio::test]
170+ async fn weighted_average_handles_empty_and_weights() {
171+ assert_eq!(weighted_average(&[]), None);
172+ assert_eq!(weighted_average(&[(70, 1)]), Some(70.0));
173+ // (50×1 + 90×3) / 4 = 80
174+ assert_eq!(weighted_average(&[(50, 1), (90, 3)]), Some(80.0));
175+ }
176+}
src/web/mod.rsmodified+1 -0
@@ -7,6 +7,7 @@ pub mod auth;
7 pub mod courses;7 pub mod courses;
8 pub mod events;8 pub mod events;
9 pub mod exams;9 pub mod exams;
10+pub mod marks;
10 pub mod notes;11 pub mod notes;
11 pub mod users;12 pub mod users;
12 13