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

course_session.rs324 lines, 13.3 KiBHistoryRawDownload
1//! Course-session workflows: who may teach a lesson (the teacher-resolution
2//! gate), and the doors the web layer takes for every session read and
3//! write. The queries live in [`crate::db::course_session`]; the
4//! timetable's wire shaping and the course-rights checks stay in the web
5//! layer.
6//!
7//! The one workflow with a plan behind it is [`materialize`]: it expands an
8//! instance's *resolved* weekly plan ([`crate::service::weekly_slot`]) into
9//! dated lessons over a range, bounded by the school-wide holiday calendar
10//! ([`crate::service::holiday::blocked_days`]). It is an explicit route's
11//! work, not a scheduler: nothing generates lessons on its own.
12
13use crate::constant::{MAX_MATERIALIZE_DAYS, MAX_MATERIALIZE_SESSIONS, MILLIS_PER_DAY};
14use crate::database::{Database, tx_with_retry};
15use crate::db::course_session::{self, NewSession};
16use crate::domain::calendar;
17use crate::domain::class_course::{ClassCourse, ClassCourseId};
18use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
19use crate::domain::holiday::HolidayName;
20use crate::domain::role::Role;
21use crate::domain::timestamp::Timestamp;
22use crate::domain::user::{User, UserId};
23use crate::error::{AppError, ValidationError};
24
25/// Resolve who a session's teacher should be: the caller when `teacher_id` is
26/// omitted (or names them), otherwise the referenced user — who must exist and
27/// hold the `teacher` role or higher (a student cannot teach a lesson).
28///
29/// Scheduling hands the named person the session's teaching seat, so the
30/// floor is checked on the *live* role here rather than at the web layer:
31/// every future roll-call right derives from this column, and a stale
32/// `teacher_id` in a request body must fail with the same 400 no matter
33/// which route named it.
34pub async fn resolve_session_teacher(
35 teacher_id: Option<&str>,
36 caller: &User,
37 db: &Database,
38) -> Result<User, AppError> {
39 let target = match teacher_id {
40 None => return Ok(caller.clone()),
41 Some(key) if key == caller.get_id().key() => return Ok(caller.clone()),
42 Some(key) => UserId::from_key(key),
43 };
44 let Some(user) = crate::db::user::read(db, &target).await? else {
45 return Err(AppError::Validation(ValidationError::Invalid {
46 field: "teacher_id",
47 reason: "session teacher does not exist",
48 }));
49 };
50 if !user.get_role().at_least(Role::Teacher) {
51 return Err(AppError::Validation(ValidationError::Invalid {
52 field: "teacher_id",
53 reason: "session teacher must hold the teacher role or higher",
54 }));
55 }
56 Ok(user)
57}
58
59/// Schedule a lesson on `class_course` — one dated occurrence of the instance,
60/// which is what a roll call hangs off.
61pub async fn create(
62 db: &Database,
63 class_course: &ClassCourseId,
64 teacher: &UserId,
65 topic: SessionTopic,
66 starts_at: Timestamp,
67 ends_at: Option<Timestamp>,
68) -> Result<CourseSession, AppError> {
69 course_session::create(db, class_course, teacher, topic, starts_at, ends_at).await
70}
71
72pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> {
73 course_session::read(db, id).await
74}
75
76/// An instance's sessions, most recent lesson first — the timetable read,
77/// unbounded by any schedule window.
78pub async fn list_for_class_course(
79 db: &Database,
80 class_course: &ClassCourseId,
81 limit: Option<i64>,
82 offset: i64,
83) -> Result<(Vec<CourseSession>, i64), AppError> {
84 list_windowed(db, class_course, None, None, limit, offset).await
85}
86
87/// The same timetable read narrowed to a half-open `[starts_after,
88/// starts_before)` on `starts_at` — a calendar month is
89/// `[month_start, next_month_start)`. The page and the count share the one
90/// SQL `WHERE`; the order does not flip.
91pub async fn list_windowed(
92 db: &Database,
93 class_course: &ClassCourseId,
94 starts_after: Option<i64>,
95 starts_before: Option<i64>,
96 limit: Option<i64>,
97 offset: i64,
98) -> Result<(Vec<CourseSession>, i64), AppError> {
99 course_session::list_for_class_course(
100 db,
101 class_course,
102 starts_after,
103 starts_before,
104 limit,
105 offset,
106 )
107 .await
108}
109
110/// Only what the request carried is written: an omitted field (`None`) is
111/// not stored at all, so a concurrent PATCH of that field survives. The
112/// range consistency re-check rides in the UPDATE's own `WHERE`, so the
113/// caller holds nothing across its read and this write.
114pub async fn update(
115 db: &Database,
116 session: CourseSession,
117 teacher: Option<UserId>,
118 topic: Option<SessionTopic>,
119 starts_at: Option<Timestamp>,
120 ends_at: Option<Option<Timestamp>>,
121) -> Result<CourseSession, AppError> {
122 course_session::update(db, session, teacher, topic, starts_at, ends_at).await
123}
124
125/// Delete the session and sweep its roll-call rows in one transaction.
126pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
127 course_session::delete(db, session).await
128}
129
130/// One non-teaching day the generator refused to schedule on: the calendar
131/// day in the school's zone, and the holiday that reaches into it.
132#[derive(Debug, Clone)]
133pub struct BlockedDay {
134 pub day: chrono::NaiveDate,
135 pub holiday: HolidayName,
136}
137
138/// What one [`materialize`] call did — or, on a dry run, would have done.
139///
140/// `created` carries the rows the database actually inserted (empty on a dry
141/// run), so a lesson a concurrent writer already put at the same instant is
142/// reported as skipped, never counted. `candidates` is the size the range
143/// asked for, `slots` the resolved plan's size, and `blocked` one entry per
144/// holiday-blocked *day*.
145#[derive(Debug, Clone)]
146pub struct MaterializeOutcome {
147 pub applied: bool,
148 pub slots: usize,
149 pub candidates: usize,
150 pub created: Vec<CourseSession>,
151 pub skipped_existing: usize,
152 pub skipped_holiday: usize,
153 pub blocked: Vec<BlockedDay>,
154 pub range_days: i64,
155}
156
157/// Expand `instance`'s resolved weekly plan into dated lessons over
158/// `[from, to]` (inclusive instants), one lesson per plan slot per matching
159/// weekday, skipping the days a holiday reaches into and the instants the
160/// section already holds a lesson at.
161///
162/// `apply == false` is a dry run: it reads, decides, and writes nothing.
163/// `apply == true` writes the collected rows in this transaction and returns
164/// exactly the rows that landed — the whole feature is additive, nothing is
165/// ever deleted or updated, and a second run over the same range is a no-op
166/// (`UNIQUE (class_course, starts_at)`). Weekends are not special-cased: a
167/// school may run Saturday, so only the plan and the holidays decide.
168///
169/// `offset_minutes` is the school's zone offset
170/// ([`crate::domain::calendar::zone_offset_minutes`]); the range's instants
171/// name *school* days, and each lesson lands at its slot's minute of that
172/// local day.
173///
174/// Refusals: an archived year, an empty plan (409
175/// `instance_has_no_weekly_plan`), no assigned teacher (409
176/// `instance_has_no_teacher`, the lesson's teacher is the instance's first
177/// assigned one), a range longer than a year or one that would mint more than
178/// [`MAX_MATERIALIZE_SESSIONS`] lessons (400), and a gone instance
179/// ([`AppError::NotFound`]).
180pub async fn materialize(
181 db: &Database,
182 instance: &ClassCourse,
183 from: Timestamp,
184 to: Timestamp,
185 apply: bool,
186 offset_minutes: i32,
187) -> Result<MaterializeOutcome, AppError> {
188 let instance_id = instance.get_id().clone();
189 let days = calendar::days_between(
190 calendar::zoned_day(from.as_millis(), offset_minutes),
191 calendar::zoned_day(to.as_millis(), offset_minutes),
192 );
193 let range_days = days.len() as i64;
194 if range_days > MAX_MATERIALIZE_DAYS {
195 return Err(AppError::Validation(ValidationError::Invalid {
196 field: "to",
197 reason: "the range must not span more than a year",
198 }));
199 }
200
201 // Every decision below is made while holding the instance's row lock, and
202 // the generated rows are written on that same connection: a rival
203 // materialize run waits here instead of racing the existence read, and a
204 // refusal rolls back whatever it had collected.
205 // Owned captures (`Send` rule of `tx_with_retry` closures): the closure may
206 // not hold a reference out of the caller's frame — a `&PgPool` or a
207 // `&ClassCourse` captured there fails the higher-ranked `Send` check the
208 // function's own future must pass, so no route could await it. `PgPool` is
209 // a cheap handle clone and the instance is one row.
210 let pool = db.clone();
211 let instance = instance.clone();
212 tx_with_retry(db, false, async move |tx| {
213 // The archived-year wall every instance write passes: a past year is
214 // read-only, and this run mints lesson rows.
215 crate::service::class_course::require_open(&pool, &instance_id).await?;
216 // The serialization point. `FOR NO KEY UPDATE` rather than
217 // `FOR UPDATE`: the batch insert below takes this same row's
218 // foreign-key `FOR KEY SHARE`, which `FOR UPDATE` would block on.
219 crate::db::weekly_slot::lock_class_tx(tx, &instance_id).await?;
220
221 let slots = crate::service::weekly_slot::resolved_for_instance(&pool, &instance).await?;
222 if slots.is_empty() {
223 return Err(AppError::ConflictCoded {
224 code: "instance_has_no_weekly_plan",
225 message: "this section's weekly plan is empty — add a slot first".into(),
226 });
227 }
228 let teachers =
229 crate::db::class_course_teacher::list_for_instance(&pool, &instance_id).await?;
230 let Some(teacher) = teachers.first().copied() else {
231 return Err(AppError::ConflictCoded {
232 code: "instance_has_no_teacher",
233 message: "assign a teacher to this section before generating lessons".into(),
234 });
235 };
236
237 // The topic chain: the slot's own first, the instance's *resolved*
238 // title second (the one display chain every surface rides), the
239 // literal `"Ders"` last. The resolved title is bounded by
240 // `MAX_COURSE_TITLE_LEN`, so it always fits a `SessionTopic`.
241 let resolved =
242 crate::service::instance_resolve::resolved_content(&pool, &[&instance]).await?;
243 let fallback_topic = resolved
244 .get(&instance_id.key())
245 .map(|content| content.title.as_str())
246 .filter(|title| !title.is_empty())
247 .and_then(|title| SessionTopic::try_new(title).ok())
248 .unwrap_or(SessionTopic::try_new("Ders")?);
249
250 let holidays = crate::service::holiday::blocked_days(&pool, from, to).await?;
251 let existing = course_session::existing_starts(&pool, &instance_id).await?;
252
253 let mut rows: Vec<NewSession> = Vec::new();
254 let mut blocked: Vec<BlockedDay> = Vec::new();
255 let mut skipped_existing = 0usize;
256 for day in &days {
257 let day_start = calendar::day_start_millis(*day, offset_minutes);
258 // Day granularity, not slot granularity: a day a holiday reaches
259 // into is named once and contributes nothing, whether or not the
260 // plan runs a lesson that weekday.
261 let day_end = day_start + MILLIS_PER_DAY - 1;
262 if let Some(holiday) = holidays.iter().find(|holiday| {
263 holiday.overlaps(
264 Timestamp::from_millis(day_start),
265 Timestamp::from_millis(day_end),
266 )
267 }) {
268 blocked.push(BlockedDay {
269 day: *day,
270 holiday: holiday.get_name().clone(),
271 });
272 continue;
273 }
274 let weekday = calendar::iso_weekday(*day);
275 for slot in slots
276 .iter()
277 .filter(|slot| slot.get_weekday().get() == weekday)
278 {
279 let starts_at = day_start + slot.get_starts_at().get() * 60_000;
280 if existing.contains(&starts_at) {
281 skipped_existing += 1;
282 continue;
283 }
284 rows.push(NewSession {
285 id: CourseSessionId::generate(),
286 class_course: instance_id.clone(),
287 teacher,
288 topic: slot
289 .get_topic()
290 .cloned()
291 .unwrap_or_else(|| fallback_topic.clone()),
292 starts_at: Timestamp::from_millis(starts_at),
293 ends_at: Timestamp::from_millis(
294 day_start + slot.get_ends_at().get() * 60_000,
295 ),
296 });
297 }
298 }
299
300 let candidates = rows.len();
301 if candidates > MAX_MATERIALIZE_SESSIONS {
302 return Err(AppError::Validation(ValidationError::Invalid {
303 field: "to",
304 reason: "this range would create more than 500 lessons — narrow it",
305 }));
306 }
307 let created = if apply {
308 course_session::insert_many_tx(tx, &rows).await?
309 } else {
310 Vec::new()
311 };
312 Ok(MaterializeOutcome {
313 applied: apply,
314 slots: slots.len(),
315 candidates,
316 created,
317 skipped_existing,
318 skipped_holiday: blocked.len(),
319 blocked,
320 range_days,
321 })
322 })
323 .await
324}