forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB0346717Ahmet Kaan Gümüş3 months ago230 commits

work.rs240 lines, 9.5 KiBHistoryRawDownload
1use axum::Json;
2use axum::extract::{Path, Query, State};
3use axum::http::StatusCode;
4use serde::{Deserialize, Serialize};
5use utoipa::ToSchema;
6use utoipa_axum::router::OpenApiRouter;
7use utoipa_axum::routes;
8
9use crate::domain::timestamp::Timestamp;
10use crate::domain::user::{User, UserId};
11use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
12use crate::error::{AppError, ErrorResponse};
13use crate::state::AppState;
14
15use super::{Page, PageParams, RequireManager, RequireTeacher};
16
17pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new()
19 .routes(routes!(check_in))
20 .routes(routes!(check_out))
21 .routes(routes!(my_work))
22 .routes(routes!(user_work))
23 .routes(routes!(update_entry, delete_entry))
24}
25
26#[derive(Deserialize, ToSchema)]
27struct UpdateWorkEntry {
28 /// Corrected check-in, UTC unix-milliseconds. Omit to keep.
29 check_in: Option<i64>,
30 /// Corrected check-out, UTC unix-milliseconds. Omit to keep.
31 check_out: Option<i64>,
32}
33
34#[derive(Serialize, ToSchema)]
35struct WorkEntryResponse {
36 id: String,
37 /// The staff member this stint belongs to.
38 user: String,
39 /// Stint start, UTC unix-milliseconds (server-stamped).
40 check_in: i64,
41 /// Stint end, UTC unix-milliseconds; `null` while still checked in.
42 check_out: Option<i64>,
43 /// `check_out - check_in`; `null` while still checked in.
44 duration_ms: Option<i64>,
45}
46
47impl WorkEntryResponse {
48 fn new(entry: &WorkEntry) -> Self {
49 let check_in = entry.get_check_in().as_millis();
50 let check_out = entry.get_check_out().map(|t| t.as_millis());
51 Self {
52 id: entry.get_id().key().to_string(),
53 user: entry.get_user().key().to_string(),
54 check_in,
55 check_out,
56 // Saturating: manager-corrected instants are arbitrary i64s, and
57 // an absurdly wide pair must cap the duration, not overflow it.
58 duration_ms: check_out.map(|out| out.saturating_sub(check_in)),
59 }
60 }
61}
62
63/// Check in for work. Requires teacher+ (staff). The instant is stamped by the
64/// server clock — clients never supply it. `409` while already checked in.
65#[utoipa::path(
66 post,
67 path = "/check-in",
68 tag = "work",
69 security(("session_cookie" = [])),
70 responses(
71 (status = 201, description = "Checked in — the open stint", body = WorkEntryResponse),
72 (status = 401, description = "Not authenticated", body = ErrorResponse),
73 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
74 (status = 409, description = "Already checked in", body = ErrorResponse),
75 ),
76)]
77async fn check_in(
78 State(st): State<AppState>,
79 RequireTeacher(user): RequireTeacher,
80) -> Result<(StatusCode, Json<WorkEntryResponse>), AppError> {
81 let entry = WorkEntry::check_in(user.get_id(), &st.db).await?;
82 Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry))))
83}
84
85/// Check out of work, closing the open stint. Requires teacher+ (staff). The
86/// instant is stamped by the server clock. `409` when not checked in.
87#[utoipa::path(
88 post,
89 path = "/check-out",
90 tag = "work",
91 security(("session_cookie" = [])),
92 responses(
93 (status = 200, description = "Checked out — the closed stint", body = WorkEntryResponse),
94 (status = 401, description = "Not authenticated", body = ErrorResponse),
95 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
96 (status = 409, description = "Not checked in", body = ErrorResponse),
97 ),
98)]
99async fn check_out(
100 State(st): State<AppState>,
101 RequireTeacher(user): RequireTeacher,
102) -> Result<Json<WorkEntryResponse>, AppError> {
103 let entry = WorkEntry::check_out(user.get_id(), &st.db).await?;
104 Ok(Json(WorkEntryResponse::new(&entry)))
105}
106
107/// The caller's own work log, newest first — the open stint (if any) included
108/// (`check_out: null`). Paged via `?limit=&offset=` (omit `limit` for the whole
109/// log). Requires teacher+ (staff). Returns a `{items, total, limit, offset}`
110/// envelope.
111#[utoipa::path(
112 get,
113 path = "/me",
114 tag = "work",
115 security(("session_cookie" = [])),
116 params(PageParams),
117 responses(
118 (status = 200, description = "A page of the caller's work log (the whole log when unpaged)", body = Page<WorkEntryResponse>),
119 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
120 (status = 401, description = "Not authenticated", body = ErrorResponse),
121 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
122 ),
123)]
124async fn my_work(
125 State(st): State<AppState>,
126 RequireTeacher(user): RequireTeacher,
127 Query(page): Query<PageParams>,
128) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
129 let (limit, offset) = page.resolve()?;
130 let (entries, total) = WorkEntry::list_for_user(user.get_id(), limit, offset, &st.db).await?;
131 let items = entries.iter().map(WorkEntryResponse::new).collect();
132 Ok(Json(Page::new(items, total, limit, offset)))
133}
134
135/// A staff member's work log, newest first, paged via `?limit=&offset=` (omit
136/// `limit` for the whole log). Requires manager+. Returns a
137/// `{items, total, limit, offset}` envelope.
138#[utoipa::path(
139 get,
140 path = "/{user}",
141 tag = "work",
142 security(("session_cookie" = [])),
143 params(("user" = String, Path, description = "User id"), PageParams),
144 responses(
145 (status = 200, description = "A page of the user's work log (the whole log when unpaged)", body = Page<WorkEntryResponse>),
146 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
147 (status = 401, description = "Not authenticated", body = ErrorResponse),
148 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
149 (status = 404, description = "User not found", body = ErrorResponse),
150 ),
151)]
152async fn user_work(
153 State(st): State<AppState>,
154 _manager: RequireManager,
155 Path(user): Path<String>,
156 Query(page): Query<PageParams>,
157) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
158 let (limit, offset) = page.resolve()?;
159 let target = UserId::from_key(&user);
160 // User must exist — a missing user is a 404, not an empty log.
161 User::read(&target, &st.db)
162 .await?
163 .ok_or(AppError::NotFound)?;
164 let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?;
165 let items = entries.iter().map(WorkEntryResponse::new).collect();
166 Ok(Json(Page::new(items, total, limit, offset)))
167}
168
169/// Correct a closed stint's instants. Requires manager+. An open stint can't
170/// be corrected (`409`) — it has no end yet; check out first (or delete it).
171#[utoipa::path(
172 patch,
173 path = "/entries/{id}",
174 tag = "work",
175 security(("session_cookie" = [])),
176 params(("id" = String, Path, description = "Work entry id")),
177 request_body = UpdateWorkEntry,
178 responses(
179 (status = 200, description = "Corrected entry", body = WorkEntryResponse),
180 (status = 400, description = "check_out precedes check_in", body = ErrorResponse),
181 (status = 401, description = "Not authenticated", body = ErrorResponse),
182 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
183 (status = 404, description = "Not found", body = ErrorResponse),
184 (status = 409, description = "Entry is still open", body = ErrorResponse),
185 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
186 ),
187)]
188async fn update_entry(
189 State(st): State<AppState>,
190 _manager: RequireManager,
191 Path(id): Path<String>,
192 Json(req): Json<UpdateWorkEntry>,
193) -> Result<Json<WorkEntryResponse>, AppError> {
194 let check_in = req.check_in.map(Timestamp::from_millis);
195 let check_out = req.check_out.map(Timestamp::from_millis);
196 let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)
197 .await?
198 .ok_or(AppError::NotFound)?;
199 let Some(current_out) = entry.get_check_out() else {
200 return Err(AppError::Conflict(
201 "entry is still open — check out first, or delete it",
202 ));
203 };
204
205 // The side the correction left out is only *read* for the ordering check —
206 // it is never written back, so a concurrent correction of it survives.
207 // Pre-flight only: `WorkEntry::update` re-makes this in the UPDATE's `WHERE`.
208 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {
209 return Err(out_before_in_error());
210 }
211
212 let updated = entry.update(check_in, check_out, &st.db).await?;
213 Ok(Json(WorkEntryResponse::new(&updated)))
214}
215
216/// Delete a work entry (open or closed). Requires manager+.
217#[utoipa::path(
218 delete,
219 path = "/entries/{id}",
220 tag = "work",
221 security(("session_cookie" = [])),
222 params(("id" = String, Path, description = "Work entry id")),
223 responses(
224 (status = 204, description = "Deleted"),
225 (status = 401, description = "Not authenticated", body = ErrorResponse),
226 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
227 (status = 404, description = "Not found", body = ErrorResponse),
228 ),
229)]
230async fn delete_entry(
231 State(st): State<AppState>,
232 _manager: RequireManager,
233 Path(id): Path<String>,
234) -> Result<StatusCode, AppError> {
235 let removed = WorkEntry::remove(&WorkEntryId::from_key(&id), &st.db).await?;
236 if removed.is_none() {
237 return Err(AppError::NotFound);
238 }
239 Ok(StatusCode::NO_CONTENT)
240}