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

class_member.rs482 lines, 21.2 KiBHistoryRawDownload
1//! Class-membership workflows: the member-axis add and the two exits — the
2//! soft `leave` a route takes and the hard `remove` a transfer rollback needs —
3//! with the pump's refusals mapped to this route's answers and a zero-row
4//! sweep turned into a 404, plus the roster reads the web layer pages through.
5//! The transaction itself lives in [`crate::db::class_pump`]; the table reads
6//! in [`crate::db::class_member`].
7
8use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
9use crate::database::Database;
10use crate::db::class_member;
11use crate::db::class_pump::{self, Axis};
12use crate::domain::class_group::ClassGroupId;
13use crate::domain::class_member::ClassMember;
14use crate::domain::user::UserId;
15use crate::error::{AppError, ValidationError};
16
17/// Put `user` in `class` and enroll them into every course the class is
18/// already attached to, in one transaction.
19///
20/// A student already enrolled in one of those instances keeps the row they
21/// have — no second enrollment and their `source` untouched, so a hand-placed
22/// enrollment is never adopted by the class.
23pub async fn add(
24 db: &Database,
25 class: &ClassGroupId,
26 user: &UserId,
27 added_by: &UserId,
28) -> Result<ClassMember, AppError> {
29 // Read off the refusal, never respelled here: this route and a
30 // blueprint pump answer one vocabulary. `Made` is the only `None`, and
31 // it takes the `Ok` arm below.
32 let landed = class_pump::add_member(db, class, user, added_by).await?;
33 let code = landed.refusal_code(&Axis::Member).unwrap_or_default();
34 match landed {
35 class_pump::Attached::Made(saved) => Ok(saved),
36 class_pump::Attached::Duplicate => Err(AppError::ConflictCoded {
37 code,
38 message: "the student is already in this class".into(),
39 }),
40 class_pump::Attached::Gone => Err(AppError::NotFound),
41 // The pivot is the student: they were demoted while this ran, which
42 // is the refusal the caller's own read makes a moment earlier and
43 // the only one that can arrive after it.
44 class_pump::Attached::PivotGone => Err(AppError::Validation(ValidationError::Invalid {
45 field: "user_id",
46 reason: "only students can be added to a class",
47 })),
48 class_pump::Attached::ClassFull => Err(AppError::ConflictCoded {
49 code,
50 message: format!("this class already holds {MAX_CLASS_MEMBERS} students"),
51 }),
52 // The other axis: adding one student enrolls them into every
53 // attached course, so a class over *that* ceiling cannot take a
54 // member however much room its roster has.
55 class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded {
56 code,
57 message: format!(
58 "this class holds more than {MAX_CLASS_COURSES} courses — \
59 detach some before adding a student"
60 ),
61 }),
62 // Not a ceiling someone can raise, and told apart from one on
63 // purpose: no number changes this class's answer, only detaching the
64 // link the deleted course left behind.
65 class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded {
66 code,
67 message: format!("{course} no longer exists — detach it from this class first"),
68 }),
69 // Only an attach run on a blueprint's behalf states that claim, and
70 // a membership is nobody's but its own.
71 class_pump::Attached::SourceGone => Err(AppError::Internal(
72 "a class membership has no blueprint to lose".into(),
73 )),
74 }
75}
76
77/// Take `user` out of `class` — the *soft* exit the route takes: the stint's
78/// `left_at` is stamped and the row stays as history, while the class's member
79/// count comes back so the student no longer counts as a live member. A
80/// student who rejoins later gets a fresh live row beside the old one, which
81/// is how "left in October, came back in January" is represented.
82///
83/// A student who was not in the class is a [`AppError::NotFound`], raised here
84/// rather than left to each caller to re-derive from a boolean. The
85/// enrollments the class pumped for them are released — one row per instance,
86/// so a seat they also hold in another section teaching the same course is
87/// that section's own row and is not touched (see
88/// [`class_pump::leave_member`]).
89pub async fn leave(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
90 let gone = class_pump::leave_member(db, class, user).await?;
91 (gone > 0).then_some(()).ok_or(AppError::NotFound)
92}
93
94/// Take `user` out of `class` for good — the hard exit, which deletes the
95/// stint rather than stamping it. Kept for the section-transfer rollback path
96/// alone, where the stint being undone must leave no trace a later read could
97/// mistake for history; every route uses [`leave`].
98///
99/// The enrollment release is [`leave`]'s: every row the stint owned goes, and
100/// no other section's seat is affected (see [`class_pump::remove_member`]).
101pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
102 let gone = class_pump::remove_member(db, class, user).await?;
103 (gone > 0).then_some(()).ok_or(AppError::NotFound)
104}
105
106/// The class's roster, newest first, paged — the read behind
107/// `GET /classes/{id}/members`.
108pub async fn list_for_class(
109 db: &Database,
110 class: &ClassGroupId,
111 limit: Option<i64>,
112 offset: i64,
113) -> Result<(Vec<ClassMember>, i64), AppError> {
114 class_member::list_for_class(db, class, limit, offset).await
115}
116
117/// The classes one student belongs to, newest membership first, paged — the
118/// read behind `GET /classes/me` and `GET /classes/user/{user}`.
119pub async fn list_for_user(
120 db: &Database,
121 user: &UserId,
122 limit: Option<i64>,
123 offset: i64,
124) -> Result<(Vec<ClassMember>, i64), AppError> {
125 class_member::list_for_user(db, user, limit, offset).await
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use crate::db::class_member::is_live_member;
132 use crate::db::class_member::tests::{
133 a_class, a_course, counter, enrollment_exists, rows, source_of,
134 };
135 use crate::service::class_course;
136
137 /// Adding a member enrolls them into every instance the class already
138 /// carries, each row tagged with the class, and the class's own member
139 /// counter ticks once.
140 #[tokio::test]
141 async fn a_member_is_enrolled_into_every_attached_instance() {
142 let (db, _leases) = crate::database::init_test_db().await;
143 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
144 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
145 let class = a_class("9-A", &db).await;
146 let algebra = a_course("algebra", &db).await;
147 let physics = a_course("physics", &db).await;
148 let algebra_instance = class_course::attach(&db, &class, &algebra, &manager)
149 .await
150 .unwrap();
151 let physics_instance = class_course::attach(&db, &class, &physics, &manager)
152 .await
153 .unwrap();
154
155 add(&db, &class, &student, &manager).await.unwrap();
156
157 for instance in [&algebra_instance, &physics_instance] {
158 assert_eq!(
159 source_of(instance.get_id(), &student, &db).await,
160 Some(Some(class.clone())),
161 "every attached instance must hold a row tagged with the class"
162 );
163 assert_eq!(
164 counter("enrollment_count", instance.get_id().uuid(), &db).await,
165 1
166 );
167 }
168 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
169 }
170
171 /// The pumped row keys the same `(instance, user)` pair a hand enroll
172 /// writes, or the two paths would key one pair two ways and only the
173 /// primary key (a 500) would notice.
174 #[tokio::test]
175 async fn a_pumped_row_uses_the_hand_enrolls_pair() {
176 let (db, _leases) = crate::database::init_test_db().await;
177 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
178 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
179 let class = a_class("9-A", &db).await;
180 let algebra = a_course("algebra", &db).await;
181 let instance = class_course::attach(&db, &class, &algebra, &manager)
182 .await
183 .unwrap();
184 add(&db, &class, &student, &manager).await.unwrap();
185
186 assert!(
187 enrollment_exists(instance.get_id(), &student, &db).await,
188 "the pump must key the pair the way enrollment does"
189 );
190 }
191
192 /// Re-adding is a 409, and it must cost nothing: no second counter tick.
193 #[tokio::test]
194 async fn a_second_add_is_refused_and_writes_nothing() {
195 let (db, _leases) = crate::database::init_test_db().await;
196 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
197 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
198 let class = a_class("9-A", &db).await;
199 let algebra = a_course("algebra", &db).await;
200 let instance = class_course::attach(&db, &class, &algebra, &manager)
201 .await
202 .unwrap();
203 add(&db, &class, &student, &manager).await.unwrap();
204
205 let again = add(&db, &class, &student, &manager).await;
206 assert!(
207 matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
208 "a second add is a 409 coded `duplicate`: {again:?}"
209 );
210 assert_eq!(
211 counter("class_member_count", class.uuid(), &db).await,
212 1,
213 "a refused add may not tick the counter"
214 );
215 assert_eq!(
216 counter("enrollment_count", instance.get_id().uuid(), &db).await,
217 1
218 );
219 }
220
221 /// A student already enrolled by hand keeps their own row: the pump skips
222 /// it, and leaving the class leaves it standing.
223 #[tokio::test]
224 async fn a_hand_placed_enrollment_is_skipped_and_survives_the_exit() {
225 let (db, _leases) = crate::database::init_test_db().await;
226 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
227 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
228 let class = a_class("9-A", &db).await;
229 let algebra = a_course("algebra", &db).await;
230 let instance = class_course::attach(&db, &class, &algebra, &manager)
231 .await
232 .unwrap();
233 crate::db::enrollment::enroll(&db, instance.get_id(), &student, &manager, None)
234 .await
235 .unwrap();
236
237 add(&db, &class, &student, &manager).await.unwrap();
238 assert_eq!(
239 source_of(instance.get_id(), &student, &db).await,
240 Some(None),
241 "the class must not adopt a hand-placed row"
242 );
243 assert_eq!(
244 counter("enrollment_count", instance.get_id().uuid(), &db).await,
245 1,
246 "the skipped pair may not be counted twice"
247 );
248
249 leave(&db, &class, &student).await.unwrap();
250 assert_eq!(
251 source_of(instance.get_id(), &student, &db).await,
252 Some(None),
253 "the sweep may only take back the rows the class wrote"
254 );
255 assert_eq!(
256 counter("enrollment_count", instance.get_id().uuid(), &db).await,
257 1
258 );
259 }
260
261 /// The soft exit: the stint is stamped, not deleted, and a rejoin writes a
262 /// fresh live row beside it — the shape "left in October, came back in
263 /// January" needs.
264 #[tokio::test]
265 async fn a_leave_stamps_the_stint_and_a_rejoin_writes_a_second_row() {
266 let (db, _leases) = crate::database::init_test_db().await;
267 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
268 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
269 let class = a_class("9-A", &db).await;
270 let algebra = a_course("algebra", &db).await;
271 let instance = class_course::attach(&db, &class, &algebra, &manager)
272 .await
273 .unwrap();
274 add(&db, &class, &student, &manager).await.unwrap();
275
276 leave(&db, &class, &student).await.unwrap();
277 assert_eq!(
278 rows("class_member", &db).await,
279 1,
280 "the stint is history, not a deletion"
281 );
282 assert!(
283 !is_live_member(&db, &class, &student).await.unwrap(),
284 "…and it no longer counts as a live member"
285 );
286 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
287
288 // The rejoin is a fresh row: the partial unique index only guards the
289 // live stint, so the pair may hold one live row again.
290 add(&db, &class, &student, &manager).await.unwrap();
291 assert_eq!(rows("class_member", &db).await, 2);
292 assert!(is_live_member(&db, &class, &student).await.unwrap());
293 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 1);
294 assert_eq!(
295 counter("enrollment_count", instance.get_id().uuid(), &db).await,
296 1,
297 "the rejoin enrols the pair once, not twice"
298 );
299 }
300
301 /// The hard exit deletes the stint and sweeps the rows the class pumped —
302 /// the transfer-rollback path.
303 #[tokio::test]
304 async fn a_remove_deletes_the_stint_and_the_rows_the_class_pumped() {
305 let (db, _leases) = crate::database::init_test_db().await;
306 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
307 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
308 let class = a_class("9-A", &db).await;
309 let algebra = a_course("algebra", &db).await;
310 let instance = class_course::attach(&db, &class, &algebra, &manager)
311 .await
312 .unwrap();
313 add(&db, &class, &student, &manager).await.unwrap();
314
315 remove(&db, &class, &student).await.unwrap();
316 assert_eq!(rows("class_member", &db).await, 0);
317 assert_eq!(source_of(instance.get_id(), &student, &db).await, None);
318 assert_eq!(
319 counter("enrollment_count", instance.get_id().uuid(), &db).await,
320 0,
321 "the count must come back with the row that held it"
322 );
323 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
324 let again = remove(&db, &class, &student).await;
325 assert!(
326 matches!(again, Err(AppError::NotFound)),
327 "a second removal is a 404, not a second sweep: {again:?}"
328 );
329 }
330
331 /// A member whose class no longer carries the course still leaves cleanly:
332 /// the membership row and the pumped enrollment are independent facts.
333 #[tokio::test]
334 async fn a_sweep_tolerates_an_instance_the_class_already_dropped() {
335 let (db, _leases) = crate::database::init_test_db().await;
336 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
337 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
338 let class = a_class("9-A", &db).await;
339 let algebra = a_course("algebra", &db).await;
340 class_course::attach(&db, &class, &algebra, &manager)
341 .await
342 .unwrap();
343 add(&db, &class, &student, &manager).await.unwrap();
344
345 // The detach takes the instance and the rows it pumped; the stint
346 // survives it, so the exit has nothing left to sweep.
347 class_course::detach(&db, &class, &algebra).await.unwrap();
348 leave(&db, &class, &student)
349 .await
350 .expect("the membership must still be removable with its enrollment gone");
351 assert_eq!(counter("class_member_count", class.uuid(), &db).await, 0);
352 }
353
354 /// The role-change sweep, which is one transaction with the role write
355 /// itself: the memberships go with their counters, the enrollment rows go
356 /// with their instance counts, and each count comes back exactly once —
357 /// the double decrement the old two-call split existed to avoid.
358 #[tokio::test]
359 async fn the_role_sweep_takes_memberships_and_enrollments_together() {
360 let (db, _leases) = crate::database::init_test_db().await;
361 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
362 // A real row, because the sweep now rides on the role write.
363 let account = crate::db::user::create(
364 &db,
365 crate::domain::user::Username::try_new("ogrenci").unwrap(),
366 None,
367 )
368 .await
369 .unwrap();
370 let student = *account.get_id();
371 let first = a_class("9-A", &db).await;
372 let second = a_class("club", &db).await;
373 let algebra = a_course("algebra", &db).await;
374 let instance = class_course::attach(&db, &first, &algebra, &manager)
375 .await
376 .unwrap();
377 add(&db, &first, &student, &manager).await.unwrap();
378 add(&db, &second, &student, &manager).await.unwrap();
379
380 crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)
381 .await
382 .unwrap();
383 assert_eq!(
384 rows("class_member", &db).await,
385 2,
386 "the stints stay as history — a soft leave, not a deletion"
387 );
388 for class in [&first, &second] {
389 assert!(
390 !is_live_member(&db, class, &student).await.unwrap(),
391 "no live stint may survive the sweep"
392 );
393 assert_eq!(
394 counter("class_member_count", class.uuid(), &db).await,
395 0,
396 "every class must get its member count back"
397 );
398 }
399 assert_eq!(
400 source_of(instance.get_id(), &student, &db).await,
401 None,
402 "the enrollment goes in the same transaction as the membership"
403 );
404 assert_eq!(
405 counter("enrollment_count", instance.get_id().uuid(), &db).await,
406 0,
407 "…and its count comes back once, not twice"
408 );
409 // Which is the point of folding them: the sweep is one transaction, so
410 // no enrollment row is left tagged with a class whose live roster is
411 // already empty — the shape that stranded rows nothing could reach.
412 assert_eq!(
413 counter("class_course_count", first.uuid(), &db).await,
414 1,
415 "the attachment itself is untouched by a role sweep"
416 );
417 }
418
419 /// D4: a member exit **releases** the rows the leaving section wrote —
420 /// there is no heir to hand one over to. Two class sections teaching the
421 /// same catalog course hold the student in their *own* instance, each with
422 /// its own row tagged with its own class, so a release may only take the
423 /// leaving section's row and count back; the rival's row stands exactly as
424 /// written. The old rule re-tagged the row with a rival section instead
425 /// (keeping it on the juncture of a class that no longer held the student),
426 /// which is what this pins gone.
427 #[tokio::test]
428 async fn a_member_exit_releases_its_own_row_and_leaves_the_rivals_standing() {
429 let (db, _leases) = crate::database::init_test_db().await;
430 let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await;
431 let student = crate::db::class_member::tests::fixture_user(&db, "student").await;
432 let first = a_class("5-A", &db).await;
433 let second = a_class("5-B", &db).await;
434 let algebra = a_course("algebra", &db).await;
435 let first_instance = class_course::attach(&db, &first, &algebra, &manager)
436 .await
437 .unwrap();
438 let second_instance = class_course::attach(&db, &second, &algebra, &manager)
439 .await
440 .unwrap();
441
442 // Both sections hold the student, so both instances carry a row — each
443 // tagged with the section that pumped it.
444 for class in [&first, &second] {
445 add(&db, class, &student, &manager).await.unwrap();
446 }
447 assert_eq!(
448 source_of(first_instance.get_id(), &student, &db).await,
449 Some(Some(first.clone()))
450 );
451 assert_eq!(
452 source_of(second_instance.get_id(), &student, &db).await,
453 Some(Some(second.clone()))
454 );
455
456 // 5-A lets the student go: its own row goes and its own count comes
457 // back. 5-B's row is a row *it* wrote, on *its* instance, and stands.
458 leave(&db, &first, &student).await.unwrap();
459 assert_eq!(
460 source_of(first_instance.get_id(), &student, &db).await,
461 None,
462 "the leaving section's row must be released"
463 );
464 assert_eq!(
465 counter("enrollment_count", first_instance.get_id().uuid(), &db).await,
466 0,
467 "…and its roster count comes back with it"
468 );
469 assert_eq!(
470 source_of(second_instance.get_id(), &student, &db).await,
471 Some(Some(second.clone())),
472 "the rival section's own row and its tag must stand"
473 );
474 assert_eq!(
475 counter("enrollment_count", second_instance.get_id().uuid(), &db).await,
476 1,
477 "…and so must the rival's roster count"
478 );
479 assert_eq!(counter("class_member_count", first.uuid(), &db).await, 0);
480 assert_eq!(counter("class_member_count", second.uuid(), &db).await, 1);
481 }
482}