forge
Explore
Log in

Don't you dare go Hollow

🎨 sync the accent color like theme and language

Browse files at this commit

94906232e5b88fb0bd5658290ff1f53eae2ef426Ahmet Kaan GümüşParent: 4fe02bc
  • feat
    • 🎨 sync the accent color like theme and language
Show full message
feat: 🎨 sync the accent color like theme and language

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.lockmodified+1 -0
@@ -1800,6 +1800,7 @@ dependencies = [
18001800 "proptest",
18011801 "quinn",
18021802 "rcgen",
1803+ "regex",
18031804 "reqwest",
18041805 "rustls",
18051806 "rustls-pemfile",
Cargo.tomlmodified+4 -0
@@ -52,3 +52,7 @@ tempfile = "3"
5252 tokio-tungstenite = "0.30.0"
5353 futures-util = "0.3.32"
5454 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
9292 course averages), attendance statuses, grade-display bands, the note-file
9393 size limit, and the chatbot's limits live in an editable **settings** singleton, and academic **terms**
9494 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).
98100 The **AI features live in separate projects**, so the backend also opens a
99101 QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in,
100102 register the capabilities they serve, and each request rides its own QUIC
@@ -292,6 +294,7 @@ response in the same commit.
292294 "min_phone_digits": 7, "max_phone_digits": 15,
293295 "roles": ["parent", "student", "teacher", "manager", "admin"],
294296 "themes": ["light", "dark"], "languages": ["tr", "en"],
297+ "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7,
295298 "session_duration_days": 7 },
296299 "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 },
297300 "file": { "max_name_len": 255, "max_content_type_len": 100,
@@ -377,6 +380,12 @@ Notes:
377380 manager edits it. What `/limits` carries for those knobs is the fixed range a
378381 manager may set them *within* (`min_`/`max_`/`default_` prefixes), plus the
379382 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.
380389 - **Closed value sets ride along.** `roles`, `themes`, `languages`, course
381390 `kinds`, exam `modes`, `question_kinds`, homework `statuses`, and the
382391 uploadable `image_content_types` are the exact accepted spellings — build
@@ -493,7 +502,7 @@ course enrollments.
493502 | 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 |
494503 | 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 |
495504 | 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 |
497506 | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere |
498507 | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |
499508 | 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.
609618 | POST | `/auth/logout` | no | Clear session (no-op if none) |
610619 | GET | `/auth/me` | student | Current user (incl. `role` and personal info) |
611620 | 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) |
613622 | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged |
614623 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |
615624 | GET | `/users` | admin | List all users · paged |
@@ -914,13 +923,17 @@ ending with a letter or digit (3–32 chars). Staff-looking names (`admin`,
914923 `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are
915924 rejected at `/auth/register` only — the `ADMIN_USERNAME` bootstrap may still
916925 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
918928 same account row and come back on every user response (`/auth/me` included).
919929 `PATCH /users/me/preferences` (or the admin `PATCH /users/{id}/preferences`)
920930 uses the same field semantics as the profile patch: omitted keeps, `""` clears
921931 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.
924937
925938 ## Appointments
926939
@@ -2556,7 +2569,7 @@ src/
25562569 bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank
25572570 question/choice picture metadata; bytes on disk under FILES_PATH)
25582571 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)
25602573 message.rs MessageId · MessageSubject · MessageBody · MessageLabel ·
25612574 Message (per-copy folders: inbox/sent/archive/trash)
25622575 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];
648648
649649 pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
650650
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+
651666 /// Folders a sender may file their side into (`Sent` is their home).
652667 pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
653668 /// 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.
55
66 use surrealdb::types::SurrealValue;
77
8-use crate::constant::{LANGUAGES, THEMES};
8+use crate::constant::{LANGUAGES, PALETTE_COLOR_LEN, THEMES};
99 use crate::error::ValidationError;
1010
1111 /// The frontend color scheme.
@@ -71,9 +71,44 @@ impl Language {
7171 }
7272 }
7373
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+
74108 #[cfg(test)]
75109 mod tests {
76110 use super::*;
111+ use crate::constant::PALETTE_COLOR_PATTERN;
77112 use surrealdb::types::Value;
78113
79114 #[tokio::test]
@@ -96,6 +131,75 @@ mod tests {
96131 assert!(Language::try_from_str("").is_err());
97132 }
98133
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+
99203 #[tokio::test]
100204 async fn surreal_values_are_plain_strings() {
101205 // `untagged` keeps the stored value a bare string so the `option<string>`
@@ -110,5 +214,9 @@ mod tests {
110214 assert_eq!(value, Value::String(language.as_str().to_string()));
111215 assert_eq!(Language::from_value(value).unwrap(), language);
112216 }
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);
113221 }
114222 }
src/domain/user.rsmodified+9 -1
@@ -9,7 +9,7 @@ use crate::constant::{DECOY_PASSWORD, USER_TABLE};
99 use crate::database::Database;
1010 use crate::domain::field_update::FieldUpdate;
1111 use crate::domain::page::PagedList;
12-use crate::domain::preferences::{Language, Theme};
12+use crate::domain::preferences::{Language, PaletteColor, Theme};
1313 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
1414 use crate::domain::role::Role;
1515 use crate::domain::text_fold::{search_fold, search_fold_sql};
@@ -204,6 +204,7 @@ pub struct User {
204204 // "never chose", which the frontend renders as the device preference.
205205 theme: Option<Theme>,
206206 language: Option<Language>,
207+ palette_color: Option<PaletteColor>,
207208 }
208209
209210 impl User {
@@ -251,6 +252,10 @@ impl User {
251252 self.language
252253 }
253254
255+ pub fn get_palette_color(&self) -> Option<&PaletteColor> {
256+ self.palette_color.as_ref()
257+ }
258+
254259 /// Register a new account. New users always start as [`Role::Student`];
255260 /// elevation is a separate, admin-only action (see [`User::set_role`]).
256261 pub async fn create(
@@ -291,6 +296,7 @@ impl User {
291296 birth_date: None,
292297 theme: None,
293298 language: None,
299+ palette_color: None,
294300 };
295301 let created: Result<Option<User>, surrealdb::Error> =
296302 db.create(user.id.record()).content(user.clone()).await;
@@ -497,11 +503,13 @@ impl User {
497503 self,
498504 theme: Option<Option<Theme>>,
499505 language: Option<Option<Language>>,
506+ palette_color: Option<Option<PaletteColor>>,
500507 db: &Database,
501508 ) -> Result<User, AppError> {
502509 FieldUpdate::new(self.id.record())
503510 .set("theme", theme)
504511 .set("language", language)
512+ .set("palette_color", palette_color)
505513 .run::<User>(db)
506514 .await
507515 }
src/lib.rsmodified+2 -2
@@ -36,7 +36,7 @@ use crate::state::AppState;
3636 info(
3737 title = "Hezarfen Backend API",
3838 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.",
4040 ),
4141 modifiers(&SecurityAddon),
4242 tags(
@@ -44,7 +44,7 @@ use crate::state::AppState;
4444 (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"),
4545 (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`"),
4646 (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"),
4848 (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`)"),
4949 (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"),
5050 (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 = "
5050 DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>;
5151 DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>;
5252 DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>;
53+ DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>;
5354 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
5455 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
5556
src/web/dto.rsmodified+5 -0
@@ -136,6 +136,10 @@ pub struct UserResponse {
136136 /// client should fall back to the device language.
137137 #[schema(example = "tr")]
138138 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>,
139143 }
140144
141145 impl UserResponse {
@@ -151,6 +155,7 @@ impl UserResponse {
151155 birth_date: user.get_birth_date().map(|v| v.as_str().to_string()),
152156 theme: user.get_theme().map(|v| v.as_str().to_string()),
153157 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()),
154159 }
155160 }
156161 }
src/web/limits.rsmodified+11 -0
@@ -52,6 +52,15 @@ struct UserLimits {
5252 /// Accepted `language` preference values (`null` clears it).
5353 #[schema(example = json!(["tr", "en"]))]
5454 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,
5564 /// How long a login session stays valid, days.
5665 session_duration_days: i64,
5766 }
@@ -346,6 +355,8 @@ impl LimitsResponse {
346355 roles: ROLES.iter().map(|role| role.as_str()).collect(),
347356 themes: THEMES.iter().map(|theme| theme.as_str()).collect(),
348357 languages: LANGUAGES.iter().map(|language| language.as_str()).collect(),
358+ palette_color_pattern: PALETTE_COLOR_PATTERN,
359+ palette_color_len: PALETTE_COLOR_LEN,
349360 session_duration_days: SESSION_DURATION_DAYS,
350361 },
351362 note: NoteLimits {
src/web/users.rsmodified+14 -6
@@ -10,7 +10,7 @@ use crate::database::Database;
1010 use crate::domain::course::Course;
1111 use crate::domain::enrollment::Enrollment;
1212 use crate::domain::parent_link::ParentLink;
13-use crate::domain::preferences::{Language, Theme};
13+use crate::domain::preferences::{Language, PaletteColor, Theme};
1414 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
1515 use crate::domain::role::Role;
1616 use crate::domain::user::{User, UserId};
@@ -76,6 +76,10 @@ struct UpdatePreferences {
7676 /// `tr` or `en` (ISO 639-1).
7777 #[schema(example = "tr")]
7878 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>,
7983 }
8084
8185 /// Resolve one patched field into what the save should write: absent (or
@@ -126,7 +130,10 @@ async fn apply_preferences(
126130 ) -> Result<UserResponse, AppError> {
127131 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
128132 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?;
130137 Ok(UserResponse::new(&updated))
131138 }
132139
@@ -238,8 +245,9 @@ async fn update_my_profile(
238245 Ok(Json(apply_profile(user, &req, &st.db).await?))
239246 }
240247
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
243251 /// are; an empty string clears one back to "never chose" (the client then
244252 /// follows the device preference). Read them back on any user response, e.g.
245253 /// `GET /auth/me`.
@@ -251,7 +259,7 @@ async fn update_my_profile(
251259 request_body = UpdatePreferences,
252260 responses(
253261 (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),
255263 (status = 401, description = "Not authenticated", body = ErrorResponse),
256264 ),
257265 )]
@@ -330,7 +338,7 @@ async fn update_user_profile(
330338 request_body = UpdatePreferences,
331339 responses(
332340 (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),
334342 (status = 401, description = "Not authenticated", body = ErrorResponse),
335343 (status = 403, description = "Requires admin role", body = ErrorResponse),
336344 (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() {
8080 json!(hezarfen_backend::constant::MAX_USERNAME_LEN)
8181 );
8282 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+ );
8393 assert_eq!(
8494 res.body["user"]["roles"],
8595 json!(["parent", "student", "teacher", "manager", "admin"])
@@ -5002,7 +5012,7 @@ async fn admin_reads_and_edits_any_profile_with_guards() {
50025012 );
50035013 }
50045014
5005-// --- users: UI preferences (theme, language) ------------------------------
5015+// --- users: UI preferences (theme, language, palette color) ------------------------------
50065016
50075017 #[tokio::test]
50085018 async fn preferences_start_null_and_update_via_me_preferences() {
@@ -5014,21 +5024,27 @@ async fn preferences_start_null_and_update_via_me_preferences() {
50145024 assert_eq!(me.status, StatusCode::OK);
50155025 assert!(me.body["theme"].is_null(), "theme should start null");
50165026 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+ );
50175031
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.
50195034 let res = send(
50205035 &app,
50215036 "PATCH",
50225037 "/users/me/preferences",
50235038 Some(&bob),
5024- Some(json!({ "theme": "dark", "language": "tr" })),
5039+ Some(json!({ "theme": "dark", "language": "tr", "palette_color": "#FEFAE0" })),
50255040 )
50265041 .await;
50275042 assert_eq!(res.status, StatusCode::OK);
50285043 assert_eq!(res.body["theme"], "dark");
50295044 assert_eq!(res.body["language"], "tr");
5045+ assert_eq!(res.body["palette_color"], "#fefae0");
50305046
5031- // Partial patch: only the theme changes, the language survives.
5047+ // Partial patch: only the theme changes, the other two survive.
50325048 let res = send(
50335049 &app,
50345050 "PATCH",
@@ -5040,8 +5056,23 @@ async fn preferences_start_null_and_update_via_me_preferences() {
50405056 assert_eq!(res.status, StatusCode::OK);
50415057 assert_eq!(res.body["theme"], "light");
50425058 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");
50435074
5044- // Empty string clears back to "never chose"; the other stays.
5075+ // Empty string clears back to "never chose"; the others stay.
50455076 let res = send(
50465077 &app,
50475078 "PATCH",
@@ -5053,10 +5084,24 @@ async fn preferences_start_null_and_update_via_me_preferences() {
50535084 assert_eq!(res.status, StatusCode::OK);
50545085 assert!(res.body["theme"].is_null());
50555086 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");
50565100
50575101 // The merged state is what /auth/me reports afterwards.
50585102 let me = send(&app, "GET", "/auth/me", Some(&bob), None).await;
50595103 assert!(me.body["theme"].is_null());
5104+ assert!(me.body["palette_color"].is_null());
50605105 assert_eq!(me.body["language"], "tr");
50615106
50625107 // No session -> 401.
@@ -5085,6 +5130,13 @@ async fn preferences_reject_invalid_values() {
50855130 json!({ "language": "turkish" }),
50865131 json!({ "language": "de" }),
50875132 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" }),
50885140 ];
50895141 for body in bad {
50905142 let res = send(
@@ -5105,6 +5157,10 @@ async fn preferences_reject_invalid_values() {
51055157 me.body["language"].is_null(),
51065158 "language should still be null"
51075159 );
5160+ assert!(
5161+ me.body["palette_color"].is_null(),
5162+ "palette_color should still be null"
5163+ );
51085164 }
51095165
51105166 #[tokio::test]
@@ -5135,12 +5191,55 @@ async fn admin_edits_any_preferences_with_guards() {
51355191 "PATCH",
51365192 &format!("/users/{alice_id}/preferences"),
51375193 Some(&admin),
5138- Some(json!({ "theme": "dark", "language": "en" })),
5194+ Some(json!({ "theme": "dark", "language": "en", "palette_color": "#FEFAE0" })),
51395195 )
51405196 .await;
51415197 assert_eq!(res.status, StatusCode::OK);
51425198 assert_eq!(res.body["theme"], "dark");
51435199 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);
51445243
51455244 // Admin reads them on the single-user lookup; alice sees them on /auth/me.
51465245 let one = send(
@@ -5153,9 +5252,11 @@ async fn admin_edits_any_preferences_with_guards() {
51535252 .await;
51545253 assert_eq!(one.body["theme"], "dark");
51555254 assert_eq!(one.body["language"], "en");
5255+ assert_eq!(one.body["palette_color"], "#fefae0");
51565256 let me = send(&app, "GET", "/auth/me", Some(&alice), None).await;
51575257 assert_eq!(me.body["theme"], "dark");
51585258 assert_eq!(me.body["language"], "en");
5259+ assert_eq!(me.body["palette_color"], "#fefae0");
51595260
51605261 // Unknown id -> 404.
51615262 assert_eq!(
tests/partial_patch_users.rsmodified+53 -1
@@ -55,7 +55,8 @@ async fn concurrent_preference_patches_keep_both_fields() {
5555 } else {
5656 ("light", "en")
5757 };
58- let (a, b) = tokio::join!(
58+ let color = if round % 2 == 0 { "#283618" } else { "#fefae0" };
59+ let (a, b, c) = tokio::join!(
5960 send(
6061 &app,
6162 "PATCH",
@@ -70,9 +71,17 @@ async fn concurrent_preference_patches_keep_both_fields() {
7071 Some(&who),
7172 Some(json!({ "language": language })),
7273 ),
74+ send(
75+ &app,
76+ "PATCH",
77+ "/users/me/preferences",
78+ Some(&who),
79+ Some(json!({ "palette_color": color })),
80+ ),
7381 );
7482 assert_eq!(a.status, StatusCode::OK, "round {round} theme patch");
7583 assert_eq!(b.status, StatusCode::OK, "round {round} language patch");
84+ assert_eq!(c.status, StatusCode::OK, "round {round} palette patch");
7685
7786 let after = send(&app, "GET", "/auth/me", Some(&who), None).await.body;
7887 assert_eq!(after["theme"], theme, "round {round}: theme reverted");
@@ -80,6 +89,10 @@ async fn concurrent_preference_patches_keep_both_fields() {
8089 after["language"], language,
8190 "round {round}: language reverted"
8291 );
92+ assert_eq!(
93+ after["palette_color"], color,
94+ "round {round}: palette_color reverted"
95+ );
8396 }
8497 }
8598
@@ -157,4 +170,43 @@ async fn omitted_keeps_empty_clears_and_validation_still_bites() {
157170 StatusCode::BAD_REQUEST,
158171 "bad theme refused"
159172 );
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+ );
160212 }
tests/persistence.rsmodified+63 -0
@@ -1695,3 +1695,66 @@ async fn fee_plans_and_their_charges_survive_remigration() {
16951695 "the charges the placement raised are still owed"
16961696 );
16971697 }
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+}