Close the delegated-access gaps the release audit left open

Seven findings from the adversarial pass before v1.36.1 was tagged. One
blocking defect shipped in that release; these did not, and they are all places
where somebody looking after another person's health record meets a wall with
no explanation, or where a guard cannot fail.

The document vault was the largest. `/documents` is marked as a shared
destination, so the shell offers it under a switch, and every read behind it
resolved the caller instead of the record: the vault painted a query-error card
and the illness view painted another beside it. That is the same failure the
release describes as fixed on the dashboard. Five GET arms move to the record
resolver now, and only the GET arms: the list, one document, its file, its
thumbnail and the vault's usage payload, which the filter bar is built from.
Uploading, retyping, deleting, linking a document to an illness and every AI
verb stay with the owner, and the two reads that spend decryption CPU key
their quota on the person calling rather than the record, the rule
`medications/compliance` already follows.

Logging a value on a metric you track yourself leaves the admitted set. It was
admitted, named on the consent screen in six languages, and unreachable: the
only form that posts one sits on a page a shared record does not open, and the
component that renders it says so in its own comment while returning null. It
is the third route the rule that withdrew allergies and family history fitted
exactly, and it was applied to two of the three. Reading those values stays.

Two guards could not fail, and both were proved by mutation before and after.
The prefetch guard checked rule three with two regexes: one was satisfied by
the doc comment every page carries, the other missed an aliased import, and
the pair stayed green with the dashboard genuinely prefetching off the
switch-blind session. It reads the AST now, resolves aliases through the
module's own import table, and pins the five prefetching pages by name so a
page that stops being detected is loud. The activity verb map decided
membership on a literal `requireRecordAuth("write")`, so putting the argument
on its own line, which is what the formatter does the moment the call grows,
dropped a route out of the scan and turned a genuinely-red run green. Both
counts are of matches now rather than of files walked.

The rest are single instances of rules applied everywhere else. "Take all due"
was withheld on a note saying it rides the bulk intake route; it does not, and
its own docblock says why not, so a helper with five morning tablets tapped
five times for nothing. Marking a dose skipped is offered wherever marking it
taken is. A form could be opened in the frame before the app knew whose record
was on screen and then stood there once the answer arrived, on the capture
sheet and on the dashboard's quick-entry sheets. Two more copies of the intake
toast were still building their own, one of them with an Undo pointing at a
route no delegate may call. The customise link on the mood page led to a page
that exists to say it is not part of what was shared. And the access-level
radios on the invitation screen are hidden by design with no focus ring on
their label, so keyboard focus moved invisibly across the one screen where
somebody grants write access to their record.

Three new structural guards, each watched fail first: the customise link sits
inside a capability branch on every surface a delegate can reach, every intake
surface confirms through the one shared decision, and the batch sweep is
offered at the level that admits it.
This commit is contained in:
Marc-André Bombeck committed 2026-08-04 14:55:32 +02:00
1 parent 80ecbd7454
commit 25e86b36b3
38 files changed
+1750 -128

No files matched your search

@@ -100,10 +100,15 @@ import { DeleteButton } from "@/components/data-list/delete-button";
import { SelectionActionBar } from "@/components/data-list/selection-action-bar";
import { MedicationCardMenu } from "@/components/medications/medication-card-menu";
import { MedicationIntakeActions } from "@/components/medications/card-parts/medication-intake-actions";
import { visibleCaptureKinds } from "@/components/layout/capture-picker";
import {
admittedCaptureKind,
visibleCaptureKinds,
} from "@/components/layout/capture-picker";
import { admittedQuickEntry } from "@/components/dashboard/quick-entry-sheets";
import { TodayHero } from "@/components/daily/today-hero";
import { VorsorgeDashboardCard } from "@/components/measurement-reminders/vorsorge-dashboard-card";
import { EpisodeDocumentsCard } from "@/components/documents/episode-documents-card";
import { LedgerRowItem } from "@/components/medications/dose-history-ledger";
import { queryKeys } from "@/lib/query-keys";
import type { DailyDigest } from "@/lib/daily/digest";
import type { MeasurementReminder } from "@/hooks/use-measurement-reminders";
@@ -348,6 +353,12 @@ describe("linking a document to an illness episode", () => {
expect(html).not.toContain(">Link<");
expect(html).not.toContain("Upload");
// The card itself stays — reading the episode's documents is a read.
// v1.36.x — and the resolver agrees now. This line was true of the
// intent and false of the route: the card's list query hit
// `GET /api/documents/inbound`, which resolved the CALLER and 403'd, so
// the card that "stays" rendered a query-error tile. That GET is
// delegable; `delegable-surface-guard.test.ts` freezes it and
// `sharing-delegable-routes.test.ts` drives it.
expect(html).toContain('data-slot="episode-documents-card"');
}
});
@@ -382,3 +393,126 @@ describe("the capture picker's kinds", () => {
).toEqual(["measurement", "medication", "mood"]);
});
});
/* -------------------------------------------------------------------------- */
/* The dose-history ledger's row actions */
/* -------------------------------------------------------------------------- */
describe("marking a dose from the dose history", () => {
const node = (
<ul>
<LedgerRowItem
row={{
kind: "slot",
at: "2026-08-04T07:00:00.000Z",
timeOfDay: "07:00",
status: "upcoming",
intake: null,
}}
marking={null}
isToday
onMark={() => {}}
onToggleSkipped={() => {}}
onEdit={() => {}}
onDelete={() => {}}
onPin={() => {}}
onUnpin={() => {}}
/>
</ul>
);
it("offers the owner take beside the kebab that holds the rest", () => {
const html = render(OWN_RECORD, node);
expect(html).toContain('data-slot="ledger-mark-taken"');
expect(html).toContain('data-slot="ledger-row-menu"');
});
it("offers a write delegate BOTH markings, and no row menu", () => {
// Taken and skipped are one admitted verb, not two — the medication card
// has always offered the pair. This surface offered a delegate only the
// first, because skip lives in the kebab and the kebab also holds edit,
// re-attribute and delete, which are the owner's. So skip gets its own
// control here rather than the menu opening up.
const html = render(WRITABLE, node);
expect(html).toContain('data-slot="ledger-mark-taken"');
expect(html).toContain('data-slot="ledger-mark-skipped"');
expect(html).not.toContain('data-slot="ledger-row-menu"');
});
it("offers a read-only delegate neither", () => {
const html = render(READ_ONLY, node);
expect(html).not.toContain('data-slot="ledger-mark-taken"');
expect(html).not.toContain('data-slot="ledger-mark-skipped"');
expect(html).not.toContain('data-slot="ledger-row-menu"');
// The row itself stays — reading the history is a read.
expect(html).toContain('data-slot="ledger-row"');
});
});
/* -------------------------------------------------------------------------- */
/* The first-paint window */
/* -------------------------------------------------------------------------- */
describe("a form opened before the record answered", () => {
/**
* The gap both capture surfaces had. `resolveRecordCapabilities(undefined)`
* reads as the caller's own record until `/api/auth/me` settles, and the
* switch flow ends in a hard reload that wipes the persisted cache — so the
* window is widest exactly when a delegate arrives. Both surfaces gated the
* CHOOSER at tap time and never asked again, which left the form standing
* once the answer landed.
*
* These assert the re-derivation, which is what closes it. What they cannot
* assert is the render, because there is no click here: the SSR note at the
* top of the file applies.
*/
it("withdraws a capture form the shrunken offer no longer holds", () => {
// The chooser offered four; the answer arrives and offers two.
expect(admittedCaptureKind("mood", ["measurement", "medication"])).toBe(
null,
);
expect(admittedCaptureKind("water", ["measurement", "medication"])).toBe(
null,
);
// …and leaves an admitted one exactly where it was.
expect(
admittedCaptureKind("medication", ["measurement", "medication"]),
).toBe("medication");
expect(admittedCaptureKind(null, ["measurement"])).toBe(null);
});
it("withdraws a dashboard quick-entry sheet the delegation does not admit", () => {
const DELEGATE = { canAdd: true, canManage: false };
expect(admittedQuickEntry("mood", DELEGATE)).toBe(null);
expect(admittedQuickEntry("water", DELEGATE)).toBe(null);
expect(admittedQuickEntry("measurement", DELEGATE)).toBe("measurement");
expect(admittedQuickEntry("medicationIntake", DELEGATE)).toBe(
"medicationIntake",
);
});
it("withdraws every quick-entry sheet from a read-only delegate", () => {
const READER = { canAdd: false, canManage: false };
for (const sheet of [
"measurement",
"mood",
"medicationIntake",
"water",
] as const) {
expect(admittedQuickEntry(sheet, READER), sheet).toBe(null);
}
});
it("leaves the owner's own sheets alone", () => {
const OWNER_CAPS = { canAdd: true, canManage: true };
for (const sheet of [
"measurement",
"mood",
"medicationIntake",
"water",
] as const) {
expect(admittedQuickEntry(sheet, OWNER_CAPS), sheet).toBe(sheet);
}
expect(admittedQuickEntry(null, OWNER_CAPS)).toBe(null);
});
});
@@ -34,9 +34,9 @@ export function CustomMetricList() {
// Defining a metric is not a delegated verb, and every row here links to
// `/custom-metrics/{id}`, which sharing does not cover: the shell turns a
// delegate away at that route, so the rows would be doors into a wall.
// Logging a value against a custom metric IS admitted, but there is no
// reachable surface for it under a switch, and inventing one is a read-model
// change this does not make.
// Logging a value against a custom metric was admitted for a release and is
// not any more: this paragraph named the gap, the release shipped over it,
// and the write withdrew rather than the sentence staying true.
const { canManage } = useRecordCapabilities();
const router = useRouter();
const [addOpen, setAddOpen] = useState(false);
@@ -29,8 +29,12 @@ import {
type DefaultMedicationOption,
} from "@/lib/medications/default-medication";
import { useAuth } from "@/hooks/use-auth";
import { useActiveRecordName } from "@/hooks/use-record-capabilities";
import { ApiError, apiGet, apiPost } from "@/lib/api/api-fetch";
import { runUndoIntake } from "@/components/medications/use-medication-intake";
import {
intakeToastOptions,
runUndoIntake,
} from "@/components/medications/use-medication-intake";
/**
* v1.4.37 W7b — dashboard "Hinzufügen" → "Medikamenteneinnahme" quick-add.
@@ -111,6 +115,8 @@ export function MedicationIntakeQuickAdd({
// logged-out mounts behave unchanged.
const { user } = useAuth();
const userTz = user?.timezone || "Europe/Berlin";
// The record this dose lands in, or null in the caller's own.
const recordName = useActiveRecordName();
const { data: medicationsRaw, isLoading: medicationsLoading } = useQuery({
queryKey: queryKeys.medications(),
@@ -220,26 +226,35 @@ export function MedicationIntakeQuickAdd({
queryKey: queryKeys.complianceChartInline(),
});
toast.success(
t("common.saved"),
eventId && selectedMedication
? {
action: {
label: t("medications.intakeUndo"),
onClick: () =>
void runUndoIntake({
medication: {
id: medicationId,
name: selectedMedication.name,
},
eventId,
t,
queryClient,
}),
},
}
// v1.36.x — the shared decision, not a fourth copy of it. This surface
// was left out of the collapse that took the other three: it offered a
// delegate an Undo hitting `DELETE /api/medications/{id}/intake/{id}`,
// which is not delegable and refuses, and it confirmed with a bare
// "Saved" — the one confirmation a person acting for somebody else does
// not need. It is reachable by a write delegate from the capture picker
// and from the dashboard quick-add, so both mattered.
const options = intakeToastOptions({
recordName,
eventId,
t,
onUndo: selectedMedication
? (id) =>
void runUndoIntake({
medication: {
id: medicationId,
name: selectedMedication.name,
},
eventId: id,
t,
queryClient,
})
: undefined,
);
});
if (options) {
toast.success(t("common.saved"), options);
} else {
toast.success(t("common.saved"));
}
onSuccess?.();
} catch (err) {
setError(
@@ -26,10 +26,47 @@ import { MoodForm } from "@/components/mood/mood-form";
import { MedicationIntakeQuickAdd } from "@/components/dashboard/medication-intake-quick-add";
import { WaterQuickAddSheet } from "@/components/insights/nutrients/water-quick-add-sheet";
import { useTranslations } from "@/lib/i18n/context";
import {
useRecordCapabilities,
type RecordCapabilities,
} from "@/hooks/use-record-capabilities";
export type QuickEntryDialog =
"measurement" | "mood" | "medicationIntake" | "water" | null;
/**
* v1.36.x — which of the four the delegation admits, and the same rule the
* capture picker states at length.
*
* A WRITE grant covers entering a reading and marking a dose. A mood entry and
* a glass of water are not admitted verbs and the server refuses both under a
* switch.
*/
const DELEGABLE_QUICK_ENTRIES: ReadonlySet<NonNullable<QuickEntryDialog>> =
new Set(["measurement", "medicationIntake"]);
/**
* The sheet that may actually be on screen.
*
* `DashboardHeader` gates the menu items that set this state, and that was the
* whole gate — so it held only for as long as the answer was already known.
* `resolveRecordCapabilities(undefined)` reads as the caller's own record
* until `/api/auth/me` settles, and the switch flow ends in a hard reload that
* wipes the persisted cache, so a delegate's first paint carries all four menu
* items. One of them opened a sheet that then stayed open on a form the server
* refuses.
*
* Re-deriving the open sheet from the current answer withdraws it instead.
* Pure and exported so the rule can be pinned without a click.
*/
export function admittedQuickEntry(
open: QuickEntryDialog,
caps: Pick<RecordCapabilities, "canAdd" | "canManage">,
): QuickEntryDialog {
if (open === null || caps.canManage) return open;
return caps.canAdd && DELEGABLE_QUICK_ENTRIES.has(open) ? open : null;
}
/**
* v1.11.3 F3 — guard the quick-entry sheets against an accidental
* dismiss (overlay tap, Esc, mobile swipe-down) discarding a partly
@@ -101,6 +138,10 @@ export function QuickEntrySheets({
onClose: () => void;
}) {
const { t } = useTranslations();
const capabilities = useRecordCapabilities();
// Re-derived on every render, never latched: the answer can arrive after the
// sheet is already open. See `admittedQuickEntry`.
const openSheet = admittedQuickEntry(open, capabilities);
// v1.4.27 R4 RC2 — DOM handles for the form action-row portal target
// on each quick-entry sheet. The Sheet branch sticky-pins this slot.
const [measurementFooterEl, setMeasurementFooterEl] =
@@ -132,7 +173,7 @@ export function QuickEntrySheets({
return (
<>
<ResponsiveSheet
open={open === "measurement"}
open={openSheet === "measurement"}
onOpenChange={handleQuickEntryOpenChange}
title={t("measurements.addMeasurement")}
footer={<div ref={setMeasurementFooterEl} className="flex w-full" />}
@@ -144,7 +185,7 @@ export function QuickEntrySheets({
/>
</ResponsiveSheet>
<ResponsiveSheet
open={open === "mood"}
open={openSheet === "mood"}
onOpenChange={handleQuickEntryOpenChange}
title={t("mood.addEntry")}
footer={<div ref={setMoodFooterEl} className="flex w-full" />}
@@ -160,7 +201,7 @@ export function QuickEntrySheets({
(Cancel + Save) portals into the sticky-pinned slot so it
stays reachable above the soft keyboard on mobile. */}
<ResponsiveSheet
open={open === "medicationIntake"}
open={openSheet === "medicationIntake"}
onOpenChange={handleQuickEntryOpenChange}
title={t("dashboard.medicationIntakeQuickAdd.sheetTitle")}
description={t("dashboard.medicationIntakeQuickAdd.sheetDescription")}
@@ -175,7 +216,7 @@ export function QuickEntrySheets({
/>
</ResponsiveSheet>
<WaterQuickAddSheet
open={open === "water"}
open={openSheet === "water"}
onOpenChange={handleQuickEntryOpenChange}
onSuccess={onClose}
/>
@@ -256,10 +256,20 @@ export function DocumentDetailSheet({
// the review-first assist, the session-only summary, and content indexing.
// The affordance itself is gated on `assistAvailable` (from usage); the
// probe only resolves the transport mode + the actionable unavailable reason.
const capability = useDocumentAiCapability(open && documentId !== null);
//
// v1.36.x — and neither probe fires inside somebody else's record. The
// document reads behind this sheet are delegable; the AI verbs above them are
// not, and both of these routes stay on the caller's own authentication. A
// delegate would fire two queries that must 403 in order to compute an
// affordance every branch below already withholds on `canManage`.
const capability = useDocumentAiCapability(
canManage && open && documentId !== null,
);
// When auto-read is ON, reading happens automatically on upload — the manual
// per-document AI action row is redundant and collapses away.
const autoRead = useDocumentsAutoAiRead(open && documentId !== null);
const autoRead = useDocumentsAutoAiRead(
canManage && open && documentId !== null,
);
const suggest = useSuggestDetails();
const summary = useDocumentSummary();
// Stored generation has an independent mutation state so transient
+40 -9
View File
@@ -74,6 +74,34 @@ const CAPTURE_KIND_ORDER: ReadonlyArray<CaptureKind> = [
"water",
];
/**
* The kind whose form may actually be on screen.
*
* Gating the chooser is not enough, and the gap is widest exactly when it
* matters. `resolveRecordCapabilities(undefined)` answers "your own record"
* until `/api/auth/me` settles — deliberately, so no add button blanks on
* every cold load — and the switch flow ends in a hard reload that wipes the
* persisted query cache. So a delegate's first paint offers all four kinds for
* as long as that query takes. `chooseKind` refused an unoffered kind at tap
* time and then never asked again, so a tap landing inside that window opened
* a form and left it open once the answer arrived: the delegate ends up
* standing on a form posting to a route the server refuses.
*
* Re-deriving the open form from the CURRENT offer is what closes it. Same
* shape `/measurements` and the medication wizard already use (`open={x &&
* capability}`) — a control that appears and withdraws is a much smaller lie
* than one that stays and 403s.
*
* Pure and exported so the rule can be pinned without a click; an SSR test
* cannot tap the button that opens the sheet.
*/
export function admittedCaptureKind(
kind: CaptureKind | null,
offered: ReadonlyArray<CaptureKind>,
): CaptureKind | null {
return kind !== null && offered.includes(kind) ? kind : null;
}
/**
* The capture kinds to offer, given what the record allows and whether the
* nutrients module is on. Exported pure so the delegation rule can be pinned
@@ -108,6 +136,9 @@ export function CapturePicker({ open, onOpenChange }: CapturePickerProps) {
CAPTURE_KIND_ORDER,
);
const [kind, setKind] = useState<CaptureKind | null>(null);
// Re-derived on every render, never latched: the offer can shrink under a
// sheet that is already open. See `admittedCaptureKind`.
const openKind = admittedCaptureKind(kind, offered);
const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
// v1.30.1 — mirrors `QuickEntrySheets`' `confirmDiscardOpen`: hold a
// dismiss attempt here instead of closing outright when the form
@@ -177,10 +208,10 @@ export function CapturePicker({ open, onOpenChange }: CapturePickerProps) {
mood: t("mood.addEntry"),
water: t("nutrients.hydration.quickAddTitle"),
};
// `kind === null` keeps the form sheet closed (the title is unread then);
// the mood label is the harmless default, matching the prior ternary's
// else branch.
const formTitle = kind ? formTitleByKind[kind] : t("mood.addEntry");
// `openKind === null` keeps the form sheet closed (the title is unread
// then); the mood label is the harmless default, matching the prior
// ternary's else branch.
const formTitle = openKind ? formTitleByKind[openKind] : t("mood.addEntry");
return (
<>
@@ -219,26 +250,26 @@ export function CapturePicker({ open, onOpenChange }: CapturePickerProps) {
{/* The chosen capture surface, reusing the existing form. */}
<ResponsiveSheet
open={kind !== null && kind !== "water"}
open={openKind !== null && openKind !== "water"}
onOpenChange={handleFormOpenChange}
title={formTitle}
footer={<div ref={setFooterEl} className="flex w-full" />}
>
{kind === "measurement" && (
{openKind === "measurement" && (
<MeasurementForm
onSuccess={closeForm}
onCancel={closeForm}
footerSlot={footerEl}
/>
)}
{kind === "medication" && (
{openKind === "medication" && (
<MedicationIntakeQuickAdd
onSuccess={closeForm}
onCancel={closeForm}
footerSlot={footerEl}
/>
)}
{kind === "mood" && (
{openKind === "mood" && (
<MoodForm
onSuccess={closeForm}
onCancel={closeForm}
@@ -247,7 +278,7 @@ export function CapturePicker({ open, onOpenChange }: CapturePickerProps) {
)}
</ResponsiveSheet>
{nutrientsEnabled && kind === "water" && (
{openKind === "water" && (
<WaterQuickAddSheet
open
onOpenChange={handleFormOpenChange}
@@ -34,6 +34,8 @@ import {
refetchInactiveDailyReads,
} from "@/lib/query-keys";
import { apiPost } from "@/lib/api/api-fetch";
import { useActiveRecordName } from "@/hooks/use-record-capabilities";
import { intakeToastOptions } from "@/components/medications/use-medication-intake";
import type { QueryKey } from "@tanstack/react-query";
import type { LedgerSchedule } from "@/components/medications/dose-history-ledger";
@@ -132,6 +134,8 @@ export function LedgerAddDialog({
}: LedgerAddDialogProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
// The record this dose lands in, or null in the caller's own.
const recordName = useActiveRecordName();
const formId = useId();
const [takenAt, setTakenAt] = useState(() => toDateTimeLocal(new Date()));
@@ -166,14 +170,28 @@ export function LedgerAddDialog({
// apiPost throws so the catch below surfaces it rather than silently
// dropping the dose.
await apiPost(`/api/medications/${medicationId}/intake`, body);
toast.success(
t(
skipped
? "medications.intakeToastSkipped"
: "medications.intakeToastTaken",
{ name: medicationName },
),
// v1.36.x — the shared decision. This surface offers no Undo, so what
// it was missing is the other half: inside somebody else's record the
// confirmation names the record, because "Taken" alone is the one
// confirmation a person acting for somebody else does not need. The
// ledger's "+ Eintrag" button that opens this dialog is gated on
// `canAdd`, so a delegate reaches it.
const toastOptions = intakeToastOptions({
recordName,
eventId: undefined,
t,
});
const message = t(
skipped
? "medications.intakeToastSkipped"
: "medications.intakeToastTaken",
{ name: medicationName },
);
if (toastOptions) {
toast.success(message, toastOptions);
} else {
toast.success(message);
}
await invalidateKeys(queryClient, [
...medicationDependentKeys,
ledgerKey,
@@ -564,8 +564,12 @@ export function DoseHistoryLedger({
* Every settled row (taken / skipped / a past missed day / ad-hoc) carries
* ONLY the kebab: Bearbeiten, the Übersprungen↔Genommen toggle, Löschen —
* and, for a past missed slot, the Genommen / Übersprungen backfill marks.
*
* v1.36.x — exported for the delegated-affordance suite. The row's capability
* gating is the interesting part and the ledger around it needs a payload, a
* medication and a query client to paint one row.
*/
function LedgerRowItem({
export function LedgerRowItem({
row,
marking,
isToday,
@@ -725,6 +729,35 @@ function LedgerRowItem({
{t("medications.detail.verlauf.markTaken")}
</Button>
)}
{/* v1.36.x — the other half of the same admitted verb. Marking a dose
taken OR skipped is one capability, and the medication card offers
both; this ledger offered a delegate only the first, because skip
lives in the kebab and the kebab is owner-only (it also holds edit,
re-attribute and delete). Rather than mix admitted and withheld
items in one menu, a delegate gets skip as its own control beside
take, which is the shape the card already uses. The owner keeps it
where it was. */}
{showTakenButton && canAdd && !canManage && (
<Button
variant="outline"
size="sm"
onClick={() => onMark(row, "skipped")}
disabled={takeBusy || skipBusy}
aria-busy={skipBusy || undefined}
className="min-h-9"
data-slot="ledger-mark-skipped"
>
{skipBusy ? (
<Loader2
aria-hidden="true"
className="size-4 animate-spin motion-reduce:animate-none"
/>
) : (
<SkipForward aria-hidden="true" className="size-4" />
)}
{t("medications.detail.verlauf.markSkipped")}
</Button>
)}
{canManage && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -21,6 +21,7 @@ import { CheckCheck, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { useTranslations } from "@/lib/i18n/context";
import { useActiveRecordName } from "@/hooks/use-record-capabilities";
import { formatDose } from "@/lib/medications/format-dose";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import {
@@ -42,13 +43,19 @@ export function TakeAllDueDialog({
}: TakeAllDueDialogProps) {
const { t, locale } = useTranslations();
const queryClient = useQueryClient();
const recordName = useActiveRecordName();
const [submitting, setSubmitting] = useState(false);
async function handleConfirm() {
if (submitting) return;
setSubmitting(true);
try {
await runTakeAllDue({ medications: dueMedications, t, queryClient });
await runTakeAllDue({
medications: dueMedications,
t,
queryClient,
recordName,
});
// Close regardless of partial failures — the summary toast carries
// the counts and failed medications stay due on the page behind it.
onOpenChange(false);
+27 -2
View File
@@ -33,12 +33,23 @@
*
* The due set is small (a handful of medications, never the 500-entry
* sync scale), so N sequential round trips are negligible.
*
* v1.36.x — a delegate may drive this, and the loop cannot half-apply on
* them. The two refusals v1.36.1 added for a delegate — snoozing, and
* changing an event the owner already resolved — live on
* `POST /api/medications/intake`, the account-wide slot route, which this
* loop does not call. The route it does call has no snooze arm at all, and
* the derivation above cannot put a resolved dose in the set: an event with
* a `takenAt` closes its window status, and `takenEarlyDaysAgo` drops the
* day-scale case ahead of it. Every entry it sends is `skipped: false` on a
* slot still in play, which is the same request the card's own button makes.
*/
import type { QueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { apiPost } from "@/lib/api/api-fetch";
import { intakeToastOptions } from "@/components/medications/use-medication-intake";
import { invalidateMedicationReads } from "@/lib/query-keys";
import {
reduceCurrentWindowStatus,
@@ -211,8 +222,16 @@ export async function runTakeAllDue(deps: {
medications: DueMedication[];
t: Translator;
queryClient: QueryClient;
/**
* v1.36.x — the record the batch lands in, when it is not the caller's own.
* The sweep is a delegated write now, so its summary carries the same
* receipt every single-dose confirmation does: a helper who confirms four
* tablets is told whose four they were. It offers no Undo, so the helper's
* other half is a no-op here.
*/
recordName?: string | null;
}): Promise<{ taken: number; failed: number }> {
const { medications, t, queryClient } = deps;
const { medications, t, queryClient, recordName } = deps;
let taken = 0;
let failed = 0;
@@ -244,7 +263,13 @@ export async function runTakeAllDue(deps: {
}
if (failed === 0) {
toast.success(t("medications.takeAllDue.successToast", { count: taken }));
const options = intakeToastOptions({ recordName, eventId: undefined, t });
const message = t("medications.takeAllDue.successToast", { count: taken });
if (options) {
toast.success(message, options);
} else {
toast.success(message);
}
} else if (taken > 0) {
toast.error(t("medications.takeAllDue.partialToast", { taken, failed }));
} else {
@@ -85,6 +85,23 @@ describe("offering a level", () => {
expect(html).toContain('data-access="WRITE" data-selected="false"');
});
it("shows keyboard focus on the option the radio is hidden inside", () => {
// The radio is `sr-only`, so the browser's own ring lands on a zero-size
// box and tabbing through this fieldset moved an invisible selection —
// WCAG 2.4.7, on the screen where somebody grants write access to their
// health record. The label wears the ring instead, and `has-[:focus-visible]`
// is what carries it from the input to the label.
const html = render(<GrantInviteCard />);
const options = html.match(
/<label[^>]*data-slot="grant-invite-access-option"[^>]*>/g,
);
expect(options).toHaveLength(2);
for (const option of options ?? []) {
expect(option, option).toContain("has-[:focus-visible]:ring-2");
expect(option, option).toContain("has-[:focus-visible]:ring-ring/50");
}
});
it("says what the wider level actually does, and what it does not", () => {
const html = render(<GrantInviteCard />);
// The thing a person reading "write access" gets wrong.
@@ -96,6 +113,12 @@ describe("offering a level", () => {
// the presence of the rest: a consent notice that over-promises is worse
// than one that is merely incomplete.
expect(html).not.toContain("allergies");
// v1.36.x — and the same again for logging a value on a tracked metric.
// The route was admitted, the copy promised it, and no delegate could
// reach a surface that posts one: `/custom-metrics/{id}` is not a
// shared-record destination, so the shell answers before the form does.
// The permission and the sentence went together.
expect(html).not.toContain("a metric you track yourself");
// Deferring a reminder is the capability the same request could reach and
// delegation does not cover; the notice has to say so.
expect(html).toContain("cannot defer one of your reminders");
@@ -191,6 +191,13 @@ function AccessOption({
data-selected={selected ? "true" : "false"}
className={[
"flex min-h-11 cursor-pointer items-start gap-3 rounded-md border p-3 transition-colors",
// The radio itself is `sr-only`, so the browser's own focus ring lands
// on a zero-size box: keyboard focus moved through this fieldset with
// nothing visible moving with it. WCAG 2.4.7, on the screen where
// somebody decides who may write into their health record. The label
// wears the ring instead, on the same `ring-ring/50 ring-2` token the
// capture picker's options use.
"has-[:focus-visible]:ring-ring/50 has-[:focus-visible]:ring-2",
selected
? "border-primary bg-primary/5"
: "border-border hover:bg-muted/40",