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

event.rs326 lines, 11.3 KiBHistoryRawDownload
1use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
2use crate::domain::class_group::ClassGroupId;
3use crate::domain::course::CourseId;
4use crate::domain::monotonic_id::next_uuid;
5use crate::domain::role::Role;
6use crate::domain::timestamp::Timestamp;
7use crate::domain::user::UserId;
8use crate::error::{AppError, ValidationError};
9use crate::validate::{validate_optional, validate_required};
10
11#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
12#[sqlx(transparent)]
13pub struct EventId(uuid::Uuid);
14
15impl EventId {
16 /// Minted from the process-wide monotonic generator, not a plain random
17 /// UUID: events list `id DESC` (newest first,
18 /// [`crate::db::event::list_windowed`]),
19 /// and a random low half scrambles rows minted in the same millisecond.
20 pub fn generate() -> Self {
21 Self(next_uuid())
22 }
23
24 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
25 /// cannot take the newtype. Static `query!` binds take `self` directly.
26 pub fn uuid(&self) -> uuid::Uuid {
27 self.0
28 }
29
30 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
31 /// which matches no row.
32 pub fn from_key(key: &str) -> Self {
33 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
34 }
35
36 pub fn key(&self) -> String {
37 self.0.to_string()
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
42#[sqlx(transparent)]
43pub struct EventTitle(String);
44
45impl EventTitle {
46 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
47 validate_required("title", value, MAX_EVENT_TITLE_LEN)?;
48 Ok(Self(value.to_string()))
49 }
50
51 pub fn as_str(&self) -> &str {
52 &self.0
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
57#[sqlx(transparent)]
58pub struct EventDescription(String);
59
60impl EventDescription {
61 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
62 validate_optional("description", value, MAX_EVENT_DESCRIPTION_LEN)?;
63 Ok(Self(value.to_string()))
64 }
65
66 pub fn as_str(&self) -> &str {
67 &self.0
68 }
69}
70
71/// Which shape of expected-attendee roster the event carries — the `kind`
72/// discriminant of the old tagged value, now a flat column. Membership is
73/// resolved live against today's users/enrollments/registrations — never
74/// snapshotted — so a role change, (un)enrollment, or (un)registration moves
75/// people in and out of rosters by itself. The audience does not gate *seeing*
76/// the event (the calendar stays school-visible); it defines who counts as
77/// expected and who may be marked.
78///
79/// The payload lives in the sibling columns: `audience_role` for
80/// [`EventAudienceKind::Role`], `audience_course` for
81/// [`EventAudienceKind::Course`], `audience_class` for
82/// [`EventAudienceKind::Class`], `audience_capacity` for
83/// [`EventAudienceKind::Registration`]. A `School` event carries none.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
85#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
86pub enum EventAudienceKind {
87 /// Everybody — the pre-audience behavior.
88 School,
89 /// Every user holding exactly this role ("all students", "all teachers").
90 Role,
91 /// A course's enrolled students. Staff running the course are not implied
92 /// members — a mixed gathering wants a registration or role audience.
93 Course,
94 /// A class section's students, read live off `class_member` — the same live
95 /// resolution `Course` and `Role` get, so adding a student to the
96 /// class puts them on every one of its events' rosters at once. The
97 /// homeroom teacher is not implied, matching `Course`. A deleted class
98 /// leaves the event standing with an empty roster, exactly as a deleted
99 /// course does (`Course::delete` never touches `event`).
100 Class,
101 /// A signup list built one person at a time through the register
102 /// endpoints — teachers place students, staff take their own seat. The
103 /// list is capped at the `audience_capacity` seats when set (`NULL` =
104 /// unlimited) and closes once the event starts. Rows survive an audience
105 /// change inertly.
106 Registration,
107}
108
109/// Who an event is aimed at, as one flat row. The five audience columns
110/// (kind + payload) are exactly the `audience_*` columns of the migration;
111/// every write goes through one validated shape, so only the payload matching
112/// `audience_kind` is ever non-NULL.
113#[derive(Debug, Clone, sqlx::FromRow)]
114pub struct Event {
115 pub(crate) id: EventId,
116 pub(crate) creator: UserId,
117 pub(crate) title: EventTitle,
118 pub(crate) description: EventDescription,
119 pub(crate) audience_kind: EventAudienceKind,
120 pub(crate) audience_role: Option<Role>,
121 pub(crate) audience_course: Option<CourseId>,
122 pub(crate) audience_class: Option<ClassGroupId>,
123 pub(crate) audience_capacity: Option<i64>,
124 pub(crate) starts_at: Option<Timestamp>,
125 pub(crate) ends_at: Option<Timestamp>,
126}
127
128impl EventAudienceKind {
129 /// The wire/storage spelling. Must stay in lockstep with `rename_all` —
130 /// the web layer publishes these as the audience `kind`.
131 pub fn as_str(self) -> &'static str {
132 match self {
133 EventAudienceKind::School => "school",
134 EventAudienceKind::Role => "role",
135
136 EventAudienceKind::Course => "course",
137 EventAudienceKind::Class => "class",
138 EventAudienceKind::Registration => "registration",
139 }
140 }
141}
142
143/// The five audience columns as one value — the write-side bundle. The row
144/// keeps them flat; every write spells them as a unit, so a kind and its
145/// payload always land together and only the payload matching `kind` is
146/// ever non-NULL.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct EventAudience {
149 pub kind: EventAudienceKind,
150 pub role: Option<Role>,
151 pub course: Option<CourseId>,
152 pub class: Option<ClassGroupId>,
153 pub capacity: Option<i64>,
154}
155
156impl EventAudience {
157 /// The audience of a row read back from the store.
158 pub fn of_row(event: &Event) -> Self {
159 Self {
160 kind: event.get_audience_kind(),
161 role: event.get_audience_role(),
162 course: event.get_audience_course().cloned(),
163 class: event.get_audience_class().cloned(),
164 capacity: event.get_audience_capacity(),
165 }
166 }
167}
168
169impl Event {
170 pub fn get_id(&self) -> &EventId {
171 &self.id
172 }
173
174 pub fn get_creator(&self) -> &UserId {
175 &self.creator
176 }
177
178 pub fn get_title(&self) -> &EventTitle {
179 &self.title
180 }
181
182 pub fn get_description(&self) -> &EventDescription {
183 &self.description
184 }
185
186 /// Which audience shape the event carries; the payload sits in the
187 /// matching sibling column.
188 pub fn get_audience_kind(&self) -> EventAudienceKind {
189 self.audience_kind
190 }
191
192 pub fn get_audience_role(&self) -> Option<Role> {
193 self.audience_role
194 }
195
196 pub fn get_audience_course(&self) -> Option<&CourseId> {
197 self.audience_course.as_ref()
198 }
199
200 pub fn get_audience_class(&self) -> Option<&ClassGroupId> {
201 self.audience_class.as_ref()
202 }
203
204 pub fn get_audience_capacity(&self) -> Option<i64> {
205 self.audience_capacity
206 }
207
208 pub fn get_starts_at(&self) -> Option<Timestamp> {
209 self.starts_at
210 }
211
212 pub fn get_ends_at(&self) -> Option<Timestamp> {
213 self.ends_at
214 }
215
216 pub fn is_creator(&self, user: &UserId) -> bool {
217 &self.creator == user
218 }
219
220 /// The shared gate for touching a signup list: the event must carry the
221 /// registration audience, and the list must still be open — it closes the
222 /// moment the event starts, or, for an ends_at-only event (a pure signup
223 /// deadline), the moment that end passes (a truly timeless event never
224 /// closes). Returns the seat cap for the register path.
225 pub fn registration_capacity(&self) -> Result<Option<i64>, AppError> {
226 if self.audience_kind != EventAudienceKind::Registration {
227 return Err(AppError::Validation(ValidationError::Invalid {
228 field: "audience",
229 reason: "this event does not take registrations",
230 }));
231 }
232 // ends_at can't precede starts_at, so when both exist starts_at governs.
233 if let Some(closes_at) = self.starts_at.or(self.ends_at)
234 && Timestamp::now().as_millis() >= closes_at.as_millis()
235 {
236 return Err(AppError::Conflict(
237 "registration closed — the event has started or ended",
238 ));
239 }
240 Ok(self.audience_capacity)
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[tokio::test]
249 async fn title_is_required() {
250 assert!(EventTitle::try_new("standup").is_ok());
251 assert!(EventTitle::try_new("").is_err());
252 assert!(EventTitle::try_new(" ").is_err());
253 }
254
255 #[tokio::test]
256 async fn description_is_optional() {
257 assert!(EventDescription::try_new("").is_ok());
258 }
259
260 /// The `audience_kind` column is `TEXT` with a CHECK listing exactly
261 /// these spellings — audience-shaped queries match on them, so the
262 /// storage form may not drift (which `rename_all` mirrors).
263 #[test]
264 fn audience_kind_spellings_are_frozen() {
265 assert_eq!(EventAudienceKind::School.as_str(), "school");
266 assert_eq!(EventAudienceKind::Role.as_str(), "role");
267 assert_eq!(EventAudienceKind::Course.as_str(), "course");
268 assert_eq!(EventAudienceKind::Class.as_str(), "class");
269 assert_eq!(EventAudienceKind::Registration.as_str(), "registration");
270 }
271
272 /// The audience columns as a row writer would set them.
273 fn event_with(
274 audience_kind: EventAudienceKind,
275 audience_capacity: Option<i64>,
276 starts_at: Option<Timestamp>,
277 ends_at: Option<Timestamp>,
278 ) -> Event {
279 Event {
280 id: EventId::generate(),
281 creator: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"),
282 title: EventTitle::try_new("signup").unwrap(),
283 description: EventDescription::try_new("").unwrap(),
284 audience_kind,
285 audience_role: None,
286 audience_course: None,
287 audience_class: None,
288 audience_capacity,
289 starts_at,
290 ends_at,
291 }
292 }
293
294 #[tokio::test]
295 async fn registration_capacity_gates_and_echoes_cap() {
296 let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1));
297
298 assert!(matches!(
299 event_with(EventAudienceKind::School, None, None, None).registration_capacity(),
300 Err(AppError::Validation(_))
301 ));
302 assert_eq!(
303 event_with(EventAudienceKind::Registration, None, None, None)
304 .registration_capacity()
305 .unwrap(),
306 None
307 );
308 assert_eq!(
309 event_with(EventAudienceKind::Registration, Some(30), None, None)
310 .registration_capacity()
311 .unwrap(),
312 Some(30)
313 );
314 // Started events close the list; an ends_at-only deadline in the past
315 // does too.
316 assert!(matches!(
317 event_with(EventAudienceKind::Registration, Some(30), past, None)
318 .registration_capacity(),
319 Err(AppError::Conflict(_))
320 ));
321 assert!(matches!(
322 event_with(EventAudienceKind::Registration, None, None, past).registration_capacity(),
323 Err(AppError::Conflict(_))
324 ));
325 }
326}