From 94906232e5b88fb0bd5658290ff1f53eae2ef426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 30 Jul 2026 04:03:22 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=A8=20sync=20the=20accent=20co?= =?UTF-8?q?lor=20like=20theme=20and=20language?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The frontend's palette picker kept the chosen accent in localStorage, so it never followed the user to another device. `palette_color` joins `theme` and `language` as a third per-user preference: a nullable hex color on the user row, self-managed and admin-editable through the same two PATCH routes, `null` until chosen. The value set is deliberately open — any `#rrggbb` — rather than an enum of the frontend's palette entries, so adding a palette is a frontend-only change. Mixed case is accepted and stored lowercase, which is why `/limits` publishes the accept-set pattern (`^#[0-9a-fA-F]{6}$`) and not the storage form: a client validating its own input against the published regex has to agree with the server, and a test now compiles that regex and runs it over the validator's own accept/reject examples. --- Cargo.lock | 1 + Cargo.toml | 4 ++ README.md | 31 ++++++--- src/constant.rs | 15 +++++ src/domain/preferences.rs | 118 +++++++++++++++++++++++++++++++++-- src/domain/user.rs | 10 ++- src/lib.rs | 4 +- src/migration_sql.rs | 1 + src/web/dto.rs | 5 ++ src/web/limits.rs | 11 ++++ src/web/users.rs | 20 ++++-- tests/integration.rs | 113 +++++++++++++++++++++++++++++++-- tests/partial_patch_users.rs | 54 +++++++++++++++- tests/persistence.rs | 63 +++++++++++++++++++ 14 files changed, 420 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8235047..c487890 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1800,6 +1800,7 @@ dependencies = [ "proptest", "quinn", "rcgen", + "regex", "reqwest", "rustls", "rustls-pemfile", diff --git a/Cargo.toml b/Cargo.toml index 6b03b5a..9dfc196 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,3 +52,7 @@ tempfile = "3" tokio-tungstenite = "0.30.0" futures-util = "0.3.32" proptest = "1.11.0" +# Compiles the pattern `GET /limits` publishes and runs it over the same inputs +# the validator sees, so the published promise cannot drift from the accept set. +# Already in the tree (tracing-subscriber's env-filter), so this costs no build. +regex = "1" diff --git a/README.md b/README.md index cc10b8b..bf82194 100644 --- a/README.md +++ b/README.md @@ -92,9 +92,11 @@ School-varying policy is data, not code: exam kinds (each with its weight in course averages), attendance statuses, grade-display bands, the note-file size limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms** are plain rows courses can link to (see "Per-school policy"). Each account -also carries its own **UI preferences** — theme (`light`/`dark`) and language -(`tr`/`en`) — self-managed, admin-editable for anyone, `null` until chosen so -the client can fall back to the device preference. +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, deliberately not a fixed palette) — self-managed, admin-editable for +anyone, `null` until chosen so the client can fall back to the device +preference (or, for the accent, its own default). The **AI features live in separate projects**, so the backend also opens a QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in, register the capabilities they serve, and each request rides its own QUIC @@ -292,6 +294,7 @@ response in the same commit. "min_phone_digits": 7, "max_phone_digits": 15, "roles": ["parent", "student", "teacher", "manager", "admin"], "themes": ["light", "dark"], "languages": ["tr", "en"], + "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7, "session_duration_days": 7 }, "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 }, "file": { "max_name_len": 255, "max_content_type_len": 100, @@ -377,6 +380,12 @@ Notes: manager edits it. What `/limits` carries for those knobs is the fixed range a manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the attendance statuses no school may remove. +- **Open sets travel as a pattern.** `palette_color` accepts any hex accent + color, so `/limits` publishes `palette_color_pattern` (a regular expression) + and `palette_color_len` instead of a value list — validate the shape, not + membership in a palette. The pattern describes what the server *accepts*, so + it matches either case; the stored (and returned) value is lowercased, which + is the one place a response may differ in case from the request. - **Closed value sets ride along.** `roles`, `themes`, `languages`, course `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the uploadable `image_content_types` are the exact accepted spellings — build @@ -493,7 +502,7 @@ course enrollments. | 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 | | 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 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | -| Edit **own** UI preferences (theme, language) | student | `null` until chosen — the client then follows the device preference | +| Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen — the client then follows the device preference | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | | 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. | POST | `/auth/logout` | no | Clear session (no-op if none) | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | | PATCH | `/users/me` | student | Update own personal info (see below) | -| PATCH | `/users/me/preferences` | student | `{theme?, language?}` — own UI preferences (see below) | +| PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` — own UI preferences (see below) | | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged | | GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); refs only, no contact info · paged | | GET | `/users` | admin | List all users · paged | @@ -914,13 +923,17 @@ ending with a letter or digit (3–32 chars). Staff-looking names (`admin`, `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are rejected at `/auth/register` only — the `ADMIN_USERNAME` bootstrap may still seed them. -UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`) ride on the +UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`, +`palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the same account row and come back on every user response (`/auth/me` included). `PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`) uses the same field semantics as the profile patch: omitted keeps, `""` clears back to `null` ("never chose" — the client then follows the device -preference), anything else must be one of the listed values or the whole patch -is a `400`. +preference, or its own default accent), anything else must be valid or the +whole patch is a `400`. `palette_color` is the one **open** set: any valid hex +passes (mixed case in, stored and returned lowercase), so a new frontend +palette needs no backend change — `/limits` publishes its pattern rather than a +list of colors. ## Appointments @@ -2556,7 +2569,7 @@ src/ bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank question/choice picture metadata; bytes on disk under FILES_PATH) profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) - preferences.rs Theme · Language (own UI preferences) + preferences.rs Theme · Language · PaletteColor (own UI preferences) message.rs MessageId · MessageSubject · MessageBody · MessageLabel · Message (per-copy folders: inbox/sent/archive/trash) parent_link.rs ParentLinkId · ParentLink (parent↔student tie = the parent's read grant) diff --git a/src/constant.rs b/src/constant.rs index 07fdddf..3b50a66 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -648,6 +648,21 @@ pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark]; pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En]; +/// A `palette_color` preference is `#` plus exactly six hex digits — the length +/// of the whole string, `#` included. +pub const PALETTE_COLOR_LEN: usize = 7; + +/// The shape a `palette_color` must match, as a regular expression. This +/// describes what the server **accepts**, so it is case-insensitive — the value +/// is normalized to lowercase on store, and a client that sent `#FEFAE0` reads +/// `#fefae0` back. Publishing the lowercase-only form would have a client +/// reject its own valid input. +/// +/// Deliberately an open value set: any valid hex accent color, not a closed +/// list of the frontend's palette, so a new palette entry needs no backend +/// change. +pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$"; + /// Folders a sender may file their side into (`Sent` is their home). pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash]; /// Folders a recipient may file their side into (`Inbox` is their home). diff --git a/src/domain/preferences.rs b/src/domain/preferences.rs index bc07c70..5350884 100644 --- a/src/domain/preferences.rs +++ b/src/domain/preferences.rs @@ -1,11 +1,11 @@ -//! Per-user UI preference newtypes: color theme and interface language. Both -//! are optional on the account — `None` means the user never chose, and the -//! frontend falls back to the device preference (`prefers-color-scheme`, -//! browser language). +//! Per-user UI preference newtypes: color theme, interface language, and accent +//! color. All are optional on the account — `None` means the user never chose, +//! and the frontend falls back to the device preference (`prefers-color-scheme`, +//! browser language) or its own default accent. use surrealdb::types::SurrealValue; -use crate::constant::{LANGUAGES, THEMES}; +use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES}; use crate::error::ValidationError; /// The frontend color scheme. @@ -71,9 +71,44 @@ impl Language { } } +/// The frontend accent color, a 6-digit hex with a leading `#`, stored +/// lowercase (`"#fefae0"`). +/// +/// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid +/// hex passes, so the frontend can grow its palette without a backend change. +/// A plain newtype over `String`, which stores as a bare string — the same +/// `option` column contract the two enums encode into. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PaletteColor(String); + +impl PaletteColor { + /// The wire/storage form: always lowercase. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Parse a wire string into an accent color. Mixed case is accepted (the + /// frontend's own validator is case-insensitive) and normalized down; no + /// trimming, so a stray space is a rejection rather than a silent fix. + pub fn try_from_str(value: &str) -> Result { + let invalid = ValidationError::Invalid { + field: "palette_color", + reason: "must be a hex color: # followed by exactly 6 hex digits, e.g. #fefae0", + }; + if value.len() != PALETTE_COLOR_LEN + || !value.starts_with('#') + || !value[1..].chars().all(|c| c.is_ascii_hexdigit()) + { + return Err(invalid); + } + Ok(Self(value.to_ascii_lowercase())) + } +} + #[cfg(test)] mod tests { use super::*; + use crate::constant::PALETTE_COLOR_PATTERN; use surrealdb::types::Value; #[tokio::test] @@ -96,6 +131,75 @@ mod tests { assert!(Language::try_from_str("").is_err()); } + #[tokio::test] + async fn palette_color_normalizes_and_rejects_non_hex() { + assert_eq!( + PaletteColor::try_from_str("#fefae0").unwrap().as_str(), + "#fefae0" + ); + // Mixed case is accepted (the frontend validator is case-insensitive) + // and stored lowercase. + assert_eq!( + PaletteColor::try_from_str("#FEFAE0").unwrap().as_str(), + "#fefae0" + ); + assert!(PaletteColor::try_from_str("fefae0").is_err()); // no # + assert!(PaletteColor::try_from_str("#fff").is_err()); // short form + assert!(PaletteColor::try_from_str("#gggggg").is_err()); // not hex + assert!(PaletteColor::try_from_str("#fefae0 ").is_err()); // untrimmed + assert!(PaletteColor::try_from_str("").is_err()); + + // The pattern `GET /limits` publishes must describe the rule above. + assert_eq!( + PALETTE_COLOR_PATTERN, + format!("^#[0-9a-fA-F]{{{}}}$", PALETTE_COLOR_LEN - 1) + ); + } + + /// The published pattern is a promise a client validates its own input + /// against, so it must describe the **accept** set exactly — not the + /// storage set. A lowercase-only pattern would have a client refuse + /// `#FEFAE0`, which this server takes and normalizes. Length agreement + /// (above) cannot catch that; only running both sides over the same + /// examples can. + #[tokio::test] + async fn published_pattern_agrees_with_the_accept_set() { + let pattern = regex::Regex::new(PALETTE_COLOR_PATTERN).expect("pattern compiles"); + for accepted in [ + "#fefae0", "#FEFAE0", "#FeFaE0", "#000000", "#ffffff", "#283618", + ] { + assert!( + PaletteColor::try_from_str(accepted).is_ok(), + "validator rejects {accepted}" + ); + assert!( + pattern.is_match(accepted), + "published pattern rejects accepted input {accepted}" + ); + } + for rejected in [ + "", + "fefae0", + "#fff", + "#gggggg", + "#fefae0 ", + " #fefae0", + "#fefae01", + "#fefae", + "#fefae0\n", + "rebeccapurple", + ] { + assert!( + PaletteColor::try_from_str(rejected).is_err(), + "validator accepts {rejected:?}" + ); + assert!( + !pattern.is_match(rejected), + "published pattern accepts rejected input {rejected:?}" + ); + } + } + #[tokio::test] async fn surreal_values_are_plain_strings() { // `untagged` keeps the stored value a bare string so the `option` @@ -110,5 +214,9 @@ mod tests { assert_eq!(value, Value::String(language.as_str().to_string())); assert_eq!(Language::from_value(value).unwrap(), language); } + let color = PaletteColor::try_from_str("#fefae0").unwrap(); + let value = color.clone().into_value(); + assert_eq!(value, Value::String("#fefae0".to_string())); + assert_eq!(PaletteColor::from_value(value).unwrap(), color); } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 6014a9b..6f7d833 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -9,7 +9,7 @@ use crate::constant::{DECOY_PASSWORD, USER_TABLE}; use crate::database::Database; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; -use crate::domain::preferences::{Language, Theme}; +use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::domain::text_fold::{search_fold, search_fold_sql}; @@ -204,6 +204,7 @@ pub struct User { // "never chose", which the frontend renders as the device preference. theme: Option, language: Option, + palette_color: Option, } impl User { @@ -251,6 +252,10 @@ impl User { self.language } + pub fn get_palette_color(&self) -> Option<&PaletteColor> { + self.palette_color.as_ref() + } + /// Register a new account. New users always start as [`Role::Student`]; /// elevation is a separate, admin-only action (see [`User::set_role`]). pub async fn create( @@ -291,6 +296,7 @@ impl User { birth_date: None, theme: None, language: None, + palette_color: None, }; let created: Result, surrealdb::Error> = db.create(user.id.record()).content(user.clone()).await; @@ -497,11 +503,13 @@ impl User { self, theme: Option>, language: Option>, + palette_color: Option>, db: &Database, ) -> Result { FieldUpdate::new(self.id.record()) .set("theme", theme) .set("language", language) + .set("palette_color", palette_color) .run::(db) .await } diff --git a/src/lib.rs b/src/lib.rs index fce30df..37e85a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( @@ -44,7 +44,7 @@ use crate::state::AppState; (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"), (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`"), (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"), - (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"), + (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"), (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`)"), (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"), (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"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 7af2683..ae5c4f7 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -50,6 +50,7 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option; DEFINE FIELD IF NOT EXISTS theme ON user TYPE option; DEFINE FIELD IF NOT EXISTS language ON user TYPE option; + DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option; DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; diff --git a/src/web/dto.rs b/src/web/dto.rs index f1f4d5c..cbe2c6a 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -136,6 +136,10 @@ pub struct UserResponse { /// client should fall back to the device language. #[schema(example = "tr")] pub language: Option, + /// UI accent color as a 6-digit hex with a leading `#`, lowercase. `null` = + /// never chosen — the client should fall back to its default accent. + #[schema(example = "#fefae0")] + pub palette_color: Option, } impl UserResponse { @@ -151,6 +155,7 @@ impl UserResponse { birth_date: user.get_birth_date().map(|v| v.as_str().to_string()), theme: user.get_theme().map(|v| v.as_str().to_string()), language: user.get_language().map(|v| v.as_str().to_string()), + palette_color: user.get_palette_color().map(|v| v.as_str().to_string()), } } } diff --git a/src/web/limits.rs b/src/web/limits.rs index 5d6b9aa..a9d9324 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -52,6 +52,15 @@ struct UserLimits { /// Accepted `language` preference values (`null` clears it). #[schema(example = json!(["tr", "en"]))] languages: Vec<&'static str>, + /// Shape a `palette_color` preference must match, as a regular expression + /// (`null` clears it). Open on purpose — any hex accent color, not a fixed + /// palette — so this is a pattern, not a value list like `themes`. Matches + /// either case: the server normalizes the value to lowercase on store, so a + /// response may differ in case from what was sent. + #[schema(example = "^#[0-9a-fA-F]{6}$")] + palette_color_pattern: &'static str, + /// Length of a `palette_color`, `#` included. + palette_color_len: usize, /// How long a login session stays valid, days. session_duration_days: i64, } @@ -346,6 +355,8 @@ impl LimitsResponse { roles: ROLES.iter().map(|role| role.as_str()).collect(), themes: THEMES.iter().map(|theme| theme.as_str()).collect(), languages: LANGUAGES.iter().map(|language| language.as_str()).collect(), + palette_color_pattern: PALETTE_COLOR_PATTERN, + palette_color_len: PALETTE_COLOR_LEN, session_duration_days: SESSION_DURATION_DAYS, }, note: NoteLimits { diff --git a/src/web/users.rs b/src/web/users.rs index a213c50..66d35af 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -10,7 +10,7 @@ use crate::database::Database; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::parent_link::ParentLink; -use crate::domain::preferences::{Language, Theme}; +use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; @@ -76,6 +76,10 @@ struct UpdatePreferences { /// `tr` or `en` (ISO 639-1). #[schema(example = "tr")] language: Option, + /// Accent color as a 6-digit hex with a leading `#`; stored lowercase. Any + /// valid hex, not a fixed palette. + #[schema(example = "#fefae0")] + palette_color: Option, } /// Resolve one patched field into what the save should write: absent (or @@ -126,7 +130,10 @@ async fn apply_preferences( ) -> Result { let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; let language = merge_field(req.language.as_deref(), Language::try_from_str)?; - let updated = user.set_preferences(theme, language, db).await?; + let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; + let updated = user + .set_preferences(theme, language, palette_color, db) + .await?; Ok(UserResponse::new(&updated)) } @@ -238,8 +245,9 @@ async fn update_my_profile( Ok(Json(apply_profile(user, &req, &st.db).await?)) } -/// Update the caller's own UI preferences: `theme` (`light`/`dark`) and -/// `language` (`tr`/`en`). Any authenticated role. Omitted fields stay as they +/// Update the caller's own UI preferences: `theme` (`light`/`dark`), +/// `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). +/// Any authenticated role. Omitted fields stay as they /// are; an empty string clears one back to "never chose" (the client then /// follows the device preference). Read them back on any user response, e.g. /// `GET /auth/me`. @@ -251,7 +259,7 @@ async fn update_my_profile( request_body = UpdatePreferences, responses( (status = 200, description = "Updated user", body = UserResponse), - (status = 400, description = "Invalid theme or language", body = ErrorResponse), + (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] @@ -330,7 +338,7 @@ async fn update_user_profile( request_body = UpdatePreferences, responses( (status = 200, description = "Updated user", body = UserResponse), - (status = 400, description = "Invalid theme or language", body = ErrorResponse), + (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires admin role", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), diff --git a/tests/integration.rs b/tests/integration.rs index 2dcb0c9..9e02eed 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -80,6 +80,16 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { json!(hezarfen_backend::constant::MAX_USERNAME_LEN) ); assert_eq!(res.body["exam"]["modes"], json!(["sync", "async", "open"])); + // The accent color is published as a pattern, not a value list — it is an + // open set, so a client validates the shape instead of a fixed palette. + assert_eq!( + res.body["user"]["palette_color_pattern"], + json!(hezarfen_backend::constant::PALETTE_COLOR_PATTERN) + ); + assert_eq!( + res.body["user"]["palette_color_len"], + json!(hezarfen_backend::constant::PALETTE_COLOR_LEN) + ); assert_eq!( res.body["user"]["roles"], json!(["parent", "student", "teacher", "manager", "admin"]) @@ -5002,7 +5012,7 @@ async fn admin_reads_and_edits_any_profile_with_guards() { ); } -// --- users: UI preferences (theme, language) ------------------------------ +// --- users: UI preferences (theme, language, palette color) ------------------------------ #[tokio::test] async fn preferences_start_null_and_update_via_me_preferences() { @@ -5014,21 +5024,27 @@ async fn preferences_start_null_and_update_via_me_preferences() { assert_eq!(me.status, StatusCode::OK); assert!(me.body["theme"].is_null(), "theme should start null"); assert!(me.body["language"].is_null(), "language should start null"); + assert!( + me.body["palette_color"].is_null(), + "palette_color should start null" + ); - // Set both through the self-service endpoint. + // Set all three through the self-service endpoint. Mixed-case hex is + // accepted and comes back lowercase. let res = send( &app, "PATCH", "/users/me/preferences", Some(&bob), - Some(json!({ "theme": "dark", "language": "tr" })), + Some(json!({ "theme": "dark", "language": "tr", "palette_color": "#FEFAE0" })), ) .await; assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["theme"], "dark"); assert_eq!(res.body["language"], "tr"); + assert_eq!(res.body["palette_color"], "#fefae0"); - // Partial patch: only the theme changes, the language survives. + // Partial patch: only the theme changes, the other two survive. let res = send( &app, "PATCH", @@ -5040,8 +5056,23 @@ async fn preferences_start_null_and_update_via_me_preferences() { assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["theme"], "light"); assert_eq!(res.body["language"], "tr"); + assert_eq!(res.body["palette_color"], "#fefae0"); + + // …and only the accent color changes, leaving theme and language alone. + let res = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&bob), + Some(json!({ "palette_color": "#283618" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["palette_color"], "#283618"); + assert_eq!(res.body["theme"], "light"); + assert_eq!(res.body["language"], "tr"); - // Empty string clears back to "never chose"; the other stays. + // Empty string clears back to "never chose"; the others stay. let res = send( &app, "PATCH", @@ -5053,10 +5084,24 @@ async fn preferences_start_null_and_update_via_me_preferences() { assert_eq!(res.status, StatusCode::OK); assert!(res.body["theme"].is_null()); assert_eq!(res.body["language"], "tr"); + assert_eq!(res.body["palette_color"], "#283618"); + + let res = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&bob), + Some(json!({ "palette_color": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert!(res.body["palette_color"].is_null()); + assert_eq!(res.body["language"], "tr"); // The merged state is what /auth/me reports afterwards. let me = send(&app, "GET", "/auth/me", Some(&bob), None).await; assert!(me.body["theme"].is_null()); + assert!(me.body["palette_color"].is_null()); assert_eq!(me.body["language"], "tr"); // No session -> 401. @@ -5085,6 +5130,13 @@ async fn preferences_reject_invalid_values() { json!({ "language": "turkish" }), json!({ "language": "de" }), json!({ "theme": "dark", "language": "nope" }), + json!({ "palette_color": "fefae0" }), // no leading # + json!({ "palette_color": "#fff" }), // short form + json!({ "palette_color": "#gggggg" }), // not hex + json!({ "palette_color": "#fefae0 " }), // untrimmed + json!({ "palette_color": "rebeccapurple" }), + // Mixed: a valid theme must not sneak through beside a bad color. + json!({ "theme": "dark", "palette_color": "#12345" }), ]; for body in bad { let res = send( @@ -5105,6 +5157,10 @@ async fn preferences_reject_invalid_values() { me.body["language"].is_null(), "language should still be null" ); + assert!( + me.body["palette_color"].is_null(), + "palette_color should still be null" + ); } #[tokio::test] @@ -5135,12 +5191,55 @@ async fn admin_edits_any_preferences_with_guards() { "PATCH", &format!("/users/{alice_id}/preferences"), Some(&admin), - Some(json!({ "theme": "dark", "language": "en" })), + Some(json!({ "theme": "dark", "language": "en", "palette_color": "#FEFAE0" })), ) .await; assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["theme"], "dark"); assert_eq!(res.body["language"], "en"); + assert_eq!( + res.body["palette_color"], "#fefae0", + "normalized on the admin path too" + ); + + // The admin route patches partially and clears by `""` exactly like the + // self-service one — one field at a time, the others untouched. + let res = send( + &app, + "PATCH", + &format!("/users/{alice_id}/preferences"), + Some(&admin), + Some(json!({ "palette_color": "#283618" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["palette_color"], "#283618"); + assert_eq!(res.body["theme"], "dark", "theme lost to the color patch"); + assert_eq!(res.body["language"], "en"); + + let res = send( + &app, + "PATCH", + &format!("/users/{alice_id}/preferences"), + Some(&admin), + Some(json!({ "palette_color": "" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert!(res.body["palette_color"].is_null()); + assert_eq!(res.body["theme"], "dark", "theme lost to the clear"); + assert_eq!(res.body["language"], "en"); + + // Back to a set value, so the reads below cover it too. + let res = send( + &app, + "PATCH", + &format!("/users/{alice_id}/preferences"), + Some(&admin), + Some(json!({ "palette_color": "#fefae0" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); // Admin reads them on the single-user lookup; alice sees them on /auth/me. let one = send( @@ -5153,9 +5252,11 @@ async fn admin_edits_any_preferences_with_guards() { .await; assert_eq!(one.body["theme"], "dark"); assert_eq!(one.body["language"], "en"); + assert_eq!(one.body["palette_color"], "#fefae0"); let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; assert_eq!(me.body["theme"], "dark"); assert_eq!(me.body["language"], "en"); + assert_eq!(me.body["palette_color"], "#fefae0"); // Unknown id -> 404. assert_eq!( diff --git a/tests/partial_patch_users.rs b/tests/partial_patch_users.rs index 1fedc86..b963787 100644 --- a/tests/partial_patch_users.rs +++ b/tests/partial_patch_users.rs @@ -55,7 +55,8 @@ async fn concurrent_preference_patches_keep_both_fields() { } else { ("light", "en") }; - let (a, b) = tokio::join!( + let color = if round % 2 == 0 { "#283618" } else { "#fefae0" }; + let (a, b, c) = tokio::join!( send( &app, "PATCH", @@ -70,9 +71,17 @@ async fn concurrent_preference_patches_keep_both_fields() { Some(&who), Some(json!({ "language": language })), ), + send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "palette_color": color })), + ), ); assert_eq!(a.status, StatusCode::OK, "round {round} theme patch"); assert_eq!(b.status, StatusCode::OK, "round {round} language patch"); + assert_eq!(c.status, StatusCode::OK, "round {round} palette patch"); let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body; assert_eq!(after["theme"], theme, "round {round}: theme reverted"); @@ -80,6 +89,10 @@ async fn concurrent_preference_patches_keep_both_fields() { after["language"], language, "round {round}: language reverted" ); + assert_eq!( + after["palette_color"], color, + "round {round}: palette_color reverted" + ); } } @@ -157,4 +170,43 @@ async fn omitted_keeps_empty_clears_and_validation_still_bites() { StatusCode::BAD_REQUEST, "bad theme refused" ); + + // The accent color joins them: set, cleared by `""`, refused when malformed + // — and never touching the other two preferences. + let set = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "theme": "dark", "palette_color": "#FEFAE0" })), + ) + .await; + assert_eq!(set.status, StatusCode::OK, "{}", set.body); + assert_eq!(set.body["palette_color"], "#fefae0", "stored lowercase"); + + let cleared = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "palette_color": "" })), + ) + .await; + assert_eq!(cleared.status, StatusCode::OK); + assert_eq!(cleared.body["palette_color"], json!(null)); + assert_eq!(cleared.body["theme"], "dark", "theme lost to the clear"); + + let bad_color = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&who), + Some(json!({ "palette_color": "#fff" })), + ) + .await; + assert_eq!( + bad_color.status, + StatusCode::BAD_REQUEST, + "bad palette color refused" + ); } diff --git a/tests/persistence.rs b/tests/persistence.rs index b7b9c53..d674977 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -1695,3 +1695,66 @@ async fn fee_plans_and_their_charges_survive_remigration() { "the charges the placement raised are still owed" ); } + +/// A user row written before `palette_color` existed needs no backfill: the +/// column is `option`, so the absent key reads back as "never chose" +/// and a later patch sets it in place. Adding an option column to a SCHEMAFULL +/// table must not strand the rows already there. +#[tokio::test] +async fn a_user_row_without_palette_color_still_reads_and_patches() { + let (app, db) = common::app_and_db().await; + let ali = common::login(&app, "ali").await; + + // Write the column first: a fresh row stores no key for a `None` option, so + // UNSET alone would be a no-op and this test would prove nothing. + let set = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&ali), + Some(json!({ "palette_color": "#283618" })), + ) + .await; + assert_eq!(set.status, StatusCode::OK, "{}", set.body); + let stored: Vec = db + .query("SELECT VALUE palette_color FROM user WHERE palette_color != NONE;") + .await + .expect("read the column") + .check() + .expect("read the column") + .take(0) + .expect("read the column"); + assert_eq!( + stored, + vec!["#283618"], + "the column must exist to be aged away" + ); + + // Now age the row into the pre-accent shape: the key goes away, exactly as + // on a row a binary without this column wrote. + db.query("UPDATE user UNSET palette_color;") + .await + .expect("age the row") + .check() + .expect("age the row"); + + let app = reboot(&db).await; + + let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; + assert_eq!(me.status, StatusCode::OK, "{}", me.body); + assert!( + me.body["palette_color"].is_null(), + "an aged row must read as never-chosen, not error" + ); + + let set = send( + &app, + "PATCH", + "/users/me/preferences", + Some(&ali), + Some(json!({ "palette_color": "#fefae0" })), + ) + .await; + assert_eq!(set.status, StatusCode::OK, "{}", set.body); + assert_eq!(set.body["palette_color"], "#fefae0"); +}