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

academic_year.rs238 lines, 9.9 KiBHistoryRawDownload
1//! The `academic_year` table: the row mint, the paged calendar listing, the
2//! field-scoped PATCH whose `WHERE` re-checks the merged range, and the 0/0
3//! delete guard.
4//!
5//! The year is the top of the academic calendar (D3): a section belongs to a
6//! year and a term ([`crate::db::term`]) is a grading slice inside it. Its two
7//! counters are the delete guard — a year that still carries a section or a
8//! term is refused outright, because dropping it silently would strand the
9//! year's structure. The rollover that reads and writes the sections lives one
10//! layer up ([`crate::service::academic_year::rollover`]).
11
12use sqlx::types::Json;
13
14use crate::database::Database;
15use crate::db::page::PagedList;
16use crate::domain::academic_year::{
17 AcademicYear, AcademicYearId, AcademicYearName, GradePromotion,
18};
19use crate::domain::timestamp::Timestamp;
20use crate::domain::user::UserId;
21use crate::error::AppError;
22
23/// Mint one year. The creator is a foreign key: a gone account is the same
24/// `NotFound` the web layer's own read answers with, never an orphan row.
25pub async fn create(
26 db: &Database,
27 creator: &UserId,
28 name: AcademicYearName,
29 starts_at: Timestamp,
30 ends_at: Timestamp,
31 grade_promotions: Vec<GradePromotion>,
32) -> Result<AcademicYear, AppError> {
33 let promotions = Json(grade_promotions);
34 let created = sqlx::query_as!(
35 AcademicYear,
36 r#"INSERT INTO academic_year (id, name, starts_at, ends_at, creator, grade_promotions)
37 VALUES ($1, $2, $3, $4, $5, $6)
38 RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName",
39 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
40 archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
41 grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
42 class_count, term_count"#,
43 AcademicYearId::generate().uuid(),
44 name.as_str(),
45 starts_at.as_millis(),
46 ends_at.as_millis(),
47 creator.uuid(),
48 promotions as _,
49 )
50 .fetch_one(db)
51 .await;
52 match created {
53 Ok(year) => Ok(year),
54 Err(err) if crate::database::foreign_key_violation(&err) => Err(AppError::NotFound),
55 // The name carries a UNIQUE constraint; a duplicate is a legacy-year
56 // naming clash. The web layer pre-checks it and answers 409 with a
57 // readable message, so reaching here is a race — reported as the same
58 // conflict rather than a 500.
59 Err(err) if crate::database::unique_violation(&err).is_some() => Err(AppError::Conflict(
60 "an academic year with that name already exists",
61 )),
62 Err(err) => Err(err.into()),
63 }
64}
65
66pub async fn read(db: &Database, id: &AcademicYearId) -> Result<Option<AcademicYear>, AppError> {
67 let year = sqlx::query_as!(
68 AcademicYear,
69 r#"SELECT id AS "id: AcademicYearId", name AS "name: AcademicYearName",
70 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
71 archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
72 grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
73 class_count, term_count
74 FROM academic_year WHERE id = $1"#,
75 id.uuid(),
76 )
77 .fetch_optional(db)
78 .await?;
79 Ok(year)
80}
81
82/// Every year, newest first — the calendar is small by nature.
83pub async fn list_all(
84 db: &Database,
85 limit: Option<i64>,
86 offset: i64,
87) -> Result<(Vec<AcademicYear>, i64), AppError> {
88 PagedList::new("academic_year", "ORDER BY starts_at DESC, id DESC")
89 .run::<AcademicYear>(limit, offset, db)
90 .await
91}
92
93/// Write only the fields the PATCH carried — `None` means the request omitted
94/// it, so the column keeps the value it holds rather than being re-stated from
95/// the snapshot the handler read. Every column here is non-clearable, so
96/// `COALESCE` is the whole rule: absent = keep.
97///
98/// The merged range is re-checked by the `WHERE` (`ends_at > starts_at` on the
99/// values this write will leave behind), so two PATCHes each moving one end
100/// cannot commit an inverted year between them. `Err(NotFound)` when the row
101/// is gone.
102pub async fn update(
103 db: &Database,
104 id: &AcademicYearId,
105 name: Option<AcademicYearName>,
106 starts_at: Option<Timestamp>,
107 ends_at: Option<Timestamp>,
108 grade_promotions: Option<Vec<GradePromotion>>,
109) -> Result<AcademicYear, AppError> {
110 let promotions = grade_promotions.map(Json);
111 let starts_millis = starts_at.map(|at| at.as_millis());
112 let ends_millis = ends_at.map(|at| at.as_millis());
113 let updated = sqlx::query_as!(
114 AcademicYear,
115 r#"UPDATE academic_year
116 SET name = COALESCE($2, name),
117 starts_at = COALESCE($3, starts_at),
118 ends_at = COALESCE($4, ends_at),
119 grade_promotions = COALESCE($5, grade_promotions)
120 WHERE id = $1
121 AND COALESCE($4, ends_at) > COALESCE($3, starts_at)
122 RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName",
123 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
124 archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
125 grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
126 class_count, term_count"#,
127 id.uuid(),
128 name.as_ref().map(AcademicYearName::as_str),
129 starts_millis,
130 ends_millis,
131 promotions as _,
132 )
133 .fetch_optional(db)
134 .await?;
135 match updated {
136 Some(year) => Ok(year),
137 // Either the row is gone or the merged range is inverted — the same
138 // shape the caller's own pre-flight range check answers, one instant
139 // later. Only the refusal path pays for the read that tells them
140 // apart.
141 None => match read(db, id).await? {
142 Some(_) => Err(AppError::Validation(
143 crate::error::ValidationError::Invalid {
144 field: "ends_at",
145 reason: "must be after starts_at",
146 },
147 )),
148 None => Err(AppError::NotFound),
149 },
150 }
151}
152
153/// Archive the year — the stamp that turns the whole year read-only. Idempotent
154/// by construction: the `WHERE` only matches an open row, so a repeat archive
155/// writes nothing and the *original* stamp stands — the year is never re-dated
156/// by a double click. `None` says this write landed on nothing: the row was
157/// already archived, or it is gone. The store does not tell those apart; the
158/// caller holds the row it read (the service layer) and only a race pays for
159/// the read that would.
160pub async fn archive(db: &Database, id: &AcademicYearId) -> Result<Option<AcademicYear>, AppError> {
161 let written = sqlx::query_as!(
162 AcademicYear,
163 r#"UPDATE academic_year SET archived_at = $2
164 WHERE id = $1 AND archived_at IS NULL
165 RETURNING id AS "id: AcademicYearId", name AS "name: AcademicYearName",
166 starts_at AS "starts_at: Timestamp", ends_at AS "ends_at: Timestamp",
167 archived_at AS "archived_at: Timestamp", creator AS "creator: UserId",
168 grade_promotions AS "grade_promotions: Json<Vec<GradePromotion>>",
169 class_count, term_count"#,
170 id.uuid(),
171 Timestamp::now().as_millis(),
172 )
173 .fetch_optional(db)
174 .await?;
175 Ok(written)
176}
177
178/// Delete the year, but only while no section and no term links it — nothing
179/// here unlinks or cascades. `false` = refused, nothing was written.
180///
181/// Both counts are read off the year's own row, so the check and the delete
182/// are one conditional write on one record: a class or term write racing this
183/// either claims first (and the delete is refused) or finds the row gone (and
184/// is refused itself). The referencing foreign keys (`class_group.year`,
185/// `term.year`, both `NO ACTION`) are the backstop behind the counters, not a
186/// second guard. The `Err(NotFound)` keeps the answer a concurrent *delete*
187/// used to get.
188pub async fn delete(db: &Database, year: AcademicYear) -> Result<bool, AppError> {
189 let gone = sqlx::query!(
190 r#"DELETE FROM academic_year
191 WHERE id = $1 AND class_count = 0 AND term_count = 0"#,
192 year.get_id().uuid(),
193 )
194 .execute(db)
195 .await?;
196 if gone.rows_affected() > 0 {
197 return Ok(true);
198 }
199 // Still linked or already gone: the one statement cannot tell those apart,
200 // and only the refusal path pays for the read that can.
201 match read(db, year.get_id()).await? {
202 Some(_) => Ok(false),
203 None => Err(AppError::NotFound),
204 }
205}
206
207/// A real academic year for the fixtures of the tables that hang off one: a
208/// term ([`crate::db::term::a_test_term`]) and, through it, every exam. Minted
209/// per call — the name is unique — with a creator that is a real `app_user`
210/// row, because `creator` is a foreign key.
211#[cfg(test)]
212pub(crate) async fn a_test_year(db: &Database) -> AcademicYearId {
213 let creator = UserId::generate();
214 // The last six hex digits of the uuid, not a fixed-width byte range: a
215 // `key()` is 36 characters, so `[30..38]` — the range a `[30..]` suffix
216 // suggests — panics before the fixture ever reaches the store.
217 let suffix = &creator.key()[30..];
218 sqlx::query(
219 "INSERT INTO app_user (id, username, created_at, role) \
220 VALUES ($1, $2, 0, 'manager')",
221 )
222 .bind(creator.uuid())
223 .bind(format!("year-fixture-{suffix}"))
224 .execute(db)
225 .await
226 .unwrap();
227 let year = crate::db::academic_year::create(
228 db,
229 &creator,
230 AcademicYearName::try_new(&format!("year-{suffix}")).unwrap(),
231 Timestamp::from_millis(0),
232 Timestamp::from_millis(1),
233 Vec::new(),
234 )
235 .await
236 .unwrap();
237 *year.get_id()
238}