diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 054370535..020b985d3 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,8 @@ blank_issues_enabled: false contact_links: + - name: Ideas and upvotes + url: https://github.com/MBombeck/HealthLog/discussions/categories/ideas?discussions_q=category%3AIdeas+sort%3Atop + about: Suggest an improvement or upvote the ones you want. One idea per discussion; the most-voted ones get looked at first. - name: Documentation url: https://docs.healthlog.dev about: Setup, configuration, and feature documentation. Most usage questions are answered here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 5229123be..fbaa1519f 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -6,7 +6,7 @@ body: - type: markdown attributes: value: | - Feature ideas welcome. HealthLog is a personal-health PWA — the bar for inclusion is high (privacy-first, offline-capable, self-hostable). Use this template to propose something concrete; for open-ended discussion, prefer a [Discussion](https://github.com/MBombeck/HealthLog/discussions) thread. + Feature ideas welcome. HealthLog is a personal-health PWA, and the bar for inclusion is high (privacy-first, offline-capable, self-hostable). Use this template to propose something concrete. For an idea you'd like others to weigh in on, or a small improvement, start it in [Ideas](https://github.com/MBombeck/HealthLog/discussions/categories/ideas) instead: people can upvote it there, and the most-voted ideas get looked at first (see #1114). - type: textarea id: problem attributes: diff --git a/bundle-budget.json b/bundle-budget.json index e45168d89..cc062e9d9 100644 --- a/bundle-budget.json +++ b/bundle-budget.json @@ -1,12 +1,12 @@ { - "$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.37.2: / 455, /insights 443, /measurements 441, /insights/mood 453, total 3328, baseline 130, lazy catalogs 849. Every per-route ceiling is unchanged. The /insights overview crept a kilobyte over its 445 ceiling when the ECG teaser began importing its overview cap from the classification module, dragging that module's label map and helpers into the eager page; the cap now lives in its own value-only module, and the Health Score's single provenance entry is split out of the full metric-provenance map, so the overview imports the bare number and citation it renders rather than every metric's label map behind them. Both are back under 445 with room to spare. The 42 KB aggregate rise from 3286 (v1.35.0) is all locale-catalog strings: v1.36 and v1.37 added the encounter, mood-context, mood-prognosis, practitioner, workout-batch and account-sharing surfaces, and their copy lands across the six locale catalogs the whole-build sum counts independently (804 to 849 KB). The non-catalog client chunks are flat against v1.35.0, so nothing a person downloads on a given route grew beyond its own ceiling. The aggregate cap therefore moves from 3310 to 3352 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged. v1.37.4's honest-error-state charge then added recoverable read-failure handling to thirteen surfaces (the shared QueryErrorCard and QueryErrorRow primitives plus an isError branch per surface) and rewrote the MCP scope note and the managed-record error copy across the six locales; the measured total rose to 3404 while every per-route ceiling stayed met (/page 457, /insights 445, /measurements 443, /insights/mood 455). The aggregate cap moves from 3352 to 3428, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.15's async-truth charge then added the refresh settling state with its two-locale-key copy, the index-outcome plain-words line (seven keys across the six catalogs) and the reindex-count wiring; the measured total rose to 3429 while every per-route ceiling stayed met (/page 456, /insights 445, /measurements 442, /insights/mood 455). The aggregate cap moves from 3428 to 3452, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.27 found /insights sitting a few hundred bytes under 445 on main and a few hundred over it on the release branch — the page had been at its ceiling for three releases and the release only had to breathe on it. The weight it was carrying was not its own: the authenticated shell imported one destination predicate from the `@/lib/record-settings` barrel, and the barrel also re-exports the managed settings-patch schemas, so Zod, the module registry and three validation modules rode into the eager bundle of every authenticated route for a function that reads a URL slug. The shell imports the `classification` leaf now. Measured across all 585 client-rendered routes: none grew by a byte, 100 fell, by 4.7 KB at the median and 8.1 KB at the most; /insights 444 to 437, /measurements 442 to 435, / 456 to 450, /insights/mood 455 to 450. The whole-build sum moved the other way, 3451 to 3476, and that direction is the metric rather than the change: the aggregate counts each emitted chunk once, so a graph that leaves the chunk group every route shares gets counted again wherever it lands — here inside the deferred settings chunks that actually use it. Bytes on disk rose 25 KB; bytes a reader downloads only ever fell. The aggregate cap moves from 3452 to 3500, the same 24 KB headroom as the four re-measurements before it. Per-route ceilings keep their old values rather than tightening to the new floor: the CI runner measures each route about 1.5 KB heavier than a local arm64 build does, and a ceiling set from a local number would fail on a build that had not regressed. The static-catalog guard and the one-Recharts-chunk guard remain unchanged. Raised to 3700 at v1.37.32 for the seventh interface language (Korean): the lazy message catalogs went 6->7 chunks (1026 KB gz measured), pushing the aggregate to 3631 against the old 3500. The raise is entirely the new catalog; no route budget moved, and the four eager route ceilings are unchanged and still passing. Most of the aggregate is the dynamic locale-switch and fallback path that a first paint never loads (see issue #253), so this ceiling guards bytes almost no visitor requests; 3700 leaves ~69 KB for ordinary drift until that double-count is cleaned up. v1.38.14 re-measures the four eager routes and changes what the number means. The ceilings had been re-stated but never re-based since v1.37.4, so /insights and /measurements sat within a kilobyte of theirs and / and /insights/mood within one of theirs; e2e run 34043772954 failed on `/insights/page: 445 KB gz exceeds the 445 KB budget` with the other two at 459 of 460, and none of it was a regression anyone had made. A ceiling a route is already touching does not measure the route, it measures whichever dependency bump landed that week. The file states the measured value per route now, plus one drift allowance over it: measured on a local arm64 build at d48bbff01 as / 447, /insights 434, /measurements 433, /insights/mood 447, with a 20 KB allowance, so the effective ceilings are 467 / 454 / 453 / 467 — a raise for all four. The allowance covers the runner delta (the CI runner measures each route a little heavier than a local arm64 build) and ordinary week-to-week drift, while the step change the gate exists for — a statically imported message catalog, a duplicated chart library — is several times larger and still fails. Every run now prints the delta against the baseline, so a route that has crept 15 KB is legible in the log long before it is red; the flat ceiling could only ever say pass or fail. Re-base by re-measuring on a build with nothing else in it and writing the new numbers here with the reason, exactly as a raised ceiling was written before. Raised to 3724 at v1.39.4 on a measured delta, not a feature. The release branch alone measured 3699 KB gz (3698.9) against the 3700 cap, so the ordinary drift room the v1.37.32 raise left had been used up by the releases since; the review fixes on top of it added 1.3 KB gz across the whole build (3700.2), almost all of it new copy in the seven lazy locale catalogs (the total and reused-table labels, the step and chip wording) plus the result-panel states. The four eager routes measured the same on both builds (/ 458, /insights/mood 456, /insights 445, /measurements 442), all inside their ceilings. The aggregate cap moves from 3700 to 3724, the same 24 KB headroom as the re-measurements before it. Raised to 3749 at v1.39.9 on a measured delta. Main measured 3718 KB gz after v1.39.7 and v1.39.8 (unit-aware copy, the phone layouts, the time-zone work and the account-settings restore labels, almost all of it new strings in the seven lazy locale catalogs), leaving 6 KB of the v1.39.4 headroom; the manual workout entry (#1085: the form, its sheet, the delete action and their copy in seven locales) adds about 7 KB and measured 3725. The four eager routes stay inside their drift allowances (/ +12.5, /insights +12.1, /insights/mood +10.2 KB of 20 on main). The aggregate cap moves from 3724 to 3749, the same 24 KB headroom as the re-measurements before it. Raised to 3790 at v1.40.0 on a measured delta. With the background document reads on main (#1103: the run polling hook, the still-reading states and their copy in seven locales), the key backup step and the plain-http sign-in notice (#1104) and the v1.40 fixes (#1106: the duration reader, the marker unit lock, the chart window) each branch measured 3752 KB gz on its own against the 3749 cap; together they add a few KB more. The four eager routes stay inside their drift allowances (/ +18.4, /insights +16.5, /measurements +14.9, /insights/mood +14.7 KB of 20). The aggregate cap moves from 3749 to 3790, about 24 KB above the combined build, the same headroom as the re-measurements before it.", + "$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.37.2: / 455, /insights 443, /measurements 441, /insights/mood 453, total 3328, baseline 130, lazy catalogs 849. Every per-route ceiling is unchanged. The /insights overview crept a kilobyte over its 445 ceiling when the ECG teaser began importing its overview cap from the classification module, dragging that module's label map and helpers into the eager page; the cap now lives in its own value-only module, and the Health Score's single provenance entry is split out of the full metric-provenance map, so the overview imports the bare number and citation it renders rather than every metric's label map behind them. Both are back under 445 with room to spare. The 42 KB aggregate rise from 3286 (v1.35.0) is all locale-catalog strings: v1.36 and v1.37 added the encounter, mood-context, mood-prognosis, practitioner, workout-batch and account-sharing surfaces, and their copy lands across the six locale catalogs the whole-build sum counts independently (804 to 849 KB). The non-catalog client chunks are flat against v1.35.0, so nothing a person downloads on a given route grew beyond its own ceiling. The aggregate cap therefore moves from 3310 to 3352 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged. v1.37.4's honest-error-state charge then added recoverable read-failure handling to thirteen surfaces (the shared QueryErrorCard and QueryErrorRow primitives plus an isError branch per surface) and rewrote the MCP scope note and the managed-record error copy across the six locales; the measured total rose to 3404 while every per-route ceiling stayed met (/page 457, /insights 445, /measurements 443, /insights/mood 455). The aggregate cap moves from 3352 to 3428, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.15's async-truth charge then added the refresh settling state with its two-locale-key copy, the index-outcome plain-words line (seven keys across the six catalogs) and the reindex-count wiring; the measured total rose to 3429 while every per-route ceiling stayed met (/page 456, /insights 445, /measurements 442, /insights/mood 455). The aggregate cap moves from 3428 to 3452, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.27 found /insights sitting a few hundred bytes under 445 on main and a few hundred over it on the release branch — the page had been at its ceiling for three releases and the release only had to breathe on it. The weight it was carrying was not its own: the authenticated shell imported one destination predicate from the `@/lib/record-settings` barrel, and the barrel also re-exports the managed settings-patch schemas, so Zod, the module registry and three validation modules rode into the eager bundle of every authenticated route for a function that reads a URL slug. The shell imports the `classification` leaf now. Measured across all 585 client-rendered routes: none grew by a byte, 100 fell, by 4.7 KB at the median and 8.1 KB at the most; /insights 444 to 437, /measurements 442 to 435, / 456 to 450, /insights/mood 455 to 450. The whole-build sum moved the other way, 3451 to 3476, and that direction is the metric rather than the change: the aggregate counts each emitted chunk once, so a graph that leaves the chunk group every route shares gets counted again wherever it lands — here inside the deferred settings chunks that actually use it. Bytes on disk rose 25 KB; bytes a reader downloads only ever fell. The aggregate cap moves from 3452 to 3500, the same 24 KB headroom as the four re-measurements before it. Per-route ceilings keep their old values rather than tightening to the new floor: the CI runner measures each route about 1.5 KB heavier than a local arm64 build does, and a ceiling set from a local number would fail on a build that had not regressed. The static-catalog guard and the one-Recharts-chunk guard remain unchanged. Raised to 3700 at v1.37.32 for the seventh interface language (Korean): the lazy message catalogs went 6->7 chunks (1026 KB gz measured), pushing the aggregate to 3631 against the old 3500. The raise is entirely the new catalog; no route budget moved, and the four eager route ceilings are unchanged and still passing. Most of the aggregate is the dynamic locale-switch and fallback path that a first paint never loads (see issue #253), so this ceiling guards bytes almost no visitor requests; 3700 leaves ~69 KB for ordinary drift until that double-count is cleaned up. v1.38.14 re-measures the four eager routes and changes what the number means. The ceilings had been re-stated but never re-based since v1.37.4, so /insights and /measurements sat within a kilobyte of theirs and / and /insights/mood within one of theirs; e2e run 34043772954 failed on `/insights/page: 445 KB gz exceeds the 445 KB budget` with the other two at 459 of 460, and none of it was a regression anyone had made. A ceiling a route is already touching does not measure the route, it measures whichever dependency bump landed that week. The file states the measured value per route now, plus one drift allowance over it: measured on a local arm64 build at d48bbff01 as / 447, /insights 434, /measurements 433, /insights/mood 447, with a 20 KB allowance, so the effective ceilings are 467 / 454 / 453 / 467 — a raise for all four. The allowance covers the runner delta (the CI runner measures each route a little heavier than a local arm64 build) and ordinary week-to-week drift, while the step change the gate exists for — a statically imported message catalog, a duplicated chart library — is several times larger and still fails. Every run now prints the delta against the baseline, so a route that has crept 15 KB is legible in the log long before it is red; the flat ceiling could only ever say pass or fail. Re-base by re-measuring on a build with nothing else in it and writing the new numbers here with the reason, exactly as a raised ceiling was written before. Raised to 3724 at v1.39.4 on a measured delta, not a feature. The release branch alone measured 3699 KB gz (3698.9) against the 3700 cap, so the ordinary drift room the v1.37.32 raise left had been used up by the releases since; the review fixes on top of it added 1.3 KB gz across the whole build (3700.2), almost all of it new copy in the seven lazy locale catalogs (the total and reused-table labels, the step and chip wording) plus the result-panel states. The four eager routes measured the same on both builds (/ 458, /insights/mood 456, /insights 445, /measurements 442), all inside their ceilings. The aggregate cap moves from 3700 to 3724, the same 24 KB headroom as the re-measurements before it. Raised to 3749 at v1.39.9 on a measured delta. Main measured 3718 KB gz after v1.39.7 and v1.39.8 (unit-aware copy, the phone layouts, the time-zone work and the account-settings restore labels, almost all of it new strings in the seven lazy locale catalogs), leaving 6 KB of the v1.39.4 headroom; the manual workout entry (#1085: the form, its sheet, the delete action and their copy in seven locales) adds about 7 KB and measured 3725. The four eager routes stay inside their drift allowances (/ +12.5, /insights +12.1, /insights/mood +10.2 KB of 20 on main). The aggregate cap moves from 3724 to 3749, the same 24 KB headroom as the re-measurements before it. Raised to 3790 at v1.40.0 on a measured delta. With the background document reads on main (#1103: the run polling hook, the still-reading states and their copy in seven locales), the key backup step and the plain-http sign-in notice (#1104) and the v1.40 fixes (#1106: the duration reader, the marker unit lock, the chart window) each branch measured 3752 KB gz on its own against the 3749 cap; together they add a few KB more. The four eager routes stay inside their drift allowances (/ +18.4, /insights +16.5, /measurements +14.9, /insights/mood +14.7 KB of 20). The aggregate cap moves from 3749 to 3790, about 24 KB above the combined build, the same headroom as the re-measurements before it. Re-based at v1.40.0 when the quick-entry forms began loading on demand. Custom symptoms added a fifth quick-entry form, and with all five forms bundled eagerly every one of the four eager routes measured over its ceiling (/ 472, /insights 457, /insights/mood 468, /measurements 454 KB gz, each 21 to 25 KB over the baseline). Loading the forms on demand brings them to / 429, /insights 368, /insights/mood 379, /measurements 411: 43 to 90 KB less on first load. The four route baselines move down to those measured values, so the gain is protected by the same 20 KB allowance rather than spent. The aggregate moves the other way, 3774 to 4077, for the reason described at v1.37.27: the aggregate counts each emitted chunk once per route group, and on-demand form chunks land in every route group that can open a quick-entry sheet. Bundling the five forms into one shared on-demand module measured the same (4078), so the split is not the cause. The aggregate cap moves from 3790 to 4100. Bytes on disk rose; bytes a reader downloads fell on every eager route.", "routeBaselineKbGz": { - "/page": 447, - "/insights/page": 434, - "/measurements/page": 433, - "/insights/mood/page": 447 + "/page": 429, + "/insights/page": 368, + "/measurements/page": 411, + "/insights/mood/page": 379 }, "routeDriftAllowanceKbGz": 20, - "totalClientKbGz": 3790, + "totalClientKbGz": 4100, "maxRechartsChunks": 1 } diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index c475bbc1a..b7f6d0ed2 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -3928,7 +3928,10 @@ paths: explicit `unit` token and a summary `stats` block. `bloodPressure` pairs systolic + diastolic (`secondary`) within ±5 min so one fetch renders the dual-line chart; `sleep` collapses per-stage rows into one per-night point carrying time-asleep in hours (`sleepStages` holds the per-stage breakdown) and is internally capped to - 365 days. `glucose` values + `unit` resolve to the user's mg/dL|mmol/L preference. Auth via cookie or Bearer. + 365 days. `glucose` values + `unit` resolve to the user's mg/dL|mmol/L preference. Where a metric has a + source-priority ladder (pulse, weight, SpO2, HRV, ...), each day shows the readings of the source the person's + ladder picks for that day, so a second provider never blends into or duplicates a day; a metric without a ladder + (glucose, body water, bone mass) keeps every source. Auth via cookie or Bearer. parameters: - in: query name: kind @@ -14543,7 +14546,7 @@ paths: schema: $ref: "#/components/schemas/OcrTextExtractRequest" responses: - "202": &a38 + "202": &a36 description: Queued for the background worker. Every refusal the route can answer quickly (capability, provider, rate limit, budget, validation) has already been answered; anything that goes wrong from here is reported on the run. @@ -16391,6 +16394,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER description: Category filter — OR inside the facet. Repeat the parameter (or send a comma-separated value). - name: episodeId @@ -16575,6 +16579,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER documentDate: description: Optional user filing date (YYYY-MM-DD). Defaults to the upload day when omitted so the library @@ -16960,13 +16965,32 @@ paths: structures the document's own stored extracted text (its content index) — the manual recovery for a skipped/failed automatic staging run, 422 `documents.inbound.notIndexed` when no stored text exists. Extraction reproduces what the document states — it never interprets. Nothing reaches the structured stores here; the - confirm route is the only write path." + confirm route is the only write path. With `Prefer: respond-async` (v1.40) the extraction runs in the + background: after the same quick refusals the route answers 202 with a run id, a second request while an + extraction of this document from the same input is queued or running answers with that run, and `GET + /api/ai-runs/{id}` serves `DocumentExtractRunResult` (`{ documentId, factsStaged, status }`, not the document + detail) as the run's `result`. Staging re-checks the document under a row lock, so a review finished while the + read ran fails the run with `documents.inbound.alreadyPartlyConfirmed` (409) or + `documents.inbound.alreadyConfirmed` (422) and leaves the review untouched; the synchronous form answers the + same in that race." parameters: - name: id in: path required: true schema: type: string + - &a37 + name: Prefer + in: header + required: false + schema: + type: string + example: respond-async + description: "Send `respond-async` (RFC 7240) to run the read in the background: the route answers 202 with a run id + once every quick refusal has passed, and `GET /api/ai-runs/{id}` serves the result. Without it the route + answers synchronously with the result, as it always has; that form is retained for clients that have not + adopted runs, and its retirement will be announced one minor release ahead. A preference the route cannot + apply is ignored and the response then carries no `Preference-Applied`." requestBody: required: false content: @@ -16980,8 +17004,9 @@ paths: application/json: schema: $ref: "#/components/schemas/InboundExtractEnvelope" + "202": *a36 "401": *a1 - "403": &a36 + "403": &a38 description: "AI refusal: the `documentAi` capability is unavailable for this record. The envelope carries `meta.errorCode`, `meta.capability` and `meta.reason` (one of `AiUnavailableReason`). `assistant.disabled.documentAi` — the operator turned off reading documents, or every AI feature (the master @@ -17005,7 +17030,7 @@ paths: $ref: "#/components/schemas/ErrorEnvelope" "422": *a4 "429": *a5 - "503": &a37 + "503": &a39 description: "`ai.unavailable` — the inputs behind the AI capability could not be read, and the answer failed closed. Nothing was sent. Retry later." content: @@ -17025,13 +17050,17 @@ paths: only consumed when the request reaches the provider, and the 429 carries `Retry-After`, the `X-RateLimit-Limit` / `-Remaining` / `-Reset` triple, and `meta.retryAt`). WRITES NOTHING — never stages facts, never flips status; the user reviews and saves. 422 (`documents.inbound.providerUnsupported`) with no provider configured. Never - interprets or diagnoses; the title is a neutral filing label." + interprets or diagnoses; the title is a neutral filing label. With `Prefer: respond-async` (v1.40) the read runs + in the background: after the same quick refusals the route answers 202 with a run id, a second request while a + suggestion read of this document over the same transport is queued or running answers with that run, and `GET + /api/ai-runs/{id}` serves this body as the run's `result`." parameters: - name: id in: path required: true schema: type: string + - *a37 requestBody: required: false content: @@ -17055,6 +17084,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER required: - mode @@ -17066,24 +17096,31 @@ paths: application/json: schema: $ref: "#/components/schemas/DocumentSuggestEnvelope" + "202": *a36 "401": *a1 - "403": *a36 + "403": *a38 "422": *a4 "429": *a5 - "503": *a37 + "503": *a39 /api/documents/inbound/{id}/summary: post: tags: - Documents summary: Summarise or transcribe a document - description: 'On-demand description of a stored document. `?mode=summary` (default) returns a short plain-language + description: "On-demand description of a stored document. `?mode=summary` (default) returns a short plain-language summary of WHAT the document is; it remains transient unless `persist=true` fills the empty stored-summary slot, while `persist=true&replace=true` explicitly replaces an existing summary. `?mode=text` returns transient raw transcribed text. Neither result reaches coach memory, snapshots, structured stores, or the search index. The summary is descriptive only and never a diagnosis. Same VISION (empty body) / TEXT (`application/json` `{ mode: - "text", text }`, opt-in local OCR) dispatch as extract. Answers under the `documentAi` capability (403 with the - capability envelope when it is closed), then rate / budget gated. 422 `documents.inbound.providerUnsupported` - with no provider.' + \"text\", text }`, opt-in local OCR) dispatch as extract. Answers under the `documentAi` capability (403 with + the capability envelope when it is closed), then rate / budget gated. 422 + `documents.inbound.providerUnsupported` with no provider. With `Prefer: respond-async` (v1.40) the read runs in + the background: after the same quick refusals the route answers 202 with a run id, and `GET /api/ai-runs/{id}` + serves this body as the run's `result`. A second request while a read with the same `mode`, `persist` and + `replace` is queued or running answers with that run. With `persist=true` the document's `summaryState` is + PENDING while the run is queued or running (unless a summary is already stored) and becomes UNAVAILABLE when the + run fails. `mode=text` over posted text calls no model and is answered synchronously either way (no + `Preference-Applied`)." parameters: - name: id in: path @@ -17114,6 +17151,7 @@ paths: type: boolean default: false description: With `persist=true`, explicitly replace an existing stored summary. + - *a37 requestBody: required: false content: @@ -17137,6 +17175,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER required: - mode @@ -17148,11 +17187,12 @@ paths: application/json: schema: $ref: "#/components/schemas/DocumentSummaryEnvelope" + "202": *a36 "401": *a1 - "403": *a36 + "403": *a38 "422": *a4 "429": *a5 - "503": *a37 + "503": *a39 /api/documents/inbound/{id}/index: post: tags: @@ -17178,17 +17218,7 @@ paths: required: true schema: type: string - - name: Prefer - in: header - required: false - schema: - type: string - example: respond-async - description: "Send `respond-async` (RFC 7240) to run the read in the background: the route answers 202 with a run id - once every quick refusal has passed, and `GET /api/ai-runs/{id}` serves the result. Without it the route - answers synchronously with the result, as it always has; that form is retained for clients that have not - adopted runs, and its retirement will be announced one minor release ahead. A preference the route cannot - apply is ignored and the response then carries no `Preference-Applied`." + - *a37 requestBody: required: false content: @@ -17212,6 +17242,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER required: - mode @@ -17223,12 +17254,12 @@ paths: application/json: schema: $ref: "#/components/schemas/DocumentIndexEnvelope" - "202": *a38 + "202": *a36 "401": *a1 - "403": *a36 + "403": *a38 "422": *a4 "429": *a5 - "503": *a37 + "503": *a39 /api/documents/inbound/{id}/chat: post: tags: @@ -17268,10 +17299,10 @@ paths: type: string description: "SSE frames: `data: \\n\\n`. See the operation description for the per-`type` frame shapes." "401": *a1 - "403": *a36 + "403": *a38 "422": *a4 "429": *a5 - "503": *a37 + "503": *a39 get: tags: - Documents @@ -17334,10 +17365,10 @@ paths: schema: $ref: "#/components/schemas/DocumentReindexEnvelope" "401": *a1 - "403": *a36 + "403": *a38 "422": *a4 "429": *a5 - "503": *a37 + "503": *a39 /api/documents/inbound/{id}/facts/{factId}: patch: tags: @@ -17444,7 +17475,7 @@ paths: schema: $ref: "#/components/schemas/CreateCustomMetricResponse" "401": *a1 - "409": &a40 + "409": &a41 description: A custom metric with this name already exists for the caller. content: application/json: @@ -17473,7 +17504,7 @@ paths: $ref: "#/components/schemas/GetCustomMetricResponse" "401": *a1 "403": *a11 - "404": &a39 + "404": &a40 description: Custom metric not found (or owned by another user). content: application/json: @@ -17507,8 +17538,8 @@ paths: schema: $ref: "#/components/schemas/UpdateCustomMetricResponse" "401": *a1 - "404": *a39 - "409": *a40 + "404": *a40 + "409": *a41 "422": *a4 "429": *a5 delete: @@ -17531,7 +17562,7 @@ paths: schema: $ref: "#/components/schemas/DeleteCustomMetricResponse" "401": *a1 - "404": *a39 + "404": *a40 "422": *a4 "429": *a5 /api/custom-metrics/{id}/entries: @@ -17575,7 +17606,7 @@ paths: $ref: "#/components/schemas/ListCustomMetricEntriesEnvelope" "401": *a1 "403": *a11 - "404": *a39 + "404": *a40 "422": *a4 "429": *a5 post: @@ -17604,7 +17635,7 @@ paths: schema: $ref: "#/components/schemas/CreateCustomMetricEntryResponse" "401": *a1 - "404": *a39 + "404": *a40 "409": *a7 "422": *a4 "429": *a12 @@ -17640,7 +17671,7 @@ paths: schema: $ref: "#/components/schemas/UpdateCustomMetricEntryResponse" "401": *a1 - "404": &a41 + "404": &a42 description: Custom metric entry not found (or owned by another user). content: application/json: @@ -17673,7 +17704,7 @@ paths: schema: $ref: "#/components/schemas/DeleteCustomMetricEntryResponse" "401": *a1 - "404": *a41 + "404": *a42 "422": *a4 "429": *a5 /api/custom-metrics/{id}/entries/restore: @@ -18085,7 +18116,7 @@ paths: schema: $ref: "#/components/schemas/NutrientOverviewEnvelope" "401": *a1 - "403": &a42 + "403": &a43 description: >- The opt-in `nutrients` module is off for this account (errorCode `module.disabled`). Stop syncing and do not retry; offer the enable-in-settings hint. Only run the HealthKit read-authorization flow while the module is @@ -18140,7 +18171,7 @@ paths: schema: $ref: "#/components/schemas/NutrientDailySeriesEnvelope" "401": *a1 - "403": *a42 + "403": *a43 "422": *a4 "429": *a5 /api/nutrients/water: @@ -18169,7 +18200,7 @@ paths: schema: $ref: "#/components/schemas/NutrientWaterWriteEnvelope" "401": *a1 - "403": *a42 + "403": *a43 "409": *a7 "422": *a4 "429": *a5 @@ -18671,26 +18702,26 @@ paths: application/json: schema: $ref: "#/components/schemas/WithingsCredentialsUpdateEnvelope" - "400": &a43 + "400": &a44 description: Body is not parseable JSON. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "413": &a44 + "413": &a45 description: Body exceeds 64 KiB. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "415": &a45 + "415": &a46 description: Content-Type is not `application/json`. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": &a46 + "422": &a47 description: "`clientId` and `clientSecret` are both required and each must be 1–200 characters. The envelope carries a single fixed message, not per-field issues." content: @@ -18876,11 +18907,11 @@ paths: application/json: schema: $ref: "#/components/schemas/FitbitCredentialsUpdateEnvelope" - "400": *a43 + "400": *a44 "401": *a1 - "413": *a44 - "415": *a45 - "422": *a46 + "413": *a45 + "415": *a46 + "422": *a47 "429": *a5 delete: tags: @@ -19023,11 +19054,11 @@ paths: application/json: schema: $ref: "#/components/schemas/GoogleHealthCredentialsUpdateEnvelope" - "400": *a43 + "400": *a44 "401": *a1 - "413": *a44 - "415": *a45 - "422": *a46 + "413": *a45 + "415": *a46 + "422": *a47 "429": *a5 delete: tags: @@ -19180,11 +19211,11 @@ paths: application/json: schema: $ref: "#/components/schemas/OuraCredentialsUpdateEnvelope" - "400": *a43 + "400": *a44 "401": *a1 - "413": *a44 - "415": *a45 - "422": *a46 + "413": *a45 + "415": *a46 + "422": *a47 "429": *a5 delete: tags: @@ -19260,21 +19291,21 @@ paths: schema: $ref: "#/components/schemas/OuraTestEnvelope" "401": *a1 - "422": &a47 + "422": &a48 description: No usable connection for this provider — nothing stored, or the stored grant could no longer be resolved into an access token. `meta.errorCode` = `not_configured`. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "429": &a48 + "429": &a49 description: More than 5 requests in 60 s from this user. `meta.errorCode` = `rate_limited_self` — this is the local limiter, distinct from a `rate_limited` 502 which is the provider's. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "502": &a49 + "502": &a50 description: "The probe did not complete. `meta.errorCode` names the class: `credentials_rejected` (the provider answered 401/403 — the stored grant is gone), `rate_limited` (the PROVIDER answered 429, which is not this endpoint's own limiter), `upstream_error` (5xx), `timeout` (no answer within 5 s), `connection_failed` @@ -19319,11 +19350,11 @@ paths: application/json: schema: $ref: "#/components/schemas/PolarCredentialsUpdateEnvelope" - "400": *a43 + "400": *a44 "401": *a1 - "413": *a44 - "415": *a45 - "422": *a46 + "413": *a45 + "415": *a46 + "422": *a47 "429": *a5 delete: tags: @@ -19399,9 +19430,9 @@ paths: schema: $ref: "#/components/schemas/PolarTestEnvelope" "401": *a1 - "422": *a47 - "429": *a48 - "502": *a49 + "422": *a48 + "429": *a49 + "502": *a50 /api/strava/credentials: get: tags: @@ -19437,11 +19468,11 @@ paths: application/json: schema: $ref: "#/components/schemas/StravaCredentialsUpdateEnvelope" - "400": *a43 + "400": *a44 "401": *a1 - "413": *a44 - "415": *a45 - "422": *a46 + "413": *a45 + "415": *a46 + "422": *a47 "429": *a5 delete: tags: @@ -19519,9 +19550,9 @@ paths: schema: $ref: "#/components/schemas/StravaTestEnvelope" "401": *a1 - "422": *a47 - "429": *a48 - "502": *a49 + "422": *a48 + "429": *a49 + "502": *a50 /api/integrations/status: get: tags: @@ -19557,7 +19588,7 @@ paths: $ref: "#/components/schemas/FitbitResumeEnvelope" "401": *a1 "422": *a4 - "429": *a48 + "429": *a49 /api/integrations/fitbit/test: post: tags: @@ -19575,9 +19606,9 @@ paths: schema: $ref: "#/components/schemas/FitbitIntegrationTestEnvelope" "401": *a1 - "422": *a47 - "429": *a48 - "502": *a49 + "422": *a48 + "429": *a49 + "502": *a50 /api/integrations/google-health/resume: post: tags: @@ -19594,7 +19625,7 @@ paths: $ref: "#/components/schemas/GoogleHealthResumeEnvelope" "401": *a1 "422": *a4 - "429": *a48 + "429": *a49 /api/integrations/google-health/test: post: tags: @@ -19627,9 +19658,9 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": *a47 - "429": *a48 - "502": *a49 + "422": *a48 + "429": *a49 + "502": *a50 /api/integrations/whoop/resume: post: tags: @@ -19646,7 +19677,7 @@ paths: $ref: "#/components/schemas/WhoopResumeEnvelope" "401": *a1 "422": *a4 - "429": *a48 + "429": *a49 /api/integrations/whoop/test: post: tags: @@ -19663,9 +19694,9 @@ paths: schema: $ref: "#/components/schemas/WhoopIntegrationTestEnvelope" "401": *a1 - "422": *a47 - "429": *a48 - "502": *a49 + "422": *a48 + "429": *a49 + "502": *a50 /api/integrations/withings/resume: post: tags: @@ -19683,7 +19714,7 @@ paths: $ref: "#/components/schemas/WithingsResumeEnvelope" "401": *a1 "422": *a4 - "429": *a48 + "429": *a49 /api/integrations/withings/test: post: tags: @@ -19701,8 +19732,8 @@ paths: schema: $ref: "#/components/schemas/WithingsIntegrationTestEnvelope" "401": *a1 - "422": *a47 - "429": *a48 + "422": *a48 + "429": *a49 "502": description: "The probe did not complete. The shared codes apply (`credentials_rejected`, `rate_limited`, `upstream_error`, `timeout`, `connection_failed`) and this path adds one of its own: @@ -19942,7 +19973,7 @@ paths: schema: $ref: "#/components/schemas/RecordActivityEnvelope" "401": *a1 - "403": &a50 + "403": &a51 description: Refused. `meta.errorCode` is `sharing.not_permitted` when the request was made while acting on another account (grant management is never delegable), or `sharing.access.denied` when the caller may not act as the account they named. The latter is byte-identical for an account that does not exist and one that granted @@ -19967,7 +19998,7 @@ paths: schema: $ref: "#/components/schemas/AccountGrantListEnvelope" "401": *a1 - "403": *a50 + "403": *a51 "422": *a4 "429": *a5 post: @@ -20069,7 +20100,7 @@ paths: schema: $ref: "#/components/schemas/AcceptedAccountGrantEnvelope" "401": *a1 - "403": *a50 + "403": *a51 "404": description: No such invitation for this account. content: @@ -20113,7 +20144,7 @@ paths: schema: $ref: "#/components/schemas/RevokedAccountGrantEnvelope" "401": *a1 - "403": *a50 + "403": *a51 "404": description: No such grant on this account's record. content: @@ -20154,7 +20185,7 @@ paths: schema: $ref: "#/components/schemas/RenouncedAccountGrantEnvelope" "401": *a1 - "403": *a50 + "403": *a51 "404": description: No such grant held by this account. content: @@ -20536,7 +20567,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "403": *a50 + "403": *a51 "409": description: "The record this browser session is on is not the record the request asserted. `meta.errorCode` is `sharing.session.changed`. It is not a refusal of access — the caller may well be entitled to both records — @@ -20866,7 +20897,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectionListEnvelope" "401": *a1 - "403": &a51 + "403": &a52 description: The operator has disabled the API instance-wide. Every route in this module refuses while that setting is off, for a cookie session as well as for a Bearer token; it is not a per-user permission and retrying will not help. @@ -20899,7 +20930,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectionRevokeEnvelope" "401": *a1 - "403": *a51 + "403": *a52 "404": description: No live connection with this id for this caller — also the answer for an already-revoked one, so a repeat revoke is 404 rather than an idempotent 200. @@ -20926,7 +20957,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectorTokenListEnvelope" "401": *a1 - "403": *a51 + "403": *a52 "422": *a4 "429": *a5 post: @@ -20959,7 +20990,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "401": *a1 - "403": *a51 + "403": *a52 "413": description: Body exceeds 16 KiB. content: @@ -21002,7 +21033,7 @@ paths: schema: $ref: "#/components/schemas/McpConnectorTokenRevokeEnvelope" "401": *a1 - "403": *a51 + "403": *a52 "404": description: No `health:read` token with this id for this caller. An already-revoked token is still found, so a repeat revoke answers 200. @@ -21060,7 +21091,7 @@ paths: description: Returns the named family's resolved settings for the record the session is acting on. Cookie session or Bearer, while acting on a managed record the caller guards. parameters: - - &a52 + - &a53 name: family in: path required: true @@ -21104,7 +21135,7 @@ paths: ride the audit row. Body capped at 64 KiB. Cookie session or Bearer, while acting on a managed record the caller guards. parameters: - - *a52 + - *a53 requestBody: required: true content: @@ -21641,13 +21672,13 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupDocument" - "403": &a53 + "403": &a54 description: Caller is not an admin. `requireAdmin()` is cookie-only, so a Bearer token lands here whatever its scope. content: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "404": &a54 + "404": &a55 description: No stored copy with this id. content: application/json: @@ -21721,8 +21752,8 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "403": *a53 - "404": *a54 + "403": *a54 + "404": *a55 "409": description: A restore of the same account is already queued or running (`meta.errorCode` = `backup.restore.active`, `meta.jobId` names it), the stored copy was replaced by a newer one while it was being checked @@ -21766,7 +21797,7 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupRestoreJobListResponse" - "403": *a53 + "403": *a54 /api/admin/backups/restores/{jobId}: get: tags: @@ -21789,7 +21820,7 @@ paths: application/json: schema: $ref: "#/components/schemas/AdminBackupRestoreJobResponse" - "403": *a53 + "403": *a54 "404": description: No restore job with this id. content: @@ -21808,7 +21839,7 @@ paths: request leaves the server. Needs neither the Documents module nor the list: with the list unset, `available` is false and any connection still stored is listed (with `originAllowed: false`) so it can be removed. Cookie session only; not delegable." - security: &a55 + security: &a56 - cookieAuth: [] responses: "200": @@ -21818,7 +21849,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourcesStatusEnvelope" "401": *a1 - "403": &a56 + "403": &a57 description: "Refused before any request to the source: `documents.sources.browserOnly` for a Bearer caller, `sharing.not_permitted` while acting on another person's record (a delegate or guardian never uses the owner's archive), or `module.disabled` when the Documents module is off." @@ -21841,9 +21872,9 @@ paths: `documents.sources.tokenRequired`), so a stored token is never sent to an address it was not saved for. A Papra organization id is letters, digits, `_` and `-`. The token is stored encrypted (AES-256-GCM) and never returned. Ten saves and tests a minute per person. Cookie session only; not delegable." - security: *a55 + security: *a56 parameters: - - &a57 + - &a58 name: system in: path required: true @@ -21882,8 +21913,8 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceConnectionEnvelope" "401": *a1 - "403": *a56 - "404": &a58 + "403": *a57 + "404": &a59 description: "`documents.sources.unavailable`: the operator has not listed any origin in `DOCUMENT_SOURCE_ORIGINS`, so the picker is off. `documents.sources.notConnected`: no connection is saved for this system. `documents.sources.notFound`: the source has no such document, or (Papra) no such organization, including @@ -21902,7 +21933,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "429": *a5 - "502": &a59 + "502": &a60 description: "The source could not answer usefully, with the reason in `meta.errorCode` and, when the source answered at all, its HTTP status in `meta.upstreamStatus` (its body is never passed on): `documents.sources.unreachable` (no connection, timeout, or a destination refused at dial time), `documents.sources.redirected` (the source @@ -21921,9 +21952,9 @@ paths: description: Deletes the caller's connection for this system, and its token with it. Works even after the operator removed the origin from the list, and with the Documents module switched off. `disconnected` is false when there was nothing to delete. Cookie session only; not delegable. - security: *a55 + security: *a56 parameters: - - *a57 + - *a58 responses: "200": description: Removed, or there was nothing to remove. @@ -21932,7 +21963,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceDisconnectEnvelope" "401": *a1 - "403": *a56 + "403": *a57 "422": *a4 "429": *a5 /api/documents/sources/{system}/test: @@ -21943,9 +21974,9 @@ paths: description: One request to the source with the stored token. Answers `ok` with the round-trip time and stamps `lastVerifiedAt`, or the reason in `meta.errorCode`. Shares the save's allowance of ten a minute. Cookie session only; not delegable. - security: *a55 + security: *a56 parameters: - - *a57 + - *a58 responses: "200": description: The source answered. @@ -21954,9 +21985,9 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceTestEnvelope" "401": *a1 - "403": *a56 - "404": *a58 - "422": &a60 + "403": *a57 + "404": *a59 + "422": &a61 description: "`documents.sources.originNotAllowed`: the base address's origin is not on the operator's list (checked on every request, so a connection saved earlier is cut off once its origin is removed), or another validation failure." @@ -21965,7 +21996,7 @@ paths: schema: $ref: "#/components/schemas/ErrorEnvelope" "429": *a5 - "502": *a59 + "502": *a60 /api/documents/sources/{system}/tags: get: tags: @@ -21973,9 +22004,9 @@ paths: summary: Tags of a connected archive description: The source's tags for the picker's filter, the first 250 by name, in the source's own ids. Shares the search allowance of sixty a minute. Cookie session only; not delegable. - security: *a55 + security: *a56 parameters: - - *a57 + - *a58 responses: "200": description: The tags. @@ -21984,11 +22015,11 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceTagsEnvelope" "401": *a1 - "403": *a56 - "404": *a58 - "422": *a60 + "403": *a57 + "404": *a59 + "422": *a61 "429": *a5 - "502": *a59 + "502": *a60 /api/documents/sources/{system}/search: get: tags: @@ -22002,9 +22033,9 @@ paths: under that source key: `new`, `imported` with the vault document's `documentId`, or `deleted` (deleted in HealthLog; importing it again stores nothing). Nothing is stored. Sixty searches a minute, shared with the tag read. Cookie session only; not delegable." - security: *a55 + security: *a56 parameters: - - *a57 + - *a58 - name: q in: query required: false @@ -22045,11 +22076,11 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceSearchEnvelope" "401": *a1 - "403": *a56 - "404": *a58 - "422": *a60 + "403": *a57 + "404": *a59 + "422": *a61 "429": *a5 - "502": *a59 + "502": *a60 /api/documents/sources/{system}/import: post: tags: @@ -22068,9 +22099,9 @@ paths: fetched), including a duplicate. `kind` sets the document type (default OTHER). Automatic AI reading follows the person's own setting. Counts against the person's upload allowance (60 an hour) and storage quota. 201 for a new document, 200 otherwise. Cookie session only; not delegable." - security: *a55 + security: *a56 parameters: - - *a57 + - *a58 requestBody: required: true content: @@ -22094,6 +22125,7 @@ paths: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER link: type: object @@ -22127,7 +22159,7 @@ paths: schema: $ref: "#/components/schemas/DocumentSourceImportEnvelope" "401": *a1 - "403": *a56 + "403": *a57 "404": description: "`documents.sources.unavailable`: the operator has not listed any origin in `DOCUMENT_SOURCE_ORIGINS`, so the picker is off. `documents.sources.notConnected`: no connection is saved for this system. @@ -22158,7 +22190,7 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "422": *a60 + "422": *a61 "429": description: "`documents.inbound.rateLimited` (the person's hourly upload allowance, with the rate-limit headers) or `documents.inbound.uploadBusy` (too many uploads in progress; `Retry-After: 1`)." @@ -22166,7 +22198,277 @@ paths: application/json: schema: $ref: "#/components/schemas/ErrorEnvelope" - "502": *a59 + "502": *a60 + /api/symptoms/definitions: + get: + tags: + - Symptoms + summary: List your own symptoms (v1.40) + description: The record's active symptom definitions with their 30-day summary; `includeHidden=true` adds the hidden + ones. Rides the illness module. + parameters: + - in: query + name: includeHidden + schema: + type: string + enum: + - "true" + - "false" + responses: + "200": + description: The definitions. + content: + application/json: + schema: + $ref: "#/components/schemas/ListSymptomDefinitionsEnvelope" + "401": *a1 + "403": &a62 + description: >- + `illness.disabled`: the record has the illness module switched off (or the operator turned it off + server-wide); symptoms ride that module. + + + Refused: this request named a record the caller may not act on (`meta.errorCode` = `sharing.access.denied`). + Byte-identical for an account that does not exist, an account that granted nothing, a grant whose sections + do not reach this surface, and a read grant on a request that writes — the response carries no reason, so it + is not an account-enumeration oracle. The reason reaches the record owner's activity feed and the operator's + audit trail instead. On the cookie transport the same code answers one further case: a session that has + entered a shared record and sends a request without its record-context assertion, which is a client older + than the fence — leave the record and reload. A request that names no record but the caller's own never + reaches this response, so a client that never switches and never sends the per-request account selector will + not see it. + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "422": *a4 + "429": *a5 + post: + tags: + - Symptoms + summary: Define a symptom (v1.40) + description: Creates one definition. Idempotent under `Idempotency-Key`. Audits as `symptoms.definition.create` without + the label. Rate-limited to 30 a minute. + parameters: + - *a6 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSymptomDefinitionRequest" + responses: + "201": + description: Definition created. + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSymptomDefinitionEnvelope" + "401": *a1 + "403": *a62 + "409": *a7 + "422": *a4 + "429": *a5 + /api/symptoms/definitions/{id}: + patch: + tags: + - Symptoms + summary: Edit, hide or show a symptom (v1.40) + description: Partial edit. Audits as `symptoms.definition.update`, naming a label change without quoting it. + parameters: + - in: path + name: id + schema: + type: string + required: true + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSymptomDefinitionRequest" + responses: + "200": + description: Definition updated. + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSymptomDefinitionEnvelope" + "401": *a1 + "403": *a62 + "404": &a63 + description: "`symptoms.definition.notFound`: no definition with this id on the record." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "422": *a4 + "429": *a5 + delete: + tags: + - Symptoms + summary: Hide or delete a symptom (v1.40) + description: Hides the definition and keeps its history. `?purge=true` deletes it and every occurrence of it. + parameters: + - in: path + name: id + schema: + type: string + required: true + - in: query + name: purge + schema: + type: string + enum: + - "true" + - "false" + responses: + "200": + description: Hidden or deleted. + content: + application/json: + schema: + $ref: "#/components/schemas/DeleteSymptomDefinitionEnvelope" + "401": *a1 + "403": *a62 + "404": *a63 + "422": *a4 + "429": *a5 + /api/symptoms/events: + get: + tags: + - Symptoms + summary: List symptom occurrences (v1.40) + description: Occurrences of the record's symptoms, newest first, narrowed by the optional query. + parameters: + - in: query + name: from + schema: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$ + - in: query + name: to + schema: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$ + - in: query + name: definitionId + schema: + type: string + minLength: 1 + maxLength: 40 + - in: query + name: episodeId + schema: + type: string + minLength: 1 + maxLength: 40 + - in: query + name: limit + schema: + default: 200 + type: integer + minimum: 1 + maximum: 500 + responses: + "200": + description: A page of occurrences. + content: + application/json: + schema: + $ref: "#/components/schemas/ListSymptomEventsEnvelope" + "401": *a1 + "403": *a62 + "422": *a4 + "429": *a5 + post: + tags: + - Symptoms + summary: Log a symptom occurrence (v1.40) + description: Creates one occurrence. Idempotent under `Idempotency-Key`. A hidden definition can still be logged + against; another record's definition 404s (`symptoms.definition.notFound`). Audits as `symptoms.event.create` + without the note. + parameters: + - *a6 + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSymptomEventRequest" + responses: + "201": + description: Occurrence logged. + content: + application/json: + schema: + $ref: "#/components/schemas/CreateSymptomEventEnvelope" + "401": *a1 + "403": *a62 + "404": *a63 + "409": *a7 + "422": *a4 + "429": *a5 + /api/symptoms/events/{id}: + patch: + tags: + - Symptoms + summary: Edit a symptom occurrence (v1.40) + description: Partial edit. Audits as `symptoms.event.update`, naming a note change without quoting it. + parameters: + - in: path + name: id + schema: + type: string + required: true + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSymptomEventRequest" + responses: + "200": + description: Occurrence updated. + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateSymptomEventEnvelope" + "401": *a1 + "403": *a62 + "404": &a64 + description: "`symptoms.event.notFound`: no occurrence with this id on the record." + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + "422": *a4 + "429": *a5 + delete: + tags: + - Symptoms + summary: Delete a symptom occurrence (v1.40) + description: Removes the occurrence. Audits as `symptoms.event.delete`. + parameters: + - in: path + name: id + schema: + type: string + required: true + responses: + "200": + description: Deleted. + content: + application/json: + schema: + $ref: "#/components/schemas/DeleteSymptomEventEnvelope" + "401": *a1 + "403": *a62 + "404": *a64 + "422": *a4 + "429": *a5 /api/bugreport: post: security: [] @@ -29604,6 +29906,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER episodeId: type: string @@ -29639,6 +29942,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER documentDate: anyOf: @@ -29693,6 +29997,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER required: - mode @@ -31994,6 +32299,97 @@ components: leaves the singleton instance settings — registration, MFA requirement, default locale and timezone, module availability, notification and AI configuration, document cap and quota — exactly as they are. Send `true` only when rebuilding a host from a snapshot, because those settings apply to every account on the installation." + CreateSymptomDefinitionRequest: + type: object + properties: + label: + type: string + minLength: 1 + maxLength: 40 + icon: + anyOf: + - type: string + - type: "null" + required: + - label + description: Define a symptom of your own. `label` (1-40 characters) is encrypted at rest; `icon` is one of the cycle + custom-symptom icon names, null for the default glyph. At most eight active definitions per account (422 + `symptoms.definition.limitReached`). + UpdateSymptomDefinitionRequest: + type: object + properties: + label: + type: string + minLength: 1 + maxLength: 40 + icon: + anyOf: + - type: string + - type: "null" + isActive: + type: boolean + sortOrder: + type: integer + minimum: 0 + maximum: 1000 + description: "Partial edit; an omitted key leaves the column untouched. `isActive: false` hides the symptom (history + kept, slot freed); `isActive: true` shows it again and re-checks the cap." + CreateSymptomEventRequest: + type: object + properties: + definitionId: + type: string + minLength: 1 + maxLength: 40 + occurredAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$ + intensity: + type: integer + minimum: 0 + maximum: 10 + note: + anyOf: + - type: string + maxLength: 500 + - type: "null" + episodeId: + anyOf: + - type: string + minLength: 1 + maxLength: 40 + - type: "null" + required: + - definitionId + - intensity + description: Log one occurrence. `intensity` is 0-10 (0 none, 10 the worst imaginable). `occurredAt` defaults to now and + may not lie in the future beyond five minutes. `episodeId`, when given, must name one of the record's own + illness episodes that is still open (422 `symptoms.episode.notOpen` otherwise). The note is encrypted at rest. + UpdateSymptomEventRequest: + type: object + properties: + occurredAt: + type: string + format: date-time + pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$ + intensity: + type: integer + minimum: 0 + maximum: 10 + note: + anyOf: + - type: string + maxLength: 500 + - type: "null" + episodeId: + anyOf: + - type: string + minLength: 1 + maxLength: 40 + - type: "null" + description: "Partial edit of one occurrence. `note: null` clears the note, `episodeId: null` drops the link. A changed + `episodeId` must name an open episode; an unchanged link to an episode that has since resolved is kept." MedicationTreatmentClass: type: string enum: @@ -32298,14 +32694,15 @@ components: sharing.renounce.already_ended, sharing.renounce.not_found, sharing.revoke.already_ended, sharing.revoke.not_found, sharing.session.changed, sharing.switch.invalid, sharing.switch.wrong_transport; source-priority — source-priority.body.invalid_json, - source-priority.body.invalid_shape; tokens — tokens.documents.ceiling_reached, - tokens.measurements.ceiling_reached, tokens.workouts.ceiling_reached; vaccination — - vaccination.booster-invalid, vaccination.booster-no-antigen, vaccination.booster-out-of-scope, - vaccination.encounter-not-found, vaccination.identity-required, vaccination.invalid, - vaccination.link.invalid, vaccination.not-found, vaccination.practitioner-not-found; workout — - workout.batch.invalid, workout.batch.payload_too_large, workout.batch.source_not_permitted, - workout.batch.too_large, workout.delete.synced_source; (unprefixed) — about_me_conflict, - ai_response_truncated, coach_prefs_conflict, dashboard_layout_conflict, empty_file, + source-priority.body.invalid_shape; symptoms — symptoms.definition.limitReached, + symptoms.definition.notFound, symptoms.episode.notOpen, symptoms.event.notFound, symptoms.invalid; + tokens — tokens.documents.ceiling_reached, tokens.measurements.ceiling_reached, + tokens.workouts.ceiling_reached; vaccination — vaccination.booster-invalid, + vaccination.booster-no-antigen, vaccination.booster-out-of-scope, vaccination.encounter-not-found, + vaccination.identity-required, vaccination.invalid, vaccination.link.invalid, vaccination.not-found, + vaccination.practitioner-not-found; workout — workout.batch.invalid, workout.batch.payload_too_large, + workout.batch.source_not_permitted, workout.batch.too_large, workout.delete.synced_source; (unprefixed) + — about_me_conflict, ai_response_truncated, coach_prefs_conflict, dashboard_layout_conflict, empty_file, health_score_config_conflict, insights_layout_conflict, invalid_base_updated_at, json_carries_no_intake_time, json_not_an_array, medication_layout_conflict, missing_required_columns, modules_conflict, mood_tag_layout_conflict, not_configured, notification_prefs_conflict, oidc_only, @@ -36716,6 +37113,86 @@ components: - onsetAt - dayLogs additionalProperties: {} + symptomDefinitions: + default: [] + type: array + items: + type: object + properties: + id: + type: string + minLength: 1 + label: + type: string + minLength: 1 + labelEncrypted: + type: string + minLength: 1 + icon: + anyOf: + - type: string + - type: "null" + sortOrder: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + isActive: + type: boolean + createdAt: + type: string + minLength: 1 + updatedAt: + type: string + minLength: 1 + events: + default: [] + type: array + items: + type: object + properties: + id: + type: string + minLength: 1 + occurredAt: + type: string + minLength: 1 + intensity: + type: integer + minimum: 0 + maximum: 10 + note: + anyOf: + - type: string + - type: "null" + noteEncrypted: + anyOf: + - type: string + minLength: 1 + - type: "null" + episodeId: + anyOf: + - type: string + minLength: 1 + - type: "null" + createdAt: + type: string + minLength: 1 + updatedAt: + type: string + minLength: 1 + required: + - occurredAt + - intensity + - createdAt + - updatedAt + additionalProperties: {} + required: + - sortOrder + - isActive + - createdAt + - updatedAt + - events + additionalProperties: {} allergies: default: [] type: array @@ -36972,6 +37449,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER title: anyOf: @@ -39231,6 +39709,7 @@ components: - labResults - biomarkers - illnessEpisodes + - symptomDefinitions - allergies - familyHistory - workouts @@ -64412,6 +64891,9 @@ components: enum: - DOCUMENT_INDEX - LABS_OCR_EXTRACT + - DOCUMENT_SUMMARY + - DOCUMENT_SUGGEST + - DOCUMENT_EXTRACT documentId: anyOf: - type: string @@ -64429,9 +64911,15 @@ components: - anyOf: - $ref: "#/components/schemas/DocumentIndexResponse" - $ref: "#/components/schemas/OcrExtractResponse" + - $ref: "#/components/schemas/DocumentSummaryResponse" + - $ref: "#/components/schemas/DocumentSuggestResponse" + - $ref: "#/components/schemas/DocumentExtractRunResult" - type: "null" description: "Present once `status` is `SUCCEEDED`: the body the queuing route answers with synchronously. - `DOCUMENT_INDEX` carries `DocumentIndexResponse`, `LABS_OCR_EXTRACT` carries `OcrExtractResponse`." + `DOCUMENT_INDEX` carries `DocumentIndexResponse`, `LABS_OCR_EXTRACT` carries `OcrExtractResponse`, + `DOCUMENT_SUMMARY` carries `DocumentSummaryResponse`, `DOCUMENT_SUGGEST` carries `DocumentSuggestResponse`, + `DOCUMENT_EXTRACT` carries `DocumentExtractRunResult` (not the extract route's detail body). Decode by + `kind`; treat an unknown `kind` as a run this client did not start." error: anyOf: - type: object @@ -64640,6 +65128,82 @@ components: reading this row likely duplicates (the review row defaults to unchecked when set); `confidence` is the model's per-field self-score (low fields are flagged for the human). Nothing is written until the commit route confirms." + DocumentSummaryResponse: + type: object + properties: + summary: + type: string + text: + type: string + persistence: + type: string + enum: + - stored + - withheld + - failed + additionalProperties: false + DocumentSuggestResponse: + type: object + properties: + suggestions: + type: object + properties: + title: + anyOf: + - type: string + - type: "null" + kind: + anyOf: + - type: string + enum: + - DOCTOR_REPORT + - DISCHARGE_LETTER + - LAB_RESULT + - IMAGING + - PRESCRIPTION + - REFERRAL + - INSURANCE + - VACCINATION + - SICK_NOTE + - OTHER + - type: "null" + documentDate: + anyOf: + - type: string + - type: "null" + required: + - title + - kind + - documentDate + additionalProperties: false + required: + - suggestions + additionalProperties: false + DocumentExtractRunResult: + type: object + properties: + documentId: + type: string + factsStaged: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + description: How many facts were staged PENDING for review. Read them from `GET /api/documents/inbound/{id}`; the + confirm route stays the only write into the record. + status: + type: string + enum: + - STORED + - EXTRACTING + - EXTRACTED + - FAILED + - CONFIRMED + - DISCARDED + required: + - documentId + - factsStaged + - status + additionalProperties: false ListBiomarkersEnvelope: type: object properties: @@ -67462,6 +68026,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER title: anyOf: @@ -67908,6 +68473,7 @@ components: - REFERRAL - INSURANCE - VACCINATION + - SICK_NOTE - OTHER title: anyOf: @@ -68274,42 +68840,6 @@ components: - data - error additionalProperties: false - DocumentSuggestResponse: - type: object - properties: - suggestions: - type: object - properties: - title: - anyOf: - - type: string - - type: "null" - kind: - anyOf: - - type: string - enum: - - DOCTOR_REPORT - - DISCHARGE_LETTER - - LAB_RESULT - - IMAGING - - PRESCRIPTION - - REFERRAL - - INSURANCE - - VACCINATION - - OTHER - - type: "null" - documentDate: - anyOf: - - type: string - - type: "null" - required: - - title - - kind - - documentDate - additionalProperties: false - required: - - suggestions - additionalProperties: false DocumentSummaryEnvelope: type: object properties: @@ -68327,20 +68857,6 @@ components: - data - error additionalProperties: false - DocumentSummaryResponse: - type: object - properties: - summary: - type: string - text: - type: string - persistence: - type: string - enum: - - stored - - withheld - - failed - additionalProperties: false DocumentIndexEnvelope: type: object properties: @@ -76391,6 +76907,293 @@ components: - data - error additionalProperties: false + ListSymptomDefinitionsEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomDefinitionList" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + SymptomDefinitionList: + type: object + properties: + definitions: + type: array + items: + $ref: "#/components/schemas/SymptomDefinition" + limit: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - definitions + - limit + additionalProperties: false + description: The record's symptom definitions in display order, and the active-definition cap. + SymptomDefinition: + type: object + properties: + id: + type: string + label: + anyOf: + - type: string + - type: "null" + icon: + anyOf: + - type: string + - type: "null" + sortOrder: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + isActive: + type: boolean + recent: + type: object + properties: + count30d: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + maxIntensity30d: + anyOf: + - type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + - type: "null" + lastOccurredAt: + anyOf: + - type: string + - type: "null" + required: + - count30d + - maxIntensity30d + - lastOccurredAt + additionalProperties: false + required: + - id + - label + - icon + - sortOrder + - isActive + - recent + additionalProperties: false + description: "A symptom the person defined. `label` is decrypted (null only on an unreadable value). `recent` is + computed server-side: occurrences and the highest intensity over the last 30 days, and the last occurrence ever. + Each active definition is also the correlation channel `SYMPTOM:`." + CreateSymptomDefinitionEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomDefinition" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + UpdateSymptomDefinitionEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomDefinition" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + DeleteSymptomDefinitionEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomDefinitionDeleted" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + SymptomDefinitionDeleted: + type: object + properties: + deleted: + type: boolean + const: true + purged: + type: boolean + eventsDeleted: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - deleted + - purged + - eventsDeleted + additionalProperties: false + description: "`purged: false` means the definition was hidden and its history kept; `purged: true` means it and + `eventsDeleted` occurrences were removed." + ListSymptomEventsEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomEventList" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + SymptomEventList: + type: object + properties: + events: + type: array + items: + $ref: "#/components/schemas/SymptomEvent" + limit: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + hasMore: + type: boolean + required: + - events + - limit + - hasMore + additionalProperties: false + description: A page of occurrences, newest first. `hasMore` is true when the page is full; page on with `to` set to the + oldest `occurredAt` seen. + SymptomEvent: + type: object + properties: + id: + type: string + definitionId: + type: string + occurredAt: + type: string + intensity: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + note: + anyOf: + - type: string + - type: "null" + episodeId: + anyOf: + - type: string + - type: "null" + createdAt: + type: string + updatedAt: + type: string + required: + - id + - definitionId + - occurredAt + - intensity + - note + - episodeId + - createdAt + - updatedAt + additionalProperties: false + description: "One occurrence of a defined symptom: when, how strong (0-10), the decrypted note, and the illness episode + it was filed against (null when none)." + CreateSymptomEventEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomEvent" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + UpdateSymptomEventEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/SymptomEvent" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + DeleteSymptomEventEnvelope: + type: object + properties: + data: + type: object + properties: + deleted: + type: boolean + const: true + required: + - deleted + additionalProperties: false + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false __schema0: anyOf: - type: string diff --git a/messages/de.json b/messages/de.json index 7c1686650..5b6425fd6 100644 --- a/messages/de.json +++ b/messages/de.json @@ -140,6 +140,18 @@ "unit": { "locked": "Dieser Marker hat schon Werte, deshalb kannst du seine Einheit nicht ändern. Die gespeicherten Werte würden sonst in der neuen Einheit angezeigt, ohne umgerechnet zu werden." } + }, + "symptoms": { + "definition": { + "limitReached": "Du hast 8 Symptome. Blende eins aus, um ein neues anzulegen.", + "notFound": "Dieses Symptom gibt es nicht mehr." + }, + "episode": { + "notOpen": "Diese Erkrankung ist nicht mehr offen. Wähle eine andere oder keine." + }, + "event": { + "notFound": "Diesen Eintrag gibt es nicht mehr." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Stimmung", "moodDescription": "Stimmung und Tags erfassen", "workout": "Workout", - "workoutDescription": "Eine Einheit, die kein Gerät aufgezeichnet hat" + "workoutDescription": "Eine Einheit, die kein Gerät aufgezeichnet hat", + "symptom": "Symptom", + "symptomDescription": "Eines deiner eigenen Symptome, mit Stärke" }, "cycle": "Zyklus", "labs": "Laborwerte", @@ -651,7 +665,8 @@ "title": "Sichere deinen Verschlüsselungsschlüssel", "body": "Ohne eine Kopie des Schlüssels lassen sich deine Daten nach einer Neuinstallation nicht wiederherstellen. Es dauert eine Minute.", "action": "Zum Schritt" - } + }, + "quickAddSymptom": "Symptom erfassen" }, "measurements": { "title": "Messungen", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "Die Wiederherstellung ist an einem unerwarteten Fehler gescheitert und wurde zurückgerollt. Das Server-Log nennt den Fehler.", "restoreFailureKeyMissing": "Die Sicherung braucht den Verschlüsselungsschlüssel {keys}, mit dem dieser Server sie nicht öffnen kann. Nimm den Schlüssel wieder in ENCRYPTION_KEYS auf, starte neu und starte die Wiederherstellung erneut.", "restoreFailureForeignReference": "Die Datei verweist auf Einträge, die zu einem anderen Konto gehören. Es wurde nichts geschrieben.", - "previewKeyMissing": "Diese Sicherung lässt sich auf diesem Server nicht wiederherstellen: Sie braucht den Verschlüsselungsschlüssel {keys}. Nimm den Schlüssel zuerst wieder in ENCRYPTION_KEYS auf und starte neu." + "previewKeyMissing": "Diese Sicherung lässt sich auf diesem Server nicht wiederherstellen: Sie braucht den Verschlüsselungsschlüssel {keys}. Nimm den Schlüssel zuerst wieder in ENCRYPTION_KEYS auf und starte neu.", + "restoreSkippedSymptomEpisodeReference": "Symptom-Eintrag mit Verknüpfung zu einer Erkrankung, die die Datei nicht enthält (ohne Verknüpfung behalten)" }, "danger-zone": { "title": "Gefahrenzone", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Rezept", "REFERRAL": "Überweisung", "INSURANCE": "Versicherung", - "VACCINATION": "Impfung" + "VACCINATION": "Impfung", + "SICK_NOTE": "Krankschreibung" }, "filter": { "searchLabel": "Dokumente durchsuchen", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "Der von {name} gestartete Einnahme-Import ist fertig", "medicationOneShotReconciled": "Ein einmaliges Medikament wurde nach einer Einnahme von {name} geöffnet oder geschlossen", "vaccinationBoosterPlanned": "{name} hat eine Auffrischung geplant", - "medicationCategoryCreate": "{name} hat eine Medikamentenkategorie angelegt" + "medicationCategoryCreate": "{name} hat eine Medikamentenkategorie angelegt", + "symptomEventCreate": "{name} hat ein Symptom erfasst", + "symptomEventUpdate": "{name} hat einen Symptom-Eintrag bearbeitet", + "symptomEventDelete": "{name} hat einen Symptom-Eintrag gelöscht", + "symptomDefinitionCreate": "{name} hat ein Symptom angelegt", + "symptomDefinitionUpdate": "{name} hat ein Symptom geändert", + "symptomDefinitionDelete": "{name} hat ein Symptom entfernt" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "Warte auf den Hintergrunddienst. Ändert sich das nicht, läuft der Worker auf dem Server vielleicht nicht.", "errorWorkerUnavailable": "Der Hintergrunddienst ist gerade nicht erreichbar. Versuch es gleich noch einmal oder bitte die Person, die den Server betreibt, ihn zu prüfen.", "errorTimedOut": "Das Lesen hat länger gedauert, als deine KI-Antwortzeit erlaubt. Versuch es noch einmal oder erhöhe die Antwortzeit in den KI-Einstellungen." + }, + "symptoms": { + "add": "Neues Symptom", + "nameLabel": "Name", + "namePlaceholder": "z. B. Aura", + "iconLabel": "Symbol", + "limitReached": "Du hast 8 Symptome. Blende eins aus, um ein neues anzulegen.", + "saveError": "Das Symptom konnte nicht gespeichert werden. Bitte versuch es noch einmal.", + "nameRequired": "Gib dem Symptom einen Namen.", + "unreadableLabel": "Unlesbares Symptom", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Symptom erfassen", + "sheetDescription": "Eines deiner eigenen Symptome, wie stark und wann.", + "symptom": "Symptom", + "symptomRequired": "Wähle ein Symptom.", + "intensity": "Stärke", + "intensityRequired": "Gib an, wie stark es war.", + "intensityUnset": "Nicht gesetzt", + "anchorLow": "Keine", + "anchorHigh": "Stärkste vorstellbare", + "intensityValueText": "{value} von {max} ({low} bis {high})", + "when": "Wann", + "during": "Während einer Erkrankung", + "duringNone": "Nicht verknüpft", + "note": "Notiz", + "notePlaceholder": "Was war sonst noch?", + "reset": "Formular zurücksetzen", + "emptyHint": "Leg dein erstes Symptom an, zum Beispiel Aura oder Kopfschmerz.", + "emptyHintNoManage": "Für diesen Datensatz sind noch keine Symptome angelegt.", + "limitHint": "Bis zu {limit} Symptome. Blende auf der Krankheitsseite eins aus, um ein neues anzulegen." + }, + "section": { + "title": "Deine Symptome", + "log": "Erfassen", + "loadError": "Deine Symptome konnten nicht geladen werden.", + "summaryOne": "Einmal in 30 Tagen, {max}/10, zuletzt {date}", + "summaryFew": "{count}-mal in 30 Tagen, bis {max}/10, zuletzt {date}", + "summaryOther": "{count}-mal in 30 Tagen, bis {max}/10, zuletzt {date}", + "summaryNoneRecent": "Nicht in den letzten 30 Tagen, zuletzt {date}", + "summaryNever": "Noch nicht erfasst", + "menuLabel": "Optionen für {symptom}", + "eventMenuLabel": "Optionen für diesen Eintrag {symptom}", + "hide": "Ausblenden", + "show": "Wieder einblenden", + "deleteTitle": "Symptom löschen?", + "deleteBody": "„{symptom}“ und alle Einträge dazu werden gelöscht. Um den Verlauf zu behalten, blende es stattdessen aus.", + "deleteEventTitle": "Eintrag löschen?", + "deleteEventBody": "Dieser Eintrag wird gelöscht.", + "hiddenOne": "Ausgeblendet (1)", + "hiddenFew": "Ausgeblendet ({count})", + "hiddenOther": "Ausgeblendet ({count})", + "recent": "Letzte 30 Tage", + "recentEmpty": "In den letzten 30 Tagen nichts erfasst.", + "editEventTitle": "{symptom} bearbeiten", + "editSymptomTitle": "Symptom bearbeiten" + }, + "episode": { + "title": "Erfasste Symptome", + "filed": "zu dieser Erkrankung erfasst" + } } } diff --git a/messages/en.json b/messages/en.json index fafb1473d..2a3c37a30 100644 --- a/messages/en.json +++ b/messages/en.json @@ -140,6 +140,18 @@ "unit": { "locked": "This marker already has readings, so its unit can't be changed. The stored values would be shown in the new unit without being converted." } + }, + "symptoms": { + "definition": { + "limitReached": "You have 8 symptoms. Hide one to add another.", + "notFound": "This symptom no longer exists." + }, + "episode": { + "notOpen": "That illness is no longer open. Choose another or none." + }, + "event": { + "notFound": "This entry no longer exists." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Mood", "moodDescription": "Log your mood and tags", "workout": "Workout", - "workoutDescription": "A session your devices did not record" + "workoutDescription": "A session your devices did not record", + "symptom": "Symptom", + "symptomDescription": "One of your own symptoms, with how strong" }, "cycle": "Cycle", "labs": "Labs", @@ -651,7 +665,8 @@ "title": "Back up your encryption key", "body": "Without a copy of the key, your data cannot be recovered after a reinstall. It takes a minute.", "action": "Open the step" - } + }, + "quickAddSymptom": "Log symptom" }, "measurements": { "title": "Measurements", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "The restore stopped on an unexpected error and was rolled back. The server log names the error.", "restoreFailureKeyMissing": "The backup needs encryption key {keys}, which this server cannot open it with. Add the key back to ENCRYPTION_KEYS, restart, and start the restore again.", "restoreFailureForeignReference": "The file points at records that belong to another account. Nothing was written.", - "previewKeyMissing": "This backup cannot be restored on this server: it needs encryption key {keys}. Add the key back to ENCRYPTION_KEYS and restart first." + "previewKeyMissing": "This backup cannot be restored on this server: it needs encryption key {keys}. Add the key back to ENCRYPTION_KEYS and restart first.", + "restoreSkippedSymptomEpisodeReference": "Symptom entry linked to an illness the file does not contain (kept without the link)" }, "danger-zone": { "title": "Danger Zone", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Prescription", "REFERRAL": "Referral", "INSURANCE": "Insurance", - "VACCINATION": "Vaccination" + "VACCINATION": "Vaccination", + "SICK_NOTE": "Sick note" }, "filter": { "searchLabel": "Search documents", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "The dose import {name} started has finished", "medicationOneShotReconciled": "A one-off medication was opened or closed after a dose {name} recorded", "vaccinationBoosterPlanned": "{name} planned a booster", - "medicationCategoryCreate": "{name} added a medication category" + "medicationCategoryCreate": "{name} added a medication category", + "symptomEventCreate": "{name} logged a symptom", + "symptomEventUpdate": "{name} edited a symptom entry", + "symptomEventDelete": "{name} deleted a symptom entry", + "symptomDefinitionCreate": "{name} added a symptom", + "symptomDefinitionUpdate": "{name} changed a symptom", + "symptomDefinitionDelete": "{name} removed a symptom" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "Waiting for the background worker. If this does not change, the server's worker may not be running.", "errorWorkerUnavailable": "The background worker is not available right now. Try again in a moment, or ask the server operator to check it.", "errorTimedOut": "Reading took longer than your AI response time allows. Try again, or raise the response time in the AI settings." + }, + "symptoms": { + "add": "New symptom", + "nameLabel": "Name", + "namePlaceholder": "e.g. Aura", + "iconLabel": "Icon", + "limitReached": "You have 8 symptoms. Hide one to add another.", + "saveError": "Couldn't save the symptom. Please try again.", + "nameRequired": "Give the symptom a name.", + "unreadableLabel": "Unreadable symptom", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Log symptom", + "sheetDescription": "One of your own symptoms, how strong and when.", + "symptom": "Symptom", + "symptomRequired": "Choose a symptom.", + "intensity": "Intensity", + "intensityRequired": "Set how strong it was.", + "intensityUnset": "Not set", + "anchorLow": "None", + "anchorHigh": "Worst imaginable", + "intensityValueText": "{value} of {max} ({low} to {high})", + "when": "When", + "during": "During an illness", + "duringNone": "Not linked", + "note": "Note", + "notePlaceholder": "What else was going on?", + "reset": "Reset form", + "emptyHint": "Add your first symptom, for example aura or headache.", + "emptyHintNoManage": "No symptoms have been set up for this record yet.", + "limitHint": "Up to {limit} symptoms. Hide one on the illness page to add another." + }, + "section": { + "title": "Your symptoms", + "log": "Log", + "loadError": "Couldn't load your symptoms.", + "summaryOne": "Once in 30 days, {max}/10, last {date}", + "summaryFew": "{count} times in 30 days, up to {max}/10, last {date}", + "summaryOther": "{count} times in 30 days, up to {max}/10, last {date}", + "summaryNoneRecent": "Not in the last 30 days, last {date}", + "summaryNever": "Not logged yet", + "menuLabel": "Options for {symptom}", + "eventMenuLabel": "Options for this {symptom} entry", + "hide": "Hide", + "show": "Show again", + "deleteTitle": "Delete symptom?", + "deleteBody": "\"{symptom}\" and every entry of it will be deleted. To keep the history, hide it instead.", + "deleteEventTitle": "Delete entry?", + "deleteEventBody": "This entry will be deleted.", + "hiddenOne": "Hidden (1)", + "hiddenFew": "Hidden ({count})", + "hiddenOther": "Hidden ({count})", + "recent": "Last 30 days", + "recentEmpty": "Nothing logged in the last 30 days.", + "editEventTitle": "Edit {symptom}", + "editSymptomTitle": "Edit symptom" + }, + "episode": { + "title": "Symptoms logged", + "filed": "logged with this illness" + } } } diff --git a/messages/es.json b/messages/es.json index aafe4581b..3c9218752 100644 --- a/messages/es.json +++ b/messages/es.json @@ -140,6 +140,18 @@ "unit": { "locked": "Este marcador ya tiene valores, así que no puedes cambiar su unidad. Los valores guardados se mostrarían en la nueva unidad sin convertirse." } + }, + "symptoms": { + "definition": { + "limitReached": "Tienes 8 síntomas. Oculta uno para añadir otro.", + "notFound": "Este síntoma ya no existe." + }, + "episode": { + "notOpen": "Esa enfermedad ya no está abierta. Elige otra o ninguna." + }, + "event": { + "notFound": "Esta entrada ya no existe." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Estado de ánimo", "moodDescription": "Registra tu estado de ánimo y etiquetas", "workout": "Entrenamiento", - "workoutDescription": "Una sesión que tus dispositivos no registraron" + "workoutDescription": "Una sesión que tus dispositivos no registraron", + "symptom": "Síntoma", + "symptomDescription": "Uno de tus propios síntomas, con su intensidad" }, "cycle": "Ciclo", "labs": "Análisis", @@ -651,7 +665,8 @@ "title": "Haz una copia de tu clave de cifrado", "body": "Sin una copia de la clave, tus datos no se pueden recuperar tras una reinstalación. Es cuestión de un minuto.", "action": "Abrir el paso" - } + }, + "quickAddSymptom": "Registrar síntoma" }, "measurements": { "title": "Mediciones", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "La restauración se detuvo por un error inesperado y se deshizo. El registro del servidor indica el error.", "restoreFailureKeyMissing": "La copia necesita la clave de cifrado {keys}, con la que este servidor no puede abrirla. Vuelve a añadir la clave a ENCRYPTION_KEYS, reinicia e inicia de nuevo la restauración.", "restoreFailureForeignReference": "El archivo apunta a registros que pertenecen a otra cuenta. No se escribió nada.", - "previewKeyMissing": "Esta copia no se puede restaurar en este servidor: necesita la clave de cifrado {keys}. Vuelve a añadir la clave a ENCRYPTION_KEYS y reinicia primero." + "previewKeyMissing": "Esta copia no se puede restaurar en este servidor: necesita la clave de cifrado {keys}. Vuelve a añadir la clave a ENCRYPTION_KEYS y reinicia primero.", + "restoreSkippedSymptomEpisodeReference": "Entrada de síntoma vinculada a una enfermedad que el archivo no contiene (se conserva sin el vínculo)" }, "danger-zone": { "title": "Zona de peligro", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Receta", "REFERRAL": "Derivación", "INSURANCE": "Seguro", - "VACCINATION": "Vacunación" + "VACCINATION": "Vacunación", + "SICK_NOTE": "Baja médica" }, "filter": { "searchLabel": "Buscar documentos", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "La importación de dosis que inició {name} ha terminado", "medicationOneShotReconciled": "Un medicamento de una sola toma se abrió o se cerró tras una dosis que registró {name}", "vaccinationBoosterPlanned": "{name} planificó un refuerzo", - "medicationCategoryCreate": "{name} añadió una categoría de medicamentos" + "medicationCategoryCreate": "{name} añadió una categoría de medicamentos", + "symptomEventCreate": "{name} registró un síntoma", + "symptomEventUpdate": "{name} editó una entrada de síntoma", + "symptomEventDelete": "{name} eliminó una entrada de síntoma", + "symptomDefinitionCreate": "{name} añadió un síntoma", + "symptomDefinitionUpdate": "{name} cambió un síntoma", + "symptomDefinitionDelete": "{name} quitó un síntoma" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "Esperando al proceso en segundo plano. Si no cambia, puede que el worker del servidor no esté en marcha.", "errorWorkerUnavailable": "El proceso en segundo plano no está disponible ahora mismo. Inténtalo de nuevo en un momento o pide a quien administra el servidor que lo revise.", "errorTimedOut": "La lectura tardó más de lo que permite tu tiempo de respuesta de IA. Inténtalo de nuevo o aumenta el tiempo de respuesta en los ajustes de IA." + }, + "symptoms": { + "add": "Nuevo síntoma", + "nameLabel": "Nombre", + "namePlaceholder": "p. ej. Aura", + "iconLabel": "Icono", + "limitReached": "Tienes 8 síntomas. Oculta uno para añadir otro.", + "saveError": "No se pudo guardar el síntoma. Inténtalo de nuevo.", + "nameRequired": "Ponle un nombre al síntoma.", + "unreadableLabel": "Síntoma ilegible", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Registrar síntoma", + "sheetDescription": "Uno de tus propios síntomas, su intensidad y cuándo.", + "symptom": "Síntoma", + "symptomRequired": "Elige un síntoma.", + "intensity": "Intensidad", + "intensityRequired": "Indica lo fuerte que fue.", + "intensityUnset": "Sin indicar", + "anchorLow": "Ninguna", + "anchorHigh": "La peor imaginable", + "intensityValueText": "{value} de {max} ({low} a {high})", + "when": "Cuándo", + "during": "Durante una enfermedad", + "duringNone": "Sin vincular", + "note": "Nota", + "notePlaceholder": "¿Qué más estaba pasando?", + "reset": "Restablecer formulario", + "emptyHint": "Añade tu primer síntoma, por ejemplo aura o dolor de cabeza.", + "emptyHintNoManage": "Este registro aún no tiene síntomas configurados.", + "limitHint": "Hasta {limit} síntomas. Oculta uno en la página de enfermedades para añadir otro." + }, + "section": { + "title": "Tus síntomas", + "log": "Registrar", + "loadError": "No se pudieron cargar tus síntomas.", + "summaryOne": "Una vez en 30 días, {max}/10, la última {date}", + "summaryFew": "{count} veces en 30 días, hasta {max}/10, la última {date}", + "summaryOther": "{count} veces en 30 días, hasta {max}/10, la última {date}", + "summaryNoneRecent": "No en los últimos 30 días, la última {date}", + "summaryNever": "Aún sin registrar", + "menuLabel": "Opciones de {symptom}", + "eventMenuLabel": "Opciones de esta entrada de {symptom}", + "hide": "Ocultar", + "show": "Mostrar de nuevo", + "deleteTitle": "¿Eliminar síntoma?", + "deleteBody": "Se eliminarán «{symptom}» y todas sus entradas. Para conservar el historial, ocúltalo.", + "deleteEventTitle": "¿Eliminar entrada?", + "deleteEventBody": "Esta entrada se eliminará.", + "hiddenOne": "Ocultos (1)", + "hiddenFew": "Ocultos ({count})", + "hiddenOther": "Ocultos ({count})", + "recent": "Últimos 30 días", + "recentEmpty": "Nada registrado en los últimos 30 días.", + "editEventTitle": "Editar {symptom}", + "editSymptomTitle": "Editar síntoma" + }, + "episode": { + "title": "Síntomas registrados", + "filed": "registrado con esta enfermedad" + } } } diff --git a/messages/fr.json b/messages/fr.json index f50881afb..7a0015014 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -140,6 +140,18 @@ "unit": { "locked": "Ce marqueur a déjà des valeurs, son unité ne peut donc pas être modifiée. Les valeurs enregistrées s'afficheraient dans la nouvelle unité sans être converties." } + }, + "symptoms": { + "definition": { + "limitReached": "Tu as 8 symptômes. Masques-en un pour en ajouter un autre.", + "notFound": "Ce symptôme n'existe plus." + }, + "episode": { + "notOpen": "Cette maladie n'est plus ouverte. Choisis-en une autre ou aucune." + }, + "event": { + "notFound": "Cette entrée n'existe plus." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Humeur", "moodDescription": "Enregistrez votre humeur et des étiquettes", "workout": "Entraînement", - "workoutDescription": "Une séance que vos appareils n’ont pas enregistrée" + "workoutDescription": "Une séance que vos appareils n’ont pas enregistrée", + "symptom": "Symptôme", + "symptomDescription": "L'un de tes propres symptômes, avec son intensité" }, "cycle": "Cycle", "labs": "Analyses", @@ -651,7 +665,8 @@ "title": "Sauvegarde ta clé de chiffrement", "body": "Sans copie de la clé, tes données ne peuvent pas être récupérées après une réinstallation. Ça prend une minute.", "action": "Ouvrir l'étape" - } + }, + "quickAddSymptom": "Noter un symptôme" }, "measurements": { "title": "Mesures", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "La restauration s'est arrêtée sur une erreur inattendue et a été annulée. Le journal du serveur indique l'erreur.", "restoreFailureKeyMissing": "La sauvegarde a besoin de la clé de chiffrement {keys}, avec laquelle ce serveur ne peut pas l'ouvrir. Remettez la clé dans ENCRYPTION_KEYS, redémarrez, puis relancez la restauration.", "restoreFailureForeignReference": "Le fichier renvoie à des éléments qui appartiennent à un autre compte. Rien n'a été écrit.", - "previewKeyMissing": "Cette sauvegarde ne peut pas être restaurée sur ce serveur : elle a besoin de la clé de chiffrement {keys}. Remettez d'abord la clé dans ENCRYPTION_KEYS et redémarrez." + "previewKeyMissing": "Cette sauvegarde ne peut pas être restaurée sur ce serveur : elle a besoin de la clé de chiffrement {keys}. Remettez d'abord la clé dans ENCRYPTION_KEYS et redémarrez.", + "restoreSkippedSymptomEpisodeReference": "Entrée de symptôme liée à une maladie absente du fichier (conservée sans le lien)" }, "danger-zone": { "title": "Zone de danger", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Ordonnance", "REFERRAL": "Lettre d'adressage", "INSURANCE": "Assurance", - "VACCINATION": "Vaccination" + "VACCINATION": "Vaccination", + "SICK_NOTE": "Arrêt de travail" }, "filter": { "searchLabel": "Rechercher des documents", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "L'import de prises lancé par {name} est terminé", "medicationOneShotReconciled": "Un médicament à prise unique a été rouvert ou clos après une prise enregistrée par {name}", "vaccinationBoosterPlanned": "{name} a planifié un rappel", - "medicationCategoryCreate": "{name} a ajouté une catégorie de médicaments" + "medicationCategoryCreate": "{name} a ajouté une catégorie de médicaments", + "symptomEventCreate": "{name} a noté un symptôme", + "symptomEventUpdate": "{name} a modifié une entrée de symptôme", + "symptomEventDelete": "{name} a supprimé une entrée de symptôme", + "symptomDefinitionCreate": "{name} a ajouté un symptôme", + "symptomDefinitionUpdate": "{name} a modifié un symptôme", + "symptomDefinitionDelete": "{name} a retiré un symptôme" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "En attente du traitement en arrière-plan. Si rien ne change, le worker du serveur n'est peut-être pas lancé.", "errorWorkerUnavailable": "Le traitement en arrière-plan n'est pas disponible pour le moment. Réessayez dans un instant ou demandez à la personne qui gère le serveur de le vérifier.", "errorTimedOut": "La lecture a pris plus de temps que votre délai de réponse IA ne le permet. Réessayez ou augmentez ce délai dans les réglages IA." + }, + "symptoms": { + "add": "Nouveau symptôme", + "nameLabel": "Nom", + "namePlaceholder": "p. ex. Aura", + "iconLabel": "Icône", + "limitReached": "Tu as 8 symptômes. Masques-en un pour en ajouter un autre.", + "saveError": "Impossible d'enregistrer le symptôme. Réessaie.", + "nameRequired": "Donne un nom au symptôme.", + "unreadableLabel": "Symptôme illisible", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Noter un symptôme", + "sheetDescription": "L'un de tes propres symptômes, son intensité et quand.", + "symptom": "Symptôme", + "symptomRequired": "Choisis un symptôme.", + "intensity": "Intensité", + "intensityRequired": "Indique à quel point c'était fort.", + "intensityUnset": "Non renseignée", + "anchorLow": "Aucune", + "anchorHigh": "La pire imaginable", + "intensityValueText": "{value} sur {max} ({low} à {high})", + "when": "Quand", + "during": "Pendant une maladie", + "duringNone": "Non lié", + "note": "Note", + "notePlaceholder": "Qu'est-ce qui se passait d'autre ?", + "reset": "Réinitialiser le formulaire", + "emptyHint": "Ajoute ton premier symptôme, par exemple aura ou mal de tête.", + "emptyHintNoManage": "Aucun symptôme n'est encore configuré pour ce dossier.", + "limitHint": "Jusqu'à {limit} symptômes. Masques-en un sur la page des maladies pour en ajouter un autre." + }, + "section": { + "title": "Tes symptômes", + "log": "Noter", + "loadError": "Impossible de charger tes symptômes.", + "summaryOne": "Une fois en 30 jours, {max}/10, la dernière {date}", + "summaryFew": "{count} fois en 30 jours, jusqu'à {max}/10, la dernière {date}", + "summaryOther": "{count} fois en 30 jours, jusqu'à {max}/10, la dernière {date}", + "summaryNoneRecent": "Pas dans les 30 derniers jours, la dernière {date}", + "summaryNever": "Pas encore noté", + "menuLabel": "Options pour {symptom}", + "eventMenuLabel": "Options pour cette entrée {symptom}", + "hide": "Masquer", + "show": "Afficher à nouveau", + "deleteTitle": "Supprimer le symptôme ?", + "deleteBody": "« {symptom} » et toutes ses entrées seront supprimés. Pour garder l'historique, masque-le plutôt.", + "deleteEventTitle": "Supprimer l'entrée ?", + "deleteEventBody": "Cette entrée sera supprimée.", + "hiddenOne": "Masqués (1)", + "hiddenFew": "Masqués ({count})", + "hiddenOther": "Masqués ({count})", + "recent": "30 derniers jours", + "recentEmpty": "Rien de noté ces 30 derniers jours.", + "editEventTitle": "Modifier {symptom}", + "editSymptomTitle": "Modifier le symptôme" + }, + "episode": { + "title": "Symptômes notés", + "filed": "noté avec cette maladie" + } } } diff --git a/messages/it.json b/messages/it.json index 5c41b39fb..98a68adbb 100644 --- a/messages/it.json +++ b/messages/it.json @@ -140,6 +140,18 @@ "unit": { "locked": "Questo marcatore ha già dei valori, quindi non puoi cambiarne l'unità. I valori salvati verrebbero mostrati nella nuova unità senza essere convertiti." } + }, + "symptoms": { + "definition": { + "limitReached": "Hai 8 sintomi. Nascondine uno per aggiungerne un altro.", + "notFound": "Questo sintomo non esiste più." + }, + "episode": { + "notOpen": "Quella malattia non è più aperta. Scegline un'altra o nessuna." + }, + "event": { + "notFound": "Questa voce non esiste più." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Umore", "moodDescription": "Registra umore e tag", "workout": "Allenamento", - "workoutDescription": "Una sessione che i tuoi dispositivi non hanno registrato" + "workoutDescription": "Una sessione che i tuoi dispositivi non hanno registrato", + "symptom": "Sintomo", + "symptomDescription": "Uno dei tuoi sintomi, con la sua intensità" }, "cycle": "Ciclo", "labs": "Esami", @@ -651,7 +665,8 @@ "title": "Fai un backup della tua chiave di cifratura", "body": "Senza una copia della chiave, i tuoi dati non si possono recuperare dopo una reinstallazione. Ci vuole un minuto.", "action": "Apri il passaggio" - } + }, + "quickAddSymptom": "Registra sintomo" }, "measurements": { "title": "Misurazioni", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "Il ripristino si è fermato per un errore imprevisto ed è stato annullato. Il log del server indica l'errore.", "restoreFailureKeyMissing": "Il backup richiede la chiave di cifratura {keys}, con cui questo server non riesce ad aprirlo. Aggiungi di nuovo la chiave a ENCRYPTION_KEYS, riavvia e avvia di nuovo il ripristino.", "restoreFailureForeignReference": "Il file rimanda a voci che appartengono a un altro account. Non è stato scritto nulla.", - "previewKeyMissing": "Questo backup non può essere ripristinato su questo server: richiede la chiave di cifratura {keys}. Aggiungi prima di nuovo la chiave a ENCRYPTION_KEYS e riavvia." + "previewKeyMissing": "Questo backup non può essere ripristinato su questo server: richiede la chiave di cifratura {keys}. Aggiungi prima di nuovo la chiave a ENCRYPTION_KEYS e riavvia.", + "restoreSkippedSymptomEpisodeReference": "Voce di sintomo collegata a una malattia assente dal file (mantenuta senza collegamento)" }, "danger-zone": { "title": "Zona pericolosa", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Prescrizione", "REFERRAL": "Impegnativa", "INSURANCE": "Assicurazione", - "VACCINATION": "Vaccinazione" + "VACCINATION": "Vaccinazione", + "SICK_NOTE": "Certificato di malattia" }, "filter": { "searchLabel": "Cerca documenti", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "L'importazione delle dosi avviata da {name} è terminata", "medicationOneShotReconciled": "Un farmaco monodose è stato riaperto o chiuso dopo una dose registrata da {name}", "vaccinationBoosterPlanned": "{name} ha pianificato un richiamo", - "medicationCategoryCreate": "{name} ha aggiunto una categoria di farmaci" + "medicationCategoryCreate": "{name} ha aggiunto una categoria di farmaci", + "symptomEventCreate": "{name} ha registrato un sintomo", + "symptomEventUpdate": "{name} ha modificato una voce di sintomo", + "symptomEventDelete": "{name} ha eliminato una voce di sintomo", + "symptomDefinitionCreate": "{name} ha aggiunto un sintomo", + "symptomDefinitionUpdate": "{name} ha modificato un sintomo", + "symptomDefinitionDelete": "{name} ha rimosso un sintomo" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "In attesa del processo in background. Se non cambia, il worker del server potrebbe non essere attivo.", "errorWorkerUnavailable": "Il processo in background non è disponibile al momento. Riprova tra poco o chiedi a chi gestisce il server di controllarlo.", "errorTimedOut": "La lettura ha richiesto più tempo di quanto consenta il tuo tempo di risposta dell'IA. Riprova o aumenta il tempo di risposta nelle impostazioni IA." + }, + "symptoms": { + "add": "Nuovo sintomo", + "nameLabel": "Nome", + "namePlaceholder": "es. Aura", + "iconLabel": "Icona", + "limitReached": "Hai 8 sintomi. Nascondine uno per aggiungerne un altro.", + "saveError": "Impossibile salvare il sintomo. Riprova.", + "nameRequired": "Dai un nome al sintomo.", + "unreadableLabel": "Sintomo illeggibile", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Registra sintomo", + "sheetDescription": "Uno dei tuoi sintomi, quanto forte e quando.", + "symptom": "Sintomo", + "symptomRequired": "Scegli un sintomo.", + "intensity": "Intensità", + "intensityRequired": "Indica quanto era forte.", + "intensityUnset": "Non impostata", + "anchorLow": "Nessuna", + "anchorHigh": "La peggiore immaginabile", + "intensityValueText": "{value} su {max} (da {low} a {high})", + "when": "Quando", + "during": "Durante una malattia", + "duringNone": "Non collegato", + "note": "Nota", + "notePlaceholder": "Cos'altro stava succedendo?", + "reset": "Reimposta modulo", + "emptyHint": "Aggiungi il tuo primo sintomo, per esempio aura o mal di testa.", + "emptyHintNoManage": "Per questo profilo non sono ancora stati creati sintomi.", + "limitHint": "Fino a {limit} sintomi. Nascondine uno nella pagina delle malattie per aggiungerne un altro." + }, + "section": { + "title": "I tuoi sintomi", + "log": "Registra", + "loadError": "Impossibile caricare i tuoi sintomi.", + "summaryOne": "Una volta in 30 giorni, {max}/10, l'ultima {date}", + "summaryFew": "{count} volte in 30 giorni, fino a {max}/10, l'ultima {date}", + "summaryOther": "{count} volte in 30 giorni, fino a {max}/10, l'ultima {date}", + "summaryNoneRecent": "Non negli ultimi 30 giorni, l'ultima {date}", + "summaryNever": "Non ancora registrato", + "menuLabel": "Opzioni per {symptom}", + "eventMenuLabel": "Opzioni per questa voce di {symptom}", + "hide": "Nascondi", + "show": "Mostra di nuovo", + "deleteTitle": "Eliminare il sintomo?", + "deleteBody": "«{symptom}» e tutte le sue voci verranno eliminati. Per conservare la cronologia, nascondilo invece.", + "deleteEventTitle": "Eliminare la voce?", + "deleteEventBody": "Questa voce verrà eliminata.", + "hiddenOne": "Nascosti (1)", + "hiddenFew": "Nascosti ({count})", + "hiddenOther": "Nascosti ({count})", + "recent": "Ultimi 30 giorni", + "recentEmpty": "Niente registrato negli ultimi 30 giorni.", + "editEventTitle": "Modifica {symptom}", + "editSymptomTitle": "Modifica sintomo" + }, + "episode": { + "title": "Sintomi registrati", + "filed": "registrato con questa malattia" + } } } diff --git a/messages/ko.json b/messages/ko.json index b3f504a0f..dc9554b81 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -140,6 +140,18 @@ "unit": { "locked": "이 마커에는 이미 기록된 값이 있어서 단위를 바꿀 수 없어요. 저장된 값이 변환되지 않은 채 새 단위로 표시되기 때문이에요." } + }, + "symptoms": { + "definition": { + "limitReached": "증상이 8개입니다. 하나를 숨기면 새로 추가할 수 있습니다.", + "notFound": "이 증상은 더 이상 없습니다." + }, + "episode": { + "notOpen": "그 질병은 더 이상 진행 중이 아닙니다. 다른 질병을 선택하거나 선택하지 마세요." + }, + "event": { + "notFound": "이 기록은 더 이상 없습니다." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "기분", "moodDescription": "기분과 태그 기록하기", "workout": "운동", - "workoutDescription": "기기가 기록하지 못한 운동" + "workoutDescription": "기기가 기록하지 못한 운동", + "symptom": "증상", + "symptomDescription": "직접 정한 증상과 강도" }, "cycle": "생리 주기", "labs": "검사", @@ -651,7 +665,8 @@ "title": "암호화 키를 백업하세요", "body": "키 사본이 없으면 다시 설치한 뒤 데이터를 복구할 수 없습니다. 1분이면 됩니다.", "action": "단계 열기" - } + }, + "quickAddSymptom": "증상 기록" }, "measurements": { "title": "측정", @@ -7517,7 +7532,8 @@ "restoreFailureUnexpected": "예상하지 못한 오류로 복원이 멈췄고 되돌려졌어요. 서버 로그에 오류가 나와 있어요.", "restoreFailureKeyMissing": "이 백업에는 암호화 키 {keys}가 필요하지만 이 서버는 그 키로 백업을 열 수 없습니다. 키를 ENCRYPTION_KEYS에 다시 추가하고 재시작한 뒤 복원을 다시 시작하세요.", "restoreFailureForeignReference": "파일이 다른 계정에 속한 기록을 가리키고 있습니다. 아무것도 기록되지 않았습니다.", - "previewKeyMissing": "이 서버에서는 이 백업을 복원할 수 없습니다. 암호화 키 {keys}가 필요합니다. 먼저 키를 ENCRYPTION_KEYS에 다시 추가하고 재시작하세요." + "previewKeyMissing": "이 서버에서는 이 백업을 복원할 수 없습니다. 암호화 키 {keys}가 필요합니다. 먼저 키를 ENCRYPTION_KEYS에 다시 추가하고 재시작하세요.", + "restoreSkippedSymptomEpisodeReference": "파일에 없는 질병과 연결된 증상 기록(연결 없이 유지됨)" }, "danger-zone": { "title": "위험 구역", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "처방", "REFERRAL": "진료 의뢰서", "INSURANCE": "보험", - "VACCINATION": "예방접종" + "VACCINATION": "예방접종", + "SICK_NOTE": "병가 진단서" }, "filter": { "searchLabel": "문서 검색", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "{name} 님이 시작한 복용 기록 불러오기가 끝났어요", "medicationOneShotReconciled": "{name} 님이 기록한 복용에 따라 일회성 약이 시작되거나 종료됐어요", "vaccinationBoosterPlanned": "{name} 님이 추가 접종을 계획했어요", - "medicationCategoryCreate": "{name} 님이 약 카테고리를 추가했어요" + "medicationCategoryCreate": "{name} 님이 약 카테고리를 추가했어요", + "symptomEventCreate": "{name}님이 증상을 기록했습니다", + "symptomEventUpdate": "{name}님이 증상 기록을 편집했습니다", + "symptomEventDelete": "{name}님이 증상 기록을 삭제했습니다", + "symptomDefinitionCreate": "{name}님이 증상을 추가했습니다", + "symptomDefinitionUpdate": "{name}님이 증상을 변경했습니다", + "symptomDefinitionDelete": "{name}님이 증상을 제거했습니다" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "백그라운드 작업자를 기다리고 있어요. 계속 그대로라면 서버의 작업자가 실행 중이 아닐 수 있어요.", "errorWorkerUnavailable": "지금은 백그라운드 작업자를 사용할 수 없어요. 잠시 후 다시 시도하거나 서버 운영자에게 확인을 요청하세요.", "errorTimedOut": "AI 응답 시간 설정보다 읽기가 오래 걸렸어요. 다시 시도하거나 AI 설정에서 응답 시간을 늘려 주세요." + }, + "symptoms": { + "add": "새 증상", + "nameLabel": "이름", + "namePlaceholder": "예: 전조", + "iconLabel": "아이콘", + "limitReached": "증상이 8개입니다. 하나를 숨기면 새로 추가할 수 있습니다.", + "saveError": "증상을 저장하지 못했습니다. 다시 시도하세요.", + "nameRequired": "증상 이름을 입력하세요.", + "unreadableLabel": "읽을 수 없는 증상", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "증상 기록", + "sheetDescription": "직접 정한 증상과 강도, 시각을 기록합니다.", + "symptom": "증상", + "symptomRequired": "증상을 선택하세요.", + "intensity": "강도", + "intensityRequired": "얼마나 심했는지 정하세요.", + "intensityUnset": "미설정", + "anchorLow": "없음", + "anchorHigh": "상상할 수 있는 최악", + "intensityValueText": "{max} 중 {value} ({low}부터 {high}까지)", + "when": "시각", + "during": "질병 기간 중", + "duringNone": "연결 안 함", + "note": "메모", + "notePlaceholder": "그 밖에 어떤 일이 있었나요?", + "reset": "양식 초기화", + "emptyHint": "첫 증상을 추가하세요. 예: 전조, 두통.", + "emptyHintNoManage": "이 기록에는 아직 설정된 증상이 없습니다.", + "limitHint": "증상은 최대 {limit}개입니다. 질병 페이지에서 하나를 숨기면 새로 추가할 수 있습니다." + }, + "section": { + "title": "내 증상", + "log": "기록", + "loadError": "증상을 불러오지 못했습니다.", + "summaryOne": "30일 동안 1회, {max}/10, 마지막 {date}", + "summaryFew": "30일 동안 {count}회, 최대 {max}/10, 마지막 {date}", + "summaryOther": "30일 동안 {count}회, 최대 {max}/10, 마지막 {date}", + "summaryNoneRecent": "최근 30일 동안 없음, 마지막 {date}", + "summaryNever": "아직 기록 없음", + "menuLabel": "{symptom} 옵션", + "eventMenuLabel": "이 {symptom} 기록의 옵션", + "hide": "숨기기", + "show": "다시 표시", + "deleteTitle": "증상을 삭제할까요?", + "deleteBody": "\"{symptom}\"과 모든 기록이 삭제됩니다. 기록을 남기려면 대신 숨기세요.", + "deleteEventTitle": "기록을 삭제할까요?", + "deleteEventBody": "이 기록이 삭제됩니다.", + "hiddenOne": "숨김 (1)", + "hiddenFew": "숨김 ({count})", + "hiddenOther": "숨김 ({count})", + "recent": "최근 30일", + "recentEmpty": "최근 30일 동안 기록이 없습니다.", + "editEventTitle": "{symptom} 편집", + "editSymptomTitle": "증상 편집" + }, + "episode": { + "title": "기록된 증상", + "filed": "이 질병과 함께 기록됨" + } } } diff --git a/messages/pl.json b/messages/pl.json index be5166a5f..ded8ce286 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -140,6 +140,18 @@ "unit": { "locked": "Ten marker ma już wyniki, więc nie możesz zmienić jego jednostki. Zapisane wartości byłyby pokazywane w nowej jednostce bez przeliczenia." } + }, + "symptoms": { + "definition": { + "limitReached": "Masz 8 objawów. Ukryj jeden, aby dodać kolejny.", + "notFound": "Ten objaw już nie istnieje." + }, + "episode": { + "notOpen": "Ta choroba nie jest już otwarta. Wybierz inną lub żadną." + }, + "event": { + "notFound": "Ten wpis już nie istnieje." + } } }, "doctorReport": { @@ -412,7 +424,9 @@ "mood": "Nastrój", "moodDescription": "Zapisz nastrój i tagi", "workout": "Trening", - "workoutDescription": "Sesja, której nie zapisały twoje urządzenia" + "workoutDescription": "Sesja, której nie zapisały twoje urządzenia", + "symptom": "Objaw", + "symptomDescription": "Jeden z twoich objawów, z nasileniem" }, "cycle": "Cykl", "labs": "Wyniki badań", @@ -651,7 +665,8 @@ "title": "Zrób kopię klucza szyfrowania", "body": "Bez kopii klucza Twoich danych nie da się odzyskać po ponownej instalacji. To zajmie minutę.", "action": "Otwórz krok" - } + }, + "quickAddSymptom": "Zapisz objaw" }, "measurements": { "title": "Pomiary", @@ -7538,7 +7553,8 @@ "restoreFailureUnexpected": "Przywracanie zatrzymało się na nieoczekiwanym błędzie i zostało wycofane. Dziennik serwera podaje błąd.", "restoreFailureKeyMissing": "Kopia wymaga klucza szyfrowania {keys}, którym ten serwer nie może jej otworzyć. Dodaj klucz z powrotem do ENCRYPTION_KEYS, uruchom ponownie i rozpocznij przywracanie jeszcze raz.", "restoreFailureForeignReference": "Plik wskazuje na wpisy należące do innego konta. Nic nie zostało zapisane.", - "previewKeyMissing": "Tej kopii nie da się przywrócić na tym serwerze: wymaga klucza szyfrowania {keys}. Najpierw dodaj klucz z powrotem do ENCRYPTION_KEYS i uruchom ponownie." + "previewKeyMissing": "Tej kopii nie da się przywrócić na tym serwerze: wymaga klucza szyfrowania {keys}. Najpierw dodaj klucz z powrotem do ENCRYPTION_KEYS i uruchom ponownie.", + "restoreSkippedSymptomEpisodeReference": "Wpis objawu powiązany z chorobą, której nie ma w pliku (zachowany bez powiązania)" }, "danger-zone": { "title": "Strefa zagrożenia", @@ -10379,7 +10395,8 @@ "PRESCRIPTION": "Recepta", "REFERRAL": "Skierowanie", "INSURANCE": "Ubezpieczenie", - "VACCINATION": "Szczepienie" + "VACCINATION": "Szczepienie", + "SICK_NOTE": "Zwolnienie lekarskie" }, "filter": { "searchLabel": "Szukaj dokumentów", @@ -11333,7 +11350,13 @@ "medicationIntakeImportFinished": "Import przyjęć rozpoczęty przez {name} zakończył się", "medicationOneShotReconciled": "Lek jednorazowy został otwarty lub zamknięty po dawce zapisanej przez {name}", "vaccinationBoosterPlanned": "{name} zaplanował dawkę przypominającą", - "medicationCategoryCreate": "{name} dodał kategorię leków" + "medicationCategoryCreate": "{name} dodał kategorię leków", + "symptomEventCreate": "{name} zapisał(a) objaw", + "symptomEventUpdate": "{name} edytował(a) wpis objawu", + "symptomEventDelete": "{name} usunął(-ęła) wpis objawu", + "symptomDefinitionCreate": "{name} dodał(a) objaw", + "symptomDefinitionUpdate": "{name} zmienił(a) objaw", + "symptomDefinitionDelete": "{name} usunął(-ęła) objaw" }, "section": { "measurements": { @@ -11564,5 +11587,66 @@ "waitingForWorker": "Oczekiwanie na proces w tle. Jeśli nic się nie zmienia, worker na serwerze może nie działać.", "errorWorkerUnavailable": "Proces w tle jest teraz niedostępny. Spróbuj ponownie za chwilę albo poproś administratora serwera o sprawdzenie go.", "errorTimedOut": "Odczyt trwał dłużej, niż pozwala ustawiony czas odpowiedzi AI. Spróbuj ponownie albo wydłuż czas odpowiedzi w ustawieniach AI." + }, + "symptoms": { + "add": "Nowy objaw", + "nameLabel": "Nazwa", + "namePlaceholder": "np. Aura", + "iconLabel": "Ikona", + "limitReached": "Masz 8 objawów. Ukryj jeden, aby dodać kolejny.", + "saveError": "Nie udało się zapisać objawu. Spróbuj ponownie.", + "nameRequired": "Nadaj objawowi nazwę.", + "unreadableLabel": "Nieczytelny objaw", + "intensityPill": "{value}/10", + "entry": { + "sheetTitle": "Zapisz objaw", + "sheetDescription": "Jeden z twoich objawów, jak silny i kiedy.", + "symptom": "Objaw", + "symptomRequired": "Wybierz objaw.", + "intensity": "Nasilenie", + "intensityRequired": "Określ, jak silny był.", + "intensityUnset": "Nie ustawiono", + "anchorLow": "Brak", + "anchorHigh": "Najgorszy wyobrażalny", + "intensityValueText": "{value} z {max} ({low} do {high})", + "when": "Kiedy", + "during": "W trakcie choroby", + "duringNone": "Bez powiązania", + "note": "Notatka", + "notePlaceholder": "Co jeszcze się działo?", + "reset": "Wyczyść formularz", + "emptyHint": "Dodaj swój pierwszy objaw, na przykład aurę lub ból głowy.", + "emptyHintNoManage": "Dla tego profilu nie ma jeszcze objawów.", + "limitHint": "Do {limit} objawów. Ukryj jeden na stronie chorób, aby dodać kolejny." + }, + "section": { + "title": "Twoje objawy", + "log": "Zapisz", + "loadError": "Nie udało się wczytać twoich objawów.", + "summaryOne": "Raz w ciągu 30 dni, {max}/10, ostatnio {date}", + "summaryFew": "{count} razy w ciągu 30 dni, do {max}/10, ostatnio {date}", + "summaryOther": "{count} razy w ciągu 30 dni, do {max}/10, ostatnio {date}", + "summaryNoneRecent": "Nie w ostatnich 30 dniach, ostatnio {date}", + "summaryNever": "Jeszcze nie zapisano", + "menuLabel": "Opcje dla {symptom}", + "eventMenuLabel": "Opcje tego wpisu: {symptom}", + "hide": "Ukryj", + "show": "Pokaż ponownie", + "deleteTitle": "Usunąć objaw?", + "deleteBody": "„{symptom}” i wszystkie jego wpisy zostaną usunięte. Aby zachować historię, ukryj go.", + "deleteEventTitle": "Usunąć wpis?", + "deleteEventBody": "Ten wpis zostanie usunięty.", + "hiddenOne": "Ukryte (1)", + "hiddenFew": "Ukryte ({count})", + "hiddenOther": "Ukryte ({count})", + "recent": "Ostatnie 30 dni", + "recentEmpty": "Nic nie zapisano w ostatnich 30 dniach.", + "editEventTitle": "Edytuj: {symptom}", + "editSymptomTitle": "Edytuj objaw" + }, + "episode": { + "title": "Zapisane objawy", + "filed": "zapisano przy tej chorobie" + } } } diff --git a/prisma/migrations/0369_symptom_definitions_and_events/migration.sql b/prisma/migrations/0369_symptom_definitions_and_events/migration.sql new file mode 100644 index 000000000..a6dc2d55a --- /dev/null +++ b/prisma/migrations/0369_symptom_definitions_and_events/migration.sql @@ -0,0 +1,73 @@ +-- Person-defined symptoms and their timestamped events. A definition is the +-- person's own name for a symptom (encrypted); an event is one occurrence with +-- a 0-10 intensity and an optional link to an illness episode. Idempotent, so +-- a re-run of a half-applied migration converges. +CREATE TABLE IF NOT EXISTS "symptom_definitions" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "label_encrypted" BYTEA NOT NULL, + "icon" TEXT, + "sort_order" INTEGER NOT NULL DEFAULT 0, + "is_active" BOOLEAN NOT NULL DEFAULT true, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + CONSTRAINT "symptom_definitions_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX IF NOT EXISTS "symptom_definitions_user_id_sort_order_idx" + ON "symptom_definitions" ("user_id", "sort_order"); + +DO $$ BEGIN + ALTER TABLE "symptom_definitions" + ADD CONSTRAINT "symptom_definitions_user_id_fkey" + FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; + +CREATE TABLE IF NOT EXISTS "symptom_events" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "definition_id" TEXT NOT NULL, + "occurred_at" TIMESTAMP(3) NOT NULL, + "intensity" INTEGER NOT NULL, + "note_encrypted" BYTEA, + "episode_id" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + CONSTRAINT "symptom_events_pkey" PRIMARY KEY ("id") +); + +CREATE INDEX IF NOT EXISTS "symptom_events_user_id_occurred_at_idx" + ON "symptom_events" ("user_id", "occurred_at"); +CREATE INDEX IF NOT EXISTS "symptom_events_definition_id_occurred_at_idx" + ON "symptom_events" ("definition_id", "occurred_at"); +CREATE INDEX IF NOT EXISTS "symptom_events_episode_id_idx" + ON "symptom_events" ("episode_id"); + +DO $$ BEGIN + ALTER TABLE "symptom_events" + ADD CONSTRAINT "symptom_events_intensity_check" + CHECK ("intensity" >= 0 AND "intensity" <= 10); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; + +DO $$ BEGIN + ALTER TABLE "symptom_events" + ADD CONSTRAINT "symptom_events_user_id_fkey" + FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; + +DO $$ BEGIN + ALTER TABLE "symptom_events" + ADD CONSTRAINT "symptom_events_definition_id_fkey" + FOREIGN KEY ("definition_id") REFERENCES "symptom_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; + +DO $$ BEGIN + ALTER TABLE "symptom_events" + ADD CONSTRAINT "symptom_events_episode_id_fkey" + FOREIGN KEY ("episode_id") REFERENCES "illness_episodes"("id") ON DELETE SET NULL ON UPDATE CASCADE; +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; diff --git a/prisma/migrations/0370_document_ai_run_kinds_summary_suggest_extract/migration.sql b/prisma/migrations/0370_document_ai_run_kinds_summary_suggest_extract/migration.sql new file mode 100644 index 000000000..ec4d4cee9 --- /dev/null +++ b/prisma/migrations/0370_document_ai_run_kinds_summary_suggest_extract/migration.sql @@ -0,0 +1,22 @@ +-- Three more kinds of background document AI run, and one more document kind. +-- +-- Summaries, filing suggestions and fact extraction can now run in the same +-- background worker as "Read with AI" and the lab scan (0366): the request +-- queues the read and answers 202, and the result is polled from the run. The +-- synchronous routes are unchanged; the new kinds only name the run. +-- +-- `SICK_NOTE` files a certificate of incapacity for work (in Germany the +-- Arbeitsunfähigkeitsbescheinigung) as its own document kind instead of +-- under Other. +-- +-- Purely additive. `ADD VALUE IF NOT EXISTS` makes a rerun safe, and no new +-- value is used elsewhere in this migration, which is the one thing Postgres +-- forbids inside the transaction that adds it. No row is rewritten. +-- +-- Reversibility: Postgres cannot drop an enum value, so the values would stay +-- (inert with no rows that carry them). +ALTER TYPE "document_ai_run_kind" ADD VALUE IF NOT EXISTS 'DOCUMENT_SUMMARY'; +ALTER TYPE "document_ai_run_kind" ADD VALUE IF NOT EXISTS 'DOCUMENT_SUGGEST'; +ALTER TYPE "document_ai_run_kind" ADD VALUE IF NOT EXISTS 'DOCUMENT_EXTRACT'; + +ALTER TYPE "inbound_document_kind" ADD VALUE IF NOT EXISTS 'SICK_NOTE'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index eb02f4ea7..6a05a5659 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -913,6 +913,8 @@ model User { // per-day timeline mirroring the CycleDayLog shape. illnessEpisodes IllnessEpisode[] illnessDayLogs IllnessDayLog[] + symptomDefinitions SymptomDefinition[] + symptomEvents SymptomEvent[] // v1.25 (W-RECORDS) — structured health-record entries. Allergies map to // FHIR AllergyIntolerance; family-history entries map to FHIR // FamilyMemberHistory. Reference records (not time-series signals); the @@ -7814,6 +7816,8 @@ model IllnessEpisode { dayLogs IllnessDayLog[] documentLinks DocumentConditionLink[] encounterLinks EncounterConditionLink[] + /// Symptom events the person filed against this episode while it was open. + symptomEvents SymptomEvent[] @@index([userId, deletedAt]) @@index([userId, onsetAt]) @@ -7902,6 +7906,68 @@ model IllnessSymptomLink { @@map("illness_symptom_links") } +/// A symptom the person defined for themselves ("aura", "headache"), v1.40. +/// +/// Separate from the seeded `IllnessSymptom` catalogue on the illness day log: +/// that one is a fixed list of cold symptoms rated 1-3 per episode day, this one +/// is the person's own vocabulary, logged as timestamped events with a 0-10 +/// intensity whether or not an episode is open. Rides the `illness` module. +/// At most eight active definitions per account +/// (`MAX_ACTIVE_SYMPTOM_DEFINITIONS`), and each active one is its own +/// correlation channel `SYMPTOM:`, so the cap also bounds the matrix. +model SymptomDefinition { + id String @id @default(cuid()) + userId String @map("user_id") + /// The person's own name for the symptom, AES-256-GCM encrypted at rest. A + /// symptom name is health data in the person's own words. + labelEncrypted Bytes @map("label_encrypted") + /// Lucide icon name from `SYMPTOM_ICON_ALLOWLIST` (the cycle custom-symptom + /// list, which the iOS client already maps). NULL = the default glyph. + icon String? + sortOrder Int @default(0) @map("sort_order") + /// FALSE = hidden: not offered in the quick entry, not a correlation + /// channel, history kept. Does not count toward the cap. + isActive Boolean @default(true) @map("is_active") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + events SymptomEvent[] + + @@index([userId, sortOrder]) + @@map("symptom_definitions") +} + +/// One occurrence of a person-defined symptom: when, how strong (0-10, the +/// same numeric rating scale the pain score uses), an optional note, and an +/// optional link to the illness episode it happened during. v1.40. +model SymptomEvent { + id String @id @default(cuid()) + userId String @map("user_id") + definitionId String @map("definition_id") + /// The instant it happened (UTC). Day grouping is the reader's concern. + occurredAt DateTime @map("occurred_at") + /// 0-10, CHECK-constrained in the migration. + intensity Int + /// Optional free-text note, AES-256-GCM encrypted at rest. + noteEncrypted Bytes? @map("note_encrypted") + /// The episode the person said this happened during. Only an open episode + /// of the same account can be linked (the route checks); deleting the + /// episode row keeps the event and drops the link. + episodeId String? @map("episode_id") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + definition SymptomDefinition @relation(fields: [definitionId], references: [id], onDelete: Cascade) + episode IllnessEpisode? @relation(fields: [episodeId], references: [id], onDelete: SetNull) + + @@index([userId, occurredAt]) + @@index([definitionId, occurredAt]) + @@index([episodeId]) + @@map("symptom_events") +} + // ─── Structured health records (v1.25 W-RECORDS) ────────────────── // // Allergies + family history kept as STRUCTURED records (not time-series @@ -8107,6 +8173,9 @@ enum InboundDocumentKind { REFERRAL INSURANCE VACCINATION + /// A certificate of incapacity for work (in Germany the + /// Arbeitsunfähigkeitsbescheinigung) and its equivalents. + SICK_NOTE OTHER @@map("inbound_document_kind") @@ -8119,6 +8188,9 @@ enum InboundDocumentKind { /// every fact, DISCARDED on a soft delete. enum InboundDocumentStatus { STORED + /// @internal: reserved, no writer. An extraction in flight is the state of + /// its background run (`DocumentAiRun`), not of the document, so the vault + /// never shows a status nothing renders. EXTRACTING EXTRACTED FAILED @@ -9121,6 +9193,15 @@ enum DocumentAiRunKind { /// A lab report scan (photo, PDF or browser-read text) into proposed rows /// for the review screen. Nothing is written until the person commits. LABS_OCR_EXTRACT + /// A plain-language summary or the transcribed text of a stored document; + /// stored on the document only when the request asked for that. + DOCUMENT_SUMMARY + /// Filing suggestions (title, kind, date) for a stored document. Drafts + /// only: nothing is written to the document. + DOCUMENT_SUGGEST + /// Structured facts read out of a stored document, staged PENDING for the + /// review step. The confirm route stays the only write into the record. + DOCUMENT_EXTRACT @@map("document_ai_run_kind") } diff --git a/scripts/import-documents.mjs b/scripts/import-documents.mjs index 194af9d24..1a249fe05 100644 --- a/scripts/import-documents.mjs +++ b/scripts/import-documents.mjs @@ -49,6 +49,7 @@ const KINDS = [ "REFERRAL", "INSURANCE", "VACCINATION", + "SICK_NOTE", "OTHER", ]; const TITLE_MAX = 200; diff --git a/scripts/rotate-encryption-key.ts b/scripts/rotate-encryption-key.ts index 984291c64..8dd9631d9 100644 --- a/scripts/rotate-encryption-key.ts +++ b/scripts/rotate-encryption-key.ts @@ -603,6 +603,21 @@ async function main() { prisma.illnessDayLog, ), ); + // v1.40 — person-defined symptoms: the name and the per-occurrence note. + results.push( + await rotateBytesColumn( + "SymptomDefinition", + "labelEncrypted", + prisma.symptomDefinition, + ), + ); + results.push( + await rotateBytesColumn( + "SymptomEvent", + "noteEncrypted", + prisma.symptomEvent, + ), + ); // ───── v1.19.0 ECG waveform (Bytes column) ───── // "waveformEncrypted" holds the JSON-encoded micro-volt sample array in the diff --git a/src/__tests__/ai-egress-capability-guard.test.ts b/src/__tests__/ai-egress-capability-guard.test.ts index 847f41bca..3b06191b0 100644 --- a/src/__tests__/ai-egress-capability-guard.test.ts +++ b/src/__tests__/ai-egress-capability-guard.test.ts @@ -19,6 +19,7 @@ import { describe, expect, it } from "vitest"; import { readFileSync } from "node:fs"; import { join } from "node:path"; +import { DOCUMENT_AI_RUN_KINDS } from "@/lib/documents/ai-runs/types"; import type { runStatusCompletion } from "@/lib/insights/status-provider"; import { walkSourceFiles } from "./helpers/source-files"; @@ -163,7 +164,7 @@ const EGRESS_SITES: Record = { */ const WORKER_REACHERS: Record = { "lib/jobs/document-ai-run.ts": - "Background document reads and lab scans (v1.40): `transcribeDocument` and `runOcrExtraction` through the shared run bodies.", + "Background document reads and lab scans (v1.40): `transcribeDocument`, `runDocumentSummary`, `runDocumentAssist` and `runOcrExtraction` through the shared run bodies.", }; const JOB_CAPABILITY = /\baiCapabilityForJob\s*\(/; @@ -190,6 +191,50 @@ describe("workers that reach an admitted helper", () => { }); }); +/** The body of one top-level `async function name(` in a source text. */ +function functionBody(text: string, name: string): string | null { + const start = text.search(new RegExp(`async function ${name}\\s*\\(`)); + if (start < 0) return null; + const end = text.indexOf("\n}\n", start); + return end < 0 ? null : text.slice(start, end); +} + +describe("every kind of background run re-checks before its read", () => { + const worker = code("lib/jobs/document-ai-run.ts"); + const table = /const RUN_DISPATCH[^=]*=\s*\{([\s\S]*?)\};/.exec(worker); + const entries = [...(table?.[1] ?? "").matchAll(/(\w+):\s*(\w+),/g)].map( + (m) => ({ kind: m[1], dispatcher: m[2] }), + ); + + it("finds the dispatch table (an empty match is a failure, not a pass)", () => { + expect(entries.length).toBeGreaterThanOrEqual(2); + }); + + it("dispatches every run kind", () => { + expect(entries.map((e) => e.kind).sort()).toEqual( + [...DOCUMENT_AI_RUN_KINDS].sort(), + ); + }); + + it("the shared document pick re-checks the wire on both transports", () => { + const pick = functionBody(worker, "pickForDocumentRead") ?? ""; + expect(pick.match(/\bassertRunMayEgress\s*\(/g)?.length ?? 0).toBe(2); + }); + + it.each(DOCUMENT_AI_RUN_KINDS)( + "%s re-checks the capability and the wire before the body runs", + (kind) => { + const entry = entries.find((e) => e.kind === kind); + const body = entry ? functionBody(worker, entry.dispatcher) : null; + expect(body, `${kind}: dispatcher not found`).not.toBeNull(); + expect( + /\b(?:assertRunMayEgress|pickForDocumentRead)\s*\(/.test(body ?? ""), + `${kind}: its dispatcher sends to a model without assertRunMayEgress`, + ).toBe(true); + }, + ); +}); + describe("AI egress call sites", () => { const found = sourceFiles().filter((rel) => EGRESS_CALL.test(code(rel))); diff --git a/src/__tests__/dense-measurement-read-guard.test.ts b/src/__tests__/dense-measurement-read-guard.test.ts index 35060ade2..224bfc15b 100644 --- a/src/__tests__/dense-measurement-read-guard.test.ts +++ b/src/__tests__/dense-measurement-read-guard.test.ts @@ -101,8 +101,6 @@ const ALLOWED: Record = { "Health-score inputs: steps (drained to one row per day nightly), sleep, waist, weight, blood pressure, fasting glucose only.", 'app/api/analytics/route.ts::"BLOOD_GLUCOSE"': "The 30-day per-context glucose summary, the same window and bound as the dashboard and coach glucose panels: at a sensor's fixed rate, below 45 000 rows.", - "app/api/measurements/series/route.ts::(shorthand)": - "The raw branch of the per-kind series. Every dense kind reaches it only inside 90 days and under 10 000 rows (counted first); the sparse kinds are a few readings a day.", "app/api/measurements/batch/route.ts::p.row.type as MeasurementType": "Cross-source merge probe: one ±tolerance window around each posted reading's instant, so the rows found are bounded by the batch size.", "app/api/measurements/route.ts::(shorthand)": diff --git a/src/__tests__/destructive-control-guard.test.ts b/src/__tests__/destructive-control-guard.test.ts index 0aa719d4b..34f750ae7 100644 --- a/src/__tests__/destructive-control-guard.test.ts +++ b/src/__tests__/destructive-control-guard.test.ts @@ -331,6 +331,14 @@ const REGISTRY: DestructiveEntry[] = [ recovery: "restorable", confirm: ["AlertDialog"], }, + { + file: "components/symptoms/use-symptoms.ts", + destroys: + "one logged symptom entry, or a person-defined symptom with every entry of it", + triggers: ["components/symptoms/symptoms-section.tsx"], + recovery: "permanent", + confirm: ["AlertDialog"], + }, { file: "components/labs/biomarker-manager.tsx", destroys: "a biomarker AND every lab reading recorded against it", diff --git a/src/__tests__/discovery-matrix-guard.test.ts b/src/__tests__/discovery-matrix-guard.test.ts index ca4d3c9f2..128b5e8ac 100644 --- a/src/__tests__/discovery-matrix-guard.test.ts +++ b/src/__tests__/discovery-matrix-guard.test.ts @@ -91,6 +91,7 @@ describe("T1 — only the assembler fetches discovery channels", () => { "fetchSymptomSeries", "fetchEnvironmentSeries", "fetchCustomMetricBehaviourSeries", + "fetchSymptomEventSeries", "fetchMoodWindowSeries", "fetchMoodFactorWindowSeries", "fetchMeasurementDailySeriesTiered", diff --git a/src/__tests__/sharing-surface-guard.test.ts b/src/__tests__/sharing-surface-guard.test.ts index 95c04a524..e2177cc3e 100644 --- a/src/__tests__/sharing-surface-guard.test.ts +++ b/src/__tests__/sharing-surface-guard.test.ts @@ -991,6 +991,22 @@ const DELEGABLE_ROUTES: Record = { domain: "illness", why: "The day logs of one episode. The episode-scoped queries are safe because `loadOwnedEpisode(id, user.id)` runs first and now resolves against the record; the upsert arm keeps `requireAuth()`.", }, + "app/api/symptoms/definitions/route.ts": { + domain: "illness", + why: "The record's own symptom list. Module-gated on the record on both arms and scoped `userId: user.id`; the create arm is MANAGE (see the manage literal), because the vocabulary is the owner's and a delegate who may log an occurrence picks from it.", + }, + "app/api/symptoms/definitions/[id]/route.ts": { + domain: "illness", + why: "One symptom definition of the record, fetch-then-guard against the resolved user. Reached only through this module's MANAGE arm; the argument for admitting it is the manage literal's reason line.", + }, + "app/api/symptoms/events/route.ts": { + domain: "illness", + why: "The record's symptom occurrences. Module-gated on the record; the definition and the optional episode a create names are both re-narrowed to the resolved user before anything is written, so a delegate cannot file one record's occurrence under another's episode. The create arm is a delegable write.", + }, + "app/api/symptoms/events/[id]/route.ts": { + domain: "illness", + why: "One symptom occurrence of the record, fetch-then-guard against the resolved user. Reached only through this module's MANAGE arm.", + }, "app/api/workouts/route.ts": { domain: "measurements", why: "The record's workout list. Verified to carry no AI-written paragraph: the single-workout route beside it does, and stays refused for exactly that reason.", @@ -1431,6 +1447,8 @@ const DELEGABLE_WRITE_ROUTES: Record = { "Adding an analyte to the record's catalogue. A name the record already tracks is the ordinary 409 from the same `(userId, name)` uniqueness the owner would hit themselves.", "app/api/illness/episodes/route.ts": "Opening an illness episode. The module gate runs against the RECORD before the write, so a delegate cannot create an episode inside a record whose owner switched the module off.", + "app/api/symptoms/events/route.ts": + "Logging a symptom occurrence. The definition and the episode the body names are looked up under the RECORD, and an episode must still be open, so a delegate cannot attach an occurrence to an episode the owner closed or to another record's.", "app/api/encounters/route.ts": "Filing a visit, or booking one. Every id the body may carry — the practitioner, the checkup it closes, the three link arrays — is re-narrowed to the resolved record before anything is written, so a delegate cannot attach one record's document to another's visit. Booking mints the appointment reminder under the RECORD, which is correct: it is the owner's appointment and the owner's channels that should be nudged about it.", "app/api/practitioners/route.ts": @@ -1600,6 +1618,21 @@ const DELEGABLE_MANAGE_ROUTES: Record = { conditions: ["C3"], why: "Writing a day of an episode. The upsert revives a tombstoned day and replaces that day's symptom links, so C3 names the date, the previous symptom set, and the revival.", }, + "app/api/symptoms/definitions/route.ts": { + domain: "illness", + conditions: ["C1"], + why: "Defining a symptom on the record. Capped at eight active ones; C1 so a manager burns their own bucket rather than the owner's.", + }, + "app/api/symptoms/definitions/[id]/route.ts": { + domain: "illness", + conditions: ["C1", "C3", "C4"], + why: "Renaming, hiding and deleting a symptom. Hiding keeps the history; the purge is hard and takes the occurrences with it, so C3 names the definition and the count. C4 on the edit, over the plaintext fields only; a rename is named, never quoted. C1 on the bucket.", + }, + "app/api/symptoms/events/[id]/route.ts": { + domain: "illness", + conditions: ["C3", "C4"], + why: "Correcting and removing one occurrence. The delete is hard, so C3 carries its time and intensity; C4 on the edit, the encrypted note named and never quoted.", + }, "app/api/mood-entries/route.ts": { domain: "mind", conditions: ["C6"], @@ -1972,9 +2005,13 @@ const ACTOR_ROUTES: Record = { * * v1.40 -- the custom medication categories add two: the vocabulary read on * the record list and its create on the manage literal, the cycle symptom - * precedent. Rename and delete stay owner-only. 232 -> 234. + * precedent. Rename and delete stay owner-only. + * v1.40 -- person-defined symptoms add eight: four modules on the record + * list, the occurrence create on the write literal, and the definition create, + * the definition edit/delete and the occurrence edit/delete on the manage + * literal. 232 -> 242 with both. */ -const FROZEN_ENTRY_COUNT = 234; +const FROZEN_ENTRY_COUNT = 242; /** * The two surfaces that authenticate a Bearer token outside `requireAuth` — @@ -2735,7 +2772,7 @@ describe("(g) the MANAGE route set is frozen", () => { it("keeps the admitted mutation inventory complete and discoverable", () => { expect(ADMITTED_MUTATING_HANDLERS.length).toBeGreaterThan(0); - expect(ADMITTED_MUTATING_HANDLERS.length).toBe(78); + expect(ADMITTED_MUTATING_HANDLERS.length).toBe(84); const expected = ADMITTED_MUTATING_HANDLERS.map( ({ handlerModule, action, level }) => diff --git a/src/__tests__/success-affordance-guard.test.ts b/src/__tests__/success-affordance-guard.test.ts index 8ddf90e93..927aaf7b6 100644 --- a/src/__tests__/success-affordance-guard.test.ts +++ b/src/__tests__/success-affordance-guard.test.ts @@ -293,6 +293,9 @@ const PINNED_AFFORDANCES: Record< "src/components/mood/manage/tag-groups-card.tsx": { "toast.success": 4 }, "src/components/mood/manage/tag-manager-card.tsx": { "toast.success": 2 }, "src/components/mood/mood-form.tsx": { "toast.success": 1 }, + // The symptom quick entry confirms a save exactly as the measurement and + // mood forms beside it do. + "src/components/symptoms/symptom-entry-form.tsx": { "toast.success": 1 }, "src/components/mood/mood-list.tsx": { "toast.success": 3 }, "src/components/onboarding/done-screen.tsx": { CheckCircle2: 2 }, "src/components/records/allergy-form.tsx": { "toast.success": 1 }, diff --git a/src/__tests__/v137-wave-zero-fixtures.test.ts b/src/__tests__/v137-wave-zero-fixtures.test.ts index 6206614c8..860b45b45 100644 --- a/src/__tests__/v137-wave-zero-fixtures.test.ts +++ b/src/__tests__/v137-wave-zero-fixtures.test.ts @@ -26,7 +26,7 @@ describe("sharing and handler inventories", () => { }); it("keeps every admitted mutation uniquely addressable and fully controlled", () => { - expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(78); + expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(84); expect( new Set( ADMITTED_MUTATING_HANDLERS.map( diff --git a/src/app/api/__tests__/ai-capability-route-inventory.test.ts b/src/app/api/__tests__/ai-capability-route-inventory.test.ts index a5b256218..2bb7afd8c 100644 --- a/src/app/api/__tests__/ai-capability-route-inventory.test.ts +++ b/src/app/api/__tests__/ai-capability-route-inventory.test.ts @@ -20,6 +20,11 @@ * files (`tests/integration/ai-optional-*.test.ts`) prove behaviour; this * proves no route escapes classification and no data route grows a gate. * + * 5. Every kind of background run (`DOCUMENT_AI_RUN_KINDS`) is queued by a + * route on `AI_ROUTES` that asks the capability the worker asks again for + * that kind (`DOCUMENT_AI_RUN_CAPABILITY`), so a run cannot answer to a + * different switch than the request that started it. + * * Mutation checks (each turned this file red by name): adding * `await requireAiCapability("statusText")` to `insights/ecg/route.ts`; * removing the capability call from `insights/chat/route.ts`; swapping @@ -31,6 +36,11 @@ import { join, relative, resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { AI_CAPABILITY_KEYS } from "@/lib/ai/capabilities/types"; +import { + DOCUMENT_AI_RUN_CAPABILITY, + DOCUMENT_AI_RUN_KINDS, + type DocumentAiRunKindValue, +} from "@/lib/documents/ai-runs/types"; import { AI_ROUTES, DATA_ROUTES } from "./ai-route-inventory"; @@ -154,3 +164,28 @@ describe("AI capability route inventory", () => { expect(both).toEqual([]); }); }); + +/** The route that queues each kind of background run. */ +const RUN_QUEUED_BY: Record = { + DOCUMENT_INDEX: "src/app/api/documents/inbound/[id]/index/route.ts", + LABS_OCR_EXTRACT: "src/app/api/labs/ocr/extract/route.ts", + DOCUMENT_SUMMARY: "src/app/api/documents/inbound/[id]/summary/route.ts", + DOCUMENT_SUGGEST: "src/app/api/documents/inbound/[id]/suggest/route.ts", + DOCUMENT_EXTRACT: "src/app/api/documents/inbound/[id]/extract/route.ts", +}; + +describe("background run kinds", () => { + it.each(DOCUMENT_AI_RUN_KINDS)( + "%s is queued by an AI route under the capability the worker re-checks", + (kind) => { + const path = RUN_QUEUED_BY[kind]; + const entry = AI_ROUTES[path]; + expect(entry, `${path} is not on AI_ROUTES`).toBeDefined(); + expect(entry.capabilities).toContain(DOCUMENT_AI_RUN_CAPABILITY[kind]); + expect( + new RegExp(`kind:\\s*"${kind}"`).test(code(path)), + `${path} does not queue ${kind}`, + ).toBe(true); + }, + ); +}); diff --git a/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts b/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts index ccb39338b..a03e75fe6 100644 --- a/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts +++ b/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts @@ -19,8 +19,11 @@ import { NextRequest } from "next/server"; */ vi.mock("@/lib/db", () => { + // The staging transaction locks the document row and asks again whether + // it may stage (a review can finish while a background read runs). const tx = { - extractedFact: { deleteMany: vi.fn() }, + $queryRaw: vi.fn(async () => [{ status: "STORED" }]), + extractedFact: { deleteMany: vi.fn(), count: vi.fn(async () => 0) }, inboundDocument: { update: vi.fn(), findUniqueOrThrow: vi.fn() }, }; return { @@ -123,7 +126,11 @@ import { AiUnavailableError } from "@/lib/ai/capabilities/refusal"; const tx = ( prisma as unknown as { __tx: { - extractedFact: { deleteMany: ReturnType }; + $queryRaw: ReturnType; + extractedFact: { + deleteMany: ReturnType; + count: ReturnType; + }; inboundDocument: { update: ReturnType; findUniqueOrThrow: ReturnType; @@ -304,6 +311,27 @@ describe("POST /api/documents/inbound/[id]/extract — stored mode", () => { ); }); + it("refuses to stage when a fact was approved while the read ran, keeping the review", async () => { + tx.extractedFact.count.mockResolvedValueOnce(1); + const res = await POST(storedReq("doc-1") as never, ctx("doc-1") as never); + expect(res.status).toBe(409); + const body = await res.json(); + expect(body.meta.errorCode).toBe( + "documents.inbound.alreadyPartlyConfirmed", + ); + expect(tx.extractedFact.deleteMany).not.toHaveBeenCalled(); + expect(tx.inboundDocument.update).not.toHaveBeenCalled(); + }); + + it("refuses to stage when the document was confirmed while the read ran", async () => { + tx.$queryRaw.mockResolvedValueOnce([{ status: "CONFIRMED" }]); + const res = await POST(storedReq("doc-1") as never, ctx("doc-1") as never); + expect(res.status).toBe(422); + const body = await res.json(); + expect(body.meta.errorCode).toBe("documents.inbound.alreadyConfirmed"); + expect(tx.extractedFact.deleteMany).not.toHaveBeenCalled(); + }); + it("422s (notIndexed) without stored text, before any bucket charge", async () => { vi.mocked(loadDocumentChatText).mockResolvedValue(null as never); const res = await POST(storedReq("doc-1") as never, ctx("doc-1") as never); diff --git a/src/app/api/documents/inbound/[id]/extract/route.ts b/src/app/api/documents/inbound/[id]/extract/route.ts index 930d8c895..1fc8338c5 100644 --- a/src/app/api/documents/inbound/[id]/extract/route.ts +++ b/src/app/api/documents/inbound/[id]/extract/route.ts @@ -22,6 +22,15 @@ * The document is UNTRUSTED (prompt-injection): the server never acts on an * instruction inside it. The staged facts land PENDING for the mandatory * review-then-confirm screen; nothing reaches the structured stores here. + * + * v1.40 — `Prefer: respond-async` (RFC 7240) runs the extraction in the + * background worker: every refusal that can be answered quickly is still + * answered here, then the route answers 202 with a run id. The run's result is + * `{ documentId, factsStaged, status }` rather than the whole detail (the + * facts are staged on the document; the client reads them from there). + * Without the header the route behaves exactly as before; the iPhone app + * relies on that. Both paths run one body (`executeDocumentExtract`), which + * re-checks the document under a row lock before it stages anything. */ import { Buffer } from "node:buffer"; @@ -40,24 +49,13 @@ import { AI_BUDGETS } from "@/lib/ai/ai-budgets"; import { requireAiCapability } from "@/lib/ai/capabilities/gate"; import { buildDateKey, - reconcileSpend, reserveBudget, resolveCostOwner, resolveDailyCap, } from "@/lib/ai/coach/budget"; -import { auditLog } from "@/lib/auth/audit"; +import type { ProviderChainType } from "@/lib/ai/provider-chain"; import { prisma } from "@/lib/db"; -import { - InboundExtractError, - runInboundExtraction, - type InboundExtractionResult, -} from "@/lib/documents/extract"; -import { - decryptDocumentContent, - encryptFactData, - encryptFactProvenance, - serialiseDocumentDetail, -} from "@/lib/documents/store"; +import { serialiseDocumentDetail } from "@/lib/documents/store"; import { requireDocumentTextProvider, requireDocumentVisionProvider, @@ -66,73 +64,34 @@ import { checkDocumentAiRateLimit, documentAiRateLimited, DOCUMENT_AI_TEXT_BODY_MAX_BYTES, + loadOwnedDocument, refundDocumentAiSlot, + type LoadedDocument, } from "@/lib/documents/ai-route-support"; +import { + executeDocumentExtract, + type DocumentExtractInput, +} from "@/lib/documents/ai-runs/extract-run"; +import { + acceptedRunResponse, + outcomeResponse, + prefersRespondAsync, +} from "@/lib/documents/ai-runs/http"; +import { findLiveDocumentRun, startAiRun } from "@/lib/documents/ai-runs/start"; +import type { AiRunBudget } from "@/lib/documents/ai-runs/types"; import { loadDocumentChatText } from "@/lib/documents/content-index"; -import { detectOcrMimeType } from "@/lib/labs/ocr-upload"; import { annotate } from "@/lib/logging/context"; import { requireModuleEnabled } from "@/lib/modules/gate"; import { inboundStoredExtractSchema, inboundTextExtractSchema, } from "@/lib/validations/inbound-documents"; -import { dateOnlyAtNoonUtc } from "@/lib/tz/date-only"; export const dynamic = "force-dynamic"; type RouteParams = { params: Promise<{ id: string }> }; -/** A loaded, owner-scoped, still-extractable document row. */ -type LoadedDocument = { - id: string; - kind: string; - contentEncrypted: Uint8Array; - contentCodec: string; - mimeType: string; - status: string; -}; - -/** - * Replace the document's staged facts and flip it to EXTRACTED in one - * transaction. Re-extraction is allowed only when NO fact is APPROVED yet (the - * POST handler refuses it otherwise), so clearing every prior staged fact here - * can never drop an approved row or sever a committed-record provenance link — - * the only facts present are PENDING / REJECTED leftovers from an earlier run. - */ -async function stageExtraction( - documentId: string, - userId: string, - result: InboundExtractionResult, -) { - return prisma.$transaction(async (tx) => { - await tx.extractedFact.deleteMany({ where: { documentId, userId } }); - await tx.inboundDocument.update({ - where: { id: documentId }, - data: { - status: "EXTRACTED", - providerType: result.providerType, - reportDate: result.reportDate - ? dateOnlyAtNoonUtc(result.reportDate) - : null, - facts: { - create: result.facts.map((f) => ({ - userId, - factType: f.factType, - status: "PENDING" as const, - confidence: f.confidence, - needsReview: f.needsReview, - dataEncrypted: encryptFactData(f.data), - provenanceEncrypted: encryptFactProvenance(f.provenance), - })), - }, - }, - }); - return tx.inboundDocument.findUniqueOrThrow({ - where: { id: documentId }, - include: { facts: { orderBy: { createdAt: "asc" } } }, - }); - }); -} +type ExtractInputMode = "text" | "stored" | "vision"; export const POST = apiHandler( async (request: NextRequest, { params }: RouteParams) => { @@ -146,17 +105,7 @@ export const POST = apiHandler( await requireAiCapability("documentAi", { pickDecides: true }); const { id } = await params; - const document = await prisma.inboundDocument.findFirst({ - where: { id, userId: user.id, deletedAt: null }, - select: { - id: true, - kind: true, - contentEncrypted: true, - contentCodec: true, - mimeType: true, - status: true, - }, - }); + const document = await loadOwnedDocument(user.id, id); if (!document) { return apiError("Document not found", 404, { errorCode: "documents.inbound.notFound", @@ -175,7 +124,8 @@ export const POST = apiHandler( // committed-record provenance link — and re-stage the same facts as PENDING, // letting the user approve them a second time and duplicate the committed // lab / condition / medication. Block it: the user must finish reviewing or - // discard the document first. + // discard the document first. Staging asks again under a row lock, because + // a review can finish while the read runs. const approvedCount = await prisma.extractedFact.count({ where: { documentId: document.id, userId: user.id, status: "APPROVED" }, }); @@ -191,6 +141,7 @@ export const POST = apiHandler( ); } + const background = prefersRespondAsync(request); const contentType = request.headers.get("content-type") ?? ""; if (contentType.includes("application/json")) { // One body read for both JSON modes, BEFORE any bucket charge — a @@ -200,20 +151,106 @@ export const POST = apiHandler( }); if (jsonError) return jsonError; if (inboundStoredExtractSchema.safeParse(body).success) { - return handleStoredExtract(request, user.id, document); + return handleStoredExtract(request, user.id, document, background); } - return handleTextExtract(request, user.id, document, body); + return handleTextExtract(request, user.id, document, body, background); } - return handleVisionExtract(request, user.id, document); + return handleVisionExtract(request, user.id, document, background); }, ); +/** + * An extraction of this document from the same input, already queued or + * running: attach to it rather than charge a second one. Background only. + */ +async function liveRunResponse( + userId: string, + documentId: string, + input: ExtractInputMode, +): Promise { + const live = await findLiveDocumentRun( + userId, + documentId, + "DOCUMENT_EXTRACT", + (params) => params.extract?.input === input, + ); + return live ? acceptedRunResponse(live) : null; +} + +/** Reserve the read's budget; null (slot refunded) when the day is spent. */ +async function reserveFor( + userId: string, + providerType: ProviderChainType, + tokens: number, +): Promise { + const dateKey = buildDateKey(); + const reservation = await reserveBudget( + userId, + tokens, + dateKey, + resolveDailyCap([{ providerType }]), + resolveCostOwner([{ providerType }]), + "coach", + ); + if (!reservation.allowed) { + await refundDocumentAiSlot(userId); + return null; + } + return { reserved: reservation.reserved, owner: reservation.owner, dateKey }; +} + +function budgetExceeded(): Response { + return apiError("Your AI usage budget for today is reached.", 429, { + errorCode: "documents.inbound.budgetExceeded", + }); +} + +/** Queue the extraction for the background worker. */ +function queueExtract( + userId: string, + document: LoadedDocument, + input: ExtractInputMode, + budget: AiRunBudget, + text: string | null, +): Promise { + return startAiRun({ + userId, + kind: "DOCUMENT_EXTRACT", + documentId: document.id, + params: { + mode: input === "vision" ? "vision" : "text", + budget, + extract: { input }, + }, + input: text === null ? null : Buffer.from(text, "utf8"), + refundSlot: () => refundDocumentAiSlot(userId), + }); +} + +/** The synchronous path: run the shared body and answer with the detail. */ +async function runNow( + request: NextRequest, + userId: string, + document: LoadedDocument, + input: DocumentExtractInput, +): Promise { + const outcome = await executeDocumentExtract({ + userId, + document, + input, + origin: { ipAddress: getClientIp(request), worker: false }, + }); + if (!outcome.ok) return outcomeResponse(outcome); + return apiSuccess(serialiseDocumentDetail(outcome.data, outcome.data.facts)); +} + /** TEXT mode — structure in-browser-OCR'd text against the stored row. */ async function handleTextExtract( request: NextRequest, userId: string, document: LoadedDocument, body: unknown, + background: boolean, ): Promise { const row = await prisma.user.findUnique({ where: { id: userId }, @@ -228,6 +265,11 @@ async function handleTextExtract( const pick = await requireDocumentTextProvider(userId); + if (background) { + const live = await liveRunResponse(userId, document.id, "text"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); @@ -244,68 +286,22 @@ async function handleTextExtract( ); } - const dateKey = buildDateKey(); - const reservation = await reserveBudget( + const budget = await reserveFor( userId, + pick.entry.providerType, AI_BUDGETS.ocrExtractText.maxTokens, - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); - } + if (!budget) return budgetExceeded(); - try { - const result = await runInboundExtraction({ - provider: pick.entry.instance, - providerType: pick.providerType, - ocrText: parsed.data.text, - }); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - - const updated = await stageExtraction(document.id, userId, result); - - await auditLog("documents.inbound.extract", { - userId, - ipAddress: getClientIp(request), - details: { - documentId: document.id, - facts: updated.facts.length, - mode: "text", - }, - }); - - return apiSuccess(serialiseDocumentDetail(updated, updated.facts)); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - if (err instanceof InboundExtractError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.inbound.extractFailed" }, - meta: { reason: "provider_error", mode: "text" }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", - }); + if (background) { + return queueExtract(userId, document, "text", budget, parsed.data.text); } + return runNow(request, userId, document, { + mode: "text", + text: parsed.data.text, + pick, + budget, + }); } /** @@ -324,6 +320,7 @@ async function handleStoredExtract( request: NextRequest, userId: string, document: LoadedDocument, + background: boolean, ): Promise { const chat = await loadDocumentChatText(userId, document.id); if (!chat || !chat.text.trim()) { @@ -334,71 +331,31 @@ async function handleStoredExtract( const pick = await requireDocumentTextProvider(userId); + if (background) { + const live = await liveRunResponse(userId, document.id, "stored"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); - const dateKey = buildDateKey(); - const reservation = await reserveBudget( + const budget = await reserveFor( userId, + pick.entry.providerType, AI_BUDGETS.ocrExtractText.maxTokens, - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); - } + if (!budget) return budgetExceeded(); - try { - const result = await runInboundExtraction({ - provider: pick.entry.instance, - providerType: pick.providerType, - ocrText: chat.text, - }); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - - const updated = await stageExtraction(document.id, userId, result); - - await auditLog("documents.inbound.extract", { - userId, - ipAddress: getClientIp(request), - details: { - documentId: document.id, - facts: updated.facts.length, - mode: "stored", - }, - }); - - return apiSuccess(serialiseDocumentDetail(updated, updated.facts)); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - if (err instanceof InboundExtractError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.inbound.extractFailed" }, - meta: { reason: "provider_error", mode: "stored" }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", - }); + if (background) { + // The worker loads the stored text itself; nothing is sealed into the run. + return queueExtract(userId, document, "stored", budget, null); } + return runNow(request, userId, document, { + mode: "stored", + text: chat.text, + pick, + budget, + }); } /** VISION mode — run the stored original through the vision provider. */ @@ -406,116 +363,29 @@ async function handleVisionExtract( request: NextRequest, userId: string, document: LoadedDocument, + background: boolean, ): Promise { const pick = await requireDocumentVisionProvider(userId); + if (background) { + const live = await liveRunResponse(userId, document.id, "vision"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); - // Decrypt the stored original and re-derive its MIME from the bytes (never - // trust a stored label for the provider call). Every miss below happens - // before the provider dispatch, so the charged slot goes back. - let buffer: Buffer; - try { - buffer = decryptDocumentContent( - document.contentEncrypted, - document.contentCodec, - ); - } catch { - await refundDocumentAiSlot(userId); - return apiError("Couldn't read the stored document.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - - const mime = detectOcrMimeType(buffer); - if (!mime) { - await refundDocumentAiSlot(userId); - return apiError( - "This document can't be scanned. Use local OCR (text mode).", - 422, - { errorCode: "documents.inbound.fileType" }, - ); - } - - if (mime === "application/pdf" && !pick.pdfSupported) { - await refundDocumentAiSlot(userId); - return apiError( - "PDF scanning needs a Claude vision provider; use local OCR instead.", - 422, - { errorCode: "documents.inbound.pdfNeedsAnthropic" }, - ); - } - - const dateKey = buildDateKey(); - const reservation = await reserveBudget( + const budget = await reserveFor( userId, + pick.entry.providerType, AI_BUDGETS.ocrExtract.maxTokens, - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); - } + if (!budget) return budgetExceeded(); - const dataBase64 = buffer.toString("base64"); - const images = - mime === "application/pdf" ? [] : [{ mediaType: mime, dataBase64 }]; - const documents = - mime === "application/pdf" - ? [{ mediaType: "application/pdf" as const, dataBase64 }] - : []; - - try { - const result = await runInboundExtraction({ - provider: pick.entry.instance, - providerType: pick.providerType, - images, - documents, - }); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - - const updated = await stageExtraction(document.id, userId, result); - - await auditLog("documents.inbound.extract", { - userId, - ipAddress: getClientIp(request), - details: { - documentId: document.id, - facts: updated.facts.length, - mode: "vision", - }, - }); - - return apiSuccess(serialiseDocumentDetail(updated, updated.facts)); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - if (err instanceof InboundExtractError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.inbound.extractFailed" }, - meta: { reason: "provider_error", mode: "vision" }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", - }); + if (background) { + // The worker decrypts the stored original itself, after it has picked + // the provider again and re-checked the wire for it. + return queueExtract(userId, document, "vision", budget, null); } + return runNow(request, userId, document, { mode: "vision", pick, budget }); } diff --git a/src/app/api/documents/inbound/[id]/suggest/route.ts b/src/app/api/documents/inbound/[id]/suggest/route.ts index c361d2929..28ac50c64 100644 --- a/src/app/api/documents/inbound/[id]/suggest/route.ts +++ b/src/app/api/documents/inbound/[id]/suggest/route.ts @@ -11,13 +11,21 @@ * The document is UNTRUSTED (prompt-injection): the server never acts on an * instruction inside it. With no provider configured this 422s the enhancement; * the stored document and the manual edit form are untouched. + * + * v1.40 — `Prefer: respond-async` (RFC 7240) runs the read in the background + * worker: every refusal that can be answered quickly is still answered here, + * then the route answers 202 with a run id and `GET /api/ai-runs/{id}` serves + * the same body this route answers with synchronously. Without the header the + * route behaves exactly as before; the iPhone app relies on that. Both paths + * run one body (`executeDocumentSuggest`). */ +import { Buffer } from "node:buffer"; + import { NextRequest } from "next/server"; import { apiHandler, requireAuth } from "@/lib/api-handler"; import { apiError, - apiSuccess, apiValidationError, getClientIp, safeJson, @@ -25,33 +33,36 @@ import { } from "@/lib/api-response"; import { AI_BUDGETS } from "@/lib/ai/ai-budgets"; import { requireAiCapability } from "@/lib/ai/capabilities/gate"; +import type { ProviderChainType } from "@/lib/ai/provider-chain"; import { buildDateKey, - reconcileSpend, reserveBudget, resolveCostOwner, resolveDailyCap, } from "@/lib/ai/coach/budget"; -import { auditLog } from "@/lib/auth/audit"; -import { - DocumentAssistError, - runDocumentAssist, - type DocumentSuggestion, -} from "@/lib/documents/assist"; import { checkDocumentAiRateLimit, documentAiRateLimited, DOCUMENT_AI_TEXT_BODY_MAX_BYTES, loadOwnedDocument, - prepareVisionInput, refundDocumentAiSlot, type LoadedDocument, } from "@/lib/documents/ai-route-support"; +import { + acceptedRunResponse, + outcomeResponse, + prefersRespondAsync, +} from "@/lib/documents/ai-runs/http"; +import { findLiveDocumentRun, startAiRun } from "@/lib/documents/ai-runs/start"; +import { + executeDocumentSuggest, + type DocumentSuggestInput, +} from "@/lib/documents/ai-runs/suggest-run"; +import type { AiRunBudget } from "@/lib/documents/ai-runs/types"; import { requireDocumentTextProvider, requireDocumentVisionProvider, } from "@/lib/documents/provider-order"; -import { annotate } from "@/lib/logging/context"; import { requireModuleEnabled } from "@/lib/modules/gate"; import { prisma } from "@/lib/db"; import { inboundTextExtractSchema } from "@/lib/validations/inbound-documents"; @@ -79,38 +90,75 @@ export const POST = apiHandler( }); } + const background = prefersRespondAsync(request); const contentType = request.headers.get("content-type") ?? ""; if (contentType.includes("application/json")) { - return handleTextSuggest(request, user.id, document); + return handleTextSuggest(request, user.id, document, background); } - return handleVisionSuggest(request, user.id, document); + return handleVisionSuggest(request, user.id, document, background); }, ); -/** Persist the AI-budget ledger side effect + the audit trail. NEVER the row. */ -async function finishSuggest( - request: NextRequest, +/** + * A suggestion read of this document over the same transport, already queued + * or running: attach to it rather than charge a second one. Background only. + */ +async function liveRunResponse( userId: string, documentId: string, mode: "vision" | "text", - suggestion: DocumentSuggestion, -): Promise { - await auditLog("documents.inbound.suggest", { +): Promise { + const live = await findLiveDocumentRun( userId, - ipAddress: getClientIp(request), - details: { documentId, mode }, + documentId, + "DOCUMENT_SUGGEST", + (params) => params.mode === mode, + ); + return live ? acceptedRunResponse(live) : null; +} + +/** Reserve the read's budget; null (slot refunded) when the day is spent. */ +async function reserveFor( + userId: string, + providerType: ProviderChainType, +): Promise { + const dateKey = buildDateKey(); + const reservation = await reserveBudget( + userId, + AI_BUDGETS.documentAssist.maxTokens, + dateKey, + resolveDailyCap([{ providerType }]), + resolveCostOwner([{ providerType }]), + "coach", + ); + if (!reservation.allowed) { + await refundDocumentAiSlot(userId); + return null; + } + return { reserved: reservation.reserved, owner: reservation.owner, dateKey }; +} + +function budgetExceeded(): Response { + return apiError("Your AI usage budget for today is reached.", 429, { + errorCode: "documents.inbound.budgetExceeded", }); - annotate({ - action: { name: "documents.assist.suggest" }, - meta: { - documentId, - mode, - hasTitle: suggestion.title !== null, - hasKind: suggestion.kind !== null, - hasDate: suggestion.documentDate !== null, - }, - }); - return apiSuccess({ suggestions: suggestion }); +} + +/** The synchronous path: run the shared body inside this request. */ +async function runNow( + request: NextRequest, + userId: string, + document: LoadedDocument, + input: DocumentSuggestInput, +): Promise { + return outcomeResponse( + await executeDocumentSuggest({ + userId, + document, + input, + origin: { ipAddress: getClientIp(request), worker: false }, + }), + ); } /** TEXT mode — suggest from in-browser-OCR'd text (opt-in local OCR). */ @@ -118,6 +166,7 @@ async function handleTextSuggest( request: NextRequest, userId: string, document: LoadedDocument, + background: boolean, ): Promise { const row = await prisma.user.findUnique({ where: { id: userId }, @@ -131,6 +180,11 @@ async function handleTextSuggest( const pick = await requireDocumentTextProvider(userId); + if (background) { + const live = await liveRunResponse(userId, document.id, "text"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); @@ -154,55 +208,28 @@ async function handleTextSuggest( ); } - const dateKey = buildDateKey(); - const reservation = await reserveBudget( - userId, - AI_BUDGETS.documentAssist.maxTokens, - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", - ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", + const budget = await reserveFor(userId, pick.entry.providerType); + if (!budget) return budgetExceeded(); + + if (background) { + // The worker picks the provider again and re-checks the wire for it right + // before the text leaves. + return startAiRun({ + userId, + kind: "DOCUMENT_SUGGEST", + documentId: document.id, + params: { mode: "text", budget }, + input: Buffer.from(parsed.data.text, "utf8"), + refundSlot: () => refundDocumentAiSlot(userId), }); } - try { - const suggestion = await runDocumentAssist({ - provider: pick.entry.instance, - providerType: pick.providerType, - ocrText: parsed.data.text, - }); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - return finishSuggest(request, userId, document.id, "text", suggestion); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - if (err instanceof DocumentAssistError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.assist.failed" }, - meta: { reason: "provider_error", mode: "text" }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", - }); - } + return runNow(request, userId, document, { + mode: "text", + text: parsed.data.text, + pick, + budget, + }); } /** VISION mode — suggest from the stored original via the vision provider. */ @@ -210,83 +237,32 @@ async function handleVisionSuggest( request: NextRequest, userId: string, document: LoadedDocument, + background: boolean, ): Promise { const pick = await requireDocumentVisionProvider(userId); + if (background) { + const live = await liveRunResponse(userId, document.id, "vision"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); - const vision = await prepareVisionInput(document, pick.pdfSupported); - if (!vision.ok) { - // Preparation failed before any provider dispatch — the slot goes back. - await refundDocumentAiSlot(userId); - if (vision.reason === "pdfNeedsAnthropic") { - return apiError( - "PDF scanning needs a Claude vision provider; use local OCR instead.", - 422, - { errorCode: "documents.inbound.pdfNeedsAnthropic" }, - ); - } - if (vision.reason === "fileType") { - return apiError( - "This document can't be scanned. Use local OCR (text mode).", - 422, - { errorCode: "documents.inbound.fileType" }, - ); - } - return apiError("Couldn't read the stored document.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } + const budget = await reserveFor(userId, pick.entry.providerType); + if (!budget) return budgetExceeded(); - const dateKey = buildDateKey(); - const reservation = await reserveBudget( - userId, - AI_BUDGETS.documentAssist.maxTokens, - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", - ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); - } - - try { - const suggestion = await runDocumentAssist({ - provider: pick.entry.instance, - providerType: pick.providerType, - images: vision.images, - documents: vision.documents, - }); - await reconcileSpend( + if (background) { + // The worker decrypts the stored original itself, after it has picked + // the provider again and re-checked the wire for it. + return startAiRun({ userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - return finishSuggest(request, userId, document.id, "vision", suggestion); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - if (err instanceof DocumentAssistError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.assist.failed" }, - meta: { reason: "provider_error", mode: "vision" }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", + kind: "DOCUMENT_SUGGEST", + documentId: document.id, + params: { mode: "vision", budget }, + refundSlot: () => refundDocumentAiSlot(userId), }); } + + return runNow(request, userId, document, { mode: "vision", pick, budget }); } diff --git a/src/app/api/documents/inbound/[id]/summary/route.ts b/src/app/api/documents/inbound/[id]/summary/route.ts index e9e785df7..9c2c7c484 100644 --- a/src/app/api/documents/inbound/[id]/summary/route.ts +++ b/src/app/api/documents/inbound/[id]/summary/route.ts @@ -18,7 +18,18 @@ * Same VISION/TEXT dispatch and gauntlet as the extract route. The document is * UNTRUSTED (prompt-injection): the server never acts on an instruction inside * it. With no provider configured this 422s; nothing is stored either way. + * + * v1.40 — `Prefer: respond-async` (RFC 7240) runs the read in the background + * worker: every refusal that can be answered quickly is still answered here, + * then the route answers 202 with a run id and `GET /api/ai-runs/{id}` serves + * the same body this route answers with synchronously. A summary that is to + * be stored marks the document PENDING while it is queued. Without the header + * the route behaves exactly as before; the iPhone app relies on that. Both + * paths run one body (`executeDocumentSummary`). A transcription of text the + * browser already read calls no model and is answered here either way. */ +import { Buffer } from "node:buffer"; + import { NextRequest } from "next/server"; import { apiHandler, requireAuth } from "@/lib/api-handler"; @@ -32,9 +43,9 @@ import { } from "@/lib/api-response"; import { AI_BUDGETS } from "@/lib/ai/ai-budgets"; import { requireAiCapability } from "@/lib/ai/capabilities/gate"; +import type { ProviderChainType } from "@/lib/ai/provider-chain"; import { buildDateKey, - reconcileSpend, reserveBudget, resolveCostOwner, resolveDailyCap, @@ -45,19 +56,23 @@ import { documentAiRateLimited, DOCUMENT_AI_TEXT_BODY_MAX_BYTES, loadOwnedDocument, - prepareVisionInput, refundDocumentAiSlot, type LoadedDocument, } from "@/lib/documents/ai-route-support"; import { - DocumentDescribeError, - runDocumentSummary, - documentSummaryBlockedCopy, - transcribeDocument, - type DescribeInput, -} from "@/lib/documents/describe"; -import { encryptDocumentSummary } from "@/lib/documents/store"; -import type { OutboundReason } from "@/lib/ai/safety/outbound-screen"; + acceptedRunResponse, + outcomeResponse, + prefersRespondAsync, +} from "@/lib/documents/ai-runs/http"; +import { findLiveDocumentRun, startAiRun } from "@/lib/documents/ai-runs/start"; +import { + executeDocumentSummary, + markSummaryQueued, + type DocumentSummaryInput, + type SummaryPersistence, +} from "@/lib/documents/ai-runs/summary-run"; +import type { AiRunBudget, AiRunParams } from "@/lib/documents/ai-runs/types"; +import { transcribeDocument } from "@/lib/documents/describe"; import { requireDocumentTextProvider, requireDocumentVisionProvider, @@ -78,11 +93,15 @@ export const dynamic = "force-dynamic"; type RouteParams = { params: Promise<{ id: string }> }; -type SummaryPersistenceTarget = { +/** What one request asks for, read once from the query and the headers. */ +interface SummaryRequest { userId: string; - documentId: string; - replaceExisting: boolean; -}; + document: LoadedDocument; + mode: DocumentSummaryMode; + locale: Locale; + persist: SummaryPersistence | null; + background: boolean; +} function resolveMode(request: NextRequest): DocumentSummaryMode { const raw = new URL(request.url).searchParams.get("mode"); @@ -98,100 +117,6 @@ function resolveReplaceExisting(request: NextRequest): boolean { return new URL(request.url).searchParams.get("replace") === "true"; } -/** - * Run the requested describe call (summary or raw text) over the input. - * - * Ordinary action-row summaries and raw transcription remain session-only. - * The document summary block opts into persistence so an empty document can be - * repaired and an existing stored summary can be explicitly regenerated. - */ -async function describe( - mode: DocumentSummaryMode, - input: DescribeInput, - locale: Locale, - persist: SummaryPersistenceTarget | null, -): Promise< - | { - summary: string; - persistence?: "stored" | "withheld" | "failed"; - } - | { text: string } -> { - if (mode === "text") return transcribeDocument(input); - // A normal summary request fills an empty slot only. Replacement is reserved - // for the document detail's explicit "Generate again" action. - const { summary, blocked } = await runDocumentSummary({ ...input, locale }); - const persistence = persist - ? await persistSummary(persist, summary, blocked) - : undefined; - return { - summary: blocked ? documentSummaryBlockedCopy(locale) : summary, - ...(persistence ? { persistence } : {}), - }; -} - -/** - * Store a screened-clean summary, or record the refusal as a state. - * - * A blocked summary NEVER lands as text — the honest statement the caller shows - * is generated copy for this response, not the model's prose, and persisting it - * would put a refusal where a summary belongs. Only the WITHHELD state is kept, - * and it is not terminal: the user can ask again. - * - * Storing is best-effort. The user is waiting on the summary they can already - * read in the response; a failed write must not turn that into an error. - */ -async function persistSummary( - target: SummaryPersistenceTarget, - summary: string, - blocked: OutboundReason | null, -): Promise<"stored" | "withheld" | "failed"> { - try { - if (blocked) { - await prisma.inboundDocument.updateMany({ - where: { - id: target.documentId, - userId: target.userId, - deletedAt: null, - summaryState: { not: "READY" }, - }, - // An explicit request is the person reading it on purpose, so an - // import's hold on automatic AI reading ends here. - data: { summaryState: "WITHHELD", aiReadDeferred: false }, - }); - return "withheld"; - } - // Preserve a previously stored summary unless the caller explicitly chose - // the replacement action. Failed or screened attempts never reach this - // write, so the previous clean summary remains available in those cases. - const written = await prisma.inboundDocument.updateMany({ - where: { - id: target.documentId, - userId: target.userId, - deletedAt: null, - ...(target.replaceExisting ? {} : { summaryEncrypted: null }), - }, - data: { - summaryEncrypted: encryptDocumentSummary(summary), - summaryGeneratedAt: new Date(), - summaryState: "READY", - aiReadDeferred: false, - }, - }); - annotate({ - action: { name: "documents.summary.persisted" }, - meta: { documentId: target.documentId, stored: written.count > 0 }, - }); - return written.count > 0 ? "stored" : "failed"; - } catch { - annotate({ - action: { name: "documents.summary.persistFailed" }, - meta: { documentId: target.documentId }, - }); - return blocked ? "withheld" : "failed"; - } -} - /** The budget the requested mode charges. */ function budgetFor(mode: DocumentSummaryMode): number { return mode === "text" @@ -219,13 +144,11 @@ export const POST = apiHandler( } const mode = resolveMode(request); - const persist: SummaryPersistenceTarget | null = + // A normal summary request fills an empty slot only. Replacement is + // reserved for the document detail's explicit "Generate again" action. + const persist: SummaryPersistence | null = mode === "summary" && resolvePersistRequested(request) - ? { - userId: user.id, - documentId: document.id, - replaceExisting: resolveReplaceExisting(request), - } + ? { replaceExisting: resolveReplaceExisting(request) } : null; // The outbound screen on the summary needs the reader's locale to pick its // pattern banks; resolve it once here and thread it into both describe legs. @@ -233,57 +156,112 @@ export const POST = apiHandler( request, userLocale: user.locale ?? null, }); - const contentType = request.headers.get("content-type") ?? ""; - if (contentType.includes("application/json")) { - return handleTextSummary( - request, - user.id, - document, - mode, - locale, - persist, - ); - } - return handleVisionSummary( - request, - user.id, + const ask: SummaryRequest = { + userId: user.id, document, mode, locale, persist, - ); + background: prefersRespondAsync(request), + }; + const contentType = request.headers.get("content-type") ?? ""; + if (contentType.includes("application/json")) { + return handleTextSummary(request, ask); + } + return handleVisionSummary(request, ask); }, ); -async function finishSummary( - request: NextRequest, - userId: string, - documentId: string, +/** The run parameters for this request (never health data). */ +function runParams( + ask: SummaryRequest, inputMode: "vision" | "text", - mode: DocumentSummaryMode, - result: { summary: string } | { text: string }, + budget: AiRunBudget, +): AiRunParams { + return { + mode: inputMode, + budget, + summary: { + output: ask.mode, + persist: ask.persist !== null, + replace: ask.persist?.replaceExisting ?? false, + locale: ask.locale, + }, + }; +} + +/** + * A run that will produce the same thing, already queued or running: attach + * to it rather than charge a second one. Background path only. + */ +async function liveRunResponse( + ask: SummaryRequest, + inputMode: "vision" | "text", +): Promise { + const live = await findLiveDocumentRun( + ask.userId, + ask.document.id, + "DOCUMENT_SUMMARY", + (params) => + params.mode === inputMode && + params.summary?.output === ask.mode && + params.summary.persist === (ask.persist !== null) && + params.summary.replace === (ask.persist?.replaceExisting ?? false), + ); + return live ? acceptedRunResponse(live) : null; +} + +/** Reserve the read's budget; null (slot refunded) when the day is spent. */ +async function reserveFor( + ask: SummaryRequest, + providerType: ProviderChainType, +): Promise { + const dateKey = buildDateKey(); + const reservation = await reserveBudget( + ask.userId, + budgetFor(ask.mode), + dateKey, + resolveDailyCap([{ providerType }]), + resolveCostOwner([{ providerType }]), + "coach", + ); + if (!reservation.allowed) { + await refundDocumentAiSlot(ask.userId); + return null; + } + return { reserved: reservation.reserved, owner: reservation.owner, dateKey }; +} + +function budgetExceeded(): Response { + return apiError("Your AI usage budget for today is reached.", 429, { + errorCode: "documents.inbound.budgetExceeded", + }); +} + +/** Queue the read; a summary that is to be stored is marked PENDING first. */ +async function queueSummary( + ask: SummaryRequest, + inputMode: "vision" | "text", + budget: AiRunBudget, + text: string | null, ): Promise { - await auditLog("documents.inbound.summary", { - userId, - ipAddress: getClientIp(request), - details: { documentId, mode, inputMode }, + if (ask.persist) await markSummaryQueued(ask.userId, ask.document.id); + return startAiRun({ + userId: ask.userId, + kind: "DOCUMENT_SUMMARY", + documentId: ask.document.id, + params: runParams(ask, inputMode, budget), + input: text === null ? null : Buffer.from(text, "utf8"), + refundSlot: () => refundDocumentAiSlot(ask.userId), }); - annotate({ - action: { name: "documents.summary.serve" }, - meta: { documentId, mode, inputMode }, - }); - return apiSuccess(result); } /** TEXT mode — summarise / echo in-browser-OCR'd text. */ async function handleTextSummary( request: NextRequest, - userId: string, - document: LoadedDocument, - mode: DocumentSummaryMode, - locale: Locale, - persist: SummaryPersistenceTarget | null, + ask: SummaryRequest, ): Promise { + const { userId, document, mode } = ask; const row = await prisma.user.findUnique({ where: { id: userId }, select: { labsLocalOcrEnabled: true }, @@ -294,6 +272,11 @@ async function handleTextSummary( }); } + if (ask.background && mode !== "text") { + const live = await liveRunResponse(ask, "text"); + if (live) return live; + } + const rl = await checkDocumentAiRateLimit(userId); if (!rl.allowed) return documentAiRateLimited(rl); @@ -319,13 +302,24 @@ async function handleTextSummary( // `mode=text` over posted OCR text is a pure echo — the text IS the // transcription. No provider egress, no consent, no budget: session-only. + // There is nothing to run in the background, so the preference is not + // applied and the answer comes straight back. if (mode === "text") { const result = await transcribeDocument({ provider: {} as never, providerType: "local-ocr", ocrText: parsed.data.text, }); - return finishSummary(request, userId, document.id, "text", mode, result); + await auditLog("documents.inbound.summary", { + userId, + ipAddress: getClientIp(request), + details: { documentId: document.id, mode, inputMode: "text" }, + }); + annotate({ + action: { name: "documents.summary.serve" }, + meta: { documentId: document.id, mode, inputMode: "text" }, + }); + return apiSuccess(result); } let pick: Awaited>; @@ -337,145 +331,65 @@ async function handleTextSummary( throw err; } - const dateKey = buildDateKey(); - const reservation = await reserveBudget( - userId, - budgetFor(mode), - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", - ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); + const budget = await reserveFor(ask, pick.entry.providerType); + if (!budget) return budgetExceeded(); + + if (ask.background) { + // The worker picks the provider again and re-checks the wire for it right + // before the text leaves. + return queueSummary(ask, "text", budget, parsed.data.text); } - try { - const result = await describe( - mode, - { - provider: pick.entry.instance, - providerType: pick.providerType, - ocrText: parsed.data.text, - }, - locale, - persist, - ); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - return finishSummary(request, userId, document.id, "text", mode, result); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - return summaryError(err, "text"); - } + return runNow(request, ask, { + mode: "text", + text: parsed.data.text, + pick, + budget, + }); } /** VISION mode — summarise / transcribe the stored original. */ async function handleVisionSummary( request: NextRequest, - userId: string, - document: LoadedDocument, - mode: DocumentSummaryMode, - locale: Locale, - persist: SummaryPersistenceTarget | null, + ask: SummaryRequest, ): Promise { - const pick = await requireDocumentVisionProvider(userId); + const pick = await requireDocumentVisionProvider(ask.userId); - const rl = await checkDocumentAiRateLimit(userId); + if (ask.background) { + const live = await liveRunResponse(ask, "vision"); + if (live) return live; + } + + const rl = await checkDocumentAiRateLimit(ask.userId); if (!rl.allowed) return documentAiRateLimited(rl); - const vision = await prepareVisionInput(document, pick.pdfSupported); - if (!vision.ok) { - // Preparation failed before any provider dispatch — the slot goes back. - await refundDocumentAiSlot(userId); - if (vision.reason === "pdfNeedsAnthropic") { - return apiError( - "PDF scanning needs a Claude vision provider; use local OCR instead.", - 422, - { errorCode: "documents.inbound.pdfNeedsAnthropic" }, - ); - } - if (vision.reason === "fileType") { - return apiError( - "This document can't be scanned. Use local OCR (text mode).", - 422, - { errorCode: "documents.inbound.fileType" }, - ); - } - return apiError("Couldn't read the stored document.", 422, { - errorCode: "documents.inbound.extractFailed", - }); + const budget = await reserveFor(ask, pick.entry.providerType); + if (!budget) return budgetExceeded(); + + if (ask.background) { + // The worker decrypts the stored original itself, after it has picked + // the provider again and re-checked the wire for it. + return queueSummary(ask, "vision", budget, null); } - const dateKey = buildDateKey(); - const reservation = await reserveBudget( - userId, - budgetFor(mode), - dateKey, - resolveDailyCap([{ providerType: pick.entry.providerType }]), - resolveCostOwner([{ providerType: pick.entry.providerType }]), - "coach", + return runNow(request, ask, { mode: "vision", pick, budget }); +} + +/** The synchronous path: run the shared body inside this request. */ +async function runNow( + request: NextRequest, + ask: SummaryRequest, + input: DocumentSummaryInput, +): Promise { + return outcomeResponse( + await executeDocumentSummary({ + userId: ask.userId, + document: ask.document, + input, + output: ask.mode, + locale: ask.locale, + persist: ask.persist, + origin: { ipAddress: getClientIp(request), worker: false }, + }), ); - if (!reservation.allowed) { - await refundDocumentAiSlot(userId); - return apiError("Your AI usage budget for today is reached.", 429, { - errorCode: "documents.inbound.budgetExceeded", - }); - } - - try { - const result = await describe( - mode, - { - provider: pick.entry.instance, - providerType: pick.providerType, - images: vision.images, - documents: vision.documents, - }, - locale, - persist, - ); - await reconcileSpend( - userId, - reservation.reserved, - reservation.reserved, - dateKey, - 0, - { servedBy: pick.entry.providerType, reservedOwner: reservation.owner }, - ); - return finishSummary(request, userId, document.id, "vision", mode, result); - } catch (err) { - await reconcileSpend(userId, reservation.reserved, 0, dateKey, 0, { - servedBy: null, - reservedOwner: reservation.owner, - }); - return summaryError(err, "vision"); - } -} - -function summaryError(err: unknown, mode: "vision" | "text"): Response { - if (err instanceof DocumentDescribeError) { - return apiError("Couldn't read the document. Try a clearer copy.", 422, { - errorCode: "documents.inbound.extractFailed", - }); - } - annotate({ - action: { name: "documents.summary.failed" }, - meta: { reason: "provider_error", mode }, - }); - return apiError("Couldn't read the document. Try a clearer copy.", 502, { - errorCode: "documents.inbound.extractFailed", - }); } diff --git a/src/app/api/export/__tests__/per-type-routes.test.ts b/src/app/api/export/__tests__/per-type-routes.test.ts index 3fa921aee..392263eff 100644 --- a/src/app/api/export/__tests__/per-type-routes.test.ts +++ b/src/app/api/export/__tests__/per-type-routes.test.ts @@ -74,6 +74,7 @@ vi.mock("@/lib/db", () => ({ documentConditionLink: { findMany: vi.fn().mockResolvedValue([]) }, extractedFact: { findMany: vi.fn().mockResolvedValue([]) }, ecgRecording: { findMany: vi.fn().mockResolvedValue([]) }, + symptomDefinition: { findMany: vi.fn().mockResolvedValue([]) }, // v1.15.0 — cycle tables read by the full-backup helper. cycleProfile: { findUnique: vi.fn() }, menstrualCycle: { findMany: vi.fn() }, @@ -169,6 +170,7 @@ beforeEach(() => { vi.mocked(prisma.coachPlan.findMany).mockResolvedValue([] as never); vi.mocked(prisma.coachReminder.findMany).mockResolvedValue([] as never); vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([] as never); + vi.mocked(prisma.symptomDefinition.findMany).mockResolvedValue([] as never); vi.mocked(prisma.moodTagCategory.findMany).mockResolvedValue([] as never); vi.mocked(prisma.moodTagHidden.findMany).mockResolvedValue([] as never); vi.mocked(prisma.mentalHealthAssessment.findMany).mockResolvedValue( diff --git a/src/app/api/export/__tests__/soft-delete-filter.test.ts b/src/app/api/export/__tests__/soft-delete-filter.test.ts index d0d5da720..0e04c6bba 100644 --- a/src/app/api/export/__tests__/soft-delete-filter.test.ts +++ b/src/app/api/export/__tests__/soft-delete-filter.test.ts @@ -75,6 +75,7 @@ vi.mock("@/lib/db", () => ({ documentConditionLink: { findMany: vi.fn() }, extractedFact: { findMany: vi.fn() }, ecgRecording: { findMany: vi.fn() }, + symptomDefinition: { findMany: vi.fn() }, onboardingRecord: { findUnique: vi.fn().mockResolvedValue(null) }, environmentTravelLocation: { findMany: vi.fn().mockResolvedValue([]) }, environmentContext: { findMany: vi.fn().mockResolvedValue([]) }, @@ -211,6 +212,7 @@ beforeEach(() => { ); vi.mocked(prisma.extractedFact.findMany).mockResolvedValue([] as never); vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([] as never); + vi.mocked(prisma.symptomDefinition.findMany).mockResolvedValue([] as never); vi.mocked(prisma.userAchievement.findMany).mockResolvedValue([] as never); }); diff --git a/src/app/api/export/encrypted/__tests__/route.test.ts b/src/app/api/export/encrypted/__tests__/route.test.ts index d83552725..8c01d3a7b 100644 --- a/src/app/api/export/encrypted/__tests__/route.test.ts +++ b/src/app/api/export/encrypted/__tests__/route.test.ts @@ -66,6 +66,7 @@ vi.mock("@/lib/db", () => ({ documentConditionLink: { findMany: vi.fn().mockResolvedValue([]) }, extractedFact: { findMany: vi.fn().mockResolvedValue([]) }, ecgRecording: { findMany: vi.fn().mockResolvedValue([]) }, + symptomDefinition: { findMany: vi.fn().mockResolvedValue([]) }, cycleProfile: { findUnique: vi.fn().mockResolvedValue(null) }, menstrualCycle: { findMany: vi.fn().mockResolvedValue([]) }, cycleDayLog: { findMany: vi.fn().mockResolvedValue([]) }, diff --git a/src/app/api/insights/correlations/__tests__/route.test.ts b/src/app/api/insights/correlations/__tests__/route.test.ts index 47fa6a4a2..42413f24f 100644 --- a/src/app/api/insights/correlations/__tests__/route.test.ts +++ b/src/app/api/insights/correlations/__tests__/route.test.ts @@ -31,6 +31,7 @@ vi.mock("@/lib/db", () => ({ // channel produces a point. environmentContext: { findMany: vi.fn().mockResolvedValue([]) }, customMetric: { findMany: vi.fn().mockResolvedValue([]) }, + symptomDefinition: { findMany: vi.fn().mockResolvedValue([]) }, }, })); @@ -153,6 +154,7 @@ beforeEach(() => { prisma.environmentContext.findMany as ReturnType ).mockResolvedValue([]); vi.mocked(prisma.customMetric.findMany).mockResolvedValue([] as never); + vi.mocked(prisma.symptomDefinition.findMany).mockResolvedValue([] as never); }); const callGet = GET as unknown as (req: NextRequest) => Promise; diff --git a/src/app/api/insights/correlations/route.ts b/src/app/api/insights/correlations/route.ts index f93c5262f..c94021409 100644 --- a/src/app/api/insights/correlations/route.ts +++ b/src/app/api/insights/correlations/route.ts @@ -236,6 +236,7 @@ async function buildCorrelationsResponse( // available for the scan. environment_days: diagnostics.environmentDays, custom_metric_channels: diagnostics.customMetricChannels, + symptom_event_channels: diagnostics.symptomEventChannels, custom_metric_days: diagnostics.customMetricDays, }, }); diff --git a/src/app/api/measurements/series/__tests__/route.test.ts b/src/app/api/measurements/series/__tests__/route.test.ts index cd220128a..37146ef82 100644 --- a/src/app/api/measurements/series/__tests__/route.test.ts +++ b/src/app/api/measurements/series/__tests__/route.test.ts @@ -9,6 +9,9 @@ vi.mock("@/lib/db", () => ({ // v1.28.25 — dense kinds (glucose / pulse) day-bucket in SQL for // windows beyond the 90-day raw cap. $queryRaw: vi.fn(), + // The series reads go through the ladder-winning source per day (see + // `seriesRowsFrom`), which is raw SQL with the user id as `$1`. + $queryRawUnsafe: vi.fn(), }, })); @@ -65,8 +68,47 @@ function req(query: string): NextRequest { return new NextRequest(`http://localhost/api/measurements/series?${query}`); } +/** + * The route reads its series through `$queryRawUnsafe` (the ladder-winning + * source per day). This file's fixtures are written as rows per type and as the + * two aggregate results, so the adapter routes each statement back to them: + * the day/hour bucket and the stats aggregate take the next `$queryRaw` result, + * and a raw read asks `findMany` for the type named in the SQL and returns the + * rows in the column names the statement selects. The SQL itself (which source + * wins, which rows count) is covered against a real database in + * `tests/integration/series-source-ladder.test.ts`. + */ +function adaptSeriesSql(sql: string): Promise { + if (/GROUP BY local_day|STDDEV_POP/.test(sql)) { + return (prisma.$queryRaw as unknown as () => Promise)(); + } + const type = /'([A-Z0-9_]+)'::"measurement_type"/.exec(sql)?.[1]; + const find = prisma.measurement.findMany as unknown as ( + a: unknown, + ) => Promise< + Array<{ + id: string; + value: number; + measuredAt: Date; + valueMin?: number | null; + valueMax?: number | null; + }> + >; + return find({ where: { type } }).then((rows) => + rows.map((r) => ({ + id: r.id, + value: r.value, + measured_at: r.measuredAt, + value_min: r.valueMin ?? null, + value_max: r.valueMax ?? null, + })), + ); +} + beforeEach(() => { vi.resetAllMocks(); + vi.mocked(prisma.$queryRawUnsafe).mockImplementation(((sql: string) => + adaptSeriesSql(sql)) as never); vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never); vi.mocked(prisma.measurement.count).mockResolvedValue(0 as never); vi.mocked(prisma.$queryRaw).mockResolvedValue([] as never); @@ -216,14 +258,14 @@ describe("GET /api/measurements/series", () => { expect(body.data.points[1].valueMin).toBeNull(); expect(body.data.points[1].valueMax).toBeNull(); - // The pulse read selects the spread columns. - const selectArg = vi.mocked(prisma.measurement.findMany).mock.calls[0][0]; - expect( - (selectArg as { select: Record }).select.valueMin, - ).toBe(true); - expect( - (selectArg as { select: Record }).select.valueMax, - ).toBe(true); + // The pulse read selects the spread columns, and reads the pulse rows of + // this person's ladder-winning source (the user id is the first parameter). + const [sql, userId] = vi.mocked(prisma.$queryRawUnsafe).mock + .calls[0] as unknown as [string, string]; + expect(sql).toContain('m."value_min"'); + expect(sql).toContain('m."value_max"'); + expect(sql).toContain(`'PULSE'::"measurement_type"`); + expect(userId).toBe("user-1"); }); it("collapses sleep stage rows into one night point in hours (v1.11.4)", async () => { @@ -627,8 +669,12 @@ describe("GET /api/measurements/series — dense-kind day-bucketing (v1.28.25)", expect(body.data.stats.count).toBe(43_200); expect(body.data.stats.mean).toBe(72.1); // The bucket read folds per hour, not per day. - const bucketSql = vi.mocked(prisma.$queryRaw).mock.calls[0] as unknown[]; - expect(bucketSql.slice(1)).toContain("hour"); + const bucketCall = vi + .mocked(prisma.$queryRawUnsafe) + .mock.calls.find(([sql]) => + /GROUP BY local_day/.test(sql as string), + ) as unknown[]; + expect(bucketCall.slice(1)).toContain("hour"); }); it("hour-buckets a CGM glucose window too dense to send raw, in the user's unit", async () => { @@ -690,8 +736,12 @@ describe("GET /api/measurements/series — dense-kind day-bucketing (v1.28.25)", max: 14.4, stdDev: 2, }); - const bucketSql = vi.mocked(prisma.$queryRaw).mock.calls[0] as unknown[]; - expect(bucketSql.slice(1)).toContain("hour"); + const bucketCall = vi + .mocked(prisma.$queryRawUnsafe) + .mock.calls.find(([sql]) => + /GROUP BY local_day/.test(sql as string), + ) as unknown[]; + expect(bucketCall.slice(1)).toContain("hour"); }); it("keeps fingerstick glucose at or under the row cap raw", async () => { diff --git a/src/app/api/measurements/series/__tests__/unknown-query-param-open.test.ts b/src/app/api/measurements/series/__tests__/unknown-query-param-open.test.ts index d51eda7e9..b852744ff 100644 --- a/src/app/api/measurements/series/__tests__/unknown-query-param-open.test.ts +++ b/src/app/api/measurements/series/__tests__/unknown-query-param-open.test.ts @@ -22,6 +22,7 @@ vi.mock("@/lib/db", () => ({ user: { findUnique: vi.fn() }, auditLog: { create: vi.fn() }, $queryRaw: vi.fn(), + $queryRawUnsafe: vi.fn(), }, })); @@ -74,6 +75,7 @@ beforeEach(() => { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never); vi.mocked(prisma.$queryRaw).mockResolvedValue([] as never); + vi.mocked(prisma.$queryRawUnsafe).mockResolvedValue([] as never); vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never); vi.mocked(prisma.user.findUnique).mockResolvedValue({ glucoseUnit: "mg/dL", diff --git a/src/app/api/measurements/series/route.ts b/src/app/api/measurements/series/route.ts index f42afb47c..35b22894e 100644 --- a/src/app/api/measurements/series/route.ts +++ b/src/app/api/measurements/series/route.ts @@ -26,6 +26,7 @@ import type { MeasurementType, SleepStage } from "@/generated/prisma/client"; import { reconstructSleepNights } from "@/lib/analytics/sleep-night"; import { VALUE_RANGES } from "@/lib/validations/measurement"; import { loadUserSourcePriority } from "@/lib/rollups/measurement-read"; +import { seriesRowsFrom } from "@/lib/measurements/series-canonical"; import { resolveUserTimezone, userDayKey } from "@/lib/tz/resolver"; import { convertGlucose, resolveGlucoseUnit } from "@/lib/glucose"; @@ -399,49 +400,57 @@ export const GET = apiHandler(async (request: NextRequest) => { // v1.28.25 — long-window read of a sample-dense kind (CGM glucose, // per-sample / hourly pulse). Day-bucket in SQL instead of walking // every raw row into JS: one aggregate pass in Postgres returns at - // most `days` rows regardless of sample density. Parameter-bound - // tagged-template `$queryRaw`, mirroring the rollup tier's - // `date_trunc(... ) GROUP BY` aggregate (measurement-rollups.ts). - const userTz = await resolveUserTimezone(user.id); + // most `days` rows regardless of sample density. Bound parameters + // mirror the rollup tier's `date_trunc(... ) GROUP BY` aggregate + // (measurement-rollups.ts), and the rows are the ladder-winning source per + // day, the same rule the rollup tier and sleep apply. + const [userTz, priorityJson] = await Promise.all([ + resolveUserTimezone(user.id), + loadUserSourcePriority(user.id), + ]); const type = KIND_TO_TYPE[kind]; - const bucketRows = await prisma.$queryRaw< + const seriesRows = seriesRowsFrom(priorityJson, type, days); + const bucketRows = await prisma.$queryRawUnsafe< Array<{ bucket_start: Date; mean: number; min_value: number; max_value: number; }> - >` + >( + ` WITH localized AS ( SELECT m."value", m."value_min", m."value_max", date_trunc( - ${grain}, - (m."measured_at" AT TIME ZONE 'UTC') AT TIME ZONE ${userTz} + $2, + (m."measured_at" AT TIME ZONE 'UTC') AT TIME ZONE $3 ) AS local_day - FROM measurements m - WHERE m."user_id" = ${user.id} - AND m."type" = ${type}::"measurement_type" - AND m."measured_at" >= ${since} - AND m."deleted_at" IS NULL + FROM ${seriesRows} + WHERE m."measured_at" >= $4 ) SELECT - local_day AT TIME ZONE ${userTz} AS bucket_start, + local_day AT TIME ZONE $3 AS bucket_start, AVG("value")::double precision AS mean, MIN(COALESCE("value_min", "value"))::double precision AS min_value, MAX(COALESCE("value_max", "value"))::double precision AS max_value FROM localized GROUP BY local_day ORDER BY bucket_start ASC - `; + `, + user.id, + grain, + userTz, + since, + ); // Stats stay aggregated over the RAW rows (not the day buckets) so the // strip's mean/min/max/stdDev/count are the same figures the raw path // computed: `AVG`/`MIN`/`MAX` over `value`, `STDDEV_POP` matching the // JS population-variance helper, exact row count. Aggregate-only — // no row transfer. - const [rawAgg] = await prisma.$queryRaw< + const [rawAgg] = await prisma.$queryRawUnsafe< Array<{ n: number; mean: number | null; @@ -449,19 +458,20 @@ export const GET = apiHandler(async (request: NextRequest) => { max: number | null; sd: number | null; }> - >` + >( + ` SELECT COUNT(*)::int AS n, AVG(m."value")::double precision AS mean, MIN(m."value")::double precision AS min, MAX(m."value")::double precision AS max, STDDEV_POP(m."value")::double precision AS sd - FROM measurements m - WHERE m."user_id" = ${user.id} - AND m."type" = ${type}::"measurement_type" - AND m."measured_at" >= ${since} - AND m."deleted_at" IS NULL - `; + FROM ${seriesRows} + WHERE m."measured_at" >= $2 + `, + user.id, + since, + ); const round2 = (v: number) => Math.round(v * 100) / 100; const dayId = (d: Date) => grain === "day" @@ -538,21 +548,37 @@ export const GET = apiHandler(async (request: NextRequest) => { // hourly average. Only PULSE rows ever carry a non-null spread (the // hourly HR bucket); every other kind selects the bare value shape. const includeSpread = kind === "pulse"; - const rows = await prisma.measurement.findMany({ - where: { - userId: user.id, - type, - measuredAt: { gte: since }, - deletedAt: null, - }, - orderBy: { measuredAt: "asc" }, - select: { - id: true, - value: true, - measuredAt: true, - ...(includeSpread ? { valueMin: true, valueMax: true } : {}), - }, - }); + // The ladder-winning source per day (see `seriesRowsFrom`), so a second + // provider neither blends into nor duplicates the series. Bounded as before: + // every dense kind reaches this read only inside 90 days and under 10 000 + // rows (counted first), and the sparse kinds are a few readings a day. + const sourcePriority = await loadUserSourcePriority(user.id); + const rawRows = await prisma.$queryRawUnsafe< + Array<{ + id: string; + value: number; + measured_at: Date; + value_min: number | null; + value_max: number | null; + }> + >( + ` + SELECT m."id", m."value", m."measured_at", m."value_min", m."value_max" + FROM ${seriesRowsFrom(sourcePriority, type, days)} + WHERE m."measured_at" >= $2 + ORDER BY m."measured_at" ASC, m."id" ASC + `, + user.id, + since, + ); + const rows = rawRows.map((r) => ({ + id: r.id, + value: r.value, + measuredAt: r.measured_at, + ...(includeSpread + ? { valueMin: r.value_min, valueMax: r.value_max } + : {}), + })); if (kind === "glucose") { // v1.16.16 — glucose is stored canonical mg/dL; convert each point to // the user's display unit AT SERIALIZATION so the wire DTO is unit- diff --git a/src/app/api/symptoms/definitions/[id]/route.ts b/src/app/api/symptoms/definitions/[id]/route.ts new file mode 100644 index 000000000..e578f4a30 --- /dev/null +++ b/src/app/api/symptoms/definitions/[id]/route.ts @@ -0,0 +1,232 @@ +/** + * One person-defined symptom (v1.40). + * + * PATCH /api/symptoms/definitions/{id} — rename, change the icon, reorder, + * hide or show again. Showing a hidden one re-clears the cap. + * DELETE /api/symptoms/definitions/{id} — hide by default (history kept); + * `?purge=true` deletes the definition and every event of it. + * + * Owner-scoped: another account's id is a 404. Module-gated on the record. + * The label is never logged. + */ +import { NextRequest } from "next/server"; + +import { prisma } from "@/lib/db"; +import { + apiSuccess, + apiError, + getClientIp, + returnAllZodIssues, + safeJson, +} from "@/lib/api-response"; +import { apiHandler, requireRecordAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { auditLog } from "@/lib/auth/audit"; +import { + destroyedDetails, + overwriteDetails, +} from "@/lib/sharing/audit-details"; +import { invalidateUserHealthContext } from "@/lib/cache/invalidate"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { requireIllnessEnabled } from "@/lib/illness/gate"; +import { + encryptSymptomText, + symptomDefinitionUpdateSchema, + toSymptomDefinitionDTO, + MAX_ACTIVE_SYMPTOM_DEFINITIONS, +} from "@/lib/symptoms/server"; + +export const dynamic = "force-dynamic"; + +type RouteParams = { params: Promise<{ id: string }> }; + +function notFound(): Response { + return apiError("Symptom not found", 404, { + errorCode: "symptoms.definition.notFound", + }); +} + +export const PATCH = apiHandler( + async (request: NextRequest, { params }: RouteParams) => { + const { user, actor } = await requireRecordAuth("manage", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const rl = await checkRateLimit( + `symptoms:definition:${actor.id}`, + 30, + 60_000, + ); + if (!rl.allowed) { + return apiError("Too many requests, try again later", 429); + } + + const { id } = await params; + const { data: rawBody, error: jsonError } = await safeJson(request, { + maxBytes: 16 * 1024, + }); + if (jsonError) return jsonError; + const parsed = symptomDefinitionUpdateSchema.safeParse(rawBody); + if (!parsed.success) { + return returnAllZodIssues(parsed.error, 422, { + errorCode: "symptoms.invalid", + }); + } + + const existing = await prisma.symptomDefinition.findFirst({ + where: { id, userId: user.id }, + select: { id: true, icon: true, isActive: true, sortOrder: true }, + }); + if (!existing) return notFound(); + + // A hidden definition does not hold a slot; showing it again takes one. + if (parsed.data.isActive === true && !existing.isActive) { + const activeCount = await prisma.symptomDefinition.count({ + where: { userId: user.id, isActive: true }, + }); + if (activeCount >= MAX_ACTIVE_SYMPTOM_DEFINITIONS) { + return apiError( + `Symptom limit reached (${MAX_ACTIVE_SYMPTOM_DEFINITIONS})`, + 422, + { + errorCode: "symptoms.definition.limitReached", + limit: MAX_ACTIVE_SYMPTOM_DEFINITIONS, + }, + ); + } + } + + const updated = await prisma.symptomDefinition.update({ + where: { id: existing.id }, + data: { + ...(parsed.data.label !== undefined + ? { labelEncrypted: encryptSymptomText(parsed.data.label) } + : {}), + ...(parsed.data.icon !== undefined ? { icon: parsed.data.icon } : {}), + ...(parsed.data.isActive !== undefined + ? { isActive: parsed.data.isActive } + : {}), + ...(parsed.data.sortOrder !== undefined + ? { sortOrder: parsed.data.sortOrder } + : {}), + }, + select: { + id: true, + labelEncrypted: true, + icon: true, + sortOrder: true, + isActive: true, + }, + }); + + await auditLog("symptoms.definition.update", { + userId: user.id, + ipAddress: getClientIp(request), + details: { + definitionId: id, + ...overwriteDetails({ + before: { + icon: existing.icon, + isActive: existing.isActive, + sortOrder: existing.sortOrder, + }, + after: { + icon: updated.icon, + isActive: updated.isActive, + sortOrder: updated.sortOrder, + }, + redacted: parsed.data.label !== undefined ? ["label"] : [], + }), + }, + }); + + // Hiding or showing one changes the correlation channel set and the + // Coach's symptom block. + if (parsed.data.isActive !== undefined) + invalidateUserHealthContext(user.id); + + annotate({ + action: { + name: "symptoms.definition.update", + entity_type: "symptom_definition", + entity_id: id, + }, + }); + + return apiSuccess(toSymptomDefinitionDTO(updated)); + }, +); + +export const DELETE = apiHandler( + async (request: NextRequest, { params }: RouteParams) => { + const { user, actor } = await requireRecordAuth("manage", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const rl = await checkRateLimit( + `symptoms:definition:${actor.id}`, + 30, + 60_000, + ); + if (!rl.allowed) { + return apiError("Too many requests, try again later", 429); + } + + const { id } = await params; + const existing = await prisma.symptomDefinition.findFirst({ + where: { id, userId: user.id }, + select: { + id: true, + createdAt: true, + _count: { select: { events: true } }, + }, + }); + if (!existing) return notFound(); + + const purge = request.nextUrl.searchParams.get("purge") === "true"; + if (purge) { + // The FK cascade removes the events with it. + await prisma.symptomDefinition.delete({ where: { id: existing.id } }); + } else { + await prisma.symptomDefinition.update({ + where: { id: existing.id }, + data: { isActive: false }, + }); + } + + await auditLog("symptoms.definition.delete", { + userId: user.id, + ipAddress: getClientIp(request), + // C3 on the purge arm: the definition and its events are gone, so the + // audit row names what went. The label stays out (the person's words). + details: purge + ? destroyedDetails({ + model: "SymptomDefinition", + id, + label: null, + effectiveAt: existing.createdAt, + extra: { eventsDeleted: existing._count.events }, + }) + : { definitionId: id, purge }, + }); + + invalidateUserHealthContext(user.id); + + annotate({ + action: { + name: "symptoms.definition.delete", + entity_type: "symptom_definition", + entity_id: id, + }, + meta: { purge }, + }); + + return apiSuccess({ + deleted: true, + purged: purge, + eventsDeleted: purge ? existing._count.events : 0, + }); + }, +); diff --git a/src/app/api/symptoms/definitions/route.ts b/src/app/api/symptoms/definitions/route.ts new file mode 100644 index 000000000..ddcc7df04 --- /dev/null +++ b/src/app/api/symptoms/definitions/route.ts @@ -0,0 +1,139 @@ +/** + * Person-defined symptoms (v1.40). + * + * GET /api/symptoms/definitions — the record's own symptom list with a + * 30-day summary per symptom. `?includeHidden=true` adds hidden ones. + * POST /api/symptoms/definitions — define one (`{ label, icon? }`). At most + * eight active definitions; the label is encrypted at rest. + * + * Rides the illness module: an account (or instance) with it off answers 403 + * `illness.disabled` even to a valid Bearer token. The label is the person's + * own words for a health complaint, so it never reaches an audit row or a + * wide event. + */ +import { NextRequest } from "next/server"; + +import { prisma } from "@/lib/db"; +import { + apiSuccess, + apiError, + getClientIp, + returnAllZodIssues, + safeJson, +} from "@/lib/api-response"; +import { apiHandler, requireRecordAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { withIdempotency } from "@/lib/idempotency"; +import { auditLog } from "@/lib/auth/audit"; +import { checkRateLimit } from "@/lib/rate-limit"; +import { requireIllnessEnabled } from "@/lib/illness/gate"; +import { + encryptSymptomText, + listSymptomDefinitions, + symptomDefinitionCreateSchema, + toSymptomDefinitionDTO, + MAX_ACTIVE_SYMPTOM_DEFINITIONS, +} from "@/lib/symptoms/server"; + +export const dynamic = "force-dynamic"; + +export const GET = apiHandler(async (request: NextRequest) => { + const { user } = await requireRecordAuth("read", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const includeHidden = + request.nextUrl.searchParams.get("includeHidden") === "true"; + const definitions = await listSymptomDefinitions(user.id, { includeHidden }); + + annotate({ + action: { name: "symptoms.definition.list" }, + meta: { count: definitions.length, includeHidden }, + }); + + return apiSuccess({ definitions, limit: MAX_ACTIVE_SYMPTOM_DEFINITIONS }); +}); + +/** + * Wrapped in `withIdempotency`: the label is ciphertext under a fresh IV, so + * no unique index can catch a replayed create, and a retry after a lost + * response would otherwise mint a second "aura" and burn a slot of eight. + */ +export const POST = apiHandler(withIdempotency<[NextRequest]>(postDefinition)); + +async function postDefinition(request: NextRequest): Promise { + // MANAGE, like the cycle module's own symptom list: the vocabulary of a + // record is the owner's, a delegate who may log an occurrence picks from it. + const { user, actor } = await requireRecordAuth("manage", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const rl = await checkRateLimit( + `symptoms:definition:${actor.id}`, + 30, + 60_000, + ); + if (!rl.allowed) { + return apiError("Too many requests, try again later", 429); + } + + const { data: rawBody, error: jsonError } = await safeJson(request, { + maxBytes: 16 * 1024, + }); + if (jsonError) return jsonError; + const parsed = symptomDefinitionCreateSchema.safeParse(rawBody); + if (!parsed.success) { + return returnAllZodIssues(parsed.error, 422, { + errorCode: "symptoms.invalid", + }); + } + + const activeCount = await prisma.symptomDefinition.count({ + where: { userId: user.id, isActive: true }, + }); + if (activeCount >= MAX_ACTIVE_SYMPTOM_DEFINITIONS) { + return apiError( + `Symptom limit reached (${MAX_ACTIVE_SYMPTOM_DEFINITIONS})`, + 422, + { + errorCode: "symptoms.definition.limitReached", + limit: MAX_ACTIVE_SYMPTOM_DEFINITIONS, + }, + ); + } + + const created = await prisma.symptomDefinition.create({ + data: { + userId: user.id, + labelEncrypted: encryptSymptomText(parsed.data.label), + icon: parsed.data.icon ?? null, + sortOrder: activeCount, + }, + select: { + id: true, + labelEncrypted: true, + icon: true, + sortOrder: true, + isActive: true, + }, + }); + + await auditLog("symptoms.definition.create", { + userId: user.id, + ipAddress: getClientIp(request), + details: { definitionId: created.id, icon: created.icon }, + }); + + annotate({ + action: { + name: "symptoms.definition.create", + entity_type: "symptom_definition", + entity_id: created.id, + }, + meta: { icon: created.icon }, + }); + + return apiSuccess(toSymptomDefinitionDTO(created), 201); +} diff --git a/src/app/api/symptoms/events/[id]/route.ts b/src/app/api/symptoms/events/[id]/route.ts new file mode 100644 index 000000000..82928b38a --- /dev/null +++ b/src/app/api/symptoms/events/[id]/route.ts @@ -0,0 +1,192 @@ +/** + * One occurrence of a person-defined symptom (v1.40). + * + * PATCH /api/symptoms/events/{id} — change the time, intensity, note or + * episode link. A new link must name an open episode of the record; + * an unchanged link to an episode that has since resolved is kept. + * DELETE /api/symptoms/events/{id} — remove it. + * + * Owner-scoped (another account's id is a 404), module-gated on the record, + * MANAGE on a shared record. The note is never logged. + */ +import { NextRequest } from "next/server"; + +import { prisma } from "@/lib/db"; +import { + apiSuccess, + apiError, + getClientIp, + returnAllZodIssues, + safeJson, +} from "@/lib/api-response"; +import { apiHandler, requireRecordAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { auditLog } from "@/lib/auth/audit"; +import { + destroyedDetails, + overwriteDetails, +} from "@/lib/sharing/audit-details"; +import { invalidateUserHealthContext } from "@/lib/cache/invalidate"; +import { requireIllnessEnabled } from "@/lib/illness/gate"; +import { + encryptSymptomText, + isLinkableEpisode, + symptomEventUpdateSchema, + toSymptomEventDTO, +} from "@/lib/symptoms/server"; + +export const dynamic = "force-dynamic"; + +type RouteParams = { params: Promise<{ id: string }> }; + +function notFound(): Response { + return apiError("Symptom event not found", 404, { + errorCode: "symptoms.event.notFound", + }); +} + +export const PATCH = apiHandler( + async (request: NextRequest, { params }: RouteParams) => { + const { user } = await requireRecordAuth("manage", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const { id } = await params; + const { data: rawBody, error: jsonError } = await safeJson(request, { + maxBytes: 16 * 1024, + }); + if (jsonError) return jsonError; + const parsed = symptomEventUpdateSchema.safeParse(rawBody); + if (!parsed.success) { + return returnAllZodIssues(parsed.error, 422, { + errorCode: "symptoms.invalid", + }); + } + const entry = parsed.data; + + const existing = await prisma.symptomEvent.findFirst({ + where: { id, userId: user.id }, + select: { + id: true, + occurredAt: true, + intensity: true, + episodeId: true, + }, + }); + if (!existing) return notFound(); + + if ( + entry.episodeId && + entry.episodeId !== existing.episodeId && + !(await isLinkableEpisode(user.id, entry.episodeId)) + ) { + return apiError("Episode is not open", 422, { + errorCode: "symptoms.episode.notOpen", + }); + } + + const updated = await prisma.symptomEvent.update({ + where: { id: existing.id }, + data: { + ...(entry.occurredAt !== undefined + ? { occurredAt: entry.occurredAt } + : {}), + ...(entry.intensity !== undefined + ? { intensity: entry.intensity } + : {}), + ...(entry.note !== undefined + ? { + noteEncrypted: entry.note ? encryptSymptomText(entry.note) : null, + } + : {}), + ...(entry.episodeId !== undefined + ? { episodeId: entry.episodeId ?? null } + : {}), + }, + }); + + await auditLog("symptoms.event.update", { + userId: user.id, + ipAddress: getClientIp(request), + details: { + eventId: id, + ...overwriteDetails({ + before: { + occurredAt: existing.occurredAt, + intensity: existing.intensity, + episodeId: existing.episodeId, + }, + after: { + occurredAt: updated.occurredAt, + intensity: updated.intensity, + episodeId: updated.episodeId, + }, + redacted: entry.note !== undefined ? ["note"] : [], + }), + }, + }); + + invalidateUserHealthContext(user.id); + + annotate({ + action: { + name: "symptoms.event.update", + entity_type: "symptom_event", + entity_id: id, + }, + }); + + return apiSuccess(toSymptomEventDTO(updated)); + }, +); + +export const DELETE = apiHandler( + async (request: NextRequest, { params }: RouteParams) => { + const { user } = await requireRecordAuth("manage", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const { id } = await params; + const existing = await prisma.symptomEvent.findFirst({ + where: { id, userId: user.id }, + select: { + id: true, + definitionId: true, + occurredAt: true, + intensity: true, + }, + }); + if (!existing) return notFound(); + + await prisma.symptomEvent.delete({ where: { id: existing.id } }); + + await auditLog("symptoms.event.delete", { + userId: user.id, + ipAddress: getClientIp(request), + // C3: the row is gone after this; the audit row says what it was. The + // symptom's name is the person's own words and stays out of it, so the + // label is the definition id. + details: destroyedDetails({ + model: "SymptomEvent", + id, + label: existing.definitionId, + effectiveAt: existing.occurredAt, + extra: { intensity: existing.intensity }, + }), + }); + + invalidateUserHealthContext(user.id); + + annotate({ + action: { + name: "symptoms.event.delete", + entity_type: "symptom_event", + entity_id: id, + }, + }); + + return apiSuccess({ deleted: true }); + }, +); diff --git a/src/app/api/symptoms/events/route.ts b/src/app/api/symptoms/events/route.ts new file mode 100644 index 000000000..447502a0b --- /dev/null +++ b/src/app/api/symptoms/events/route.ts @@ -0,0 +1,166 @@ +/** + * Occurrences of person-defined symptoms (v1.40). + * + * GET /api/symptoms/events — newest first, optionally narrowed by + * `from` / `to` (ISO instants), `definitionId` and `episodeId`; at most + * 500 per page. + * POST /api/symptoms/events — log one (`{ definitionId, intensity, + * occurredAt?, note?, episodeId? }`). `occurredAt` defaults to now and + * may not lie in the future beyond the shared five-minute skew; + * `episodeId` must name one of the record's own episodes that is still + * open. The note is encrypted at rest. + * + * Module-gated on the record (`illness.disabled`). `userId` comes from auth + * and is never a body field. + */ +import { NextRequest } from "next/server"; + +import { prisma } from "@/lib/db"; +import { + apiSuccess, + apiError, + getClientIp, + returnAllZodIssues, + safeJson, +} from "@/lib/api-response"; +import { apiHandler, requireRecordAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { withIdempotency } from "@/lib/idempotency"; +import { auditLog } from "@/lib/auth/audit"; +import { invalidateUserHealthContext } from "@/lib/cache/invalidate"; +import { requireIllnessEnabled } from "@/lib/illness/gate"; +import type { Prisma } from "@/generated/prisma/client"; +import { + encryptSymptomText, + isLinkableEpisode, + symptomEventCreateSchema, + symptomEventListQuerySchema, + toSymptomEventDTO, +} from "@/lib/symptoms/server"; + +export const dynamic = "force-dynamic"; + +export const GET = apiHandler(async (request: NextRequest) => { + const { user } = await requireRecordAuth("read", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const sp = request.nextUrl.searchParams; + const parsed = symptomEventListQuerySchema.safeParse({ + from: sp.get("from") ?? undefined, + to: sp.get("to") ?? undefined, + definitionId: sp.get("definitionId") ?? undefined, + episodeId: sp.get("episodeId") ?? undefined, + limit: sp.get("limit") ?? undefined, + }); + if (!parsed.success) { + return returnAllZodIssues(parsed.error, 422, { + errorCode: "symptoms.invalid", + }); + } + const q = parsed.data; + + const occurredAt: Prisma.DateTimeFilter = {}; + if (q.from) occurredAt.gte = new Date(q.from); + if (q.to) occurredAt.lte = new Date(q.to); + + const rows = await prisma.symptomEvent.findMany({ + where: { + userId: user.id, + ...(q.from || q.to ? { occurredAt } : {}), + ...(q.definitionId ? { definitionId: q.definitionId } : {}), + ...(q.episodeId ? { episodeId: q.episodeId } : {}), + }, + orderBy: [{ occurredAt: "desc" }, { id: "desc" }], + take: q.limit, + }); + + annotate({ + action: { name: "symptoms.event.list" }, + meta: { count: rows.length, limit: q.limit }, + }); + + return apiSuccess({ + events: rows.map(toSymptomEventDTO), + limit: q.limit, + hasMore: rows.length === q.limit, + }); +}); + +// A retry from a flaky connection re-sends the same `Idempotency-Key` and gets +// the first answer back instead of a second occurrence at the same minute. +export const POST = apiHandler(withIdempotency<[NextRequest]>(postEvent)); + +async function postEvent(request: NextRequest): Promise { + // WRITE, like opening an episode or adding a reading: logging what happened + // is an admitted delegated write; editing or removing it is MANAGE. + const { user } = await requireRecordAuth("write", "illness"); + + const gate = await requireIllnessEnabled(user.id); + if (!gate.enabled) return gate.response; + + const { data: rawBody, error: jsonError } = await safeJson(request, { + maxBytes: 16 * 1024, + }); + if (jsonError) return jsonError; + const parsed = symptomEventCreateSchema.safeParse(rawBody); + if (!parsed.success) { + return returnAllZodIssues(parsed.error, 422, { + errorCode: "symptoms.invalid", + }); + } + const entry = parsed.data; + + // A hidden definition stays loggable from an older client's cached list; + // only another account's id (or none) is refused. + const definition = await prisma.symptomDefinition.findFirst({ + where: { id: entry.definitionId, userId: user.id }, + select: { id: true }, + }); + if (!definition) { + return apiError("Symptom not found", 404, { + errorCode: "symptoms.definition.notFound", + }); + } + + if (entry.episodeId && !(await isLinkableEpisode(user.id, entry.episodeId))) { + return apiError("Episode is not open", 422, { + errorCode: "symptoms.episode.notOpen", + }); + } + + const created = await prisma.symptomEvent.create({ + data: { + userId: user.id, + definitionId: definition.id, + occurredAt: entry.occurredAt ?? new Date(), + intensity: entry.intensity, + noteEncrypted: entry.note ? encryptSymptomText(entry.note) : null, + episodeId: entry.episodeId ?? null, + }, + }); + + await auditLog("symptoms.event.create", { + userId: user.id, + ipAddress: getClientIp(request), + details: { + eventId: created.id, + definitionId: created.definitionId, + linked: created.episodeId !== null, + }, + }); + + invalidateUserHealthContext(user.id); + + annotate({ + action: { + name: "symptoms.event.create", + entity_type: "symptom_event", + entity_id: created.id, + }, + meta: { linked: created.episodeId !== null }, + }); + + return apiSuccess(toSymptomEventDTO(created), 201); +} diff --git a/src/components/admin/backups-section.tsx b/src/components/admin/backups-section.tsx index bcd8cca24..3a0550cc5 100644 --- a/src/components/admin/backups-section.tsx +++ b/src/components/admin/backups-section.tsx @@ -461,6 +461,9 @@ function catalogueLabel( if (catalogue === "ecgReference") { return t("admin.section.backups.restoreSkippedEcgReference"); } + if (catalogue === "symptomEpisodeReference") { + return t("admin.section.backups.restoreSkippedSymptomEpisodeReference"); + } if (catalogue === "medicationTarget") { return t("admin.section.backups.restoreSkippedMedicationTarget"); } diff --git a/src/components/dashboard/__tests__/dashboard-header.test.tsx b/src/components/dashboard/__tests__/dashboard-header.test.tsx index 0e5579c44..ab0909ef2 100644 --- a/src/components/dashboard/__tests__/dashboard-header.test.tsx +++ b/src/components/dashboard/__tests__/dashboard-header.test.tsx @@ -153,7 +153,8 @@ describe(" — every entry follows its module, as the capture p { mood: false }, { medications: false }, { workouts: false }, - { mood: false, medications: false, workouts: false }, + { illness: false }, + { mood: false, medications: false, workouts: false, illness: false }, ]; for (const modules of cases) { modulesRef.value = modules; @@ -170,6 +171,7 @@ describe(" — every entry follows its module, as the capture p measurement: "Log measurement", medication: "Log medication intake", mood: "Log mood", + symptom: "Log symptom", workout: "Log workout", } as const; for (const kind of CAPTURE_KIND_ORDER) { diff --git a/src/components/dashboard/dashboard-header.tsx b/src/components/dashboard/dashboard-header.tsx index db6ad7cc0..c969eb495 100644 --- a/src/components/dashboard/dashboard-header.tsx +++ b/src/components/dashboard/dashboard-header.tsx @@ -12,7 +12,15 @@ */ import { useMemo } from "react"; import Link from "next/link"; -import { Activity, Footprints, Pill, Plus, Waves, Wrench } from "lucide-react"; +import { + Activity, + Footprints, + Pill, + Plus, + Stethoscope, + Waves, + Wrench, +} from "lucide-react"; import { Button } from "@/components/ui/button"; import { DropdownMenu, @@ -62,6 +70,7 @@ export function DashboardHeader({ const canAddMeasurement = offered.includes("measurement"); const canAddIntake = offered.includes("medication"); const canAddMood = offered.includes("mood"); + const canAddSymptom = offered.includes("symptom"); const canAddWorkout = offered.includes("workout"); const canAddAnything = offered.length > 0; @@ -198,6 +207,12 @@ export function DashboardHeader({ {t("dashboard.quickAddMedicationIntake")} )} + {canAddSymptom && ( + onQuickEntry("symptom")}> + + )} {canAddWorkout && ( onQuickEntry("workout")}>