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

profile.rs154 lines, 6.1 KiBHistoryRawDownload
1//! The profile's motivational stats: the one aggregate read behind a profile
2//! response. The counters themselves are [`crate::domain::profile`]'s; the
3//! auto-earned badge rules next door are [`crate::domain::badge`] (pure) and
4//! [`crate::db::badge`] (reads and writes).
5
6use crate::database::Database;
7use crate::domain::badge::BadgeStats;
8use crate::domain::profile::ProfileStats;
9use crate::domain::user::UserId;
10use crate::error::AppError;
11
12/// One round trip, and only one: `courses` and `classes` arrive from the
13/// caller, which already holds them as the `total` of the paged class and
14/// course readers it ran for the profile's own blocks — re-counting them
15/// here would be two extra reads for numbers already in hand.
16///
17/// The pomodoro aggregate rides the per-user index, so it is a lookup and
18/// not a scan. `finished_at IS NOT NULL` is the filter: an open stint
19/// contributes to neither the count nor the sum — unfinished focus has no
20/// honest duration to add. The Postgres aggregate always answers exactly
21/// one row (`count` 0, `sum` NULL on no rows), so the empty school reads as
22/// zeros rather than as a missing row; `COALESCE` floors the sum the same
23/// way the old `GROUP ALL`-absent case did.
24///
25/// The lifetime counters ride along as a second statement in the *same*
26/// round rather than a [`super::badge::load`] call, which would be a second
27/// round trip for one record lookup. It repeats that projection — the
28/// `*_total` columns, because they are the badge rules' inputs — so the two
29/// must move together if the shape changes.
30pub async fn load(
31 db: &Database,
32 user: &UserId,
33 courses: i64,
34 classes: i64,
35) -> Result<ProfileStats, AppError> {
36 let totals = sqlx::query!(
37 r#"SELECT count(*) AS "sessions!: i64",
38 COALESCE(sum(finished_at - started_at), 0)::BIGINT AS "focus_ms!: i64"
39 FROM pomodoro_session
40 WHERE app_user = $1 AND finished_at IS NOT NULL"#,
41 user.uuid()
42 )
43 .fetch_one(db)
44 .await?;
45 let stats = sqlx::query_as!(
46 BadgeStats,
47 r#"SELECT homework_submitted_total AS homework_submitted,
48 homework_on_time_total AS homework_on_time,
49 exam_sat_total AS exam_sat,
50 pomodoro_finished_total AS pomodoro_finished,
51 pomodoro_focus_ms_total AS pomodoro_focus_ms,
52 marks_given_total AS marks_given,
53 lessons_held_total AS lessons_held,
54 pool_approved_total AS pool_approved,
55 pool_published_total AS pool_published,
56 lessons_attended_total AS lessons_attended,
57 high_mark_total AS high_mark,
58 study_streak_longest AS study_streak
59 FROM app_user WHERE id = $1"#,
60 user.uuid()
61 )
62 .fetch_optional(db)
63 .await?;
64 Ok(ProfileStats {
65 totals: stats.unwrap_or_default(),
66 pomodoro_sessions: totals.sessions,
67 // Floored at zero: a stint stamped by a wall clock that stepped
68 // backwards mid-session sums as negative time, and "you focused for
69 // minus five seconds" is never the truthful answer. New stints
70 // cannot go inverted (see [`PomodoroSession::finish`]); rows written
71 // before that guard still can, and this is what covers them.
72 pomodoro_focus_ms: totals.focus_ms.max(0),
73 courses,
74 classes,
75 })
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81 use crate::database::init_test_db;
82 use crate::domain::user::Username;
83
84 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
85 crate::db::user::create(db, Username::try_new(username).unwrap(), None)
86 .await
87 .unwrap()
88 }
89
90 #[tokio::test]
91 async fn an_account_with_no_history_reads_as_zeros() {
92 let (db, _leases) = init_test_db().await;
93 let user = a_user("profil-bos", &db).await;
94
95 let stats = load(&db, user.get_id(), 3, 1).await.unwrap();
96 assert_eq!(stats.pomodoro_sessions, 0);
97 assert_eq!(stats.pomodoro_focus_ms, 0);
98 assert_eq!(stats.totals.get_homework_submitted(), 0);
99 // The caller-supplied counts ride through untouched.
100 assert_eq!(stats.courses, 3);
101 assert_eq!(stats.classes, 1);
102 }
103
104 #[tokio::test]
105 async fn only_finished_stints_count_and_an_open_one_is_invisible() {
106 let (db, _leases) = init_test_db().await;
107 let user = a_user("profil-dolu", &db).await;
108
109 sqlx::query(
110 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \
111 VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)",
112 )
113 .bind(uuid::Uuid::now_v7())
114 .bind(user.get_id().uuid())
115 .bind(uuid::Uuid::now_v7())
116 .execute(&db)
117 .await
118 .unwrap();
119 // An open stint: contributes to neither the count nor the sum.
120 sqlx::query(
121 "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)",
122 )
123 .bind(uuid::Uuid::now_v7())
124 .bind(user.get_id().uuid())
125 .execute(&db)
126 .await
127 .unwrap();
128
129 let stats = load(&db, user.get_id(), 0, 0).await.unwrap();
130 assert_eq!(stats.pomodoro_sessions, 2);
131 assert_eq!(stats.pomodoro_focus_ms, 2000 + 1000);
132 }
133
134 #[tokio::test]
135 async fn a_negative_stint_sum_is_floored_at_zero() {
136 let (db, _leases) = init_test_db().await;
137 let user = a_user("profil-terstarihi", &db).await;
138
139 // A stint closed by a wall clock that stepped backwards: the sum is
140 // negative and "minus five seconds of focus" is never the answer.
141 sqlx::query(
142 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \
143 VALUES ($1, $2, 5000, 1000)",
144 )
145 .bind(uuid::Uuid::now_v7())
146 .bind(user.get_id().uuid())
147 .execute(&db)
148 .await
149 .unwrap();
150
151 let stats = load(&db, user.get_id(), 0, 0).await.unwrap();
152 assert_eq!(stats.pomodoro_focus_ms, 0);
153 }
154}