mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
feat(medications): store a supplement's composition, read its label with the document AI, and carry it through backup and restore
This commit is contained in:
1 parent
98d64c2052
commit
eb3cc4237f
28 files changed
+1078
-97
No files matched your search
@@ -115,6 +115,11 @@ const EGRESS_SITES: Record<string, EgressSite> = {
|
||||
reason:
|
||||
"Document extraction/indexing; reached from the document routes and the index jobs, which resolve `documentAi` first.",
|
||||
},
|
||||
"lib/medications/ingredients/label-extract.ts": {
|
||||
recheck: false,
|
||||
reason:
|
||||
"Supplement label read (v1.43); reached from the background run worker (`lib/jobs/document-ai-run.ts`), which re-checks `supplementLabel` for the picked provider, for a label the ingredients extract route queued under that capability.",
|
||||
},
|
||||
"lib/labs/ocr-extract.ts": {
|
||||
recheck: false,
|
||||
reason:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* v1.43 — pair guard binding the `MedicationIngredient` model to both ends of
|
||||
* the backup: the writer's `ingredients: m.ingredients.map(...)` block in
|
||||
* `full-backup-payload.ts` and the nested create in `restore-backup.ts`.
|
||||
*
|
||||
* The failure it catches is the one the measurement guard beside it was
|
||||
* written for: a column added to the composition in a later release, the
|
||||
* writer or the restore left as "the follow-up", the payload schema's
|
||||
* `.passthrough()` swallowing it, and the column coming back empty on every
|
||||
* restored row. The column-by-column round trip
|
||||
* (`tests/integration/backup-round-trip.test.ts`) proves the same against a
|
||||
* database; this is the fast edge of it that runs with the unit suite.
|
||||
*
|
||||
* Mutation check: delete `enteredUnit: i.enteredUnit,` from the writer and the
|
||||
* first leg names `enteredUnit`; delete `source: i.source,` from the restore
|
||||
* and the second leg names `source`.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const read = (...parts: string[]) => readFileSync(join(ROOT, ...parts), "utf8");
|
||||
|
||||
/**
|
||||
* Columns neither end carries, each with its reason.
|
||||
* - `userId`: re-derived from the restoring account.
|
||||
* - `medicationId`: the rows are nested in their medication on both ends, so
|
||||
* the restore binds them to whatever id the medication got.
|
||||
* - `updatedAt`: `@updatedAt`, stamped by the restore's own write.
|
||||
*/
|
||||
const EXCLUDED: Record<string, string> = {
|
||||
userId: "owner re-derived from the restoring account",
|
||||
medicationId: "nested in its medication; bound by the nested create",
|
||||
updatedAt: "@updatedAt; stamped by the restore's write",
|
||||
};
|
||||
|
||||
function modelColumns(): string[] {
|
||||
const schema = read("prisma", "schema.prisma");
|
||||
const start = schema.indexOf("model MedicationIngredient {");
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const block = schema.slice(start, schema.indexOf("\n}", start));
|
||||
const out: string[] = [];
|
||||
for (const raw of block.split("\n").slice(1)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith("//") || line.startsWith("@@")) continue;
|
||||
const m = /^([a-zA-Z_]\w*)\s+([A-Za-z_]\w*)/.exec(line);
|
||||
if (!m || line.includes("@relation")) continue;
|
||||
out.push(m[1]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The keys one end's ingredient block names, read off `<key>: i.<field>`. */
|
||||
function blockKeys(source: string, opener: string): Set<string> {
|
||||
const start = source.indexOf(opener);
|
||||
expect(start, `${opener} not found`).toBeGreaterThan(-1);
|
||||
const end = source.indexOf("})),", start);
|
||||
expect(end).toBeGreaterThan(start);
|
||||
const body = source.slice(start, end);
|
||||
return new Set(
|
||||
[...body.matchAll(/\b([a-zA-Z_]\w*):\s*(?:i\.|new Date\(i\.)/g)].map(
|
||||
(m) => m[1],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe("medication ingredient backup completeness", () => {
|
||||
const columns = modelColumns();
|
||||
const carried = columns.filter((c) => !(c in EXCLUDED));
|
||||
|
||||
it("reads the model's columns", () => {
|
||||
expect(columns).toEqual(
|
||||
expect.arrayContaining(["nutrient", "amountPerUnit", "enteredUnit"]),
|
||||
);
|
||||
for (const key of Object.keys(EXCLUDED)) expect(columns).toContain(key);
|
||||
});
|
||||
|
||||
it("the writer carries every column", () => {
|
||||
const keys = blockKeys(
|
||||
read("src", "lib", "export", "full-backup-payload.ts"),
|
||||
"ingredients: m.ingredients.map((i) => ({",
|
||||
);
|
||||
expect(carried.filter((c) => !keys.has(c))).toEqual([]);
|
||||
});
|
||||
|
||||
it("the restore writes every column back", () => {
|
||||
const keys = blockKeys(
|
||||
read("src", "lib", "export", "restore-backup.ts"),
|
||||
"create: m.ingredients.map((i) => ({",
|
||||
);
|
||||
expect(carried.filter((c) => !keys.has(c))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1101,6 +1101,10 @@ const DELEGABLE_ROUTES: Record<string, DelegableEntry> = {
|
||||
domain: "medications",
|
||||
why: "One medication of the record, fetch-then-guard against the resolved user before anything is serialised.",
|
||||
},
|
||||
"app/api/medications/[id]/ingredients/route.ts": {
|
||||
domain: "medications",
|
||||
why: "One medication's composition per unit (v1.43), behind the ownership check against the resolved record. The PUT is the route's only verb and is manage-level; the label read beside it stays owner-only, because provider work is never admitted inside somebody else's record.",
|
||||
},
|
||||
"app/api/medications/[id]/cadence/route.ts": {
|
||||
domain: "medications",
|
||||
why: "One medication's cadence, behind `assertMedicationOwnership(id, user.id)` — the shared guard, resolved against the record.",
|
||||
@@ -1762,6 +1766,11 @@ const DELEGABLE_MANAGE_ROUTES: Record<string, ManageEntry> = {
|
||||
conditions: ["C4", "C7"],
|
||||
why: "Replacing a medication and its schedule. C4, and C7 because the previous cadence and the tombstoned pending slots are the only unrecoverable part. The DELETE beside it stays refused.",
|
||||
},
|
||||
"app/api/medications/[id]/ingredients/route.ts": {
|
||||
domain: "medications",
|
||||
conditions: ["C1", "C4"],
|
||||
why: "Replacing a supplement's composition (v1.43), which rewrites what every taken dose adds to the record's micronutrients. C1, and C4 because the replaced composition is filed as one comparable line. The recompute it queues is arithmetic, not generation.",
|
||||
},
|
||||
"app/api/medications/[id]/schedule-revisions/route.ts": {
|
||||
domain: "medications",
|
||||
conditions: [],
|
||||
@@ -2117,8 +2126,12 @@ const ACTOR_ROUTES: Record<string, string> = {
|
||||
* facts (`profile`) and the nutrient catalogue beside the nutrient reads
|
||||
* (`measurements`). The biomarker DELETE joins the manage literal on a module
|
||||
* that was already there. 256 -> 258.
|
||||
*
|
||||
* v1.43 -- a supplement's composition joins the record list and the manage
|
||||
* literal: its PUT replaces the composition every taken dose counts with.
|
||||
* 258 -> 260.
|
||||
*/
|
||||
const FROZEN_ENTRY_COUNT = 258;
|
||||
const FROZEN_ENTRY_COUNT = 260;
|
||||
|
||||
/**
|
||||
* The two surfaces that authenticate a Bearer token outside `requireAuth` —
|
||||
@@ -2879,7 +2892,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(88);
|
||||
expect(ADMITTED_MUTATING_HANDLERS.length).toBe(89);
|
||||
|
||||
const expected = ADMITTED_MUTATING_HANDLERS.map(
|
||||
({ handlerModule, action, level }) =>
|
||||
|
||||
@@ -26,7 +26,7 @@ describe("sharing and handler inventories", () => {
|
||||
});
|
||||
|
||||
it("keeps every admitted mutation uniquely addressable and fully controlled", () => {
|
||||
expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(88);
|
||||
expect(ADMITTED_MUTATING_HANDLERS).toHaveLength(89);
|
||||
expect(
|
||||
new Set(
|
||||
ADMITTED_MUTATING_HANDLERS.map(
|
||||
|
||||
Reference in new issue
Block a user