Merge remote-tracking branch 'origin/work/parity-contracts' into release/v1.30.34

This commit is contained in:
Marc-André Bombeck committed 2026-07-19 12:46:10 +02:00
commit d68a7ca244
28 files changed
+1087 -86

No files matched your search

+181 -4
View File
@@ -9,6 +9,10 @@ import {
IOS_PIN_ONLY_WIDGET_IDS,
DEFAULT_HERO_RING_ORDER,
resolveHeroRingOrder,
LAYOUT_FIELD_MERGE_DISPOSITION,
PRESERVED_LAYOUT_FIELDS,
layoutNeedsPreserveRead,
mergePreservedLayoutFields,
type DashboardLayout,
} from "@/lib/dashboard-layout";
@@ -438,7 +442,7 @@ describe("resolveDashboardLayout() — retired heroVisible field", () => {
* iOS-only ids extend it without touching the writable PUT enum.
*/
describe("DASHBOARD_WIDGET_CATALOGUE_IDS — 27-id catalogue", () => {
it("carries exactly 37 distinct ids (28 server-known + 9 iOS-only)", () => {
it("carries exactly 42 distinct ids (29 server-known + 13 iOS-only)", () => {
// v1.11.2 B5 — the 8 v1.10 additive metrics became web-writable, so
// the server-known set grew 16 → 24 and the catalogue 27 → 35.
// v1.18.2 — the Vorsorge summary widget added one server-known id
@@ -450,10 +454,42 @@ describe("DASHBOARD_WIDGET_CATALOGUE_IDS — 27-id catalogue", () => {
// v1.29 — the nutrients-store-backed fluid-intake strip tile
// (`waterIntake`) added one server-known id, so the catalogue grew
// 37 → 38.
// The four clinical signals the native client pins (grip strength, pain
// NRS, waist circumference, waist-to-height) joined the iOS-only set
// (9 → 13), so the catalogue grew 38 → 42. Before they were catalogued
// the widgets PUT dropped them as unknown ids and every native layout
// save lost the user's placement of those tiles.
expect(DASHBOARD_WIDGET_IDS).toHaveLength(29);
expect(DASHBOARD_IOS_ONLY_WIDGET_IDS).toHaveLength(9);
expect(DASHBOARD_WIDGET_CATALOGUE_IDS).toHaveLength(38);
expect(new Set(DASHBOARD_WIDGET_CATALOGUE_IDS).size).toBe(38);
expect(DASHBOARD_IOS_ONLY_WIDGET_IDS).toHaveLength(13);
expect(DASHBOARD_WIDGET_CATALOGUE_IDS).toHaveLength(42);
expect(new Set(DASHBOARD_WIDGET_CATALOGUE_IDS).size).toBe(42);
});
it("catalogues the four clinical signals the native client pins", () => {
// Regression guard: these four reached the widgets PUT as unknown ids,
// were filtered out before Zod, and vanished from the persisted layout
// — a silent loss of the user's tile placement on every save.
for (const id of [
"gripStrength",
"painNRS",
"waistCircumference",
"waistToHeight",
]) {
expect(DASHBOARD_WIDGET_CATALOGUE_IDS).toContain(id);
}
});
it("keeps the four clinical signals out of the web-writable set", () => {
// The web dashboard has no render path for them — their charts live on
// the /insights sub-pages — so a web Settings toggle would do nothing.
for (const id of [
"gripStrength",
"painNRS",
"waistCircumference",
"waistToHeight",
]) {
expect(DASHBOARD_WIDGET_IDS).not.toContain(id);
}
});
it("ships the sleep / steps / glucose strip tiles default-on (v1.20.0)", () => {
@@ -498,6 +534,9 @@ describe("DASHBOARD_WIDGET_CATALOGUE_IDS — 27-id catalogue", () => {
it("carries the locked iOS-only ids verbatim", () => {
// v1.28.52 — `hrv` + `respiratoryRate` left this set for the writable
// DASHBOARD_WIDGET_IDS (they gained a web strip tile).
// The four clinical signals joined so the widgets PUT stops dropping
// them as unknown ids; `painNRS` is spelled as the native client sends
// it, which differs in case from the `painNrs` chart-overlay slot.
expect([...DASHBOARD_IOS_ONLY_WIDGET_IDS]).toEqual([
"restingHeartRate",
"walkingSpeed",
@@ -508,6 +547,10 @@ describe("DASHBOARD_WIDGET_CATALOGUE_IDS — 27-id catalogue", () => {
"walkingDoubleSupport",
"audioExposureEnvironment",
"audioExposureHeadphone",
"gripStrength",
"painNRS",
"waistCircumference",
"waistToHeight",
]);
});
});
@@ -909,3 +952,137 @@ describe("resolveDashboardLayout() / serialize — heroRingOrder", () => {
expect(DEFAULT_HERO_RING_ORDER[0]).toBe("HEALTH_SCORE");
});
});
/**
* Preserve-when-absent contract for the widgets PUT.
*
* `comparisonBaseline` was a top-level layout field that the merge forgot.
* Because `serializeDashboardLayout` clamps a missing baseline to `"none"`,
* every layout save from a client that doesn't send the field — the native
* client documents it as web-only and never sends it — silently reset the
* comparison baseline the user had picked on the web. No error, no audit row.
*
* The fix is not "remember to add the field to the merge". It is a
* disposition map the type system forces to cover every field of
* `DashboardLayout`, from which the preserve set is derived. These tests pin
* the behaviour that map buys.
*/
describe("layout field merge disposition", () => {
/**
* A layout with EVERY top-level field populated. Typed as
* `Required<DashboardLayout>` so adding a field to the interface without
* adding it here is a type error too — the runtime assertion below then
* proves the disposition map covers it.
*/
const fullyPopulatedLayout: Required<DashboardLayout> = {
version: 1,
widgets: [{ id: "weight", visible: true, tileVisible: true, order: 0 }],
comparisonBaseline: "lastYear",
chartOverlayPrefs: {
weight: {
showTrendIndicator: true,
showTrendArrow: false,
showTargetRange: false,
comparisonBaseline: "none",
},
},
selectedScoreRings: ["MED_COMPLIANCE"],
heroRingOrder: ["HEALTH_SCORE", "MED_COMPLIANCE"],
};
it("assigns a disposition to every top-level layout field", () => {
// The guard that makes the next field impossible to forget. Adding a
// field to `DashboardLayout` without a disposition fails typecheck at
// the `satisfies Record<keyof DashboardLayout, …>`; this asserts the
// same coverage at runtime so the failure is loud in the suite too.
expect(Object.keys(LAYOUT_FIELD_MERGE_DISPOSITION).sort()).toEqual(
Object.keys(fullyPopulatedLayout).sort(),
);
});
it("only ever assigns a known disposition", () => {
for (const disposition of Object.values(LAYOUT_FIELD_MERGE_DISPOSITION)) {
expect(["replace", "preserve"]).toContain(disposition);
}
});
it("preserves comparisonBaseline alongside the other client-owned fields", () => {
// The regression itself: `comparisonBaseline` must be in the preserve
// set, not merely present in the disposition map.
expect([...PRESERVED_LAYOUT_FIELDS].sort()).toEqual([
"chartOverlayPrefs",
"comparisonBaseline",
"heroRingOrder",
"selectedScoreRings",
]);
});
it("replaces the fields the request itself owns", () => {
expect(LAYOUT_FIELD_MERGE_DISPOSITION.version).toBe("replace");
expect(LAYOUT_FIELD_MERGE_DISPOSITION.widgets).toBe("replace");
});
it("skips the stored-layout read when the client sent every preserved field", () => {
expect(layoutNeedsPreserveRead(fullyPopulatedLayout)).toBe(false);
});
it("requires the stored-layout read when any preserved field is absent", () => {
for (const field of PRESERVED_LAYOUT_FIELDS) {
const incoming: Partial<DashboardLayout> = { ...fullyPopulatedLayout };
delete incoming[field];
expect(layoutNeedsPreserveRead(incoming)).toBe(true);
}
});
it("carries an omitted comparisonBaseline forward from the stored layout", () => {
// A widgets-only save, which is exactly what the native client sends.
const incoming: Partial<DashboardLayout> = {
version: 1,
widgets: fullyPopulatedLayout.widgets,
};
const merged = mergePreservedLayoutFields(incoming, fullyPopulatedLayout);
expect(merged.comparisonBaseline).toBe("lastYear");
});
it("carries every omitted preserved field forward, one field at a time", () => {
for (const field of PRESERVED_LAYOUT_FIELDS) {
const incoming: Partial<DashboardLayout> = { ...fullyPopulatedLayout };
delete incoming[field];
const merged = mergePreservedLayoutFields(incoming, fullyPopulatedLayout);
expect(merged[field]).toEqual(fullyPopulatedLayout[field]);
}
});
it("never overwrites a preserved field the client did send", () => {
const stored: DashboardLayout = {
...fullyPopulatedLayout,
comparisonBaseline: "lastMonth",
selectedScoreRings: ["MED_COMPLIANCE"],
};
const incoming: Partial<DashboardLayout> = {
version: 1,
widgets: fullyPopulatedLayout.widgets,
comparisonBaseline: "none",
chartOverlayPrefs: fullyPopulatedLayout.chartOverlayPrefs,
selectedScoreRings: [],
heroRingOrder: fullyPopulatedLayout.heroRingOrder,
};
const merged = mergePreservedLayoutFields(incoming, stored);
// An explicit "none" is a real choice — clearing must survive the merge.
expect(merged.comparisonBaseline).toBe("none");
expect(merged.selectedScoreRings).toEqual([]);
});
it("leaves the replace-fields untouched by the merge", () => {
const stored: DashboardLayout = {
...fullyPopulatedLayout,
widgets: [{ id: "bp", visible: false, tileVisible: false, order: 0 }],
};
const incoming: Partial<DashboardLayout> = {
version: 1,
widgets: fullyPopulatedLayout.widgets,
};
const merged = mergePreservedLayoutFields(incoming, stored);
expect(merged.widgets).toEqual(fullyPopulatedLayout.widgets);
});
});
+99
View File
@@ -139,6 +139,27 @@ export const DASHBOARD_IOS_ONLY_WIDGET_IDS = [
"walkingDoubleSupport",
"audioExposureEnvironment",
"audioExposureHeadphone",
// The four clinical signals the v1.25 sub-pages already chart
// (`/insights/grip-strength`, `/insights/pain`, `/insights/waist`,
// `/insights/waist-to-height`). The native client offers a dashboard tile
// for each; before they joined the catalogue the widgets PUT dropped them
// through the unknown-id filter, so every native layout save silently lost
// the user's placement of those four tiles.
//
// They live here rather than in `DASHBOARD_WIDGET_IDS` because the web
// dashboard has no render path for them — the chart lives on the insights
// sub-page, not on the Startseite. That keeps them out of the web Settings
// list (built from `DASHBOARD_WIDGET_IDS`) while the PUT enum, the on-read
// resolver, and the snapshot catalogue all accept and retain them.
//
// `painNRS` matches the id the native client sends. The sibling
// chart-overlay slot spells it `painNrs` (see `CHART_OVERLAY_KEYS`); the
// two namespaces are independent and neither is derived from the other, so
// the casing difference is deliberate rather than a typo.
"gripStrength",
"painNRS",
"waistCircumference",
"waistToHeight",
] as const;
/**
@@ -548,6 +569,84 @@ export interface DashboardLayout {
heroRingOrder?: HeroRingId[];
}
/**
* How the widgets PUT treats each top-level layout field when the client
* omits it.
*
* - `"replace"` — the field is the point of the request. A PUT that omits it
* is either rejected by Zod (`version`, `widgets` are required) or means
* the caller genuinely has nothing to say.
* - `"preserve"` — the field is owned by a surface OTHER than the one making
* this request, so an omission means "I don't know about this", never
* "clear it". The route reads the stored layout and carries the existing
* value forward.
*
* The preserve set exists because clients legitimately don't know every
* field. The per-chart overlay popover PUTs through
* `/api/dashboard/chart-overlay-prefs`; the hero rings are a Settings-only
* control; `comparisonBaseline` is web-only and the native client documents
* that it never sends it. Without preserve-when-absent, a tile reorder on one
* surface silently resets a choice made on another — which is exactly what
* happened to `comparisonBaseline` before it joined this map: the serializer
* clamps a missing value to `"none"`, so every native layout save wiped the
* baseline the user had picked on the web.
*
* `satisfies Record<keyof DashboardLayout, …>` is the load-bearing part.
* Adding a field to `DashboardLayout` without adding it here is a TYPE error,
* so the next field cannot repeat the `comparisonBaseline` mistake by
* omission — somebody has to make the decision explicitly.
*/
export const LAYOUT_FIELD_MERGE_DISPOSITION = {
version: "replace",
widgets: "replace",
comparisonBaseline: "preserve",
chartOverlayPrefs: "preserve",
selectedScoreRings: "preserve",
heroRingOrder: "preserve",
} as const satisfies Record<keyof DashboardLayout, "replace" | "preserve">;
/**
* The top-level layout fields the widgets PUT carries forward from the stored
* layout when the request omits them. Derived from
* `LAYOUT_FIELD_MERGE_DISPOSITION` so the two can never drift.
*/
export const PRESERVED_LAYOUT_FIELDS = (
Object.keys(LAYOUT_FIELD_MERGE_DISPOSITION) as Array<keyof DashboardLayout>
).filter(
(field) => LAYOUT_FIELD_MERGE_DISPOSITION[field] === "preserve",
) as ReadonlyArray<keyof DashboardLayout>;
/**
* True when the incoming layout omits at least one preserved field, i.e. the
* route has to read the stored layout to merge. Lets the common full-layout
* save from Settings skip the extra query.
*/
export function layoutNeedsPreserveRead(
incoming: Partial<DashboardLayout>,
): boolean {
return PRESERVED_LAYOUT_FIELDS.some((field) => incoming[field] === undefined);
}
/**
* Carry every omitted preserved field forward from the stored layout.
* Fields the client DID send win untouched; `"replace"` fields are never
* consulted here. One stored-layout read covers all of them.
*/
export function mergePreservedLayoutFields(
incoming: Partial<DashboardLayout>,
existing: DashboardLayout,
): Partial<DashboardLayout> {
const merged: Partial<DashboardLayout> = { ...incoming };
for (const field of PRESERVED_LAYOUT_FIELDS) {
if (merged[field] === undefined) {
// Each key maps to its own value type; the loop is homogeneous over
// `keyof DashboardLayout`, which TypeScript cannot express per-key.
(merged as Record<string, unknown>)[field] = existing[field];
}
}
return merged;
}
const DASHBOARD_LAYOUT_VERSION = 1;
/**
+3 -3
View File
@@ -752,11 +752,11 @@ describe("buildDashboardSnapshot — layoutCatalogue (35-id round-trip)", () =>
isFullyCovered.mockReturnValue(false);
});
it("emits all 38 catalogue ids with visibility + order", async () => {
it("emits all 42 catalogue ids with visibility + order", async () => {
const snap = await buildDashboardSnapshot(fakePrisma, baseUser());
expect(snap.layoutCatalogue).toHaveLength(38);
expect(snap.layoutCatalogue).toHaveLength(42);
const ids = new Set(snap.layoutCatalogue.map((w) => w.id));
expect(ids.size).toBe(38);
expect(ids.size).toBe(42);
// iOS-only ids appended default-invisible.
const walkingSpeed = snap.layoutCatalogue.find(
(w) => w.id === "walkingSpeed",
+12
View File
@@ -74,6 +74,11 @@ export const SUMMARY_TYPE_MODULE: Partial<Record<string, ModuleKey>> = {
// `NutrientIntakeDay` (nutrient="water", summed across sources). Gated
// on the `nutrients` module like the rest of that store's surfaces.
NUTRIENT_WATER: "nutrients",
// Mood is a `MoodEntry`-derived summary, not a `MeasurementType`, so it
// rides the same synthetic-key route as `NUTRIENT_WATER`. Gated on the
// `mood` module: turning the module off must drop the dashboard card on
// every client, not just hide the web widget.
MOOD_ENTRY: "mood",
};
/**
@@ -123,6 +128,13 @@ export const SUMMARY_METRIC_TYPE_BY_KIND: Record<string, string> = {
totalBodyWater: "TOTAL_BODY_WATER",
boneMass: "BONE_MASS",
oxygenSaturation: "OXYGEN_SATURATION",
// Synthetic key — see `MOOD_ENTRY` in `SUMMARY_TYPE_MODULE`.
mood: "MOOD_ENTRY",
// BMI is derived from weight + the profile height and belongs to no
// module, exactly like weight and body fat. Listed so the full emitted
// set stays readable and a future card cannot be added without deciding
// what backs it.
bmi: "WEIGHT",
};
/**
@@ -80,6 +80,8 @@ describe("buildCreateInventoryInput", () => {
containerType: "PEN",
printedExpiry: printed,
purchasedAt: null,
manufacturer: null,
doseStrength: null,
notes: null,
});
expect(input).toMatchObject({
@@ -100,6 +102,8 @@ describe("buildCreateInventoryInput", () => {
containerType: "OTHER",
printedExpiry: null,
purchasedAt: null,
manufacturer: null,
doseStrength: null,
notes: null,
});
expect(input.expiresAt).toBeNull();
@@ -157,3 +161,40 @@ describe("serializeInventoryItem (iOS#31)", () => {
expect(out).toMatchObject({ id: "i5", state: "ACTIVE" });
});
});
describe("buildCreateInventoryInput — carton labelling", () => {
it("carries manufacturer + doseStrength onto the create input", () => {
// The native pen list renders these as its headline and subhead; a
// container created on the web carried neither, so the row could not be
// shown there without fabricating an empty card.
const input = buildCreateInventoryInput({
userId: "u",
medicationId: "m",
unitsTotal: 4,
containerType: "PEN",
printedExpiry: null,
purchasedAt: null,
manufacturer: "Example Pharma",
doseStrength: "5 mg/0.5 ml",
notes: null,
});
expect(input.manufacturer).toBe("Example Pharma");
expect(input.doseStrength).toBe("5 mg/0.5 ml");
});
it("leaves both null for a plain supply container", () => {
const input = buildCreateInventoryInput({
userId: "u",
medicationId: "m",
unitsTotal: 30,
containerType: "BLISTER",
printedExpiry: null,
purchasedAt: null,
manufacturer: null,
doseStrength: null,
notes: null,
});
expect(input.manufacturer).toBeNull();
expect(input.doseStrength).toBeNull();
});
});
+4
View File
@@ -144,6 +144,8 @@ export function buildCreateInventoryInput(input: {
containerType: MedicationContainerType;
printedExpiry: Date | null;
purchasedAt: Date | null;
manufacturer: string | null;
doseStrength: string | null;
notes: string | null;
}) {
return {
@@ -157,6 +159,8 @@ export function buildCreateInventoryInput(input: {
printedExpiry: input.printedExpiry,
purchasedAt: input.purchasedAt,
expiresAt: computeExpiresAt(null, input.printedExpiry),
manufacturer: input.manufacturer,
doseStrength: input.doseStrength,
// Encrypt the free-text note at rest; the plaintext column stays null.
notesEncrypted: encryptNote(input.notes),
notes: null,
@@ -314,6 +314,18 @@ export const medicationInventoryItemResource = z
),
printedExpiry: z.iso.datetime({ offset: true }).nullable(),
purchasedAt: z.iso.datetime({ offset: true }).nullable(),
manufacturer: z
.string()
.nullable()
.describe(
"Marketing-authorisation holder / maker as printed on the carton. NULL for a container registered before the field existed, and for plain supply rows that never carried one.",
),
doseStrength: z
.string()
.nullable()
.describe(
'Strength as printed on the container, e.g. "5 mg/0.5 ml". Free text, not split into a number + unit — pens state strength per dose, per ml, or per cartridge. NULL when unknown.',
),
notes: z.string().nullable(),
createdAt: z.iso.datetime({ offset: true }),
updatedAt: z.iso.datetime({ offset: true }),
@@ -54,6 +54,24 @@ export const createInventoryItemSchema = z
.transform((s) => new Date(s))
.nullable()
.optional(),
/** Carton labelling — free text, see the schema comment on the model
* for why neither is parsed into a structured value. */
manufacturer: z
.string()
.max(120)
.nullable()
.optional()
.describe(
"Marketing-authorisation holder / maker as printed on the carton. Free text, max 120 chars.",
),
doseStrength: z
.string()
.max(60)
.nullable()
.optional()
.describe(
'Strength as printed on the container, e.g. "5 mg/0.5 ml". Free text, max 60 chars — deliberately not split into a number + unit because pens state strength per dose, per ml, or per cartridge.',
),
notes: z.string().max(200).nullable().optional(),
})
.meta({
@@ -99,6 +117,24 @@ export const updateInventoryItemSchema = z
.describe(
"Absolute remaining-unit correction (0–1000, fractional allowed). Clamped server-side to the item's `unitsTotal`; the canonical state machine re-derives the state (0 ⇒ USED_UP).",
),
/** Carton labelling — free text, see the schema comment on the model
* for why neither is parsed into a structured value. */
manufacturer: z
.string()
.max(120)
.nullable()
.optional()
.describe(
"Marketing-authorisation holder / maker as printed on the carton. Free text, max 120 chars.",
),
doseStrength: z
.string()
.max(60)
.nullable()
.optional()
.describe(
'Strength as printed on the container, e.g. "5 mg/0.5 ml". Free text, max 60 chars — deliberately not split into a number + unit because pens state strength per dose, per ml, or per cartridge.',
),
notes: z.string().max(200).nullable().optional(),
})
.meta({