diff --git a/README.md b/README.md index d131ee0..8a45c64 100644 --- a/README.md +++ b/README.md @@ -1006,7 +1006,7 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it — its charges name it | | POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≤ 200) — place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` | | GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first · paged | -| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` — record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` | +| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` — record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory) and `409` naming the reversal when the charge was reversed. A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` | | POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` — hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety | | POST | `/payments/reversals` | manager | `{line_id, note?}` — undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line | | GET | `/payments/ledger/{user}` | student | One student's raw lines — charges, payments, refunds, reversals — newest first · paged · own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) | @@ -2114,7 +2114,13 @@ account. - **A reversal only undoes a `charge` or a `refund`**, for its exact amount and nothing else (`400` on any other kind). It is keyed `_r`, so a line has at most one reversal however often the call is retried, and the reversed line - itself stays on the record beside it. + itself stays on the record beside it. A **reversed charge is no longer owed**, + so it takes no payment: `POST /payments/credits` against one is a `409` naming + the *reversal* as the reason. It has to name it, because a reversal fills + exactly the room a payment would (it is a `+amount` child of the charge, which + is what makes the fold read as full), and a bursar told "already paid in full" + about a charge where not one kuruş ever arrived would go hunting for money + that does not exist. - **A refund frees the charge's room.** The cap on a payment is folded over the target's whole source subtree, so refunding a payment gives that charge its room back and the charge **can be paid again** — and reversing that refund diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index 877f930..f597978 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -402,7 +402,9 @@ impl PaymentLedger { /// Money in, against one named `charge`. Partial payments are the norm, so /// a charge may collect several credits; together they may not exceed it - /// (advisory — see the module doc's accepted race). + /// (advisory — see the module doc's accepted race). A *reversed* charge + /// takes no payment either, and is refused saying so rather than claiming + /// it was paid. /// /// With a `request_key` the line is keyed by it (see /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without @@ -423,6 +425,9 @@ impl PaymentLedger { PaymentLedgerKind::Credit, "a payment must be recorded against a charge", "the charge is already paid in full", + // A charge *is* reversible, and its reversal fills the same room a + // payment would, so the fold refuses the two cases identically. + Some("the charge was reversed, so it is no longer owed"), amount_minor, method, note, @@ -452,6 +457,10 @@ impl PaymentLedger { PaymentLedgerKind::Refund, "a refund must be recorded against a payment", "the payment is already refunded in full", + // A credit is never reversed ([`PaymentLedger::reversal`] refuses + // it), so a full fold here can only mean the refunds, and there is + // no second reason to tell apart — nor a read to spend looking. + None, amount_minor, method, note, @@ -479,6 +488,7 @@ impl PaymentLedger { kind: PaymentLedgerKind, wrong_target: &'static str, over: &'static str, + reversed: Option<&'static str>, amount_minor: LedgerAmount, method: Option, note: Option, @@ -512,6 +522,21 @@ impl PaymentLedger { } let taken = Self::applied_to(target, db).await?; if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { + // The fold cannot say *why* the room is gone: a reversal is a child + // of the line it undoes and folds in at `+amount` exactly as a + // payment does, so a reversed charge reads as full to the kuruş. + // The stored answer is the same either way — nothing may be + // recorded against it — but "already paid in full" told a bursar + // money had arrived when none ever did. The reversal's id is + // derived from its target's, so telling the two apart is one read, + // taken only on the refusal path. + if let Some(reversed) = reversed + && Self::read(&PaymentLedgerId::for_reversal(&target.id), db) + .await? + .is_some() + { + return Err(AppError::Conflict(reversed)); + } return Err(AppError::Conflict(over)); } Self::append( diff --git a/src/lib.rs b/src/lib.rs index 31f7e6e..ad79830 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,7 +59,7 @@ use crate::state::AppState; (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller's own latest sitting on that exam is in progress, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), diff --git a/src/web/payments.rs b/src/web/payments.rs index 6b754ff..846cbd5 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -612,7 +612,9 @@ fn request_key_of(raw: Option<&str>) -> Result, AppErr /// Record money received against one named charge. Allocation is recorded, not /// inferred: a payment always says which installment it settles. Partial /// payments accumulate; one that would take the charge past what it is worth is -/// a `409`. +/// a `409`. A charge that was **reversed** takes no payment either — it is no +/// longer owed — and that `409` says so, rather than reporting money that never +/// arrived as "paid in full". /// /// **Retry-safe on request** — send a `request_key` and a repeat of the call /// (a client retry after a network timeout) returns the line the first attempt @@ -632,7 +634,7 @@ fn request_key_of(raw: Option<&str>) -> Result, AppErr (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such ledger line", body = ErrorResponse), - (status = 409, description = "The charge is already paid in full, or the request_key was used for a different amount or charge", body = ErrorResponse), + (status = 409, description = "The charge is already paid in full, the charge was reversed (so it is no longer owed), or the request_key was used for a different amount or charge", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] diff --git a/tests/integration.rs b/tests/integration.rs index 43abdce..987ced5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -23871,6 +23871,28 @@ async fn reversal_undoes_a_charge_once_and_refuses_a_payment() { "a replayed reversal must not append a second line" ); + // A reversed charge is no longer owed, so it takes no money — and the + // refusal must say *reversed*. The reversal folds in at `+amount` exactly + // as a payment does, so the cap alone cannot tell the two apart, and + // "already paid in full" would send a bursar hunting for money that never + // arrived against a charge nobody ever paid a kuruş on. + let res = pay(&app, &mgr, &charge, 1).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let message = res.body["error"].as_str().unwrap_or_default(); + assert!( + message.contains("reversed"), + "the refusal must name the reversal, not a payment: {message}" + ); + assert!( + !message.contains("paid in full"), + "no money ever arrived on this charge: {message}" + ); + assert_eq!( + pay_row_count(&db, "payment_ledger").await, + 2, + "the refused payment must not have landed" + ); + // A mistaken payment is corrected with a refund, never a reversal. let (mgr2, other_id, _) = { let student = login(&app, "veli").await;