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.rs354 lines, 12.1 KiBHistoryRawDownload
1//! Personal-info newtypes shared by every account role — student, teacher,
2//! manager, and admin records all carry the same optional contact fields.
3
4use crate::constant::{MAX_ADDRESS_LEN, MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN};
5use crate::domain::badge::BadgeStats;
6use crate::domain::timestamp::Timestamp;
7use crate::error::ValidationError;
8use crate::validate::{validate_email, validate_optional, validate_phone, validate_required};
9
10/// A person's given or family name. One type serves both fields — the `field`
11/// tag only steers the error message ("name …" vs "surname …"). Stored trimmed;
12/// unicode is welcome (names are not ASCII).
13#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
14#[sqlx(transparent)]
15pub struct PersonName(String);
16
17impl PersonName {
18 pub fn try_new(field: &'static str, value: &str) -> Result<Self, ValidationError> {
19 validate_required(field, value, MAX_NAME_LEN)?;
20 Ok(Self(value.trim().to_string()))
21 }
22
23 pub fn as_str(&self) -> &str {
24 &self.0
25 }
26}
27
28/// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed.
29#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
30#[sqlx(transparent)]
31pub struct Email(String);
32
33impl Email {
34 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
35 validate_email(value)?;
36 Ok(Self(value.trim().to_string()))
37 }
38
39 pub fn as_str(&self) -> &str {
40 &self.0
41 }
42}
43
44/// A phone number: optional leading `+`, 7–15 digits, cosmetic separators
45/// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given.
46#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
47#[sqlx(transparent)]
48pub struct Phone(String);
49
50impl Phone {
51 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
52 validate_phone(value)?;
53 Ok(Self(value.trim().to_string()))
54 }
55
56 pub fn as_str(&self) -> &str {
57 &self.0
58 }
59}
60
61/// A birth date, canonicalized to `YYYY-MM-DD`. Construction parses the input
62/// as a real calendar date (no 2026-02-30) and refuses future dates.
63///
64/// "Future" is judged against UTC **plus one day of grace**: a birth date is a
65/// calendar date on the writer's wall, and a client ahead of UTC (up to
66/// UTC+14) legitimately submits a date the server's UTC calendar hasn't
67/// reached yet. Without the grace, "born today" entered from Istanbul or
68/// Auckland shortly after local midnight is wrongly rejected.
69#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
70#[sqlx(transparent)]
71pub struct BirthDate(String);
72
73impl BirthDate {
74 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
75 let date = chrono::NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d").map_err(|_| {
76 ValidationError::Invalid {
77 field: "birth_date",
78 reason: "must be a calendar date in YYYY-MM-DD form",
79 }
80 })?;
81 let latest_allowed = Timestamp::today_utc()
82 .succ_opt()
83 .unwrap_or(chrono::NaiveDate::MAX);
84 if date > latest_allowed {
85 return Err(ValidationError::Invalid {
86 field: "birth_date",
87 reason: "must not be in the future",
88 });
89 }
90 Ok(Self(date.format("%Y-%m-%d").to_string()))
91 }
92
93 pub fn as_str(&self) -> &str {
94 &self.0
95 }
96}
97
98/// The name a profile shows instead of the legal one — a nickname, a shortened
99/// form, whatever the person answers to. Stored trimmed; unicode is welcome,
100/// same as [`PersonName`] and unlike the ASCII-only username.
101#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
102#[sqlx(transparent)]
103pub struct DisplayName(String);
104
105impl DisplayName {
106 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
107 validate_required("display_name", value, MAX_DISPLAY_NAME_LEN)?;
108 Ok(Self(value.trim().to_string()))
109 }
110
111 pub fn as_str(&self) -> &str {
112 &self.0
113 }
114}
115
116/// A short self-description on the public profile. Free text within
117/// [`MAX_BIO_LEN`], blank allowed — an empty bio is a written-then-erased one,
118/// which is a legitimate state and not an error. Stored trimmed.
119#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
120#[sqlx(transparent)]
121pub struct Bio(String);
122
123impl Bio {
124 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
125 validate_optional("bio", value, MAX_BIO_LEN)?;
126 Ok(Self(value.trim().to_string()))
127 }
128
129 pub fn as_str(&self) -> &str {
130 &self.0
131 }
132}
133
134/// A person's gender, self-declared and deliberately coarse — the school
135/// office needs a word for a form, not an identity system. One of four fixed
136/// wire values (`female`, `male`, `other`, `undisclosed`), stored as the same
137/// string; `NULL` (never chosen) is a row state, not a fifth value.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
139#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
140pub enum Gender {
141 Female,
142 Male,
143 Other,
144 Undisclosed,
145}
146
147impl Gender {
148 /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`.
149 pub fn as_str(self) -> &'static str {
150 match self {
151 Gender::Female => "female",
152 Gender::Male => "male",
153 Gender::Other => "other",
154 Gender::Undisclosed => "undisclosed",
155 }
156 }
157
158 /// Parse a wire string into a gender — the inverse of [`Gender::as_str`].
159 /// The vocabulary is closed, so an unknown value is a plain 400, the same
160 /// refusal an out-of-vocabulary `theme` gets.
161 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
162 GENDERS
163 .into_iter()
164 .find(|gender| gender.as_str() == value)
165 .ok_or(ValidationError::Invalid {
166 field: "gender",
167 reason: "must be one of: female, male, other, undisclosed",
168 })
169 }
170}
171
172pub const GENDERS: [Gender; 4] = [
173 Gender::Female,
174 Gender::Male,
175 Gender::Other,
176 Gender::Undisclosed,
177];
178
179/// A postal address, [`MAX_ADDRESS_LEN`] characters at most. Free text on
180/// purpose — addresses do not fit a shape the way a phone number does, and
181/// enforcing one would only reject real ones. Stored trimmed.
182#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
183#[sqlx(transparent)]
184pub struct Address(String);
185
186impl Address {
187 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
188 validate_required("address", value, MAX_ADDRESS_LEN)?;
189 Ok(Self(value.trim().to_string()))
190 }
191
192 pub fn as_str(&self) -> &str {
193 &self.0
194 }
195}
196
197/// The motivational counters on a public profile. Every field is a derived
198/// count, never a settable one: zero rows is a true zero, so these are `i64`
199/// and never `Option` — a `null` in this API means "never chose", which a
200/// derived number can't be. An account that predates the feature therefore
201/// reads exactly like a fresh one.
202///
203/// One named struct on purpose: the auto-earned badge rules take a whole
204/// `ProfileStats` as their sole input, so a counter added here reaches them
205/// without touching a signature.
206#[derive(Debug, Clone)]
207pub struct ProfileStats {
208 pub(crate) pomodoro_sessions: i64,
209 pub(crate) pomodoro_focus_ms: i64,
210 pub(crate) courses: i64,
211 pub(crate) classes: i64,
212 pub(crate) totals: BadgeStats,
213}
214
215impl ProfileStats {
216 pub fn get_pomodoro_sessions(&self) -> i64 {
217 self.pomodoro_sessions
218 }
219
220 pub fn get_pomodoro_focus_ms(&self) -> i64 {
221 self.pomodoro_focus_ms
222 }
223
224 pub fn get_courses(&self) -> i64 {
225 self.courses
226 }
227
228 pub fn get_classes(&self) -> i64 {
229 self.classes
230 }
231
232 /// The stored lifetime counters — the same numbers [`crate::domain::badge`]
233 /// decides an award from, so a profile read can check the shelf without a
234 /// second load of them.
235 pub fn get_totals(&self) -> &BadgeStats {
236 &self.totals
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[tokio::test]
245 async fn person_name_trims_and_validates() {
246 assert_eq!(
247 PersonName::try_new("name", " Ada ").unwrap().as_str(),
248 "Ada"
249 );
250 // Unicode names must pass — this is not the ASCII-only username rule.
251 assert_eq!(
252 PersonName::try_new("surname", "Gümüş").unwrap().as_str(),
253 "Gümüş"
254 );
255 assert!(PersonName::try_new("name", " ").is_err());
256 assert!(PersonName::try_new("name", &"x".repeat(101)).is_err());
257 }
258
259 #[tokio::test]
260 async fn name_errors_carry_the_field_tag() {
261 // One newtype serves two fields; the message must still say which one.
262 let err = PersonName::try_new("surname", "").unwrap_err();
263 assert!(err.to_string().contains("surname"));
264 }
265
266 #[tokio::test]
267 async fn email_and_phone_store_trimmed() {
268 assert_eq!(
269 Email::try_new(" ada@example.com ").unwrap().as_str(),
270 "ada@example.com"
271 );
272 assert_eq!(
273 Phone::try_new(" +90 555 123 45 67 ").unwrap().as_str(),
274 "+90 555 123 45 67"
275 );
276 }
277
278 #[tokio::test]
279 async fn birth_date_canonicalizes() {
280 assert_eq!(
281 BirthDate::try_new("1990-1-2").unwrap().as_str(),
282 "1990-01-02"
283 );
284 assert!(BirthDate::try_new("1990-02-30").is_err()); // not a real date
285 assert!(BirthDate::try_new("02/01/1990").is_err()); // wrong format
286 assert!(BirthDate::try_new("9999-01-01").is_err()); // future
287 assert!(BirthDate::try_new("").is_err());
288 }
289
290 #[tokio::test]
291 async fn birth_date_tolerates_clients_ahead_of_utc() {
292 let fmt = |d: chrono::NaiveDate| d.format("%Y-%m-%d").to_string();
293 let today = Timestamp::today_utc();
294
295 // "Today" for a client in UTC+14 can be the server's UTC tomorrow —
296 // that must pass, or "born today" fails near midnight east of UTC.
297 assert!(BirthDate::try_new(&fmt(today)).is_ok());
298 assert!(BirthDate::try_new(&fmt(today.succ_opt().unwrap())).is_ok());
299
300 // Two days out is beyond any real timezone: still rejected.
301 let two_days_out = today.succ_opt().unwrap().succ_opt().unwrap();
302 assert!(BirthDate::try_new(&fmt(two_days_out)).is_err());
303 }
304
305 #[tokio::test]
306 async fn display_name_trims_and_validates() {
307 assert_eq!(DisplayName::try_new(" Ada ").unwrap().as_str(), "Ada");
308 // A display name is a name, not a username: unicode passes.
309 assert_eq!(
310 DisplayName::try_new("Gümüş 🐢").unwrap().as_str(),
311 "Gümüş 🐢"
312 );
313 assert!(DisplayName::try_new(" ").is_err());
314 assert!(DisplayName::try_new(&"x".repeat(MAX_DISPLAY_NAME_LEN + 1)).is_err());
315 }
316
317 #[tokio::test]
318 async fn bio_trims_and_validates() {
319 assert_eq!(Bio::try_new(" hello ").unwrap().as_str(), "hello");
320 // Blank is a legitimate bio (erased), unlike a blank display name.
321 assert_eq!(Bio::try_new(" ").unwrap().as_str(), "");
322 assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN)).is_ok());
323 assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN + 1)).is_err());
324 }
325
326 #[tokio::test]
327 async fn gender_parses_the_closed_vocabulary() {
328 assert_eq!(Gender::try_from_str("female").unwrap(), Gender::Female);
329 assert_eq!(Gender::try_from_str("male").unwrap().as_str(), "male");
330 assert_eq!(Gender::try_from_str("other").unwrap(), Gender::Other);
331 assert_eq!(
332 Gender::try_from_str("undisclosed").unwrap(),
333 Gender::Undisclosed
334 );
335 // The vocabulary is closed: no synonyms, no case play, no blank.
336 assert!(Gender::try_from_str("woman").is_err());
337 assert!(Gender::try_from_str("FEMALE").is_err());
338 assert!(Gender::try_from_str("").is_err());
339 }
340
341 #[tokio::test]
342 async fn address_trims_and_respects_the_bound() {
343 assert_eq!(
344 Address::try_new(" Çamlık Mah. 2. Sk. No: 7 ")
345 .unwrap()
346 .as_str(),
347 "Çamlık Mah. 2. Sk. No: 7"
348 );
349 // Blank is "not given" — the three-state PATCH clears it, never stores it.
350 assert!(Address::try_new(" ").is_err());
351 assert!(Address::try_new(&"x".repeat(MAX_ADDRESS_LEN)).is_ok());
352 assert!(Address::try_new(&"x".repeat(MAX_ADDRESS_LEN + 1)).is_err());
353 }
354}