forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

sessions.rs399 lines, 17.0 KiBHistoryRawDownload
1use std::collections::HashMap;
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::{Path, Query};
6use axum::http::StatusCode;
7use serde::{Deserialize, Serialize};
8use utoipa::ToSchema;
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::database::Database;
13use crate::domain::attendance::AttendanceStatus;
14use crate::domain::class_course::ClassCourse;
15use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
16
17use crate::domain::role::Role;
18use crate::domain::session_attendance::{SessionAttendance, SessionAttendanceId};
19use crate::domain::timestamp::Timestamp;
20use crate::domain::user::{User, UserId};
21use crate::error::{AppError, ErrorResponse};
22use crate::service;
23use crate::service::instance::can_manage_instance;
24use crate::state::AppState;
25
26use super::instances::can_view_instance;
27use super::{
28 CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,
29 check_time_range, person_map, set_or_clear,
30};
31
32pub fn routes() -> OpenApiRouter<AppState> {
33 OpenApiRouter::new()
34 .routes(routes!(get_session, update_session, delete_session))
35 .routes(routes!(mark_roll_call, list_roll_call))
36 .routes(routes!(remove_roll_call))
37}
38
39#[derive(Deserialize, ToSchema)]
40struct UpdateSession {
41 #[schema(max_length = 200)]
42 topic: Option<String>,
43 /// Reassign the session's teacher. Omit to keep; must be teacher+.
44 teacher_id: Option<String>,
45 /// Unix-millisecond timestamp. Omit to keep the current value. A newly
46 /// set value must not be in the past.
47 starts_at: Option<i64>,
48 /// Unix-millisecond timestamp. Omit to keep the current value; send `null`
49 /// to clear it. A newly set value must not be in the past.
50 #[serde(default, deserialize_with = "set_or_clear")]
51 #[schema(value_type = Option<i64>)]
52 ends_at: Option<Option<i64>>,
53}
54
55#[derive(Deserialize, ToSchema)]
56struct MarkRollCall {
57 /// One of the school's attendance statuses (`GET /settings`; the core
58 /// four are `present`, `absent`, `late`, `excused`).
59 #[schema(max_length = 50, example = "present")]
60 status: String,
61 /// Whose roll-call state to record: an enrolled student, or the session's
62 /// teacher (the latter requires manager+).
63 user_id: String,
64}
65
66#[derive(Serialize, ToSchema)]
67struct SessionAttendanceResponse {
68 id: String,
69 session: String,
70 class_course: String,
71 /// Whose attendance this row records.
72 user: PersonRef,
73 status: String,
74 /// Who recorded it.
75 marked_by: PersonRef,
76}
77
78impl SessionAttendanceResponse {
79 fn new(attendance: &SessionAttendance, people: &HashMap<String, PersonRef>) -> Self {
80 Self {
81 id: SessionAttendanceId::composite(attendance.get_session(), attendance.get_user())
82 .key(),
83 session: attendance.get_session().key().to_string(),
84 class_course: attendance.get_class_course().key().to_string(),
85 user: PersonRef::resolve(people, attendance.get_user()),
86 status: attendance.get_status().as_str().to_string(),
87 marked_by: PersonRef::resolve(people, attendance.get_marked_by()),
88 }
89 }
90}
91
92/// Load a session and its instance together; a session whose instance is gone
93/// cannot happen given the delete cascade, so both misses are plain 404s.
94async fn session_with_instance(
95 id: &str,
96 db: &Database,
97) -> Result<(CourseSession, ClassCourse), AppError> {
98 let session = service::course_session::read(db, &CourseSessionId::from_key(id))
99 .await?
100 .ok_or(AppError::NotFound)?;
101 let instance = crate::service::class_course::read(db, session.get_class_course())
102 .await?
103 .ok_or(AppError::NotFound)?;
104 Ok((session, instance))
105}
106
107/// Whether `user` is the session's own teacher *and* still `teacher`+ today.
108///
109/// The `teacher` column is a historical fact like an instance's assignment (a
110/// demotion never rewrites past sessions), so teaching a session grants nothing
111/// once the account falls below `teacher` — see [`can_manage_instance`], which
112/// carries the same floor.
113fn is_live_session_teacher(session: &CourseSession, user: &User) -> bool {
114 user.get_role().at_least(Role::Teacher) && session.is_teacher(user.get_id())
115}
116
117/// Who may take (or amend) a session's roll call: the session's own teacher,
118/// or anyone who manages its instance (manager+, one of its teachers, or its
119/// section's homeroom teacher) — in both cases only while still `teacher`+.
120async fn can_roll_call(
121 session: &CourseSession,
122 instance: &ClassCourse,
123 user: &User,
124 db: &Database,
125) -> Result<bool, AppError> {
126 Ok(is_live_session_teacher(session, user)
127 || can_manage_instance(db, instance.get_id(), user).await?)
128}
129
130// ---- sessions -------------------------------------------------------------
131
132/// Fetch a single session by id. Visible to the instance's enrolled students, the
133/// session's own teacher, the instance's teachers, and managers/admins.
134#[utoipa::path(
135 get,
136 path = "/{id}",
137 tag = "sessions",
138 security(("session_cookie" = [])),
139 params(("id" = String, Path, description = "Session id")),
140 responses(
141 (status = 200, description = "The session", body = SessionResponse),
142 (status = 401, description = "Not authenticated", body = ErrorResponse),
143 (status = 403, description = "Not enrolled, not the session's teacher, and without instance rights", body = ErrorResponse),
144 (status = 404, description = "Not found", body = ErrorResponse),
145 ),
146)]
147async fn get_session(
148 State(st): State<AppState>,
149 CurrentUser(user): CurrentUser,
150 Path(id): Path<String>,
151) -> Result<Json<SessionResponse>, AppError> {
152 let (session, instance) = session_with_instance(&id, &st.db).await?;
153 if !is_live_session_teacher(&session, &user)
154 && !can_view_instance(&st.db, instance.get_id(), &user).await?
155 {
156 return Err(AppError::Forbidden(
157 "only the instance's enrolled students, the session's teacher, its teachers, or a manager/admin can view this session",
158 ));
159 }
160 let people = person_map([*session.get_teacher()], &st.db).await?;
161 Ok(Json(SessionResponse::new(&session, &people)))
162}
163
164/// Update a session. Requires teacher+ with instance-management rights. Omitted
165/// fields keep their value; an explicit `null` clears `ends_at`.
166#[utoipa::path(
167 patch,
168 path = "/{id}",
169 tag = "sessions",
170 security(("session_cookie" = [])),
171 params(("id" = String, Path, description = "Session id")),
172 request_body = UpdateSession,
173 responses(
174 (status = 200, description = "Updated session", body = SessionResponse),
175 (status = 400, description = "Invalid fields, time range, newly set times in the past, or teacher", body = ErrorResponse),
176 (status = 401, description = "Not authenticated", body = ErrorResponse),
177 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
178 (status = 404, description = "Not found", body = ErrorResponse),
179 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
180 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
181 ),
182)]
183async fn update_session(
184 State(st): State<AppState>,
185 RequireTeacher(user): RequireTeacher,
186 Path(id): Path<String>,
187 Json(req): Json<UpdateSession>,
188) -> Result<Json<SessionResponse>, AppError> {
189 // Only values this request sets are held to the no-past rule — a kept
190 // `starts_at` of a lesson already underway is legitimately past. A provided
191 // `ends_at` sets the field, an explicit `null` clears it, an omitted one is
192 // left alone.
193 let starts_at = req.starts_at.map(Timestamp::from_millis);
194 check_not_past("starts_at", starts_at)?;
195 let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
196 if let Some(ends_at) = ends_at {
197 check_not_past("ends_at", ends_at)?;
198 }
199 let (session, instance) = session_with_instance(&id, &st.db).await?;
200 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
201 return Err(AppError::Forbidden(
202 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can edit this session",
203 ));
204 }
205 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
206
207 let topic = req
208 .topic
209 .as_deref()
210 .map(SessionTopic::try_new)
211 .transpose()?;
212 let teacher = match req.teacher_id {
213 Some(ref key) => Some(
214 *service::course_session::resolve_session_teacher(Some(key), &user, &st.db)
215 .await?
216 .get_id(),
217 ),
218 None => None,
219 };
220 // The end this request left out is only *read* for the range check — it is
221 // never written back, so a concurrent move of it survives. Pre-flight only:
222 // the write's own `WHERE` re-makes this check (the db layer's `update`).
223 check_time_range(
224 Some(starts_at.unwrap_or_else(|| session.get_starts_at())),
225 ends_at.unwrap_or_else(|| session.get_ends_at()),
226 )?;
227
228 let updated =
229 service::course_session::update(&st.db, session, teacher, topic, starts_at, ends_at)
230 .await?;
231 let people = person_map([*updated.get_teacher()], &st.db).await?;
232 Ok(Json(SessionResponse::new(&updated, &people)))
233}
234
235/// Delete a session and its roll-call rows. Requires teacher+ with
236/// instance-management rights.
237#[utoipa::path(
238 delete,
239 path = "/{id}",
240 tag = "sessions",
241 security(("session_cookie" = [])),
242 params(("id" = String, Path, description = "Session id")),
243 responses(
244 (status = 204, description = "Deleted"),
245 (status = 401, description = "Not authenticated", body = ErrorResponse),
246 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
247 (status = 404, description = "Not found", body = ErrorResponse),
248 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
249 ),
250)]
251async fn delete_session(
252 State(st): State<AppState>,
253 RequireTeacher(user): RequireTeacher,
254 Path(id): Path<String>,
255) -> Result<StatusCode, AppError> {
256 let (session, instance) = session_with_instance(&id, &st.db).await?;
257 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
258 return Err(AppError::Forbidden(
259 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can delete this session",
260 ));
261 }
262 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
263 service::course_session::delete(&st.db, session).await?;
264 Ok(StatusCode::NO_CONTENT)
265}
266
267// ---- roll call --------------------------------------------------------------
268
269/// Record a user's roll-call state for a session. The session's teacher or a
270/// manager of its instance marks **enrolled students** (only students attend
271/// classes); marking the **session's teacher** requires manager+ (staff
272/// presence is management's call, so a teacher can't mark themselves present).
273/// Students never self-mark a lesson.
274#[utoipa::path(
275 post,
276 path = "/{id}/attendance",
277 tag = "sessions",
278 security(("session_cookie" = [])),
279 params(("id" = String, Path, description = "Session id")),
280 request_body = MarkRollCall,
281 responses(
282 (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse),
283 (status = 400, description = "Invalid status, unknown user, target not a student, or not on the roster", body = ErrorResponse),
284 (status = 401, description = "Not authenticated", body = ErrorResponse),
285 (status = 403, description = "Not the session's teacher or a manager of its instance; or marking the teacher without manager+", body = ErrorResponse),
286 (status = 404, description = "Session not found", body = ErrorResponse),
287 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
288 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
289 ),
290)]
291async fn mark_roll_call(
292 State(st): State<AppState>,
293 RequireTeacher(user): RequireTeacher,
294 Path(id): Path<String>,
295 Json(req): Json<MarkRollCall>,
296) -> Result<Json<SessionAttendanceResponse>, AppError> {
297 let (session, instance) = session_with_instance(&id, &st.db).await?;
298 if !can_roll_call(&session, &instance, &user, &st.db).await? {
299 return Err(AppError::Forbidden(
300 "only the session's teacher or a manager of its instance can take roll call",
301 ));
302 }
303 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
304
305 let school = service::settings::load(&st.db).await?;
306 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;
307 let target = UserId::from_key(&req.user_id);
308
309 let (attendance, target_user) =
310 service::session_attendance::mark(&st.db, &session, &user, &target, status).await?;
311 let people = PersonRef::map_of(&[&target_user, &user]);
312 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))
313}
314
315/// List a session's roll call, paged via `?limit=&offset=` (omit `limit` for
316/// the whole roster). Same rights as taking it: the session's teacher or a
317/// manager of its instance — students see their own tallies via
318/// `GET /attendance/me`.
319/// Returns a `{items, total, limit, offset}` envelope.
320#[utoipa::path(
321 get,
322 path = "/{id}/attendance",
323 tag = "sessions",
324 security(("session_cookie" = [])),
325 params(("id" = String, Path, description = "Session id"), PageParams),
326 responses(
327 (status = 200, description = "A page of the roll-call roster (all of it when unpaged)", body = Page<SessionAttendanceResponse>),
328 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
329 (status = 401, description = "Not authenticated", body = ErrorResponse),
330 (status = 403, description = "Not the session's teacher or a manager of its instance", body = ErrorResponse),
331 (status = 404, description = "Session not found", body = ErrorResponse),
332 ),
333)]
334async fn list_roll_call(
335 State(st): State<AppState>,
336 RequireTeacher(user): RequireTeacher,
337 Path(id): Path<String>,
338 Query(page): Query<PageParams>,
339) -> Result<Json<Page<SessionAttendanceResponse>>, AppError> {
340 let (limit, offset) = page.resolve()?;
341 let (session, instance) = session_with_instance(&id, &st.db).await?;
342 if !can_roll_call(&session, &instance, &user, &st.db).await? {
343 return Err(AppError::Forbidden(
344 "only the session's teacher or a manager of its instance can list the roll call",
345 ));
346 }
347 let (rows, total) =
348 service::session_attendance::list_for_session(&st.db, session.get_id(), limit, offset)
349 .await?;
350 // Join people onto the page alone — the lookup shrinks with the window.
351 let people = person_map(
352 rows.iter()
353 .flat_map(|a| [*a.get_user(), *a.get_marked_by()]),
354 &st.db,
355 )
356 .await?;
357 let items = rows
358 .iter()
359 .map(|a| SessionAttendanceResponse::new(a, &people))
360 .collect();
361 Ok(Json(Page::new(items, total, limit, offset)))
362}
363
364/// Remove a user's roll-call row from a session. Same rights as marking:
365/// the session's teacher or a manager of its instance for students, manager+
366/// for a staff row (any target holding teacher or higher).
367#[utoipa::path(
368 delete,
369 path = "/{id}/attendance/{user}",
370 tag = "sessions",
371 security(("session_cookie" = [])),
372 params(
373 ("id" = String, Path, description = "Session id"),
374 ("user" = String, Path, description = "User id"),
375 ),
376 responses(
377 (status = 204, description = "Removed"),
378 (status = 401, description = "Not authenticated", body = ErrorResponse),
379 (status = 403, description = "Not the session's teacher or a manager of its instance; or removing a staff row without manager+", body = ErrorResponse),
380 (status = 404, description = "Not found", body = ErrorResponse),
381 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
382 ),
383)]
384async fn remove_roll_call(
385 State(st): State<AppState>,
386 RequireTeacher(user): RequireTeacher,
387 Path((id, target)): Path<(String, String)>,
388) -> Result<StatusCode, AppError> {
389 let (session, instance) = session_with_instance(&id, &st.db).await?;
390 if !can_roll_call(&session, &instance, &user, &st.db).await? {
391 return Err(AppError::Forbidden(
392 "only the session's teacher or a manager of its instance can take roll call",
393 ));
394 }
395 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
396 let target = UserId::from_key(&target);
397 service::session_attendance::remove(&st.db, &session, &user, &target).await?;
398 Ok(StatusCode::NO_CONTENT)
399}