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

term.rs148 lines, 4.3 KiBHistoryRawDownload
1use sqlx::Type;
2use uuid::Uuid;
3
4use crate::constant::MAX_TERM_NAME_LEN;
5use crate::domain::academic_year::AcademicYearId;
6use crate::domain::monotonic_id::next_uuid;
7use crate::domain::timestamp::Timestamp;
8use crate::error::{AppError, ValidationError};
9use crate::validate::validate_required;
10
11/// Typed term row id. A UUIDv7 minted by the process-wide monotonic
12/// generator, so `id` order is mint order.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
14#[sqlx(transparent)]
15pub struct TermId(Uuid);
16
17impl TermId {
18 /// Minted from the process-wide monotonic generator, not a random v4:
19 /// terms sort `starts_at DESC, id DESC` and the id breaks the tie between
20 /// two terms starting at the same instant,
21 /// and a random low half sorts arbitrarily inside one millisecond.
22 pub fn generate() -> Self {
23 Self(next_uuid())
24 }
25
26 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
27 /// cannot take the newtype. Static `query!` binds take `self` directly.
28 pub fn uuid(&self) -> Uuid {
29 self.0
30 }
31
32 /// Parse a wire key. A key that parses as no UUID — a malformed path
33 /// segment — reads as the nil id, which matches no row: exactly the 404 a
34 /// dangling record key produced under the old store, without turning a
35 /// typo into a panic.
36 pub fn from_key(key: &str) -> Self {
37 Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
38 }
39
40 /// The hyphenated wire form.
41 pub fn key(&self) -> String {
42 self.0.to_string()
43 }
44}
45pub fn gone_error() -> AppError {
46 AppError::Validation(ValidationError::Invalid {
47 field: "term_id",
48 reason: "term does not exist",
49 })
50}
51
52/// The refusal every write against archived structure gets, coded so a client
53/// can tell it from the other 409s on the same route.
54pub fn archived_error() -> AppError {
55 AppError::ConflictCoded {
56 code: "term_archived",
57 message: "this term is archived — past years are read-only".into(),
58 }
59}
60
61/// What a PATCH's `term` field owes the refcounts: the term to claim, and the
62/// one to give back. Covers all three moves — set (none→some), move
63/// (some→other) and clear (some→none) — and moves nothing for a PATCH that
64/// omitted the field or re-stated the link it already had.
65pub fn ref_move(
66 current: Option<&TermId>,
67 patch: &Option<Option<TermId>>,
68) -> (Option<TermId>, Option<TermId>) {
69 match patch {
70 None => (None, None),
71 Some(next) if next.as_ref() == current => (None, None),
72 Some(next) => (*next, current.copied()),
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
77#[sqlx(transparent)]
78pub struct TermName(String);
79
80impl TermName {
81 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
82 validate_required("name", value, MAX_TERM_NAME_LEN)?;
83 Ok(Self(value.to_string()))
84 }
85
86 pub fn as_str(&self) -> &str {
87 &self.0
88 }
89}
90
91/// One term on the school's academic calendar. Both ends are required — a
92/// term is a date range by definition.
93#[derive(Debug, Clone, sqlx::FromRow)]
94pub struct Term {
95 pub(crate) id: TermId,
96 /// The academic year this term is a grading slice of.
97 pub(crate) year: AcademicYearId,
98 pub(crate) name: TermName,
99 pub(crate) starts_at: Timestamp,
100 pub(crate) ends_at: Timestamp,
101 /// When a manager archived this term; `None` = open. The column is
102 /// nullable, so a term that predates archiving reads exactly like an
103 /// open one.
104 pub(crate) archived_at: Option<Timestamp>,
105}
106
107impl Term {
108 pub fn get_id(&self) -> &TermId {
109 &self.id
110 }
111
112 pub fn get_year(&self) -> &AcademicYearId {
113 &self.year
114 }
115
116 pub fn get_name(&self) -> &TermName {
117 &self.name
118 }
119
120 pub fn get_starts_at(&self) -> Timestamp {
121 self.starts_at
122 }
123
124 pub fn get_ends_at(&self) -> Timestamp {
125 self.ends_at
126 }
127
128 pub fn get_archived_at(&self) -> Option<Timestamp> {
129 self.archived_at
130 }
131
132 pub fn is_archived(&self) -> bool {
133 self.archived_at.is_some()
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[tokio::test]
142 async fn name_is_required_and_bounded() {
143 assert!(TermName::try_new("2026 Fall").is_ok());
144 assert!(TermName::try_new("").is_err());
145 assert!(TermName::try_new(" ").is_err());
146 assert!(TermName::try_new(&"x".repeat(101)).is_err());
147 }
148}