Merge branch 'main' into feat/vaccinations-phase-1

The visit stage's second half landed while this was in flight and both
touched the same three places. Resolved as one set: the link facade
carries the reverse document-to-visit direction and the new dose pair
side by side, the sharing literals hold both sets of admissions with the
count re-added on top, and the language bundles take the shorter module
description the trunk settled on.
This commit is contained in:
Marc-André Bombeck committed 2026-08-08 17:07:58 +02:00
commit e1a4b7631c
200 files changed
+13599 -2858

No files matched your search

+26 -2
View File
@@ -91,13 +91,13 @@ inboundFactEditSchema.meta({
documentUpdateSchema.meta({
id: "DocumentUpdateRequest",
description:
"Metadata edit for a stored document: `title` (user label; null clears it), `kind` (category), `documentDate` (user filing date, YYYY-MM-DD; null clears it), `episodeIds` (REPLACE-SET of condition links — the document's links become exactly this set; an empty array unlinks everything; every id must be a live episode of the caller or the whole request answers 404). At least one field required. No `userId` field — narrowed from the session and fed to the Prisma `where` with the row id.",
"Metadata edit for a stored document: `title` (user label; null clears it), `kind` (category), `documentDate` (user filing date, YYYY-MM-DD; null clears it), `episodeIds` (REPLACE-SET of condition links — the document's links become exactly this set; an empty array unlinks everything; every id must be a live episode of the caller or the whole request answers 404), `encounterIds` (the same replace-set semantics over the caller's visits). At least one field required. No `userId` field — narrowed from the session and fed to the Prisma `where` with the row id.",
});
documentBulkSchema.meta({
id: "DocumentBulkRequest",
description:
"One bulk action over up to 100 owner-scoped documents: `setKind` (requires `kind`), `linkEpisode` / `unlinkEpisode` (require `episodeId`), `delete` (tombstone, undo-able for 30 days), `restore` (clear tombstone). Partial failures never abort the batch — see the per-id result array.",
"One bulk action over up to 100 owner-scoped documents: `setKind` (requires `kind`), `linkEpisode` / `unlinkEpisode` (require `episodeId`), `linkEncounter` / `unlinkEncounter` (require `encounterId`), `delete` (tombstone, undo-able for 30 days), `restore` (clear tombstone). Partial failures never abort the batch — see the per-id result array.",
});
const factProvenance = z.object({
@@ -137,6 +137,18 @@ const conditionLink = z
"A link to one of the caller's illness/condition episodes. `name` is the episode's user-facing label.",
});
const encounterLink = z
.object({
encounterId: z.string(),
kind: z.string(),
occurredAt: z.string().nullable(),
})
.meta({
id: "DocumentEncounterLink",
description:
"A link to one of the caller's visits — \"this letter belongs to that appointment\". `kind` is the visit-kind ENUM CONSTANT rather than a rendered name: unlike a condition label, which is the person's own words, a visit kind is one of eight closed values whose human name the reader's own bundle owns, so publishing the constant is what lets a German reader and an English one each see it named correctly.",
});
const inboundDocument = z
.object({
id: z.string(),
@@ -153,6 +165,7 @@ const inboundDocument = z
factCount: z.number(),
pendingCount: z.number(),
conditionLinks: z.array(conditionLink),
encounterLinks: z.array(encounterLink),
servingClass: z.enum(["inline", "attachment"]),
hasContentIndex: z.boolean(),
contentIndexSource: z
@@ -256,6 +269,13 @@ export const inboundDocumentPaths: NonNullable<ZodOpenApiObject["paths"]> = {
description:
"Only documents linked to this illness/condition episode.",
},
{
name: "encounterId",
in: "query",
required: false,
schema: { type: "string" },
description: "Only documents linked to this visit.",
},
{
name: "year",
in: "query",
@@ -356,6 +376,10 @@ export const inboundDocumentPaths: NonNullable<ZodOpenApiObject["paths"]> = {
description:
"Optional condition pre-links (repeat the field per id). Every id must be a live episode of the caller.",
}),
encounterIds: z.array(z.string()).optional().meta({
description:
"Optional visit pre-links (repeat the field per id). Every id must be a live visit of the caller; an unknown one refuses the upload rather than dropping the link the person asked for.",
}),
}),
},
},
+63 -3
View File
@@ -21,6 +21,7 @@ import {
encounterCreateSchema,
encounterUpdateSchema,
encounterListQuerySchema,
encounterSuggestQuerySchema,
encounterLinkSchema,
encounterStatusEnum,
encounterKindEnum,
@@ -53,7 +54,13 @@ encounterUpdateSchema.meta({
encounterListQuerySchema.meta({
id: "ListEncountersQuery",
description:
"Window and filters for the visit list: `from` / `to` (ISO-8601 instants), `status`, `practitionerId`, and `limit` (1–200, default 100).",
"Window and filters for the visit list: `from` / `to` (ISO-8601 instants), `status`, `practitionerId`, `episodeId` (only visits filed against that condition episode — the condition side of the link, and the only direction it is offered in), and `limit` (1–200, default 100).",
});
encounterSuggestQuerySchema.meta({
id: "SuggestEncounterQuery",
description:
"The date to resolve around, as an ISO-8601 instant with an offset. A document uses `reportDate ?? documentDate`; a lab panel uses `takenAt`.",
});
encounterLinkSchema.meta({
@@ -77,7 +84,7 @@ practitionerUpdateSchema.meta({
practitionerListQuerySchema.meta({
id: "ListPractitionersQuery",
description:
"Query params for the address book: `q` (case-insensitive substring of the name) and `limit` (1–200, default 100). Name-ordered.",
"Query params for the address book: `q` (case-insensitive substring of the name OR the practice — a person looks one up by whichever of the two they remember) and `limit` (1–200, default 100). Name-ordered.",
});
const practitioner = z
@@ -120,7 +127,7 @@ const encounterLinks = z
.meta({
id: "EncounterLinks",
description:
"The three link families of one visit, each ordered by when it was filed. Present on the detail response, absent from the list.",
"The three link families of one visit, each ordered by when it was filed. Present on BOTH the list and the detail: a card shows counts of what the visit produced, and an edit opened from a list row seeds its pickers from that row — a list without them would make the first read zero and the second unfile everything on save. The list resolves them in three grouped queries for the whole page, not three per row.",
});
const skipReport = z
@@ -172,6 +179,35 @@ const encounterList = z
"Visits split server-side rather than client-side. `upcoming` reads soonest-first and `past` reads newest-first — opposite directions, resolved once here so the ordering lives in one place.",
});
const suggestionCandidate = z
.object({
id: z.string(),
occurredAt: z.string(),
status: encounterStatusEnum,
kind: encounterKindEnum,
practitionerName: z.string().nullable(),
})
.meta({
id: "EncounterSuggestionCandidate",
description:
"One visit a record might belong to, resolved far enough to render a row without a second round trip. `practitionerName` is null when the visit names no practice, which is an absence rather than a gap.",
});
const encounterSuggestion = z
.discriminatedUnion("kind", [
z.object({ kind: z.literal("one"), encounter: suggestionCandidate }),
z.object({
kind: z.literal("many"),
encounters: z.array(suggestionCandidate),
}),
z.object({ kind: z.literal("none") }),
])
.meta({
id: "EncounterSuggestion",
description:
"The verdict, as a shape rather than a best guess. There is deliberately no field on the `many` arm a client could read as a pre-selection: collapsing two candidates into one is the failure this union exists to make impossible.",
});
const encounterNotFound = {
"404": {
description: "Visit not found (or owned by another user).",
@@ -232,6 +268,30 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/encounters/suggest": {
get: {
tags: ["Records"],
summary: "Which visit does a record dated around this day belong to?",
description:
"Resolves the caller's live DONE or PLANNED visits within ±7 days of `anchor` into a verdict, so the three capture moments that ask the question — a document arriving, a lab panel committed from an extraction, a lab panel typed by hand — all read the same answer. `one` means pre-select it visibly with one undo; `many` means offer a picker with NOTHING pre-selected, because pre-selecting the first of two teaches a person to stop reading suggestions; `none` means offer nothing at all. Cancelled visits and no-shows are never candidates: neither happened, so neither produced the record being filed. No AI provider is involved and none is required.",
requestParams: { query: encounterSuggestQuerySchema },
responses: {
...recordRefusal(),
"200": {
description: "The verdict.",
content: {
"application/json": {
schema: dataEnvelope(
encounterSuggestion,
"SuggestEncounterEnvelope",
),
},
},
},
...stdResponses,
},
},
},
"/api/encounters/{id}": {
get: {
tags: ["Records"],
+1 -1
View File
@@ -26,7 +26,7 @@ import {
createLabResultSchema.meta({
id: "CreateLabResultRequest",
description:
'Record a single biomarker reading (HbA1c, LDL, ferritin, TSH, …). A reading is EITHER numeric (`value` + `unit`, optional reference bounds) OR qualitative (`valueText`, e.g. "negativ" / "positiv") — exactly one, never both, never neither. `analyte` + `unit` are free-form (a lab prints its own naming); a qualitative reading needs no unit / bounds. When both numeric bounds are present `referenceLow` must not exceed `referenceHigh`. `takenAt` is a backdatable ISO instant (no future, ≤ 50 years past). The optional `note` is encrypted at rest. The optional `source` records provenance: `"OCR"` for an on-device-OCR capture (the raw image never reaches the server on this path), defaulting to `"MANUAL"` when omitted.',
'Record a single biomarker reading (HbA1c, LDL, ferritin, TSH, …). A reading is EITHER numeric (`value` + `unit`, optional reference bounds) OR qualitative (`valueText`, e.g. "negativ" / "positiv") — exactly one, never both, never neither. `analyte` + `unit` are free-form (a lab prints its own naming); a qualitative reading needs no unit / bounds. When both numeric bounds are present `referenceLow` must not exceed `referenceHigh`. `takenAt` is a backdatable ISO instant (no future, ≤ 50 years past). The optional `note` is encrypted at rest. The optional `source` records provenance: `"OCR"` for an on-device-OCR capture (the raw image never reaches the server on this path), defaulting to `"MANUAL"` when omitted. The optional `encounterId` files the reading against a visit the caller owns — always optional, and a link that could not be made never fails the reading.',
});
updateLabResultSchema.meta({
+132
View File
@@ -35,7 +35,9 @@ import {
import {
dataEnvelope,
errorEnvelope,
recordRefusal,
stdResponses,
MODULE_DISABLED_DESCRIPTION,
baseUpdatedAtField,
updatedAtTokenField,
conflictResponse409,
@@ -386,7 +388,137 @@ const bulkMoodResponse = z
})
.meta({ id: "BulkMoodResponse" });
// ── The day's two readings ───────────────────────────────────────────
//
// Published as the RESOLVED value. The server computes the expected value, the
// band, the count, the deviation and the age; the client renders them. Nothing
// here is a hint the client is meant to re-derive — two clients deriving the
// same figure is how they start disagreeing about it, and this figure is about
// somebody's health record.
const moodPrognosisContribution = z
.object({
feature: z
.string()
.describe(
"Stable feature identifier: `dimension:a2`, `context:workLoad`, `context:workStatus=off` or `linked:steps`. A client that does not recognise one skips it — an older row can name a feature a later model dropped.",
),
contribution: z
.number()
.describe(
"Signed: how far this feature moved the expected value away from the account's own average day. Ordered by absolute size, largest first.",
),
})
.meta({ id: "MoodPrognosisContribution" });
const moodPrognosisPresent = z.object({
present: z.literal(true),
date: z.string().describe("The local day this is about, `YYYY-MM-DD`."),
predicted: z
.number()
.describe(
"The expected pleasantness (A1) for that day, 0-10, on the account's own past pattern. A counterfactual, never a measurement — and never to be displayed without `n` and the band.",
),
ciLow: z.number().nullable(),
ciHigh: z
.number()
.nullable()
.describe(
"The band, from the validation residuals. It widens when the model fits badly, so a wide band is the signal to present the value cautiously.",
),
n: z
.number()
.int()
.describe(
"Complete days the fit used. Display it WHEREVER `predicted` is displayed: a value built from 30 days and one built from 300 look identical otherwise.",
),
modelVersion: z.string(),
computedAt: z.iso.datetime({ offset: true }),
ageDays: z
.number()
.int()
.nullable()
.describe("Whole days between that day and the reader's today."),
current: z
.boolean()
.describe(
"Whether it is fresh enough to back a present-tense sentence. False means the copy must name the day it is about.",
),
provisional: z
.boolean()
.describe("True below 60 days of history: label it as provisional."),
stage: z.enum(["provisional", "regular", "seasonal"]),
entries: z.number().int().describe("Days of history behind the ladder."),
seasonalUnlocked: z.boolean(),
selfAssessment: z
.number()
.int()
.nullable()
.describe(
"The person's own rating for that day, stored exactly as they gave it. It LEADS: it is the primary value on any surface that shows both, and it is never merged with `predicted`.",
),
deviation: z
.enum(["within", "above", "below"])
.nullable()
.describe(
"Where the self-assessment sat against the BAND, not against `predicted`. `within` means the day went as the account's own past days suggest.",
),
deviationAmount: z
.number()
.nullable()
.describe("How far outside the band, in scale points. `0` when inside."),
contributions: z.array(moodPrognosisContribution),
});
const moodPrognosisAbsent = z.object({
present: z.literal(false),
reason: z
.enum(["no-output-yet", "learning-phase", "no-pattern"])
.describe(
"`no-output-yet`: too few days for anything. `learning-phase`: enough to describe, not to compare. `no-pattern`: enough days, nothing steady enough in them. None of the three is an error and none is a zero.",
),
entries: z.number().int(),
nextThreshold: z
.number()
.int()
.nullable()
.describe("Days at which the next step unlocks, when a count is missing."),
});
const moodPrognosisResponse = z
.union([moodPrognosisPresent, moodPrognosisAbsent])
.meta({
id: "MoodPrognosis",
description:
"Two separate readings of one day: what the person recorded, and what a comparison with their own past days would have expected. They are never merged — the distance between them is the finding, and a single blended figure destroys it. The comparison is a regularised regression over the account's own history: observational only, never causal. Any copy built on it must state the value as a counterfactual (a value around X would have been expected), must carry `n`, and must not say that anything caused anything.",
});
export const moodPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/mood/prognosis": {
get: {
tags: ["Mood"],
summary: "The day's own rating and what the account's days imply (v1.38)",
description:
"The newest stored comparison for the account, with the person's own rating for that day beside it. Written nightly by a job and never by a request: the value cannot be overwritten, which is what keeps the two readings separate. Absence is explicit (`present: false` with a reason and a count) and is a normal answer, not an error — the comparison refuses when the history does not support one. Whole-record read: the fit takes the day's context AND the sleep, activity and recovery figures the owning modules hold, and it names them, so a section-scoped grant is refused rather than served a filtered list. Gated: `module.disabled` 403 when the mood module is off.",
responses: {
"200": {
description: "The day's two readings, or an explained absence.",
content: {
"application/json": {
schema: dataEnvelope(
moodPrognosisResponse,
"MoodPrognosisEnvelope",
),
},
},
},
// Two reasons, one status: the module gate and the sharing fence both
// answer 403, and OpenAPI allows one response per status.
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
...stdResponses,
},
},
},
"/api/mood-entries/bulk": {
post: {
tags: ["Mood"],
+1 -1
View File
@@ -22,7 +22,7 @@ import { dataEnvelope, stdResponses } from "./shared";
ocrCommitSchema.meta({
id: "OcrCommitRequest",
description:
"The rows a human confirmed on the Lab-OCR review screen. Each row is EITHER numeric (`value` + `unit`, optional reference bounds) OR qualitative (`valueText`) — exactly one. `analyte` drives a resolve-or-mint of the user-scoped biomarker; `takenAt` is a backdatable ISO instant. No `userId` field — it is narrowed from the session. 1..100 rows. The route skips a row that duplicates a live reading (same analyte + day + value).",
"The rows a human confirmed on the Lab-OCR review screen. Each row is EITHER numeric (`value` + `unit`, optional reference bounds) OR qualitative (`valueText`) — exactly one. `analyte` drives a resolve-or-mint of the user-scoped biomarker; `takenAt` is a backdatable ISO instant. No `userId` field — it is narrowed from the session. 1..100 rows. The route skips a row that duplicates a live reading (same analyte + day + value). The optional `encounterId` files the panel against a visit the caller owns — ONE link per written result row, so a marker re-run on a different day belongs to its own visit; always optional, and a link that could not be made never fails the commit.",
});
const capabilityResponse = z