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

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