mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(glp1): match side-effect tags by key, not by an English/German word list
The GLP-1 side-effect chips in the mood form write the localised label into the flat `MoodEntry.tags` column, and three readers matched that label against a hand-written list of English and German words: the therapy timeline, the Coach snapshot, and the doctor report's GLP-1 block. The app ships six locales. Tap the nausea chip with the UI in French, Spanish, Italian or Polish and the day never reached the timeline, the Coach grounded its answers on an empty side-effect list, and a clinician read an empty table over a record that had three months of symptoms. Nothing on any of those surfaces said the table was a filter rather than the truth. The three lists had also drifted apart from each other. The chips are a closed set with stable keys, so matching the label was the defect and the key is the fix. `glp1-side-effect-tags.ts` holds the catalogue — seven keys, each with the i18n key its chip renders — and the mood form now draws its strip from it, so the write side and the read side cannot diverge again. `glp1-side-effect-tag-match.ts` builds the label-to-key index by reading `messages/<locale>.json` for every entry in `locales`, rather than transcribing the labels into a second list. Transcribing would have fixed today's four locales and reopened the same hole on the day a seventh is added; deriving means a new bundle is matchable as soon as it lands, with no edit in the matcher. Comparison folds case, accents and separators, so the English and German tags already in the database keep resolving and a straight apostrophe matches the typographic one the French bundle uses. All three readers now report the catalogue key instead of the stored string. The same recorded symptom yields one key whatever language it was tagged in, which also fixes the mixed-language output an account gets after switching UI locale; the doctor-report PDF resolves the key through the label map so the clinician reads it in the report's language. A tag outside the catalogue is still never counted — a free-text mood tag must not reach a doctor as an invented symptom, and the rest of somebody's day does not belong on a therapy timeline. It is no longer dropped without trace: the timeline route annotates the unresolved count on its wide event, so the classification rate stays answerable while the tag text stays in the database. The Coach's copy of the list also carried `vomiting`, `reflux` and `erbrechen`. Those are removed. No chip writes them, so they only ever matched a hand-typed tag in two of six languages; keeping them would have rebuilt the defect inside its own fix. Restoring either symptom means giving it a chip and a label in all six bundles. The response schema for `GET /api/insights/glp1-timeline` now enumerates the keys, and its description no longer documents the bilingual match as if it were the contract.
This commit is contained in:
1 parent
b76468f455
commit
97d0c26ceb
14 files changed
+833
-167
No files matched your search
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* `GET /api/insights/glp1-timeline` — the reported surface.
|
||||
*
|
||||
* A side-effect day was assembled by matching the stored mood tag against a
|
||||
* hand-written English/German word list. Tap the nausea chip with the UI in
|
||||
* French, Spanish, Italian or Polish and the day never appeared on the
|
||||
* timeline: a thinner therapy history, with nothing anywhere saying why.
|
||||
*
|
||||
* The property asserted here is equality, not presence — a tag recorded in any
|
||||
* shipped locale contributes exactly what the English one does.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
medicationFindMany: vi.fn(),
|
||||
moodFindMany: vi.fn(),
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: (handler: unknown) => handler,
|
||||
requireRecordAuth: vi.fn(async () => ({
|
||||
user: { id: "user-1" },
|
||||
actor: { id: "user-1" },
|
||||
grantId: null,
|
||||
})),
|
||||
}));
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: mocks.annotate }));
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medication: { findMany: mocks.medicationFindMany },
|
||||
moodEntry: { findMany: mocks.moodFindMany },
|
||||
},
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
|
||||
const handler = GET as unknown as (req: NextRequest) => Promise<Response>;
|
||||
|
||||
function request(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/insights/glp1-timeline");
|
||||
}
|
||||
|
||||
/** One GLP-1 medication with no events of its own, so only mood days show. */
|
||||
function medication() {
|
||||
return {
|
||||
name: "Mounjaro",
|
||||
doseChanges: [],
|
||||
intakeEvents: [],
|
||||
inventoryEvents: [],
|
||||
};
|
||||
}
|
||||
|
||||
function moodDay(day: number, tags: string[]) {
|
||||
return {
|
||||
moodLoggedAt: new Date(Date.UTC(2026, 3, day, 9, 0, 0)),
|
||||
tags: JSON.stringify(tags),
|
||||
};
|
||||
}
|
||||
|
||||
interface TimelineBody {
|
||||
data: {
|
||||
hasGlp1: boolean;
|
||||
entries: Array<{ date: string; kind: string; tags?: string[] }>;
|
||||
};
|
||||
}
|
||||
|
||||
async function timeline(moods: ReturnType<typeof moodDay>[]) {
|
||||
mocks.medicationFindMany.mockResolvedValue([medication()]);
|
||||
mocks.moodFindMany.mockResolvedValue(moods);
|
||||
const res = await handler(request());
|
||||
const body = (await res.json()) as TimelineBody;
|
||||
return body.data;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("GET /api/insights/glp1-timeline side-effect days", () => {
|
||||
it("builds the same timeline from a French record as from an English one", async () => {
|
||||
const en = await timeline([
|
||||
moodDay(10, ["nausea"]),
|
||||
moodDay(11, ["headache", "fatigue"]),
|
||||
]);
|
||||
const fr = await timeline([
|
||||
moodDay(10, ["Nausées"]),
|
||||
moodDay(11, ["Maux de tête", "Fatigue"]),
|
||||
]);
|
||||
expect(fr).toEqual(en);
|
||||
expect(fr.entries).toEqual([
|
||||
{
|
||||
date: "2026-04-11T12:00:00Z",
|
||||
kind: "side-effect",
|
||||
tags: ["headache", "fatigue"],
|
||||
},
|
||||
{ date: "2026-04-10T12:00:00Z", kind: "side-effect", tags: ["nausea"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognises the chip label of every shipped locale", async () => {
|
||||
const out = await timeline([
|
||||
moodDay(10, ["Übelkeit"]),
|
||||
moodDay(11, ["Estreñimiento"]),
|
||||
moodDay(12, ["Stitichezza"]),
|
||||
moodDay(13, ["Zgaga"]),
|
||||
moodDay(14, ["Perte d’appétit"]),
|
||||
]);
|
||||
expect(out.entries.map((e) => e.tags)).toEqual([
|
||||
["appetite-loss"],
|
||||
["heartburn"],
|
||||
["constipation"],
|
||||
["constipation"],
|
||||
["nausea"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits the catalogue key, not the string the entry was written with", async () => {
|
||||
// The stored column mixes languages as soon as an account switches UI
|
||||
// locale. A key renders in the reader's language; a stored label renders
|
||||
// in whichever one the writer happened to be using.
|
||||
const out = await timeline([moodDay(10, ["Nudności", "Übelkeit"])]);
|
||||
expect(out.entries[0].tags).toEqual(["nausea"]);
|
||||
});
|
||||
|
||||
it("leaves free-text mood tags off the therapy timeline", async () => {
|
||||
const out = await timeline([moodDay(10, ["gym", "date night"])]);
|
||||
expect(out.entries).toEqual([]);
|
||||
});
|
||||
|
||||
it("counts what it could not classify on the wide event", async () => {
|
||||
// Not dropped without trace: the miss rate stays answerable from a
|
||||
// dashboard, while the tag text — the user's own prose — stays in the
|
||||
// database.
|
||||
await timeline([moodDay(10, ["Nudności", "siłownia", "rodzina"])]);
|
||||
expect(mocks.annotate).toHaveBeenCalledWith({
|
||||
action: { name: "insights.glp1-timeline.read" },
|
||||
meta: { side_effect_days: 1, unresolved_mood_tags: 2 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -13,25 +13,12 @@ import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { readNote } from "@/lib/crypto/note-cipher";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { matchGlp1SideEffectTags } from "@/lib/medications/glp1-side-effect-tag-match";
|
||||
import type { Glp1SideEffectTag } from "@/lib/medications/glp1-side-effect-tags";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const DEFAULT_LIMIT = 60;
|
||||
const SIDE_EFFECT_TAGS = new Set([
|
||||
"nausea",
|
||||
"constipation",
|
||||
"diarrhea",
|
||||
"fatigue",
|
||||
"appetite-loss",
|
||||
"heartburn",
|
||||
"headache",
|
||||
"übelkeit",
|
||||
"verstopfung",
|
||||
"durchfall",
|
||||
"müdigkeit",
|
||||
"appetitlosigkeit",
|
||||
"sodbrennen",
|
||||
"kopfschmerzen",
|
||||
]);
|
||||
|
||||
interface TimelineEntry {
|
||||
date: string;
|
||||
@@ -44,25 +31,7 @@ interface TimelineEntry {
|
||||
injectionSite?: string | null;
|
||||
inventoryDelta?: number;
|
||||
reason?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
function parseTagList(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed
|
||||
.map((v) => (typeof v === "string" ? v.trim() : ""))
|
||||
.filter(Boolean);
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return raw
|
||||
.split(",")
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean);
|
||||
tags?: Glp1SideEffectTag[];
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
@@ -157,17 +126,23 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Side-effect days — collapse to one entry per day (most recent
|
||||
// first) listing every recognised tag picked up that day.
|
||||
const sideEffectByDay = new Map<string, string[]>();
|
||||
// Side-effect days — collapse to one entry per day (most recent first)
|
||||
// listing every catalogue side effect picked up that day.
|
||||
//
|
||||
// `tags` carries the catalogue KEY, not the string the entry was written
|
||||
// with. The chip writes the label of whatever language the writer's UI was
|
||||
// in, so the stored column mixes languages within one account the moment
|
||||
// somebody switches locale; a key renders in the reader's language and a
|
||||
// stored label renders in the writer's.
|
||||
const sideEffectByDay = new Map<string, Glp1SideEffectTag[]>();
|
||||
let unresolvedTagCount = 0;
|
||||
for (const mood of moods) {
|
||||
const tags = parseTagList(mood.tags).filter((t) =>
|
||||
SIDE_EFFECT_TAGS.has(t.toLowerCase()),
|
||||
);
|
||||
if (tags.length === 0) continue;
|
||||
const { matched, unresolvedCount } = matchGlp1SideEffectTags(mood.tags);
|
||||
unresolvedTagCount += unresolvedCount;
|
||||
if (matched.length === 0) continue;
|
||||
const dayKey = mood.moodLoggedAt.toISOString().slice(0, 10);
|
||||
const existing = sideEffectByDay.get(dayKey) ?? [];
|
||||
for (const t of tags) {
|
||||
for (const t of matched) {
|
||||
if (!existing.includes(t)) existing.push(t);
|
||||
}
|
||||
sideEffectByDay.set(dayKey, existing);
|
||||
@@ -182,5 +157,18 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
entries.sort((a, b) => b.date.localeCompare(a.date));
|
||||
|
||||
// Mood tags that are not catalogue side effects are correctly absent from a
|
||||
// GLP-1 timeline — they are the user's own prose about their day, and this
|
||||
// surface is not where it belongs. Absent is not the same as untracked
|
||||
// though: the count rides the wide event so the classification rate stays
|
||||
// answerable from a dashboard, without the text leaving the database.
|
||||
annotate({
|
||||
action: { name: "insights.glp1-timeline.read" },
|
||||
meta: {
|
||||
side_effect_days: sideEffectByDay.size,
|
||||
unresolved_mood_tags: unresolvedTagCount,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ hasGlp1: true, entries: entries.slice(0, limit) });
|
||||
});
|
||||
Reference in new issue
Block a user