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

weekly_plan.rs574 lines, 25.0 KiBHistoryRawDownload
1//! The weekly plan surface: the timetable template's routes on both owners —
2//! the grade-level offering (`/offerings/{id}/weekly-plan`, the office's
3//! door) and the class×course instance (`/instances/{id}/weekly-plan`, the
4//! D10 door), split into the two mount functions the router composes
5//! (`offering_routes` under `/offerings`, `instance_routes` inside
6//! `/instances`) so each carries its own module's gate.
7//!
8//! A slot is one weekday plus a minutes-past-midnight window (`1` = Monday
9//! through `7` = Sunday, `540` = 09:00), and may carry an optional lesson
10//! topic. Two slots of one owner may touch but never overlap (409
11//! `slot_overlap`); a plan holds at most
12//! [`crate::constant::MAX_WEEKLY_SLOTS`] slots (409 `slot_cap`).
13//! Writing any instance-side row flips `weekly_plan_inherited` to `false` in
14//! the same statement, and `DELETE /instances/{id}/weekly-plan` (no slot id)
15//! is the reset back to inherit — the resolved reads never merge the two
16//! sets.
17//!
18//! **No scheduler** — but one explicit door: `POST
19//! /instances/{id}/weekly-plan/materialize` expands the section's *resolved*
20//! plan into dated `course_session` rows over a range, dry-run first and
21//! bounded by the school's holiday calendar
22//! ([`crate::service::course_session::materialize`]). Nothing generates
23//! lessons on its own; a caller asks, and a second ask over the same range
24//! writes nothing new.
25
26use axum::Json;
27use axum::extract::Path;
28use axum::http::StatusCode;
29use serde::{Deserialize, Serialize};
30use utoipa::ToSchema;
31use utoipa_axum::router::OpenApiRouter;
32use utoipa_axum::routes;
33
34use crate::database::Database;
35use crate::domain::calendar::zone_offset_minutes;
36use crate::domain::class_course::{ClassCourse, ClassCourseId};
37use crate::domain::course_offering::{CourseOffering, CourseOfferingId};
38use crate::domain::course_session::SessionTopic;
39use crate::domain::timestamp::Timestamp;
40use crate::domain::weekly_slot::{SlotMinute, Weekday, WeeklySlot, WeeklySlotId};
41use crate::error::{AppError, ErrorResponse};
42use crate::service;
43use crate::state::AppState;
44use crate::web::tenant_state::State;
45
46use super::instances::can_view_instance;
47use super::{
48 CurrentUser, RequireManager, RequireTeacher, SessionResponse, check_not_past, check_time_range,
49 person_map,
50};
51
52/// The route set mounted under `/offerings` (relative paths): the template
53/// week's reads and the office's writes.
54pub fn offering_routes() -> OpenApiRouter<AppState> {
55 OpenApiRouter::new()
56 .routes(routes!(list_offering_weekly_plan, add_offering_slot))
57 .routes(routes!(remove_offering_slot))
58}
59
60/// The instance-side half: mounted inside `/instances` — the section's
61/// resolved plan, its override writes, and the reset. The two `DELETE`s stay
62/// in separate `routes!` calls — one call may register each HTTP method only
63/// once.
64pub fn instance_routes() -> OpenApiRouter<AppState> {
65 OpenApiRouter::new()
66 .routes(routes!(list_instance_weekly_plan, add_instance_slot))
67 .routes(routes!(remove_instance_slot))
68 .routes(routes!(reset_instance_weekly_plan))
69 .routes(routes!(materialize_weekly_plan))
70}
71
72/// A weekly plan line the caller sent: the ISO weekday, the two
73/// minutes-past-midnight bounds of the lesson window, and the optional topic
74/// every lesson generated from it is stamped with.
75#[derive(Deserialize, ToSchema)]
76struct CreateSlot {
77 /// `1` = Monday through `7` = Sunday.
78 #[schema(example = 1)]
79 weekday: i16,
80 /// Minutes past midnight (`540` = 09:00) — the window opens here.
81 #[schema(example = 540)]
82 starts_at: i64,
83 /// Minutes past midnight — strictly after `starts_at`.
84 #[schema(example = 600)]
85 ends_at: i64,
86 /// What this line's lessons are about. The materializer stamps it onto
87 /// every lesson it generates from this slot; omit it and a generated
88 /// lesson takes the instance's resolved course title instead (then the
89 /// literal `"Ders"`).
90 #[schema(example = "Üslü sayılar", max_length = 200)]
91 topic: Option<String>,
92}
93
94/// Public shape of one weekly plan slot. Times stay the minutes-past-midnight
95/// form the request sent; `weekday` stays the integer (`1` = Monday).
96#[derive(Serialize, ToSchema)]
97pub struct WeeklySlotDto {
98 pub id: String,
99 /// `1` = Monday through `7` = Sunday.
100 pub weekday: i16,
101 /// Minutes past midnight — the window opens here.
102 pub starts_at: i64,
103 /// Minutes past midnight, strictly after `starts_at`.
104 pub ends_at: i64,
105 /// The topic this line's generated lessons carry; `null` = fall back to
106 /// the instance's resolved title.
107 pub topic: Option<String>,
108}
109
110impl WeeklySlotDto {
111 pub fn new(slot: &WeeklySlot) -> Self {
112 Self {
113 id: slot.get_id().key(),
114 weekday: slot.get_weekday().get(),
115 starts_at: slot.get_starts_at().get(),
116 ends_at: slot.get_ends_at().get(),
117 topic: slot.get_topic().map(|topic| topic.as_str().to_string()),
118 }
119 }
120}
121
122/// The section's **resolved** weekly plan: whose rows are authoritative and
123/// what they are — the offering's template week while
124/// `weekly_plan_inherited` stands, the section's own rows (possibly empty)
125/// once it overrode. Ordered weekday first, then start time.
126#[derive(Serialize, ToSchema)]
127pub struct InstanceWeeklyPlan {
128 pub weekly_plan: Vec<WeeklySlotDto>,
129 /// `true` = the offering's template week is authoritative; `false` = the
130 /// section's own rows below, including when that list is empty.
131 pub weekly_plan_inherited: bool,
132}
133
134async fn offering_or_404(key: &str, db: &Database) -> Result<CourseOffering, AppError> {
135 service::course_offering::read(db, &CourseOfferingId::from_key(key))
136 .await?
137 .ok_or(AppError::NotFound)
138}
139
140/// The instance a path id names, or a 404 — the read arm mirrors
141/// [`super::instances`]'s.
142async fn instance_or_404(key: &str, db: &Database) -> Result<ClassCourse, AppError> {
143 service::class_course::read(db, &ClassCourseId::from_key(key))
144 .await?
145 .ok_or(AppError::NotFound)
146}
147
148/// The body's slot, range-checked before anything is written: weekday and
149/// minute bounds here, the non-empty window inside the domain `WeeklySlot`,
150/// and the optional topic through its own newtype.
151fn parse_slot(
152 req: &CreateSlot,
153) -> Result<(Weekday, SlotMinute, SlotMinute, Option<SessionTopic>), crate::error::ValidationError> {
154 Ok((
155 Weekday::new(req.weekday)?,
156 SlotMinute::new(req.starts_at)?,
157 SlotMinute::new(req.ends_at)?,
158 req.topic
159 .as_deref()
160 .map(SessionTopic::try_new)
161 .transpose()?,
162 ))
163}
164
165/// List the offering's template week — weekday first, then start time. Any
166/// signed-in session, the same visibility as the offering read itself.
167#[utoipa::path(
168 get,
169 path = "/{id}/weekly-plan",
170 tag = "offerings",
171 security(("session_cookie" = [])),
172 params(("id" = String, Path, description = "Offering id")),
173 responses(
174 (status = 200, description = "The template week, ordered weekday then start time", body = [WeeklySlotDto]),
175 (status = 401, description = "Not authenticated", body = ErrorResponse),
176 (status = 404, description = "Offering not found", body = ErrorResponse),
177 ),
178)]
179async fn list_offering_weekly_plan(
180 State(st): State<AppState>,
181 CurrentUser(_user): CurrentUser,
182 Path(id): Path<String>,
183) -> Result<Json<Vec<WeeklySlotDto>>, AppError> {
184 let offering = offering_or_404(&id, &st.db).await?;
185 let slots = service::weekly_slot::resolved_for_offering(&st.db, offering.get_id()).await?;
186 Ok(Json(slots.iter().map(WeeklySlotDto::new).collect()))
187}
188
189/// Add one slot to the offering's template week. Manager+. Refused with 409
190/// `slot_overlap` when a template slot already occupies an intersecting
191/// window on that weekday (an exact duplicate overlaps too), 409 `slot_cap`
192/// when the week already holds the maximum.
193#[utoipa::path(
194 post,
195 path = "/{id}/weekly-plan",
196 tag = "offerings",
197 security(("session_cookie" = [])),
198 params(("id" = String, Path, description = "Offering id")),
199 request_body = CreateSlot,
200 responses(
201 (status = 201, description = "Slot added", body = WeeklySlotDto),
202 (status = 400, description = "Invalid weekday or minutes, an empty window, or an over-long topic", body = ErrorResponse),
203 (status = 401, description = "Not authenticated", body = ErrorResponse),
204 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
205 (status = 404, description = "Offering not found", body = ErrorResponse),
206 (status = 409, description = "Another slot of this week overlaps the window (`slot_overlap`), or the plan is at the slot cap (`slot_cap`)", body = ErrorResponse),
207 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
208 ),
209)]
210async fn add_offering_slot(
211 State(st): State<AppState>,
212 RequireManager(_user): RequireManager,
213 Path(id): Path<String>,
214 Json(req): Json<CreateSlot>,
215) -> Result<(StatusCode, Json<WeeklySlotDto>), AppError> {
216 let offering = offering_or_404(&id, &st.db).await?;
217 let (weekday, starts_at, ends_at, topic) = parse_slot(&req)?;
218 let slot = service::weekly_slot::add_for_offering(
219 &st.db,
220 offering.get_id(),
221 weekday,
222 starts_at,
223 ends_at,
224 topic,
225 )
226 .await?;
227 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))
228}
229
230/// Drop one slot of the offering's template week. Manager+. A slot of another
231/// offering, or one already gone, is a 404.
232#[utoipa::path(
233 delete,
234 path = "/{id}/weekly-plan/{slot}",
235 tag = "offerings",
236 security(("session_cookie" = [])),
237 params(
238 ("id" = String, Path, description = "Offering id"),
239 ("slot" = String, Path, description = "Slot id"),
240 ),
241 responses(
242 (status = 204, description = "Slot removed"),
243 (status = 401, description = "Not authenticated", body = ErrorResponse),
244 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
245 (status = 404, description = "Offering or slot not found", body = ErrorResponse),
246 ),
247)]
248async fn remove_offering_slot(
249 State(st): State<AppState>,
250 RequireManager(_user): RequireManager,
251 Path((id, slot)): Path<(String, String)>,
252) -> Result<StatusCode, AppError> {
253 let offering = offering_or_404(&id, &st.db).await?;
254 service::weekly_slot::remove_for_offering(
255 &st.db,
256 offering.get_id(),
257 &WeeklySlotId::from_key(&slot),
258 )
259 .await?;
260 Ok(StatusCode::NO_CONTENT)
261}
262
263/// The section's resolved weekly plan plus whose rows it is. Visible to the
264/// same eyes as the instance read: enrolled students, its teachers, its
265/// şube's homeroom teacher, and managers/admins.
266#[utoipa::path(
267 get,
268 path = "/{id}/weekly-plan",
269 tag = "instances",
270 security(("session_cookie" = [])),
271 params(("id" = String, Path, description = "Instance id")),
272 responses(
273 (status = 200, description = "The resolved plan and the flag that picked it", body = InstanceWeeklyPlan),
274 (status = 401, description = "Not authenticated", body = ErrorResponse),
275 (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
276 (status = 404, description = "Instance not found", body = ErrorResponse),
277 ),
278)]
279async fn list_instance_weekly_plan(
280 State(st): State<AppState>,
281 CurrentUser(user): CurrentUser,
282 Path(id): Path<String>,
283) -> Result<Json<InstanceWeeklyPlan>, AppError> {
284 let instance = instance_or_404(&id, &st.db).await?;
285 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
286 return Err(AppError::Forbidden(
287 "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view it",
288 ));
289 }
290 let weekly_plan = service::weekly_slot::resolved_for_instance(&st.db, &instance).await?;
291 Ok(Json(InstanceWeeklyPlan {
292 weekly_plan: weekly_plan.iter().map(WeeklySlotDto::new).collect(),
293 weekly_plan_inherited: instance.weekly_plan_inherited(),
294 }))
295}
296
297/// Add one slot to the section's own week. Requires teacher+ and a right over
298/// the instance; the write flips `weekly_plan_inherited` to `false` in the
299/// same statement, so from here the section's own rows — not the offering's
300/// template — are what every read resolves. Same overlap and cap refusals as
301/// the offering side.
302#[utoipa::path(
303 post,
304 path = "/{id}/weekly-plan",
305 tag = "instances",
306 security(("session_cookie" = [])),
307 params(("id" = String, Path, description = "Instance id")),
308 request_body = CreateSlot,
309 responses(
310 (status = 201, description = "Slot added; the section now overrides the template", body = WeeklySlotDto),
311 (status = 400, description = "Invalid weekday or minutes, an empty window, or an over-long topic", body = ErrorResponse),
312 (status = 401, description = "Not authenticated", body = ErrorResponse),
313 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
314 (status = 404, description = "Instance not found", body = ErrorResponse),
315 (status = 409, description = "This instance's academic year is archived; another slot of this week overlaps the window (`slot_overlap`); or the plan is at the slot cap (`slot_cap`)", body = ErrorResponse),
316 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
317 ),
318)]
319async fn add_instance_slot(
320 State(st): State<AppState>,
321 RequireTeacher(user): RequireTeacher,
322 Path(id): Path<String>,
323 Json(req): Json<CreateSlot>,
324) -> Result<(StatusCode, Json<WeeklySlotDto>), AppError> {
325 let instance = instance_or_404(&id, &st.db).await?;
326 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
327 service::class_course::require_open(&st.db, instance.get_id()).await?;
328 let (weekday, starts_at, ends_at, topic) = parse_slot(&req)?;
329 let slot =
330 service::weekly_slot::add_for_class(
331 &st.db,
332 instance.get_id(),
333 weekday,
334 starts_at,
335 ends_at,
336 topic,
337 )
338 .await?;
339 Ok((StatusCode::CREATED, Json(WeeklySlotDto::new(&slot))))
340}
341
342/// Drop one slot of the section's own week. Requires teacher+ and a right
343/// over the instance. The flag flip to `false` rides the delete in the same
344/// statement — dropping the last own row leaves the section with an
345/// authoritative *empty* plan, not a quiet return to the template
346/// (`DELETE /{id}/weekly-plan` is the way back to inherit). A slot of another
347/// instance, or one already gone, is a 404 that leaves the flag untouched.
348#[utoipa::path(
349 delete,
350 path = "/{id}/weekly-plan/{slot}",
351 tag = "instances",
352 security(("session_cookie" = [])),
353 params(
354 ("id" = String, Path, description = "Instance id"),
355 ("slot" = String, Path, description = "Slot id"),
356 ),
357 responses(
358 (status = 204, description = "Slot removed"),
359 (status = 401, description = "Not authenticated", body = ErrorResponse),
360 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
361 (status = 404, description = "Instance or slot not found", body = ErrorResponse),
362 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
363 ),
364)]
365async fn remove_instance_slot(
366 State(st): State<AppState>,
367 RequireTeacher(user): RequireTeacher,
368 Path((id, slot)): Path<(String, String)>,
369) -> Result<StatusCode, AppError> {
370 let instance = instance_or_404(&id, &st.db).await?;
371 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
372 service::class_course::require_open(&st.db, instance.get_id()).await?;
373 service::weekly_slot::remove_for_class(
374 &st.db,
375 instance.get_id(),
376 &WeeklySlotId::from_key(&slot),
377 )
378 .await?;
379 Ok(StatusCode::NO_CONTENT)
380}
381
382/// Reset the section's weekly plan to inherit — delete every slot of its own
383/// week and flip `weekly_plan_inherited` back to `true` in one statement, so
384/// the offering's template week is what every read resolves again.
385/// Idempotent for a section that never overrode.
386#[utoipa::path(
387 delete,
388 path = "/{id}/weekly-plan",
389 tag = "instances",
390 security(("session_cookie" = [])),
391 params(("id" = String, Path, description = "Instance id")),
392 responses(
393 (status = 204, description = "The section's own week is gone; the offering's template is authoritative again"),
394 (status = 401, description = "Not authenticated", body = ErrorResponse),
395 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
396 (status = 404, description = "Instance not found", body = ErrorResponse),
397 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
398 ),
399)]
400async fn reset_instance_weekly_plan(
401 State(st): State<AppState>,
402 RequireTeacher(user): RequireTeacher,
403 Path(id): Path<String>,
404) -> Result<StatusCode, AppError> {
405 let instance = instance_or_404(&id, &st.db).await?;
406 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
407 service::class_course::require_open(&st.db, instance.get_id()).await?;
408 service::weekly_slot::reset_for_class(&st.db, instance.get_id()).await?;
409 Ok(StatusCode::NO_CONTENT)
410}
411
412// ---- materialize: the plan, made real ----------------------------------------
413
414/// One materialize call: the range to cover, and whether to write.
415#[derive(Deserialize, ToSchema)]
416struct MaterializeRequest {
417 /// First instant to generate lessons from, UTC unix-milliseconds. The
418 /// instant names a *school* day (the school's timezone), so a late-evening
419 /// UTC instant is the next Turkish day.
420 #[schema(example = 1_793_318_400_000_i64)]
421 from: i64,
422 /// Last instant to generate lessons through, UTC unix-milliseconds; must
423 /// not precede `from`, and the span between the two may not exceed
424 /// `max_materialize_days` (`GET /limits`).
425 #[schema(example = 1_794_873_600_000_i64)]
426 to: i64,
427 /// `false` (the default) is a **dry run**: it reads, decides, and writes
428 /// nothing, so a client shows the outcome before committing. `true` writes
429 /// the lessons and answers with the rows that landed.
430 #[serde(default)]
431 #[schema(example = false)]
432 apply: bool,
433}
434
435/// One non-teaching day the range reached into.
436#[derive(Serialize, ToSchema)]
437struct BlockedDayResponse {
438 /// The calendar day, `YYYY-MM-DD`, in the school's timezone.
439 #[schema(example = "2026-10-29")]
440 date: String,
441 /// The holiday blocking it (`GET /holidays`).
442 #[schema(example = "29 Ekim Cumhuriyet Bayramı")]
443 holiday: String,
444}
445
446/// What one materialize call did — or, on a dry run, would have done.
447#[derive(Serialize, ToSchema)]
448struct MaterializeReport {
449 /// The range the call covered, UTC unix-milliseconds.
450 from: i64,
451 to: i64,
452 /// Whether the call wrote: `false` for a dry run.
453 applied: bool,
454 /// The resolved weekly plan's size — the lines the range was expanded
455 /// from.
456 slots: usize,
457 /// How many lessons the range *asked* for, before the holidays and the
458 /// instants the section already holds were subtracted.
459 candidates: usize,
460 /// The rows the database actually inserted, empty on a dry run. Same shape
461 /// as a hand-created lesson (`POST /instances/{id}/sessions`).
462 created: Vec<SessionResponse>,
463 /// Candidate instants the section already had a lesson at.
464 skipped_existing: usize,
465 /// Days a holiday reached into — one `blocked` entry each; a day counted
466 /// here produces no lesson at all.
467 skipped_holiday: usize,
468 blocked: Vec<BlockedDayResponse>,
469 /// How many days the range spanned, inclusive.
470 range_days: i64,
471}
472
473/// Expand this section's **resolved** weekly plan into dated lessons over
474/// `from`–`to`. Requires teacher+ and a right over the instance (the same door
475/// as adding a slot, since this writes lessons).
476///
477/// Nothing is ever deleted or updated: the call is additive, and a second call
478/// over the same range writes nothing (`UNIQUE (class_course, starts_at)`), so
479/// retrying after a failure is safe. A weekday the plan has no slot for
480/// produces nothing, and so does every day a holiday reaches into — those days
481/// are named in `blocked`. Weekends are *not* special-cased: a school may run
482/// Saturday, so only the plan and the calendar decide.
483///
484/// The generated lesson's teacher is the instance's **first assigned**
485/// teacher, and its topic is the slot's own topic, else the instance's
486/// resolved course title, else the literal `"Ders"`.
487#[utoipa::path(
488 post,
489 path = "/{id}/weekly-plan/materialize",
490 tag = "instances",
491 security(("session_cookie" = [])),
492 params(("id" = String, Path, description = "Instance id")),
493 request_body = MaterializeRequest,
494 responses(
495 (status = 200, description = "What the call did, or would do on a dry run", body = MaterializeReport),
496 (status = 400, description = "The range is inverted, lies in the past, spans more than a year, or would create more than `max_materialize_sessions` lessons", body = ErrorResponse),
497 (status = 401, description = "Not authenticated", body = ErrorResponse),
498 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
499 (status = 404, description = "Instance not found", body = ErrorResponse),
500 (status = 409, description = "This instance's academic year is archived; the section's weekly plan is empty (`instance_has_no_weekly_plan`); or no teacher is assigned to it (`instance_has_no_teacher`)", body = ErrorResponse),
501 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
502 ),
503)]
504async fn materialize_weekly_plan(
505 State(st): State<AppState>,
506 RequireTeacher(user): RequireTeacher,
507 Path(id): Path<String>,
508 Json(req): Json<MaterializeRequest>,
509) -> Result<Json<MaterializeReport>, AppError> {
510 let instance = instance_or_404(&id, &st.db).await?;
511 service::class_course::ensure_instance_teacher(&st.db, &user, instance.get_id()).await?;
512 // The day math shifts each instant by the zone offset before it reads the
513 // date off it, and `zoned_day` panics when that shifted value leaves
514 // chrono's representable range — so an absurd magnitude must be refused
515 // *here*, with checked arithmetic, naming the field. Checked before the
516 // offset is even loaded: the refusal cannot depend on the school's zone.
517 for (field, millis) in [("from", req.from), ("to", req.to)] {
518 if millis
519 .checked_add(i64::from(
520 crate::domain::calendar::MAX_ZONE_OFFSET_MINUTES,
521 ) * 60_000)
522 .and_then(chrono::DateTime::from_timestamp_millis)
523 .is_none()
524 {
525 return Err(AppError::Validation(crate::error::ValidationError::Invalid {
526 field,
527 reason: "is outside the representable calendar range",
528 }));
529 }
530 }
531 let from = Timestamp::from_millis(req.from);
532 let to = Timestamp::from_millis(req.to);
533 check_time_range(Some(from), Some(to))?;
534 // The same rule a hand-created lesson's `starts_at` obeys: nothing is
535 // scheduled to begin in the past. (`to` is deliberately not checked — a
536 // range may legitimately end in the past when `from` does not, which is
537 // how a school backfills a plan it only now entered.)
538 check_not_past("from", Some(from))?;
539 let school = service::settings::load(&st.db).await?;
540 let offset = zone_offset_minutes(school.get_timezone());
541
542 let outcome =
543 service::course_session::materialize(&st.db, &instance, from, to, req.apply, offset).await?;
544 // The teacher every generated row names, in one query.
545 let people = person_map(
546 outcome.created.iter().map(|session| *session.get_teacher()),
547 &st.db,
548 )
549 .await?;
550 let created = outcome
551 .created
552 .iter()
553 .map(|session| SessionResponse::new(session, &people))
554 .collect();
555 Ok(Json(MaterializeReport {
556 from: from.as_millis(),
557 to: to.as_millis(),
558 applied: outcome.applied,
559 slots: outcome.slots,
560 candidates: outcome.candidates,
561 created,
562 skipped_existing: outcome.skipped_existing,
563 skipped_holiday: outcome.skipped_holiday,
564 blocked: outcome
565 .blocked
566 .iter()
567 .map(|day| BlockedDayResponse {
568 date: day.day.to_string(),
569 holiday: day.holiday.as_str().to_string(),
570 })
571 .collect(),
572 range_days: outcome.range_days,
573 }))
574}