Commits
2026-09-25
✨ feat(api): server-side filters on the list doorsAhmet Kaan Gümüş · d8dad92
✨ feat(api): server-side filters on the list doors A caller no longer has to download a capped collection and narrow it in the client: - events, exams: the WindowParams pair is SQL (no whole-table load) and gains starts_before/ends_before, so a past/completed view is expressible - sessions: starts_after/starts_before, half-open months - homework: due_after/due_before (the open/past tabs), class_course - meals menus: slot (was a post-page JS filter — page counts lied) - users (admin): roles= comma set; courses: kind, q, taught - appointments + slots: teacher (or me), starts_after/starts_before, status - pomodoro log: from/to, with the focus total summed in SQL - messages and boards: q (folded literal substring) - pool questions: ?status= is a WHERE, not a post-filter - bank/course-notes id filters: garbage is a 400 naming the field, not an empty page Absent params return today's response byte-shape; page and count share one WHERE.
2026-09-17
📝 docs: rewrite the Turkish comments and doc comments in EnglishAhmet Kaan Gümüş · 7fec874
📝 docs: rewrite the Turkish comments and doc comments in English The Rust repo's own language is English; Turkish had leaked in from the sibling AI services. Translate every comment and doc comment to English using the code's own vocabulary (şube -> class section, dönem -> term, sınıf öğretmeni -> homeroom teacher, ortak sınav -> shared exam, karne -> report card, …). Quoted Turkish letters/words that are themselves the data under test (the text-fold examples in `text_fold`/`settings`, the non-ASCII filename sample) are kept. The README endpoint table is generated from those doc comments, so it is regenerated. AGENTS.md records the convention going forward: Turkish survives only where it is the data under test or user-visible content.
2026-09-16
✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)
`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.
Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).
Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.
Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.2026-09-12
2026-09-11
Merge branch 'layer-split/meal'Ahmet Kaan Gümüş · b0e9ab8
Merge branch 'layer-split/meal' # Conflicts: # src/db/mod.rs # src/service/mod.rs
🧹 chore: split meal_attendance, meal_ledger, menu, menu_dish, dietary_profile into domain/db/service layersAhmet Kaan Gümüş · d548120
🧹 chore: split meal_attendance, meal_ledger, menu, menu_dish, dietary_profile into domain/db/service layers - db/: menu (publish/read/find/list/CAS cap update/cascading delete + bump_menu_and_write), menu_dish (create/read/listings/count/patch/delete), meal_attendance (mark/list_for_menu/list_for_student), meal_ledger (append/read/price_snapshot/list_for_student/balance_of + KindTotal), dietary_profile (read/tags_of/save). Bodies byte-identical; entity fields pub(crate) for cross-layer construction (exam precedent). - service/: menu owns MENU_LOCK (multi-call count-then-write span) and every dish write (add_dish with the MAX_DISHES_PER_MENU gate, update_dish/delete_dish) plus menu/dish read pass-throughs; meal_ledger owns charge_booking/reverse_booking/credit orchestration; meal_attendance and dietary_profile are read-through pass-throughs. - domain/: pure remnants only — ids, newtypes, getters, sign convention, charge_for/reversal_for row builders, conflicts; ULID IDS minters stay; persistence tests ride with their fns into db/. - web/meals.rs: handlers call service::* only; MENU_LOCK leases and the dish-cap gate moved out; validation order preserved. - re-pointed merged callers (service/meal_booking, db/meal_booking, db/exam_attempt doc link) and test imports (integration, regress_meals). cargo check --all-targets clean; cargo test --lib 577 passed 0 failed; cargo test --test regress_meals 18 passed 0 failed.
🧹 chore: split message/parent_link/registration into domain/db/service layersAhmet Kaan Gümüş · f820c36Browse files
Merge branch 'layer-split/user'Ahmet Kaan Gümüş · f30faee
Merge branch 'layer-split/user' # Conflicts: # src/domain/appointment_slot.rs # src/domain/exam_question.rs # src/domain/user.rs # src/service/course.rs # src/web/courses.rs # src/web/sessions.rs
🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers
Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.
- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
it spans a multi-call pair (retire names, CAS save, restore), so it is a
service lock, not a db lock. The service takes its own input records
(SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
its original order, including the try_kept grandfathering that needs the
stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
purge → db/session, settings load/save/CAS → db/settings, the whole
settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
note_file, tests/regress_roles); NoteId::generate's stale
'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
note_file-domain persistence (note_file splits in C3).2026-09-05
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a `control` database with the school registry, builder accounts and builder sessions. `Tenants` keeps one separately-connected handle per school; the shadow `web::tenant_state::State` resolves the school from the `<slug>.<token>` cookie so every handler's `st.db` is school-scoped by construction. `POST /auth/login` / `register` carry `school`; a suspended school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the vendor account; the boot admin seed is gone. No customers, no compat shims.
2026-08-13
📝 feat: generate README endpoint table from the served OpenAPI specAhmet Kaan Gümüş · bf8046e
📝 feat: generate README endpoint table from the served OpenAPI spec tests/doc_sync.rs renders the 275-row table from /api-docs/openapi.json (auth floor from declared 403s, else the handler's Require* extractor, asserting exactly one floor per operation), drift-gated in the suite; UPDATE_DOCS=1 regenerates. Static rows are router-verified and plain .route() registrations must reach the table or the suite fails. Curated prose folded into handler doc comments; CLAUDE.md convention updated (table generated; full suite = cargo nextest run).
2026-08-05
🥗 fix: stop the canteen billing meals that were already servedAhmet Kaan Gümüş · 0894a5e
🥗 fix: stop the canteen billing meals that were already served
A menu dated 2020 was publishable, bookable and BILLABLE under the shipped
defaults. `check_cutoff` was the only gate a booking passed, and it returns
early twice: with `meal_cancel_cutoff_minutes` unset (the default) and with a
slot carrying no `serving_minute` (the default for all three shipped slots).
`POST /meals/menus` was also the one create path in the crate with no
`check_not_past`. So a manager published `2020-01-01_lunch`, a student booked
it, and `MealLedger::charge_for` wrote a real, permanent charge line for food
nobody could be served.
Both halves, because the create-side check alone does not close it: a menu
published legitimately last week, for a day that has SINCE passed, stays on
the volume and stays addressable. `check_not_past("date", date.day_end())`
refuses publishing a day already over (400, measured against the end of the
day so today publishes at any hour), and `check_day_not_past` refuses a
booking on one (409).
That guard is deliberately NOT part of `check_cutoff` and takes no settings:
the cutoff is policy about the serving *hour* and is unenforced by design when
the school has set none — the decision that keeps the canteen online — while
this is the calendar day itself being over, which no configuration makes
untrue. Today's menu on a slot with no serving hour books exactly as before.
It binds `book` alone: cancelling stays open on a past day, since a cancel
reverses a charge and money already taken has to stay reachable — the same
reason manager+ bypasses the cutoff. Nothing bypasses the past-day guard, and
nothing needs to: only students and their parents book at all.
`MenuDate::try_new` also stops disagreeing with chrono. `"+1".parse::<u32>()`
is `Ok(1)`, so `2026-+1-01` passed the calendar-day check and minted a SECOND
record id for the 1st of January — its own capacity and seat counter, missing
from every `?from=&to=` read (`+` sorts below `0`) and unbookable besides,
since the serving-instant parser could not read it back. The date is now
parsed by chrono and compared to the text it came from, so the two parsers
agree by construction rather than by two checks that can drift.
Test dates in the meal suites move beyond the calendar (2026-09 → 2099-09):
under the new rule a fixture dated next month is a suite that expires. The two
tests that used a past date as a shortcut to "the cutoff has closed" now reach
the cutoff the way a deployment does — today's menu, served at 00:00 UTC, with
the knob set.
Live volume: zero menus, zero bookings, zero ledger lines, so no residue to
repair. The defect was future-affecting only.🍽️ fix: close the canteen's existence oracle and its cutoff trapAhmet Kaan Gümüş · 4586d9a
🍽️ fix: close the canteen's existence oracle and its cutoff trap cancel_booking read the booking before authorising, and booking ids are derivable from the menu date, slot and user key. Any teacher could enumerate exactly which student booked which meal by reading the status code — 403 meant booked, 404 meant not — bypassing the deliberate manager+ gate on the bookings list. It now authorises off the path id first, so an unauthorised caller cannot tell the two apart. It was the only read-then-authorise ordering in the file. served_at fell back to midnight UTC when a slot carried no serving_minute, and all three shipped slots carry none. Setting meal_cancel_cutoff_minutes without serving hours therefore made every same-day menu unbookable and uncancellable by students. A slot with no serving hour now has no cutoff; the impossible-day refusal still runs first, so the fail-closed rule survives. claim_and_place and release_seat were the only conflict-retry loops in the crate with no backoff and three tries, while every sibling uses eight with exponential backoff — and these are precisely the "one HTTP burst on a single parent" case that sizing exists for. DietaryProfile::save did read-then-create, so two concurrent first writes made the loser a 500. book's held-seat path answered from a row read a round trip earlier, so a cancel in the gap produced a 201 claiming a seat the store had already cancelled and refunded. Book/cancel cycles are now capped, and balance_of aggregates per kind instead of folding the student's entire ledger in process.
docs: 📝 make six doc surfaces say what the code now doesAhmet Kaan Gümüş · 2e0b57a
docs: 📝 make six doc surfaces say what the code now does The batch that gated `lessons_held_total` on the lesson having started, made un-grading refund both counters, taught `Course::delete` to prune blueprints, held both meal date bounds to the calendar and turned a half-configured TLS pair into a boot error moved only README. The utoipa annotations and the tag descriptions still carried the old rules, and one README bullet list stated two opposite decrement rules 24 lines apart.
fix: 🍽️ make a meal credit retry-safe on requestAhmet Kaan Gümüş · 4fe4487
fix: 🍽️ make a meal credit retry-safe on request `POST /meals/credits` minted a fresh ulid per call, so the ledger's identity-based idempotence — the rule that keeps a double-clicked booking from billing twice — could never bite here. A response lost after the commit (proxy timeout, closed tab) left the client resending the identical body, and the money was taken a second time with no route able to edit or delete either line. It now takes the optional `request_key` its twin `POST /payments/credits` already takes, same validator and same grammar, folded into the line's id as `<student>_k_<key>`. The student is part of the id, so a key cannot reach another account; the same key for a different amount is a 409, checked on what the append gave back rather than on a read before it, so two retries racing get the same answer. Omitting the key keeps the old behaviour: two identical posts are two credits. Also carries the rustfmt reflow of the cancel-fence test added earlier.
fix: 🍽️ stop a cancel from freeing a seat it never readAhmet Kaan Gümüş · bd941b9
fix: 🍽️ stop a cancel from freeing a seat it never read `release_seat` flipped on `status = 'booked'` alone, while the revival on the book side fences on the attempt. A cancel that read attempt N and spent a round trip re-reading the menu could therefore flip attempt N+1: a seat a `POST` had just been answered `201` for was cancelled, its capacity handed back, and nothing refunded — the ids bound to that transaction are N's, whose reversal already exists — leaving the newer charge standing with its own `(booking, N+1)` reversal id unwritable by any route. The flip now carries `AND attempt = $attempt`, and a cancel that finds the seat booked again answers 409 rather than 200 with a `booked` row: the newer seat is one nobody on this request asked to free.
2026-08-04
fix: 🍽️ stop an attendance mark from outliving its menuAhmet Kaan Gümüş · 84c873c
fix: 🍽️ stop an attendance mark from outliving its menu Marking attendance guarded itself by reading the menu, and a delete sweeps its children in one transaction. A mark landing after that delete removed the row but before it committed read a menu that was still there, while the sweep ran on a snapshot taken before the mark existed — so both committed and neither caller was told. The store does not track an insert into a range another transaction already swept. That left a mark nothing could reach or remove, on an id minted from the date and slot: republishing that day brought it back as a mark on the new menu, the kitchen reading served for a student who never came. Measured on the real engine, not theorised: 378 of 3600 raced rounds. A dish never had this hole because it bumps the menu's revision, so the two writes collide on one key and the store aborts a side. Marks now go through the same helper, which moves to the menu itself since both its children need it. The dish test that found this was asserting a store-enforced invariant on the in-memory engine, which cannot enforce one — a few percent of loaded runs failed on correct code. It now pins the logic without a race, and the concurrent claim moves to a real-server test that holds the delete open with an event and races one child per round: racing both hides the bug, because the first writer makes the delete re-send and the re-sent sweep takes the other's row.
2026-08-02
fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2 Ten defects and two features, worked as one series because the doc surfaces and the const table are shared. Defects closed: - Cross-exam answer-key leak. The bank copies `correct` into every instantiation, so reviewing exam A handed out the key to a question the caller was still writing in exam B. Review now blanks those questions rather than closing: the join matches on `from_bank` AND `banked_as` (a question can carry both — instantiated, then re-saved to the bank — so a coalesce misses a copy), redacting `correct`, the correctness flag and that question's `auto_score` share. Keyed on the template, never the exam, so the rest of the review reads normally. - `set_role` was not atomic with its sweeps. The role write and every grant it invalidates now commit as one transaction; the board rooms are told after COMMIT from the cascade's own result slot. Built best-of-N; the losing charter left the one sweep outside whose failure strands an event seat no route can free. - Board rosters held below-student ids, which 400d the creator's next roster PATCH. Repaired at boot, and a PATCH may now send back the roster it was served: an id already present that stopped qualifying is dropped, a new one still refused. - `note_file` blobs leaked. The delete transaction returns the rows it removed and the handler unlinks exactly those, not a pre-read snapshot. - Rate limiting failed open on a saturated map. Never-seen clients now share one metered overflow budget instead of arriving unmetered. - Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks a clear marker the socket filters out, and a locked board refuses its creator's clear (409) — the lock now means one thing on every path. - Blueprint skips named the wrong record: `Attached::Gone` was two facts under one name, split into `Gone` (class) and `PivotGone` (course). Features: - Event audience `kind=class` — live from `class_member`, membership checked in one select because the (class, user) pair is the row id. - Grade blueprints: a grade's course template, retro-pumped best-effort with a skip list. Attachments carry a provenance tag, so removal spares what a human placed. A course deleted out from under a blueprint is pruned from the template by the pump that finds it. Forcing functions, because a hand-kept copy drifts: - `protected_routes_require_session` is derived from the emitted OpenAPI: 248 -> 254 operations swept, was 80 typed by hand. - Every JSON-bodied operation declares 422 (74 sites), pinned both ways — and multipart routes, which answer 400, are pinned to NOT declare it. - The SurrealQL registration-freeze guard is pinned against the Rust it copies; both mutations of it fail the test. - `migration_mark` gates one-time backfills. The roster repair rescanned every board against every user on every boot (773ms at 300/2000 with nothing to write); it is now skipped once done. Verified by a three-lens verifier panel — which caught the `banked_as` half of the answer-key leak by executing a probe, after the first fix had been reported complete — and by a podman boot against the existing volume: both new fields defined, the marker written, boot 2 skipping the scan, and the live API answering on the new routes.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps A three-domain hunt, its fixes, and a verifier panel that refuted two of them. Kept as one commit because the pieces interlock — cap.rs, the settings pair and the pump all move together, and no smaller cut compiles. Money can no longer be lost or stranded. Both seat transitions carry their ledger line inside their own transaction: the claim writes the charge, the flip writes the reversal. Before, a crash between the two left a seat held with no bill, or a bill with no seat, keyed to an attempt no later request could ever reach. A lost cancel could refund a live seat. The menu revision was bumped in a query of its own, so a booking reading in the gap claimed against a capacity or a price the menu had already left. Deleting a menu now takes its marks and its dishes with it, in the transaction that deletes the row. The id is deterministic on (date, slot), so anything left behind came back on the next publish — the kitchen reading "served" for a student who never came. A seat is always releasable: manager+ cancels any booking and is not bound by the cutoff, so a promoted student's seat no longer wedges its menu forever, and a debt that outlived its owner's role can be settled. Canteen money follows /payments and is manager+, not teacher+ — what a family owes the school is not classroom information. The class pump claims its pivot in-transaction. An attach racing a course delete used to commit a link to a row that was gone, and nothing could then detach it or delete the class. A hand enroll now disowns a pumped row, so a sweep cannot take back a roster decision an operator made by hand. The role sweep is one transaction. Rosters are ordered by when a student was added, which is what they always claimed. Both class axes have a ceiling, and each refuses on the other's, because a pump writes one row per member per course in a single transaction. Settings edits are serialized: retire is idempotent, so an undo log cannot tell the attempt that flipped a name from one that found it already flipped, and the loser un-retired what the winner had legally retired — leaving a kind gone from the list, gradable, and unremovable for good. Grading now checks the school's list, not only the counter. Three caps that read a snapshot integer now read the live column. A clear marker is charged to the board's lifetime counter and boot repairs the boards that predate it. Blank canvases refuse the clear, and the room reports that as its own code: the refusal text had drifted into the substring the WebSocket read as "closed", which told a live room it was permanently read-only. Verified against the real volume: both boot backfills, the slot-name rule and its grandfather clause, and the new money gate.
2026-07-30
chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run The backend runs as one process against one database, deployed stop-the-world. The machinery that let several of them agree was built ahead of a multi-replica rollout that stayed parked, so none of it was ever load-bearing: the boot lease elected a leader out of a field of one, the ai_worker table announced a worker to nobody, and the chat claim queue only ever claimed its own writes. Boot now migrates and seeds straight-line; a chat turn is dispatched by the handler that accepted it; the 503 gate reads the in-process registry. The retired columns and tables are unset and removed in separate batches, repair before REMOVE. What stays, with its reason corrected rather than removed: cap.rs, field_update.rs, the refcounts, the CAS retry loops and the in-process locks. Those close write skew between concurrent requests inside one process, which two replicas made worse but never caused. A turn orphaned by a restart or a panic is no longer reclaimed. It settles as timed_out within CHATBOT_PENDING_STALE_SECS. The design survives in the ledger if a second process is ever wanted.
2026-07-27
fix: 🧷 close the cross-table races the locks never closedAhmet Kaan Gümüş · 4f7bdaf
fix: 🧷 close the cross-table races the locks never closed
Every remaining check-then-write that spanned tables becomes a
single-record conditional write, so it holds across replicas:
- subject delete: refcounts (exam_question_count/homework_count) claimed
and released by every question/homework write; the triple lock hold
dies, BANK/TERM/ENROLL locks die outright
- exam kinds: kind_ref {count,retired} records; grading claims, removal
retires only at zero — grading a removed kind and re-kinding a graded
exam are now 409 (both previously silently mis-weighted marks)
- homework: the grade stamps the submission row in its own transaction;
student writes are conditional on the stamp being absent
- appointments: slot occupancy is a cap-1 counter; the lock survives
only for the within-replica approved-overlap check
- meals: seat counter + menu version CAS (price can no longer tear mid
booking) + deterministic menu:date_slot id kills duplicate publish
- cap::claim_and_create: member gate, then seat, then child CREATE in
one transaction — a duplicate loser no longer eats a stranger's seat
or gets refused for a row it already owns
- boot: the two unguarded lease statements now retry on transaction
conflict (the escape was ~1-in-15 under full-suite load)
Two races reviewed and accepted, documented in README ## Concurrency
model: the attempt-seq late save (one history row, grade of record
untouched) and cross-replica approved-overlap (visible, cancellable).
Deployment contract (README): counter-adding releases restart all
replicas together — an old binary's writes skip new counters and the
= NONE backfill guard rightly refuses to re-seed.
Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process
Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:
- count caps (enroll/register/files/threads) become a counter column
claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
images,review}; image uploads single-source in web/image.rs; the
bare-seq key rule lives once in domain/key.rs; migration SQL moves
to migration_sql.rs
Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.
Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.2026-07-26
fix: 🕛 anchor the meal cutoff to when lunch is actually servedAhmet Kaan Gümüş · 21f4643
fix: 🕛 anchor the meal cutoff to when lunch is actually served
The booking and cancel deadline counted back from midnight UTC of the
menu date, so a two-hour cutoff on lunch barred bookings from 22:00 the
day before. Meal slots now carry an optional serving time and the
deadline counts back from that; a slot without one keeps the old
midnight behaviour, so nothing changes until a school sets hours.
Times are minutes past midnight UTC. There is deliberately no school
timezone setting, so a UTC+3 school enters 09:00 to mean noon; the
field says so wherever it is described.
Serving time is looked up live rather than snapshotted onto the menu,
because the cutoff minutes already are — freezing one half of a
deadline and not the other would split a single policy in two.
Storing an Option inside an object turned out to break the settings
CAS. SurrealDB drops an object key whose value is NONE, and a stored
{name} never again equals the {name, serving_minute: NONE} the derive
emits, so every PATCH /settings would have answered 409 forever for any
school whose slots predate this field. The guard now compares a rebuilt
projection. Verified against the live volume, whose singleton is
exactly that aged shape.
Also: losing a race to write a ledger line returned 500 rather than the
line the winner had already written. A duplicate record id is now read
back instead, matched on the typed error so real database failures
still surface.feat: 🍽️ run the canteen: menus, seats, allergens and a ledgerAhmet Kaan Gümüş · fd5cfd1
feat: 🍽️ run the canteen: menus, seats, allergens and a ledger Published menu calendar (manager+ authors, everyone reads), per-student dietary profiles that mark conflicting dishes, meal booking with an optional per-menu capacity, meal attendance, and booking-triggered billing. Booking is the charge trigger: reserving a seat stamps a charge at a price snapshot, so later dish edits never rewrite what a student owes. No-show still pays, because the kitchen already bought the food, which is why attendance has no billing effect at all. Money enters only as admin-recorded credit entries; there is no gateway and no card data. The ledger is append-only. Cancelling appends a reversal rather than deleting the charge, balance is always folded from the rows, and the sign lives in exactly one function. A deletable ledger row would rewrite a student's financial history leaving no trace. Charges and reversals are keyed per (booking, attempt) and written under MENU_LOCK alongside the seat, so a double-click, a retry, or a cancel cut short mid-flight all settle to one charge and one refund. That lock is in-process only: a second replica would break every capacity and charge guarantee here. A parent may book for a linked student, the first write parent_link has ever authorised, and sees only seats whose link is still live.