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

karne.rs66 lines, 2.4 KiBHistoryRawDownload
1//! The `karne_snapshot` table: the frozen per-student, per-term report card
2//! written when a term is archived.
3//!
4//! A report card is a *computed* read (D8) — per-instance weighted average,
5//! graded against the school's bands, then a `ders_saati`-weighted year
6//! average. The snapshot exists for the moment that computation must stop
7//! moving: once a term is archived, the report is a record of what the school
8//! issued, and a later correction to a mark must not silently rewrite a report
9//! card a family already holds. [`crate::service::karne::freeze`] writes the
10//! rows; [`crate::service::karne::build`] serves the snapshot back for an
11//! archived term and computes live for an open one.
12
13use sqlx::types::Json;
14
15use crate::database::Database;
16use crate::domain::term::TermId;
17use crate::domain::timestamp::Timestamp;
18use crate::domain::user::UserId;
19use crate::error::AppError;
20
21/// Write (or refresh) `user`'s frozen report for `term`.
22///
23/// An upsert rather than an insert: freezing is idempotent and converges —
24/// archiving an already-archived term writes nothing
25/// ([`crate::db::term::archive`]), and a re-run recomputes the same payload
26/// from the same rows, so overwriting it is a no-op in substance and one
27/// statement instead of an existence dance.
28pub async fn snapshot(
29 db: &Database,
30 term: &TermId,
31 user: &UserId,
32 payload: &serde_json::Value,
33) -> Result<(), AppError> {
34 let payload = Json(payload.clone());
35 sqlx::query!(
36 r#"INSERT INTO karne_snapshot (term, app_user, payload, created_at)
37 VALUES ($1, $2, $3, $4)
38 ON CONFLICT (term, app_user) DO UPDATE
39 SET payload = EXCLUDED.payload, created_at = EXCLUDED.created_at"#,
40 term.uuid(),
41 user.uuid(),
42 payload as _,
43 Timestamp::now().as_millis(),
44 )
45 .execute(db)
46 .await?;
47 Ok(())
48}
49
50/// `user`'s frozen report for `term`, or `None` when that term was never
51/// frozen (or they had no roster row to freeze).
52pub async fn read_snapshot(
53 db: &Database,
54 term: &TermId,
55 user: &UserId,
56) -> Result<Option<serde_json::Value>, AppError> {
57 let row = sqlx::query!(
58 r#"SELECT payload AS "payload: Json<serde_json::Value>"
59 FROM karne_snapshot WHERE term = $1 AND app_user = $2"#,
60 term.uuid(),
61 user.uuid(),
62 )
63 .fetch_optional(db)
64 .await?;
65 Ok(row.map(|row| row.payload.0))
66}