forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB466ea10Ahmet Kaan Gümüş2 months ago341 commits

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