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.rs234 lines, 8.0 KiBHistoryRawDownload
1//! The `class_member` table: the roster reads. The membership writes are the
2//! pump's, along the member axis ([`crate::db::class_pump`]); the
3//! refusals-to-errors policy and the detach live in
4//! [`crate::service::class_member`].
5//!
6//! The table is a history: `left_at` NULL is the live stint, and every read
7//! here filters on it — a student who left the section holds no seat and
8//! appears on no roster, while their earlier row survives for the record (and
9//! for the report card's attribution).
10
11use crate::constant::CLASS_MEMBER_TABLE;
12use crate::database::Database;
13use crate::db::page::PagedList;
14use crate::domain::class_group::ClassGroupId;
15use crate::domain::class_member::ClassMember;
16use crate::domain::user::UserId;
17use crate::error::AppError;
18
19/// The class's live roster, newest first — by when the student joined. The
20/// surrogate id breaks the tie, so the order is total.
21pub async fn list_for_class(
22 db: &Database,
23 class: &ClassGroupId,
24 limit: Option<i64>,
25 offset: i64,
26) -> Result<(Vec<ClassMember>, i64), AppError> {
27 PagedList::new(
28 format!("{CLASS_MEMBER_TABLE} WHERE class = $1 AND left_at IS NULL"),
29 "ORDER BY joined_at DESC, id DESC",
30 )
31 .bind(class.uuid())
32 .run(limit, offset, db)
33 .await
34}
35
36/// The classes one student is currently in, newest stint first — the read
37/// behind "which class section am I in". A left stint is history and
38/// does not appear.
39pub async fn list_for_user(
40 db: &Database,
41 user: &UserId,
42 limit: Option<i64>,
43 offset: i64,
44) -> Result<(Vec<ClassMember>, i64), AppError> {
45 PagedList::new(
46 format!("{CLASS_MEMBER_TABLE} WHERE app_user = $1 AND left_at IS NULL"),
47 "ORDER BY joined_at DESC, id DESC",
48 )
49 .bind(user.uuid())
50 .run(limit, offset, db)
51 .await
52}
53
54/// Whether `user` holds a live stint in `class` right now — the membership
55/// gate a class-scoped route reads before it writes.
56pub async fn is_live_member(
57 db: &Database,
58 class: &ClassGroupId,
59 user: &UserId,
60) -> Result<bool, AppError> {
61 let row = sqlx::query!(
62 r#"SELECT 1 AS "one" FROM class_member
63 WHERE class = $1 AND app_user = $2 AND left_at IS NULL"#,
64 class.uuid(),
65 user.uuid(),
66 )
67 .fetch_optional(db)
68 .await?;
69 Ok(row.is_some())
70}
71
72#[cfg(test)]
73pub(crate) mod tests {
74 use super::*;
75 use crate::domain::class_group::{ClassGroupId, ClassName};
76 use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
77 use crate::domain::user::UserId;
78
79 /// A real `app_user` row for fixtures, by username — the username is
80 /// unique, so every call for the same name shares one row, whichever call
81 /// minted it. Creators, graders, and `added_by` are foreign keys now, so
82 use sqlx::Row as _;
83
84 /// fixture actors are rows, not fabricated ids.
85 pub(crate) async fn fixture_user(db: &Database, username: &str) -> UserId {
86 sqlx::query(
87 "INSERT INTO app_user (id, username, created_at, role) \
88 VALUES ($1, $2, 0, 'student') ON CONFLICT DO NOTHING",
89 )
90 .bind(crate::domain::user::UserId::generate().uuid())
91 .bind(username)
92 .execute(db)
93 .await
94 .unwrap();
95 let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1")
96 .bind(username)
97 .fetch_one(db)
98 .await
99 .unwrap()
100 .try_get(0)
101 .unwrap();
102 UserId::from_key(&id.to_string())
103 }
104
105 /// A class with no year, at a fixed ladder rung: the shape most fixtures
106 /// want, since the year only matters to the academic-calendar reads and
107 /// the grade level only to the blueprint/rollover ones.
108 pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
109 let manager = fixture_user(db, "manager").await;
110 crate::db::class_group::create(
111 db,
112 &manager,
113 ClassName::try_new(name).unwrap(),
114 crate::domain::grade::GradeLevel::new(9).unwrap(),
115 None,
116 None,
117 )
118 .await
119 .unwrap()
120 .get_id()
121 .clone()
122 }
123
124 /// A catalog course. Capacity is gone from the catalog (D5): the instance
125 /// carries the roster counter and there is no seat gate to trip.
126 pub(crate) async fn a_course(title: &str, db: &Database) -> CourseId {
127 let manager = fixture_user(db, "manager").await;
128 crate::db::course::create(
129 db,
130 &manager,
131 CourseTitle::try_new(title).unwrap(),
132 CourseDescription::try_new("").unwrap(),
133 CourseKind::course(),
134 )
135 .await
136 .unwrap()
137 .get_id()
138 .clone()
139 }
140
141 /// A counter column on its row, re-read out of the store — never off a
142 /// return value. The field picks the table for the counters whose home is
143 /// unambiguous; `class_course_count` now exists on *both* the class (how
144 /// many courses it carries) and the catalog course (how many instances are
145 /// taught in), so that one names the class here and
146 /// [`counter_on`] is the way to read the course's.
147 pub(crate) async fn counter(field: &str, of: uuid::Uuid, db: &Database) -> i64 {
148 let table = match field {
149 // The roster counter is the *instance's* (the catalog course has
150 // no roster since D4/D5).
151 "enrollment_count" => "class_course",
152 "class_member_count" | "class_course_count" => "class_group",
153 other => panic!("no table known for the counter {other}"),
154 };
155 counter_on(table, field, of, db).await
156 }
157
158 /// [`counter`] with the table named outright, for the columns two tables
159 /// share.
160 pub(crate) async fn counter_on(table: &str, field: &str, of: uuid::Uuid, db: &Database) -> i64 {
161 sqlx::query(sqlx::AssertSqlSafe(format!(
162 "SELECT COALESCE({field}, 0) FROM {table} WHERE id = $1"
163 )))
164 .bind(of)
165 .fetch_one(db)
166 .await
167 .unwrap()
168 .try_get::<i64, _>(0)
169 .unwrap()
170 }
171
172 /// How many rows `table` holds.
173 pub(crate) async fn rows(table: &str, db: &Database) -> i64 {
174 sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}")))
175 .fetch_one(db)
176 .await
177 .unwrap()
178 .try_get::<i64, _>(0)
179 .unwrap()
180 }
181
182 /// Whether the course row is still there.
183 pub(crate) async fn course_exists(course: &CourseId, db: &Database) -> bool {
184 sqlx::query("SELECT 1 FROM course WHERE id = $1")
185 .bind(course.uuid())
186 .fetch_optional(db)
187 .await
188 .unwrap()
189 .is_some()
190 }
191
192 /// Whether the enrollment pair still has its row.
193 pub(crate) async fn enrollment_exists(
194 class_course: &crate::domain::class_course::ClassCourseId,
195 user: &UserId,
196 db: &Database,
197 ) -> bool {
198 sqlx::query("SELECT 1 FROM enrollment WHERE class_course = $1 AND app_user = $2")
199 .bind(class_course.uuid())
200 .bind(user.uuid())
201 .fetch_optional(db)
202 .await
203 .unwrap()
204 .is_some()
205 }
206
207 /// Whether the class-course link is still attached.
208 pub(crate) async fn link_exists(
209 class: &ClassGroupId,
210 course: &CourseId,
211 db: &Database,
212 ) -> bool {
213 sqlx::query("SELECT 1 FROM class_course WHERE class = $1 AND course = $2")
214 .bind(class.uuid())
215 .bind(course.uuid())
216 .fetch_optional(db)
217 .await
218 .unwrap()
219 .is_some()
220 }
221
222 /// The class that wrote an instance's enrollment, or `None` for a
223 /// hand-placed row.
224 pub(crate) async fn source_of(
225 class_course: &crate::domain::class_course::ClassCourseId,
226 user: &UserId,
227 db: &Database,
228 ) -> Option<Option<ClassGroupId>> {
229 crate::db::enrollment::read_for_user(db, class_course, user)
230 .await
231 .unwrap()
232 .map(|row| row.get_source().cloned())
233 }
234}