🎨 sync the accent color like theme and language
Browse files at this commit94906232e5b88fb0bd5658290ff1f53eae2ef426Parent: 4fe02bc- feat
- 🎨 sync the accent color like theme and language
14 changed files +420 -30
- Cargo.lock +1 -0
- Cargo.toml +4 -0
- README.md +22 -9
- src/constant.rs +15 -0
- src/domain/preferences.rs +113 -5
- src/domain/user.rs +9 -1
- src/lib.rs +2 -2
- src/migration_sql.rs +1 -0
- src/web/dto.rs +5 -0
- src/web/limits.rs +11 -0
- src/web/users.rs +14 -6
- tests/integration.rs +107 -6
- tests/partial_patch_users.rs +53 -1
- tests/persistence.rs +63 -0
Cargo.lockmodified+1 -0
| @@ -1800,6 +1800,7 @@ dependencies = [ | ||
| 1800 | 1800 | "proptest", |
| 1801 | 1801 | "quinn", |
| 1802 | 1802 | "rcgen", |
| 1803 | + "regex", | |
| 1803 | 1804 | "reqwest", |
| 1804 | 1805 | "rustls", |
| 1805 | 1806 | "rustls-pemfile", |
Cargo.tomlmodified+4 -0
| @@ -52,3 +52,7 @@ tempfile = "3" | ||
| 52 | 52 | tokio-tungstenite = "0.30.0" |
| 53 | 53 | futures-util = "0.3.32" |
| 54 | 54 | proptest = "1.11.0" |
| 55 | +# Compiles the pattern `GET /limits` publishes and runs it over the same inputs | |
| 56 | +# the validator sees, so the published promise cannot drift from the accept set. | |
| 57 | +# Already in the tree (tracing-subscriber's env-filter), so this costs no build. | |
| 58 | +regex = "1" |
README.mdmodified+22 -9
| @@ -92,9 +92,11 @@ School-varying policy is data, not code: exam kinds (each with its weight in | ||
| 92 | 92 | course averages), attendance statuses, grade-display bands, the note-file |
| 93 | 93 | size limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms** |
| 94 | 94 | are plain rows courses can link to (see "Per-school policy"). Each account |
| 95 | -also carries its own **UI preferences** — theme (`light`/`dark`) and language | |
| 96 | -(`tr`/`en`) — self-managed, admin-editable for anyone, `null` until chosen so | |
| 97 | -the client can fall back to the device preference. | |
| 95 | +also carries its own **UI preferences** — theme (`light`/`dark`), language | |
| 96 | +(`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — | |
| 97 | +any hex, deliberately not a fixed palette) — self-managed, admin-editable for | |
| 98 | +anyone, `null` until chosen so the client can fall back to the device | |
| 99 | +preference (or, for the accent, its own default). | |
| 98 | 100 | The **AI features live in separate projects**, so the backend also opens a |
| 99 | 101 | QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in, |
| 100 | 102 | register the capabilities they serve, and each request rides its own QUIC |
| @@ -292,6 +294,7 @@ response in the same commit. | ||
| 292 | 294 | "min_phone_digits": 7, "max_phone_digits": 15, |
| 293 | 295 | "roles": ["parent", "student", "teacher", "manager", "admin"], |
| 294 | 296 | "themes": ["light", "dark"], "languages": ["tr", "en"], |
| 297 | + "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7, | |
| 295 | 298 | "session_duration_days": 7 }, |
| 296 | 299 | "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 }, |
| 297 | 300 | "file": { "max_name_len": 255, "max_content_type_len": 100, |
| @@ -377,6 +380,12 @@ Notes: | ||
| 377 | 380 | manager edits it. What `/limits` carries for those knobs is the fixed range a |
| 378 | 381 | manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the |
| 379 | 382 | attendance statuses no school may remove. |
| 383 | +- **Open sets travel as a pattern.** `palette_color` accepts any hex accent | |
| 384 | + color, so `/limits` publishes `palette_color_pattern` (a regular expression) | |
| 385 | + and `palette_color_len` instead of a value list — validate the shape, not | |
| 386 | + membership in a palette. The pattern describes what the server *accepts*, so | |
| 387 | + it matches either case; the stored (and returned) value is lowercased, which | |
| 388 | + is the one place a response may differ in case from the request. | |
| 380 | 389 | - **Closed value sets ride along.** `roles`, `themes`, `languages`, course |
| 381 | 390 | `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the |
| 382 | 391 | uploadable `image_content_types` are the exact accepted spellings — build |
| @@ -493,7 +502,7 @@ course enrollments. | ||
| 493 | 502 | | Submit **own** homework (text + files); read own submission and grade | student | **Students only** — staff never submit; enrolled + in the audience; editable until graded; ≤ 10 files of any type, each ≤ `max_file_bytes`, always downloaded as attachments | |
| 494 | 503 | | Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full — statuses/marks/flags, never files | |
| 495 | 504 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | |
| 496 | -| Edit **own** UI preferences (theme, language) | student | `null` until chosen — the client then follows the device preference | | |
| 505 | +| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen — the client then follows the device preference | | |
| 497 | 506 | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere | |
| 498 | 507 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | |
| 499 | 508 | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call | |
| @@ -609,7 +618,7 @@ window filtering, before paging; negative values are a `400` naming the field. | ||
| 609 | 618 | | POST | `/auth/logout` | no | Clear session (no-op if none) | |
| 610 | 619 | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | |
| 611 | 620 | | PATCH | `/users/me` | student | Update own personal info (see below) | |
| 612 | -| PATCH | `/users/me/preferences` | student | `{theme?, language?}` — own UI preferences (see below) | | |
| 621 | +| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` — own UI preferences (see below) | | |
| 613 | 622 | | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged | |
| 614 | 623 | | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged | |
| 615 | 624 | | GET | `/users` | admin | List all users · paged | |
| @@ -914,13 +923,17 @@ ending with a letter or digit (3–32 chars). Staff-looking names (`admin`, | ||
| 914 | 923 | `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are |
| 915 | 924 | rejected at `/auth/register` only — the `ADMIN_USERNAME` bootstrap may still |
| 916 | 925 | seed them. |
| 917 | -UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`) ride on the | |
| 926 | +UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`, | |
| 927 | +`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the | |
| 918 | 928 | same account row and come back on every user response (`/auth/me` included). |
| 919 | 929 | `PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`) |
| 920 | 930 | uses the same field semantics as the profile patch: omitted keeps, `""` clears |
| 921 | 931 | back to `null` ("never chose" — the client then follows the device |
| 922 | -preference), anything else must be one of the listed values or the whole patch | |
| 923 | -is a `400`. | |
| 932 | +preference, or its own default accent), anything else must be valid or the | |
| 933 | +whole patch is a `400`. `palette_color` is the one **open** set: any valid hex | |
| 934 | +passes (mixed case in, stored and returned lowercase), so a new frontend | |
| 935 | +palette needs no backend change — `/limits` publishes its pattern rather than a | |
| 936 | +list of colors. | |
| 924 | 937 | |
| 925 | 938 | ## Appointments |
| 926 | 939 | |
| @@ -2556,7 +2569,7 @@ src/ | ||
| 2556 | 2569 | bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank |
| 2557 | 2570 | question/choice picture metadata; bytes on disk under FILES_PATH) |
| 2558 | 2571 | profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) |
| 2559 | - preferences.rs Theme · Language (own UI preferences) | |
| 2572 | + preferences.rs Theme · Language · PaletteColor (own UI preferences) | |
| 2560 | 2573 | message.rs MessageId · MessageSubject · MessageBody · MessageLabel · |
| 2561 | 2574 | Message (per-copy folders: inbox/sent/archive/trash) |
| 2562 | 2575 | parent_link.rs ParentLinkId · ParentLink (parent↔student tie = the parent's read grant) |
src/constant.rsmodified+15 -0
| @@ -648,6 +648,21 @@ pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark]; | ||
| 648 | 648 | |
| 649 | 649 | pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En]; |
| 650 | 650 | |
| 651 | +/// A `palette_color` preference is `#` plus exactly six hex digits — the length | |
| 652 | +/// of the whole string, `#` included. | |
| 653 | +pub const PALETTE_COLOR_LEN: usize = 7; | |
| 654 | + | |
| 655 | +/// The shape a `palette_color` must match, as a regular expression. This | |
| 656 | +/// describes what the server **accepts**, so it is case-insensitive — the value | |
| 657 | +/// is normalized to lowercase on store, and a client that sent `#FEFAE0` reads | |
| 658 | +/// `#fefae0` back. Publishing the lowercase-only form would have a client | |
| 659 | +/// reject its own valid input. | |
| 660 | +/// | |
| 661 | +/// Deliberately an open value set: any valid hex accent color, not a closed | |
| 662 | +/// list of the frontend's palette, so a new palette entry needs no backend | |
| 663 | +/// change. | |
| 664 | +pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$"; | |
| 665 | + | |
| 651 | 666 | /// Folders a sender may file their side into (`Sent` is their home). |
| 652 | 667 | pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash]; |
| 653 | 668 | /// Folders a recipient may file their side into (`Inbox` is their home). |
src/domain/preferences.rsmodified+113 -5
| @@ -1,11 +1,11 @@ | ||
| 1 | -//! Per-user UI preference newtypes: color theme and interface language. Both | |
| 2 | -//! are optional on the account — `None` means the user never chose, and the | |
| 3 | -//! frontend falls back to the device preference (`prefers-color-scheme`, | |
| 4 | -//! browser language). | |
| 1 | +//! Per-user UI preference newtypes: color theme, interface language, and accent | |
| 2 | +//! color. All are optional on the account — `None` means the user never chose, | |
| 3 | +//! and the frontend falls back to the device preference (`prefers-color-scheme`, | |
| 4 | +//! browser language) or its own default accent. | |
| 5 | 5 | |
| 6 | 6 | use surrealdb::types::SurrealValue; |
| 7 | 7 | |
| 8 | -use crate::constant::{LANGUAGES, THEMES}; | |
| 8 | +use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; | |
| 9 | 9 | use crate::error::ValidationError; |
| 10 | 10 | |
| 11 | 11 | /// The frontend color scheme. |
| @@ -71,9 +71,44 @@ impl Language { | ||
| 71 | 71 | } |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | +/// The frontend accent color, a 6-digit hex with a leading `#`, stored | |
| 75 | +/// lowercase (`"#fefae0"`). | |
| 76 | +/// | |
| 77 | +/// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid | |
| 78 | +/// hex passes, so the frontend can grow its palette without a backend change. | |
| 79 | +/// A plain newtype over `String`, which stores as a bare string — the same | |
| 80 | +/// `option<string>` column contract the two enums encode into. | |
| 81 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 82 | +pub struct PaletteColor(String); | |
| 83 | + | |
| 84 | +impl PaletteColor { | |
| 85 | + /// The wire/storage form: always lowercase. | |
| 86 | + pub fn as_str(&self) -> &str { | |
| 87 | + &self.0 | |
| 88 | + } | |
| 89 | + | |
| 90 | + /// Parse a wire string into an accent color. Mixed case is accepted (the | |
| 91 | + /// frontend's own validator is case-insensitive) and normalized down; no | |
| 92 | + /// trimming, so a stray space is a rejection rather than a silent fix. | |
| 93 | + pub fn try_from_str(value: &str) -> Result<Self, ValidationError> { | |
| 94 | + let invalid = ValidationError::Invalid { | |
| 95 | + field: "palette_color", | |
| 96 | + reason: "must be a hex color: # followed by exactly 6 hex digits, e.g. #fefae0", | |
| 97 | + }; | |
| 98 | + if value.len() != PALETTE_COLOR_LEN | |
| 99 | + || !value.starts_with('#') | |
| 100 | + || !value[1..].chars().all(|c| c.is_ascii_hexdigit()) | |
| 101 | + { | |
| 102 | + return Err(invalid); | |
| 103 | + } | |
| 104 | + Ok(Self(value.to_ascii_lowercase())) | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 74 | 108 | #[cfg(test)] |
| 75 | 109 | mod tests { |
| 76 | 110 | use super::*; |
| 111 | + use crate::constant::PALETTE_COLOR_PATTERN; | |
| 77 | 112 | use surrealdb::types::Value; |
| 78 | 113 | |
| 79 | 114 | #[tokio::test] |
| @@ -96,6 +131,75 @@ mod tests { | ||
| 96 | 131 | assert!(Language::try_from_str("").is_err()); |
| 97 | 132 | } |
| 98 | 133 | |
| 134 | + #[tokio::test] | |
| 135 | + async fn palette_color_normalizes_and_rejects_non_hex() { | |
| 136 | + assert_eq!( | |
| 137 | + PaletteColor::try_from_str("#fefae0").unwrap().as_str(), | |
| 138 | + "#fefae0" | |
| 139 | + ); | |
| 140 | + // Mixed case is accepted (the frontend validator is case-insensitive) | |
| 141 | + // and stored lowercase. | |
| 142 | + assert_eq!( | |
| 143 | + PaletteColor::try_from_str("#FEFAE0").unwrap().as_str(), | |
| 144 | + "#fefae0" | |
| 145 | + ); | |
| 146 | + assert!(PaletteColor::try_from_str("fefae0").is_err()); // no # | |
| 147 | + assert!(PaletteColor::try_from_str("#fff").is_err()); // short form | |
| 148 | + assert!(PaletteColor::try_from_str("#gggggg").is_err()); // not hex | |
| 149 | + assert!(PaletteColor::try_from_str("#fefae0 ").is_err()); // untrimmed | |
| 150 | + assert!(PaletteColor::try_from_str("").is_err()); | |
| 151 | + | |
| 152 | + // The pattern `GET /limits` publishes must describe the rule above. | |
| 153 | + assert_eq!( | |
| 154 | + PALETTE_COLOR_PATTERN, | |
| 155 | + format!("^#[0-9a-fA-F]{{{}}}$", PALETTE_COLOR_LEN - 1) | |
| 156 | + ); | |
| 157 | + } | |
| 158 | + | |
| 159 | + /// The published pattern is a promise a client validates its own input | |
| 160 | + /// against, so it must describe the **accept** set exactly — not the | |
| 161 | + /// storage set. A lowercase-only pattern would have a client refuse | |
| 162 | + /// `#FEFAE0`, which this server takes and normalizes. Length agreement | |
| 163 | + /// (above) cannot catch that; only running both sides over the same | |
| 164 | + /// examples can. | |
| 165 | + #[tokio::test] | |
| 166 | + async fn published_pattern_agrees_with_the_accept_set() { | |
| 167 | + let pattern = regex::Regex::new(PALETTE_COLOR_PATTERN).expect("pattern compiles"); | |
| 168 | + for accepted in [ | |
| 169 | + "#fefae0", "#FEFAE0", "#FeFaE0", "#000000", "#ffffff", "#283618", | |
| 170 | + ] { | |
| 171 | + assert!( | |
| 172 | + PaletteColor::try_from_str(accepted).is_ok(), | |
| 173 | + "validator rejects {accepted}" | |
| 174 | + ); | |
| 175 | + assert!( | |
| 176 | + pattern.is_match(accepted), | |
| 177 | + "published pattern rejects accepted input {accepted}" | |
| 178 | + ); | |
| 179 | + } | |
| 180 | + for rejected in [ | |
| 181 | + "", | |
| 182 | + "fefae0", | |
| 183 | + "#fff", | |
| 184 | + "#gggggg", | |
| 185 | + "#fefae0 ", | |
| 186 | + " #fefae0", | |
| 187 | + "#fefae01", | |
| 188 | + "#fefae", | |
| 189 | + "#fefae0\n", | |
| 190 | + "rebeccapurple", | |
| 191 | + ] { | |
| 192 | + assert!( | |
| 193 | + PaletteColor::try_from_str(rejected).is_err(), | |
| 194 | + "validator accepts {rejected:?}" | |
| 195 | + ); | |
| 196 | + assert!( | |
| 197 | + !pattern.is_match(rejected), | |
| 198 | + "published pattern accepts rejected input {rejected:?}" | |
| 199 | + ); | |
| 200 | + } | |
| 201 | + } | |
| 202 | + | |
| 99 | 203 | #[tokio::test] |
| 100 | 204 | async fn surreal_values_are_plain_strings() { |
| 101 | 205 | // `untagged` keeps the stored value a bare string so the `option<string>` |
| @@ -110,5 +214,9 @@ mod tests { | ||
| 110 | 214 | assert_eq!(value, Value::String(language.as_str().to_string())); |
| 111 | 215 | assert_eq!(Language::from_value(value).unwrap(), language); |
| 112 | 216 | } |
| 217 | + let color = PaletteColor::try_from_str("#fefae0").unwrap(); | |
| 218 | + let value = color.clone().into_value(); | |
| 219 | + assert_eq!(value, Value::String("#fefae0".to_string())); | |
| 220 | + assert_eq!(PaletteColor::from_value(value).unwrap(), color); | |
| 113 | 221 | } |
| 114 | 222 | } |
src/domain/user.rsmodified+9 -1
| @@ -9,7 +9,7 @@ use crate::constant::{DECOY_PASSWORD, USER_TABLE}; | ||
| 9 | 9 | use crate::database::Database; |
| 10 | 10 | use crate::domain::field_update::FieldUpdate; |
| 11 | 11 | use crate::domain::page::PagedList; |
| 12 | -use crate::domain::preferences::{Language, Theme}; | |
| 12 | +use crate::domain::preferences::{Language, PaletteColor, Theme}; | |
| 13 | 13 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; |
| 14 | 14 | use crate::domain::role::Role; |
| 15 | 15 | use crate::domain::text_fold::{search_fold, search_fold_sql}; |
| @@ -204,6 +204,7 @@ pub struct User { | ||
| 204 | 204 | // "never chose", which the frontend renders as the device preference. |
| 205 | 205 | theme: Option<Theme>, |
| 206 | 206 | language: Option<Language>, |
| 207 | + palette_color: Option<PaletteColor>, | |
| 207 | 208 | } |
| 208 | 209 | |
| 209 | 210 | impl User { |
| @@ -251,6 +252,10 @@ impl User { | ||
| 251 | 252 | self.language |
| 252 | 253 | } |
| 253 | 254 | |
| 255 | + pub fn get_palette_color(&self) -> Option<&PaletteColor> { | |
| 256 | + self.palette_color.as_ref() | |
| 257 | + } | |
| 258 | + | |
| 254 | 259 | /// Register a new account. New users always start as [`Role::Student`]; |
| 255 | 260 | /// elevation is a separate, admin-only action (see [`User::set_role`]). |
| 256 | 261 | pub async fn create( |
| @@ -291,6 +296,7 @@ impl User { | ||
| 291 | 296 | birth_date: None, |
| 292 | 297 | theme: None, |
| 293 | 298 | language: None, |
| 299 | + palette_color: None, | |
| 294 | 300 | }; |
| 295 | 301 | let created: Result<Option<User>, surrealdb::Error> = |
| 296 | 302 | db.create(user.id.record()).content(user.clone()).await; |
| @@ -497,11 +503,13 @@ impl User { | ||
| 497 | 503 | self, |
| 498 | 504 | theme: Option<Option<Theme>>, |
| 499 | 505 | language: Option<Option<Language>>, |
| 506 | + palette_color: Option<Option<PaletteColor>>, | |
| 500 | 507 | db: &Database, |
| 501 | 508 | ) -> Result<User, AppError> { |
| 502 | 509 | FieldUpdate::new(self.id.record()) |
| 503 | 510 | .set("theme", theme) |
| 504 | 511 | .set("language", language) |
| 512 | + .set("palette_color", palette_color) | |
| 505 | 513 | .run::<User>(db) |
| 506 | 514 | .await |
| 507 | 515 | } |
src/lib.rsmodified+2 -2
| @@ -36,7 +36,7 @@ use crate::state::AppState; | ||
| 36 | 36 | info( |
| 37 | 37 | title = "Hezarfen Backend API", |
| 38 | 38 | version = env!("CARGO_PKG_VERSION"), |
| 39 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", | |
| 39 | + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole class or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", | |
| 40 | 40 | ), |
| 41 | 41 | modifiers(&SecurityAddon), |
| 42 | 42 | tags( |
| @@ -44,7 +44,7 @@ use crate::state::AppState; | ||
| 44 | 44 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), |
| 45 | 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), |
| 46 | 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 47 | - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), | |
| 47 | + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), | |
| 48 | 48 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), |
| 49 | 49 | (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), |
| 50 | 50 | (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), |
src/migration_sql.rsmodified+1 -0
| @@ -50,6 +50,7 @@ pub const MIGRATION: &str = " | ||
| 50 | 50 | DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>; |
| 51 | 51 | DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>; |
| 52 | 52 | DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>; |
| 53 | + DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>; | |
| 53 | 54 | DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>; |
| 54 | 55 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; |
| 55 | 56 |
src/web/dto.rsmodified+5 -0
| @@ -136,6 +136,10 @@ pub struct UserResponse { | ||
| 136 | 136 | /// client should fall back to the device language. |
| 137 | 137 | #[schema(example = "tr")] |
| 138 | 138 | pub language: Option<String>, |
| 139 | + /// UI accent color as a 6-digit hex with a leading `#`, lowercase. `null` = | |
| 140 | + /// never chosen — the client should fall back to its default accent. | |
| 141 | + #[schema(example = "#fefae0")] | |
| 142 | + pub palette_color: Option<String>, | |
| 139 | 143 | } |
| 140 | 144 | |
| 141 | 145 | impl UserResponse { |
| @@ -151,6 +155,7 @@ impl UserResponse { | ||
| 151 | 155 | birth_date: user.get_birth_date().map(|v| v.as_str().to_string()), |
| 152 | 156 | theme: user.get_theme().map(|v| v.as_str().to_string()), |
| 153 | 157 | language: user.get_language().map(|v| v.as_str().to_string()), |
| 158 | + palette_color: user.get_palette_color().map(|v| v.as_str().to_string()), | |
| 154 | 159 | } |
| 155 | 160 | } |
| 156 | 161 | } |
src/web/limits.rsmodified+11 -0
| @@ -52,6 +52,15 @@ struct UserLimits { | ||
| 52 | 52 | /// Accepted `language` preference values (`null` clears it). |
| 53 | 53 | #[schema(example = json!(["tr", "en"]))] |
| 54 | 54 | languages: Vec<&'static str>, |
| 55 | + /// Shape a `palette_color` preference must match, as a regular expression | |
| 56 | + /// (`null` clears it). Open on purpose — any hex accent color, not a fixed | |
| 57 | + /// palette — so this is a pattern, not a value list like `themes`. Matches | |
| 58 | + /// either case: the server normalizes the value to lowercase on store, so a | |
| 59 | + /// response may differ in case from what was sent. | |
| 60 | + #[schema(example = "^#[0-9a-fA-F]{6}$")] | |
| 61 | + palette_color_pattern: &'static str, | |
| 62 | + /// Length of a `palette_color`, `#` included. | |
| 63 | + palette_color_len: usize, | |
| 55 | 64 | /// How long a login session stays valid, days. |
| 56 | 65 | session_duration_days: i64, |
| 57 | 66 | } |
| @@ -346,6 +355,8 @@ impl LimitsResponse { | ||
| 346 | 355 | roles: ROLES.iter().map(|role| role.as_str()).collect(), |
| 347 | 356 | themes: THEMES.iter().map(|theme| theme.as_str()).collect(), |
| 348 | 357 | languages: LANGUAGES.iter().map(|language| language.as_str()).collect(), |
| 358 | + palette_color_pattern: PALETTE_COLOR_PATTERN, | |
| 359 | + palette_color_len: PALETTE_COLOR_LEN, | |
| 349 | 360 | session_duration_days: SESSION_DURATION_DAYS, |
| 350 | 361 | }, |
| 351 | 362 | note: NoteLimits { |
src/web/users.rsmodified+14 -6
| @@ -10,7 +10,7 @@ use crate::database::Database; | ||
| 10 | 10 | use crate::domain::course::Course; |
| 11 | 11 | use crate::domain::enrollment::Enrollment; |
| 12 | 12 | use crate::domain::parent_link::ParentLink; |
| 13 | -use crate::domain::preferences::{Language, Theme}; | |
| 13 | +use crate::domain::preferences::{Language, PaletteColor, Theme}; | |
| 14 | 14 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; |
| 15 | 15 | use crate::domain::role::Role; |
| 16 | 16 | use crate::domain::user::{User, UserId}; |
| @@ -76,6 +76,10 @@ struct UpdatePreferences { | ||
| 76 | 76 | /// `tr` or `en` (ISO 639-1). |
| 77 | 77 | #[schema(example = "tr")] |
| 78 | 78 | language: Option<String>, |
| 79 | + /// Accent color as a 6-digit hex with a leading `#`; stored lowercase. Any | |
| 80 | + /// valid hex, not a fixed palette. | |
| 81 | + #[schema(example = "#fefae0")] | |
| 82 | + palette_color: Option<String>, | |
| 79 | 83 | } |
| 80 | 84 | |
| 81 | 85 | /// Resolve one patched field into what the save should write: absent (or |
| @@ -126,7 +130,10 @@ async fn apply_preferences( | ||
| 126 | 130 | ) -> Result<UserResponse, AppError> { |
| 127 | 131 | let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; |
| 128 | 132 | let language = merge_field(req.language.as_deref(), Language::try_from_str)?; |
| 129 | - let updated = user.set_preferences(theme, language, db).await?; | |
| 133 | + let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; | |
| 134 | + let updated = user | |
| 135 | + .set_preferences(theme, language, palette_color, db) | |
| 136 | + .await?; | |
| 130 | 137 | Ok(UserResponse::new(&updated)) |
| 131 | 138 | } |
| 132 | 139 | |
| @@ -238,8 +245,9 @@ async fn update_my_profile( | ||
| 238 | 245 | Ok(Json(apply_profile(user, &req, &st.db).await?)) |
| 239 | 246 | } |
| 240 | 247 | |
| 241 | -/// Update the caller's own UI preferences: `theme` (`light`/`dark`) and | |
| 242 | -/// `language` (`tr`/`en`). Any authenticated role. Omitted fields stay as they | |
| 248 | +/// Update the caller's own UI preferences: `theme` (`light`/`dark`), | |
| 249 | +/// `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). | |
| 250 | +/// Any authenticated role. Omitted fields stay as they | |
| 243 | 251 | /// are; an empty string clears one back to "never chose" (the client then |
| 244 | 252 | /// follows the device preference). Read them back on any user response, e.g. |
| 245 | 253 | /// `GET /auth/me`. |
| @@ -251,7 +259,7 @@ async fn update_my_profile( | ||
| 251 | 259 | request_body = UpdatePreferences, |
| 252 | 260 | responses( |
| 253 | 261 | (status = 200, description = "Updated user", body = UserResponse), |
| 254 | - (status = 400, description = "Invalid theme or language", body = ErrorResponse), | |
| 262 | + (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), | |
| 255 | 263 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 256 | 264 | ), |
| 257 | 265 | )] |
| @@ -330,7 +338,7 @@ async fn update_user_profile( | ||
| 330 | 338 | request_body = UpdatePreferences, |
| 331 | 339 | responses( |
| 332 | 340 | (status = 200, description = "Updated user", body = UserResponse), |
| 333 | - (status = 400, description = "Invalid theme or language", body = ErrorResponse), | |
| 341 | + (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), | |
| 334 | 342 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 335 | 343 | (status = 403, description = "Requires admin role", body = ErrorResponse), |
| 336 | 344 | (status = 404, description = "User not found", body = ErrorResponse), |
tests/integration.rsmodified+107 -6
| @@ -80,6 +80,16 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { | ||
| 80 | 80 | json!(hezarfen_backend::constant::MAX_USERNAME_LEN) |
| 81 | 81 | ); |
| 82 | 82 | assert_eq!(res.body["exam"]["modes"], json!(["sync", "async", "open"])); |
| 83 | + // The accent color is published as a pattern, not a value list — it is an | |
| 84 | + // open set, so a client validates the shape instead of a fixed palette. | |
| 85 | + assert_eq!( | |
| 86 | + res.body["user"]["palette_color_pattern"], | |
| 87 | + json!(hezarfen_backend::constant::PALETTE_COLOR_PATTERN) | |
| 88 | + ); | |
| 89 | + assert_eq!( | |
| 90 | + res.body["user"]["palette_color_len"], | |
| 91 | + json!(hezarfen_backend::constant::PALETTE_COLOR_LEN) | |
| 92 | + ); | |
| 83 | 93 | assert_eq!( |
| 84 | 94 | res.body["user"]["roles"], |
| 85 | 95 | json!(["parent", "student", "teacher", "manager", "admin"]) |
| @@ -5002,7 +5012,7 @@ async fn admin_reads_and_edits_any_profile_with_guards() { | ||
| 5002 | 5012 | ); |
| 5003 | 5013 | } |
| 5004 | 5014 | |
| 5005 | -// --- users: UI preferences (theme, language) ------------------------------ | |
| 5015 | +// --- users: UI preferences (theme, language, palette color) ------------------------------ | |
| 5006 | 5016 | |
| 5007 | 5017 | #[tokio::test] |
| 5008 | 5018 | async fn preferences_start_null_and_update_via_me_preferences() { |
| @@ -5014,21 +5024,27 @@ async fn preferences_start_null_and_update_via_me_preferences() { | ||
| 5014 | 5024 | assert_eq!(me.status, StatusCode::OK); |
| 5015 | 5025 | assert!(me.body["theme"].is_null(), "theme should start null"); |
| 5016 | 5026 | assert!(me.body["language"].is_null(), "language should start null"); |
| 5027 | + assert!( | |
| 5028 | + me.body["palette_color"].is_null(), | |
| 5029 | + "palette_color should start null" | |
| 5030 | + ); | |
| 5017 | 5031 | |
| 5018 | - // Set both through the self-service endpoint. | |
| 5032 | + // Set all three through the self-service endpoint. Mixed-case hex is | |
| 5033 | + // accepted and comes back lowercase. | |
| 5019 | 5034 | let res = send( |
| 5020 | 5035 | &app, |
| 5021 | 5036 | "PATCH", |
| 5022 | 5037 | "/users/me/preferences", |
| 5023 | 5038 | Some(&bob), |
| 5024 | - Some(json!({ "theme": "dark", "language": "tr" })), | |
| 5039 | + Some(json!({ "theme": "dark", "language": "tr", "palette_color": "#FEFAE0" })), | |
| 5025 | 5040 | ) |
| 5026 | 5041 | .await; |
| 5027 | 5042 | assert_eq!(res.status, StatusCode::OK); |
| 5028 | 5043 | assert_eq!(res.body["theme"], "dark"); |
| 5029 | 5044 | assert_eq!(res.body["language"], "tr"); |
| 5045 | + assert_eq!(res.body["palette_color"], "#fefae0"); | |
| 5030 | 5046 | |
| 5031 | - // Partial patch: only the theme changes, the language survives. | |
| 5047 | + // Partial patch: only the theme changes, the other two survive. | |
| 5032 | 5048 | let res = send( |
| 5033 | 5049 | &app, |
| 5034 | 5050 | "PATCH", |
| @@ -5040,8 +5056,23 @@ async fn preferences_start_null_and_update_via_me_preferences() { | ||
| 5040 | 5056 | assert_eq!(res.status, StatusCode::OK); |
| 5041 | 5057 | assert_eq!(res.body["theme"], "light"); |
| 5042 | 5058 | assert_eq!(res.body["language"], "tr"); |
| 5059 | + assert_eq!(res.body["palette_color"], "#fefae0"); | |
| 5060 | + | |
| 5061 | + // …and only the accent color changes, leaving theme and language alone. | |
| 5062 | + let res = send( | |
| 5063 | + &app, | |
| 5064 | + "PATCH", | |
| 5065 | + "/users/me/preferences", | |
| 5066 | + Some(&bob), | |
| 5067 | + Some(json!({ "palette_color": "#283618" })), | |
| 5068 | + ) | |
| 5069 | + .await; | |
| 5070 | + assert_eq!(res.status, StatusCode::OK); | |
| 5071 | + assert_eq!(res.body["palette_color"], "#283618"); | |
| 5072 | + assert_eq!(res.body["theme"], "light"); | |
| 5073 | + assert_eq!(res.body["language"], "tr"); | |
| 5043 | 5074 | |
| 5044 | - // Empty string clears back to "never chose"; the other stays. | |
| 5075 | + // Empty string clears back to "never chose"; the others stay. | |
| 5045 | 5076 | let res = send( |
| 5046 | 5077 | &app, |
| 5047 | 5078 | "PATCH", |
| @@ -5053,10 +5084,24 @@ async fn preferences_start_null_and_update_via_me_preferences() { | ||
| 5053 | 5084 | assert_eq!(res.status, StatusCode::OK); |
| 5054 | 5085 | assert!(res.body["theme"].is_null()); |
| 5055 | 5086 | assert_eq!(res.body["language"], "tr"); |
| 5087 | + assert_eq!(res.body["palette_color"], "#283618"); | |
| 5088 | + | |
| 5089 | + let res = send( | |
| 5090 | + &app, | |
| 5091 | + "PATCH", | |
| 5092 | + "/users/me/preferences", | |
| 5093 | + Some(&bob), | |
| 5094 | + Some(json!({ "palette_color": "" })), | |
| 5095 | + ) | |
| 5096 | + .await; | |
| 5097 | + assert_eq!(res.status, StatusCode::OK); | |
| 5098 | + assert!(res.body["palette_color"].is_null()); | |
| 5099 | + assert_eq!(res.body["language"], "tr"); | |
| 5056 | 5100 | |
| 5057 | 5101 | // The merged state is what /auth/me reports afterwards. |
| 5058 | 5102 | let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; |
| 5059 | 5103 | assert!(me.body["theme"].is_null()); |
| 5104 | + assert!(me.body["palette_color"].is_null()); | |
| 5060 | 5105 | assert_eq!(me.body["language"], "tr"); |
| 5061 | 5106 | |
| 5062 | 5107 | // No session -> 401. |
| @@ -5085,6 +5130,13 @@ async fn preferences_reject_invalid_values() { | ||
| 5085 | 5130 | json!({ "language": "turkish" }), |
| 5086 | 5131 | json!({ "language": "de" }), |
| 5087 | 5132 | json!({ "theme": "dark", "language": "nope" }), |
| 5133 | + json!({ "palette_color": "fefae0" }), // no leading # | |
| 5134 | + json!({ "palette_color": "#fff" }), // short form | |
| 5135 | + json!({ "palette_color": "#gggggg" }), // not hex | |
| 5136 | + json!({ "palette_color": "#fefae0 " }), // untrimmed | |
| 5137 | + json!({ "palette_color": "rebeccapurple" }), | |
| 5138 | + // Mixed: a valid theme must not sneak through beside a bad color. | |
| 5139 | + json!({ "theme": "dark", "palette_color": "#12345" }), | |
| 5088 | 5140 | ]; |
| 5089 | 5141 | for body in bad { |
| 5090 | 5142 | let res = send( |
| @@ -5105,6 +5157,10 @@ async fn preferences_reject_invalid_values() { | ||
| 5105 | 5157 | me.body["language"].is_null(), |
| 5106 | 5158 | "language should still be null" |
| 5107 | 5159 | ); |
| 5160 | + assert!( | |
| 5161 | + me.body["palette_color"].is_null(), | |
| 5162 | + "palette_color should still be null" | |
| 5163 | + ); | |
| 5108 | 5164 | } |
| 5109 | 5165 | |
| 5110 | 5166 | #[tokio::test] |
| @@ -5135,12 +5191,55 @@ async fn admin_edits_any_preferences_with_guards() { | ||
| 5135 | 5191 | "PATCH", |
| 5136 | 5192 | &format!("/users/{alice_id}/preferences"), |
| 5137 | 5193 | Some(&admin), |
| 5138 | - Some(json!({ "theme": "dark", "language": "en" })), | |
| 5194 | + Some(json!({ "theme": "dark", "language": "en", "palette_color": "#FEFAE0" })), | |
| 5139 | 5195 | ) |
| 5140 | 5196 | .await; |
| 5141 | 5197 | assert_eq!(res.status, StatusCode::OK); |
| 5142 | 5198 | assert_eq!(res.body["theme"], "dark"); |
| 5143 | 5199 | assert_eq!(res.body["language"], "en"); |
| 5200 | + assert_eq!( | |
| 5201 | + res.body["palette_color"], "#fefae0", | |
| 5202 | + "normalized on the admin path too" | |
| 5203 | + ); | |
| 5204 | + | |
| 5205 | + // The admin route patches partially and clears by `""` exactly like the | |
| 5206 | + // self-service one — one field at a time, the others untouched. | |
| 5207 | + let res = send( | |
| 5208 | + &app, | |
| 5209 | + "PATCH", | |
| 5210 | + &format!("/users/{alice_id}/preferences"), | |
| 5211 | + Some(&admin), | |
| 5212 | + Some(json!({ "palette_color": "#283618" })), | |
| 5213 | + ) | |
| 5214 | + .await; | |
| 5215 | + assert_eq!(res.status, StatusCode::OK); | |
| 5216 | + assert_eq!(res.body["palette_color"], "#283618"); | |
| 5217 | + assert_eq!(res.body["theme"], "dark", "theme lost to the color patch"); | |
| 5218 | + assert_eq!(res.body["language"], "en"); | |
| 5219 | + | |
| 5220 | + let res = send( | |
| 5221 | + &app, | |
| 5222 | + "PATCH", | |
| 5223 | + &format!("/users/{alice_id}/preferences"), | |
| 5224 | + Some(&admin), | |
| 5225 | + Some(json!({ "palette_color": "" })), | |
| 5226 | + ) | |
| 5227 | + .await; | |
| 5228 | + assert_eq!(res.status, StatusCode::OK); | |
| 5229 | + assert!(res.body["palette_color"].is_null()); | |
| 5230 | + assert_eq!(res.body["theme"], "dark", "theme lost to the clear"); | |
| 5231 | + assert_eq!(res.body["language"], "en"); | |
| 5232 | + | |
| 5233 | + // Back to a set value, so the reads below cover it too. | |
| 5234 | + let res = send( | |
| 5235 | + &app, | |
| 5236 | + "PATCH", | |
| 5237 | + &format!("/users/{alice_id}/preferences"), | |
| 5238 | + Some(&admin), | |
| 5239 | + Some(json!({ "palette_color": "#fefae0" })), | |
| 5240 | + ) | |
| 5241 | + .await; | |
| 5242 | + assert_eq!(res.status, StatusCode::OK); | |
| 5144 | 5243 | |
| 5145 | 5244 | // Admin reads them on the single-user lookup; alice sees them on /auth/me. |
| 5146 | 5245 | let one = send( |
| @@ -5153,9 +5252,11 @@ async fn admin_edits_any_preferences_with_guards() { | ||
| 5153 | 5252 | .await; |
| 5154 | 5253 | assert_eq!(one.body["theme"], "dark"); |
| 5155 | 5254 | assert_eq!(one.body["language"], "en"); |
| 5255 | + assert_eq!(one.body["palette_color"], "#fefae0"); | |
| 5156 | 5256 | let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; |
| 5157 | 5257 | assert_eq!(me.body["theme"], "dark"); |
| 5158 | 5258 | assert_eq!(me.body["language"], "en"); |
| 5259 | + assert_eq!(me.body["palette_color"], "#fefae0"); | |
| 5159 | 5260 | |
| 5160 | 5261 | // Unknown id -> 404. |
| 5161 | 5262 | assert_eq!( |
tests/partial_patch_users.rsmodified+53 -1
| @@ -55,7 +55,8 @@ async fn concurrent_preference_patches_keep_both_fields() { | ||
| 55 | 55 | } else { |
| 56 | 56 | ("light", "en") |
| 57 | 57 | }; |
| 58 | - let (a, b) = tokio::join!( | |
| 58 | + let color = if round % 2 == 0 { "#283618" } else { "#fefae0" }; | |
| 59 | + let (a, b, c) = tokio::join!( | |
| 59 | 60 | send( |
| 60 | 61 | &app, |
| 61 | 62 | "PATCH", |
| @@ -70,9 +71,17 @@ async fn concurrent_preference_patches_keep_both_fields() { | ||
| 70 | 71 | Some(&who), |
| 71 | 72 | Some(json!({ "language": language })), |
| 72 | 73 | ), |
| 74 | + send( | |
| 75 | + &app, | |
| 76 | + "PATCH", | |
| 77 | + "/users/me/preferences", | |
| 78 | + Some(&who), | |
| 79 | + Some(json!({ "palette_color": color })), | |
| 80 | + ), | |
| 73 | 81 | ); |
| 74 | 82 | assert_eq!(a.status, StatusCode::OK, "round {round} theme patch"); |
| 75 | 83 | assert_eq!(b.status, StatusCode::OK, "round {round} language patch"); |
| 84 | + assert_eq!(c.status, StatusCode::OK, "round {round} palette patch"); | |
| 76 | 85 | |
| 77 | 86 | let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body; |
| 78 | 87 | assert_eq!(after["theme"], theme, "round {round}: theme reverted"); |
| @@ -80,6 +89,10 @@ async fn concurrent_preference_patches_keep_both_fields() { | ||
| 80 | 89 | after["language"], language, |
| 81 | 90 | "round {round}: language reverted" |
| 82 | 91 | ); |
| 92 | + assert_eq!( | |
| 93 | + after["palette_color"], color, | |
| 94 | + "round {round}: palette_color reverted" | |
| 95 | + ); | |
| 83 | 96 | } |
| 84 | 97 | } |
| 85 | 98 | |
| @@ -157,4 +170,43 @@ async fn omitted_keeps_empty_clears_and_validation_still_bites() { | ||
| 157 | 170 | StatusCode::BAD_REQUEST, |
| 158 | 171 | "bad theme refused" |
| 159 | 172 | ); |
| 173 | + | |
| 174 | + // The accent color joins them: set, cleared by `""`, refused when malformed | |
| 175 | + // — and never touching the other two preferences. | |
| 176 | + let set = send( | |
| 177 | + &app, | |
| 178 | + "PATCH", | |
| 179 | + "/users/me/preferences", | |
| 180 | + Some(&who), | |
| 181 | + Some(json!({ "theme": "dark", "palette_color": "#FEFAE0" })), | |
| 182 | + ) | |
| 183 | + .await; | |
| 184 | + assert_eq!(set.status, StatusCode::OK, "{}", set.body); | |
| 185 | + assert_eq!(set.body["palette_color"], "#fefae0", "stored lowercase"); | |
| 186 | + | |
| 187 | + let cleared = send( | |
| 188 | + &app, | |
| 189 | + "PATCH", | |
| 190 | + "/users/me/preferences", | |
| 191 | + Some(&who), | |
| 192 | + Some(json!({ "palette_color": "" })), | |
| 193 | + ) | |
| 194 | + .await; | |
| 195 | + assert_eq!(cleared.status, StatusCode::OK); | |
| 196 | + assert_eq!(cleared.body["palette_color"], json!(null)); | |
| 197 | + assert_eq!(cleared.body["theme"], "dark", "theme lost to the clear"); | |
| 198 | + | |
| 199 | + let bad_color = send( | |
| 200 | + &app, | |
| 201 | + "PATCH", | |
| 202 | + "/users/me/preferences", | |
| 203 | + Some(&who), | |
| 204 | + Some(json!({ "palette_color": "#fff" })), | |
| 205 | + ) | |
| 206 | + .await; | |
| 207 | + assert_eq!( | |
| 208 | + bad_color.status, | |
| 209 | + StatusCode::BAD_REQUEST, | |
| 210 | + "bad palette color refused" | |
| 211 | + ); | |
| 160 | 212 | } |
tests/persistence.rsmodified+63 -0
| @@ -1695,3 +1695,66 @@ async fn fee_plans_and_their_charges_survive_remigration() { | ||
| 1695 | 1695 | "the charges the placement raised are still owed" |
| 1696 | 1696 | ); |
| 1697 | 1697 | } |
| 1698 | + | |
| 1699 | +/// A user row written before `palette_color` existed needs no backfill: the | |
| 1700 | +/// column is `option<string>`, so the absent key reads back as "never chose" | |
| 1701 | +/// and a later patch sets it in place. Adding an option column to a SCHEMAFULL | |
| 1702 | +/// table must not strand the rows already there. | |
| 1703 | +#[tokio::test] | |
| 1704 | +async fn a_user_row_without_palette_color_still_reads_and_patches() { | |
| 1705 | + let (app, db) = common::app_and_db().await; | |
| 1706 | + let ali = common::login(&app, "ali").await; | |
| 1707 | + | |
| 1708 | + // Write the column first: a fresh row stores no key for a `None` option, so | |
| 1709 | + // UNSET alone would be a no-op and this test would prove nothing. | |
| 1710 | + let set = send( | |
| 1711 | + &app, | |
| 1712 | + "PATCH", | |
| 1713 | + "/users/me/preferences", | |
| 1714 | + Some(&ali), | |
| 1715 | + Some(json!({ "palette_color": "#283618" })), | |
| 1716 | + ) | |
| 1717 | + .await; | |
| 1718 | + assert_eq!(set.status, StatusCode::OK, "{}", set.body); | |
| 1719 | + let stored: Vec<String> = db | |
| 1720 | + .query("SELECT VALUE palette_color FROM user WHERE palette_color != NONE;") | |
| 1721 | + .await | |
| 1722 | + .expect("read the column") | |
| 1723 | + .check() | |
| 1724 | + .expect("read the column") | |
| 1725 | + .take(0) | |
| 1726 | + .expect("read the column"); | |
| 1727 | + assert_eq!( | |
| 1728 | + stored, | |
| 1729 | + vec!["#283618"], | |
| 1730 | + "the column must exist to be aged away" | |
| 1731 | + ); | |
| 1732 | + | |
| 1733 | + // Now age the row into the pre-accent shape: the key goes away, exactly as | |
| 1734 | + // on a row a binary without this column wrote. | |
| 1735 | + db.query("UPDATE user UNSET palette_color;") | |
| 1736 | + .await | |
| 1737 | + .expect("age the row") | |
| 1738 | + .check() | |
| 1739 | + .expect("age the row"); | |
| 1740 | + | |
| 1741 | + let app = reboot(&db).await; | |
| 1742 | + | |
| 1743 | + let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; | |
| 1744 | + assert_eq!(me.status, StatusCode::OK, "{}", me.body); | |
| 1745 | + assert!( | |
| 1746 | + me.body["palette_color"].is_null(), | |
| 1747 | + "an aged row must read as never-chosen, not error" | |
| 1748 | + ); | |
| 1749 | + | |
| 1750 | + let set = send( | |
| 1751 | + &app, | |
| 1752 | + "PATCH", | |
| 1753 | + "/users/me/preferences", | |
| 1754 | + Some(&ali), | |
| 1755 | + Some(json!({ "palette_color": "#fefae0" })), | |
| 1756 | + ) | |
| 1757 | + .await; | |
| 1758 | + assert_eq!(set.status, StatusCode::OK, "{}", set.body); | |
| 1759 | + assert_eq!(set.body["palette_color"], "#fefae0"); | |
| 1760 | +} |