mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
Merge remote-tracking branch 'origin/release/v1.42.0' into v142/pwa
This commit is contained in:
commit
8a7eddaf26
67 files changed
+3473
-606
No files matched your search
@@ -454,6 +454,7 @@ export const USER_RESET = {
|
||||
dashboardWidgetsJson: Prisma.DbNull,
|
||||
medicationListLayoutJson: Prisma.DbNull,
|
||||
moodTagLayoutJson: Prisma.DbNull,
|
||||
documentsLayoutJson: Prisma.DbNull,
|
||||
reportSelectionJson: Prisma.DbNull,
|
||||
modulePreferencesJson: Prisma.DbNull,
|
||||
healthScoreConfigJson: Prisma.DbNull,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Document vault presentation — persisted in `User.documentsLayoutJson`.
|
||||
*
|
||||
* Two independent choices, both display-only:
|
||||
*
|
||||
* - `view`: `cards` is the monthly grid of preview tiles; `list` is one
|
||||
* compact row per document.
|
||||
* - `arrangement`: `stacked` gives every month its own block, one under the
|
||||
* other; `flow` lets the documents run left to right across the full width
|
||||
* and wrap, with each month's name riding inline as a small marker that does
|
||||
* not break the run.
|
||||
*
|
||||
* Null / missing column = the defaults below (cards, stacked — the vault as it
|
||||
* has always looked). The GET endpoint never lazy-writes, so the column only
|
||||
* carries data once the user has changed one of the two. Mirrors
|
||||
* `medication-list-layout.ts`: tolerant resolver on read, normaliser on write,
|
||||
* preserve-when-absent PUT (see the route).
|
||||
*/
|
||||
|
||||
export const DOCUMENTS_LAYOUT_VIEWS = ["cards", "list"] as const;
|
||||
export type DocumentsLayoutView = (typeof DOCUMENTS_LAYOUT_VIEWS)[number];
|
||||
|
||||
export const DOCUMENTS_LAYOUT_ARRANGEMENTS = ["stacked", "flow"] as const;
|
||||
export type DocumentsLayoutArrangement =
|
||||
(typeof DOCUMENTS_LAYOUT_ARRANGEMENTS)[number];
|
||||
|
||||
export interface DocumentsLayout {
|
||||
version: 1;
|
||||
view: DocumentsLayoutView;
|
||||
arrangement: DocumentsLayoutArrangement;
|
||||
}
|
||||
|
||||
export const DEFAULT_DOCUMENTS_LAYOUT: DocumentsLayout = {
|
||||
version: 1,
|
||||
view: "cards",
|
||||
arrangement: "stacked",
|
||||
};
|
||||
|
||||
function isView(value: unknown): value is DocumentsLayoutView {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
(DOCUMENTS_LAYOUT_VIEWS as readonly string[]).includes(value)
|
||||
);
|
||||
}
|
||||
|
||||
function isArrangement(value: unknown): value is DocumentsLayoutArrangement {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
(DOCUMENTS_LAYOUT_ARRANGEMENTS as readonly string[]).includes(value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Any malformed, partial or legacy blob collapses onto the defaults field by
|
||||
* field, so a GET never fails on a stored row and a field added later
|
||||
* defaults cleanly for blobs written before it existed.
|
||||
*/
|
||||
export function resolveDocumentsLayout(raw: unknown): DocumentsLayout {
|
||||
if (raw === null || raw === undefined || typeof raw !== "object") {
|
||||
return { ...DEFAULT_DOCUMENTS_LAYOUT };
|
||||
}
|
||||
const blob = raw as { view?: unknown; arrangement?: unknown };
|
||||
return {
|
||||
version: 1,
|
||||
view: isView(blob.view) ? blob.view : DEFAULT_DOCUMENTS_LAYOUT.view,
|
||||
arrangement: isArrangement(blob.arrangement)
|
||||
? blob.arrangement
|
||||
: DEFAULT_DOCUMENTS_LAYOUT.arrangement,
|
||||
};
|
||||
}
|
||||
@@ -524,6 +524,7 @@ const ACCOUNT_SETTING_CODECS: Readonly<
|
||||
insightsLayoutJson: json("insightsLayoutJson"),
|
||||
medicationListLayoutJson: json("medicationListLayoutJson"),
|
||||
moodTagLayoutJson: json("moodTagLayoutJson"),
|
||||
documentsLayoutJson: json("documentsLayoutJson"),
|
||||
reportSelectionJson: json("reportSelectionJson"),
|
||||
globalExcludedInjectionSites: excludedSites,
|
||||
healthKitConfigJson: json("healthKitConfigJson"),
|
||||
|
||||
@@ -950,6 +950,7 @@ export const USER_COLUMN_BACKUP_CLASS = {
|
||||
insightsLayoutJson: "SETTING",
|
||||
medicationListLayoutJson: "SETTING",
|
||||
moodTagLayoutJson: "SETTING",
|
||||
documentsLayoutJson: "SETTING",
|
||||
reportSelectionJson: "SETTING",
|
||||
globalExcludedInjectionSites: "SETTING",
|
||||
healthKitConfigJson: "SETTING",
|
||||
|
||||
@@ -75,6 +75,7 @@ const sleepScore: SleepScoreValue = {
|
||||
{ key: "composition", value: 88, weight: 0.15 },
|
||||
],
|
||||
windowNights: 20,
|
||||
series: [78, 82],
|
||||
};
|
||||
|
||||
const recovery: WellnessScoreValue = {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* The readiness course is read, never recomputed: the nightly job persists
|
||||
* this blend as the COMPUTED recovery row, and a device's own recovery number
|
||||
* (WHOOP, Oura, Polar) is not this blend, so it never enters the series.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { findMany } = vi.hoisted(() => ({ findMany: vi.fn() }));
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { measurement: { findMany } },
|
||||
}));
|
||||
|
||||
import { readReadinessHistory } from "../readiness";
|
||||
|
||||
const NOW = new Date("2026-06-02T07:00:00Z");
|
||||
|
||||
beforeEach(() => findMany.mockReset());
|
||||
|
||||
describe("readReadinessHistory", () => {
|
||||
it("reads only the persisted blend inside the window, oldest first", async () => {
|
||||
// Newest first, as the query orders them.
|
||||
findMany.mockResolvedValue([
|
||||
{ value: 71.6 },
|
||||
{ value: 64.2 },
|
||||
{ value: 80 },
|
||||
]);
|
||||
|
||||
const series = await readReadinessHistory("u1", NOW, 30);
|
||||
|
||||
expect(series).toEqual([80, 64, 72]);
|
||||
const where = findMany.mock.calls[0][0].where;
|
||||
expect(where).toMatchObject({
|
||||
userId: "u1",
|
||||
type: "RECOVERY_SCORE",
|
||||
source: "COMPUTED",
|
||||
deletedAt: null,
|
||||
});
|
||||
expect(where.measuredAt.lte).toEqual(NOW);
|
||||
expect(where.measuredAt.gte).toEqual(new Date("2026-05-03T07:00:00Z"));
|
||||
});
|
||||
|
||||
it("answers an empty course when the job never ran", async () => {
|
||||
findMany.mockResolvedValue([]);
|
||||
expect(await readReadinessHistory("u1", NOW, 30)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -326,6 +326,38 @@ describe("computeSleepScore", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("carries the score of every night in the window, ending on the headline", async () => {
|
||||
const rows = [
|
||||
...night("2026-05-31", [
|
||||
["IN_BED", 480, "06:00"],
|
||||
["REM", 90, "02:00"],
|
||||
["CORE", 240, "03:00"],
|
||||
["DEEP", 60, "04:00"],
|
||||
]),
|
||||
// A short night, so the course is not flat.
|
||||
...night("2026-06-01", [
|
||||
["IN_BED", 300, "06:10"],
|
||||
["REM", 40, "02:10"],
|
||||
["CORE", 200, "03:10"],
|
||||
["DEEP", 20, "04:10"],
|
||||
]),
|
||||
...night("2026-06-02", [
|
||||
["IN_BED", 480, "06:05"],
|
||||
["REM", 95, "02:05"],
|
||||
["CORE", 235, "03:05"],
|
||||
["DEEP", 65, "04:05"],
|
||||
]),
|
||||
];
|
||||
findMany.mockResolvedValue(rows);
|
||||
const result = await computeSleepScore("u1", PROFILE, { now: NOW });
|
||||
expect(result.status).toBe("ok");
|
||||
if (result.status === "ok") {
|
||||
expect(result.value.series).toHaveLength(3);
|
||||
expect(result.value.series.at(-1)).toBe(result.value.score);
|
||||
expect(result.value.series[1]).toBeLessThan(result.value.series[0]);
|
||||
}
|
||||
});
|
||||
|
||||
it("reweights around composition on a legacy ASLEEP-only night", async () => {
|
||||
const rows = [
|
||||
...night("2026-05-31", [["ASLEEP", 420, "06:00"]]),
|
||||
|
||||
@@ -27,7 +27,7 @@ import { computeVascularAgeDelta } from "./vascular-age";
|
||||
import { computeHrvBalance } from "./hrv-balance";
|
||||
import { computeBmi } from "./bmi";
|
||||
import { computeSleepScore } from "./sleep-score";
|
||||
import { computeReadiness } from "./readiness";
|
||||
import { computeReadiness, readReadinessHistory } from "./readiness";
|
||||
import { computeCoincidentDeviation } from "./coincident-deviation";
|
||||
import { computeTrajectory } from "./trajectory";
|
||||
import { computeSameTimeBaseline } from "./same-time-baseline";
|
||||
@@ -141,11 +141,22 @@ export async function computeDerivedMetric(
|
||||
windowDays: args.windowDays,
|
||||
now,
|
||||
}) as Promise<Derived<unknown>>;
|
||||
case "READINESS":
|
||||
return computeReadiness(args.userId, args.profile, {
|
||||
case "READINESS": {
|
||||
const readiness = await computeReadiness(args.userId, args.profile, {
|
||||
windowDays: args.windowDays,
|
||||
now,
|
||||
}) as Promise<Derived<unknown>>;
|
||||
});
|
||||
// The blend's course rides beside today's score for the surfaces that
|
||||
// draw it; the nightly job's own compute never pays for the read.
|
||||
if (readiness.status === "ok" && readiness.value) {
|
||||
readiness.value.series = await readReadinessHistory(
|
||||
args.userId,
|
||||
now,
|
||||
readiness.provenance.windowDays,
|
||||
);
|
||||
}
|
||||
return readiness as Derived<unknown>;
|
||||
}
|
||||
case "COINCIDENT_DEVIATION":
|
||||
return computeCoincidentDeviation(args.userId, args.profile, {
|
||||
windowDays: args.windowDays,
|
||||
|
||||
@@ -50,7 +50,11 @@ import {
|
||||
} from "./coverage";
|
||||
import { computeVitalsBaseline, type BaselineProfile } from "./baseline";
|
||||
import { computeSleepScore } from "./sleep-score";
|
||||
import type { Derived, DerivedProvenanceSource } from "./types";
|
||||
import {
|
||||
SPARKLINE_MAX_POINTS,
|
||||
type Derived,
|
||||
type DerivedProvenanceSource,
|
||||
} from "./types";
|
||||
|
||||
const DEFAULT_WINDOW_DAYS = 30;
|
||||
/**
|
||||
@@ -89,6 +93,45 @@ export interface ReadinessValue {
|
||||
score: number;
|
||||
band: "green" | "yellow" | "red";
|
||||
components: ReadinessComponent[];
|
||||
/**
|
||||
* v1.42 — the blend's own course over the window (oldest → newest, capped
|
||||
* to `SPARKLINE_MAX_POINTS`), read from what the nightly job persisted; see
|
||||
* `readReadinessHistory`. Attached by the derived dispatch for the surfaces
|
||||
* that show it, absent on the job's own compute. Additive.
|
||||
*/
|
||||
series?: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The readiness blend's history, without recomputing a single day.
|
||||
*
|
||||
* The nightly recovery job persists exactly this blend — `computeRecoveryScore`
|
||||
* delegates to `computeReadiness` verbatim — as the `COMPUTED`-source
|
||||
* `RECOVERY_SCORE` row. Those rows ARE the readiness score of each past night.
|
||||
* A device-native recovery row (WHOOP, Oura, Polar) shares the type but is the
|
||||
* vendor's number, not this blend, so the read is held to `COMPUTED`.
|
||||
*/
|
||||
export async function readReadinessHistory(
|
||||
userId: string,
|
||||
now: Date,
|
||||
windowDays: number,
|
||||
): Promise<number[]> {
|
||||
const rows = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: "RECOVERY_SCORE" satisfies MeasurementType,
|
||||
source: "COMPUTED",
|
||||
deletedAt: null,
|
||||
measuredAt: {
|
||||
gte: new Date(now.getTime() - windowDays * MS_PER_DAY),
|
||||
lte: now,
|
||||
},
|
||||
},
|
||||
select: { value: true },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: SPARKLINE_MAX_POINTS,
|
||||
});
|
||||
return rows.map((row) => Math.round(row.value)).reverse();
|
||||
}
|
||||
|
||||
// ── pure deviation scorers (exported for tests) ────────────────────────
|
||||
|
||||
@@ -52,7 +52,7 @@ import {
|
||||
nowProvenanceTimestamp,
|
||||
} from "./coverage";
|
||||
import type { BaselineProfile } from "./baseline";
|
||||
import type { Derived } from "./types";
|
||||
import { SPARKLINE_MAX_POINTS, type Derived } from "./types";
|
||||
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
/** Default trailing window for the consistency/timing baseline (days). */
|
||||
@@ -93,6 +93,14 @@ export interface SleepScoreValue {
|
||||
subScores: SleepSubScore[];
|
||||
/** Nights in the window that backed the consistency/timing baseline. */
|
||||
windowNights: number;
|
||||
/**
|
||||
* v1.42 — the score of every scorable night in the window (oldest → newest,
|
||||
* capped to `SPARKLINE_MAX_POINTS`), so a surface can show the score's
|
||||
* course rather than one night. Each night is scored by the same blend as
|
||||
* the headline, against the same window's habitual midpoint, so the last
|
||||
* point IS `score`. Additive; older clients ignore it.
|
||||
*/
|
||||
series: number[];
|
||||
}
|
||||
|
||||
// ── pure scorers (exported for tests) ─────────────────────────────────
|
||||
@@ -530,6 +538,26 @@ export async function computeSleepScore(
|
||||
};
|
||||
|
||||
const { score, subScores } = blendSleepSubScores(raw);
|
||||
|
||||
// The same blend over every scorable night in the window. Consistency is a
|
||||
// window-level figure and timing reads against the window's habitual
|
||||
// midpoint, so every night is judged by the yardstick the headline uses.
|
||||
const consistency = scoreConsistency(midpoints);
|
||||
const series = scorableNights.slice(-SPARKLINE_MAX_POINTS).map(
|
||||
(night) =>
|
||||
blendSleepSubScores({
|
||||
sufficiency: scoreSufficiency(night.asleepMinutes, needMinutes),
|
||||
efficiency: scoreEfficiency(night.asleepMinutes, night.inBedMinutes),
|
||||
consistency,
|
||||
timing: scoreTiming(night.midpoint, habitualMidpoint, midpoints.length),
|
||||
composition: scoreComposition(
|
||||
night.remMinutes,
|
||||
night.deepMinutes,
|
||||
night.asleepMinutes,
|
||||
night.hasStageBreakdown,
|
||||
),
|
||||
}).score,
|
||||
);
|
||||
const presentCount = subScores.filter((s) => s.value !== null).length;
|
||||
const missing = subScores.filter((s) => s.value === null).map((s) => s.key);
|
||||
|
||||
@@ -557,6 +585,7 @@ export async function computeSleepScore(
|
||||
latest.inBedMinutes === null ? null : Math.round(latest.inBedMinutes),
|
||||
subScores,
|
||||
windowNights: scorableNights.length,
|
||||
series,
|
||||
},
|
||||
coverage,
|
||||
confidence,
|
||||
|
||||
@@ -979,3 +979,30 @@ export async function fetchMoodAggregates(
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The `/api/mood/insights` wire for one stability window.
|
||||
*
|
||||
* The per-window map is the cache's, not the wire's: the chosen window is
|
||||
* served as `stability`. An aggregate cached before the map existed has only
|
||||
* the year, so a shorter window reads as not yet computed (`null`) until the
|
||||
* next rebuild rather than as the year's score under a new name.
|
||||
*
|
||||
* Shared by the route and by the `/insights/mood` server prefetch, so the
|
||||
* cell the prefetch seeds is byte-for-byte what the client's own fetch would
|
||||
* have put there — the same key with a different shape is silent cache poison.
|
||||
*/
|
||||
export function moodInsightsWire(
|
||||
result: MoodAggregates,
|
||||
stabilityWindowDays: MoodStabilityWindow,
|
||||
) {
|
||||
const { stabilityByWindow, ...wire } = result;
|
||||
return {
|
||||
...wire,
|
||||
stability:
|
||||
stabilityWindowDays === 365
|
||||
? result.stability
|
||||
: (stabilityByWindow?.[stabilityWindowDays] ?? null),
|
||||
stabilityWindowDays,
|
||||
};
|
||||
}
|
||||
@@ -200,6 +200,7 @@ const STATIC_SURFACE_MODULE = {
|
||||
"settings-layout:mood": "mood",
|
||||
"settings-layout:labs": "labs",
|
||||
"settings-layout:illness": "illness",
|
||||
"settings-layout:documents": "inboundDocuments",
|
||||
|
||||
// ── Correlation channels ──
|
||||
// Rated mood factors (`FACTOR:<key>`) are mood's too; see
|
||||
|
||||
@@ -30,6 +30,10 @@ import {
|
||||
INBOUND_DOCUMENT_KINDS,
|
||||
INBOUND_DOCUMENT_STATUSES,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
import {
|
||||
DOCUMENTS_LAYOUT_ARRANGEMENTS,
|
||||
DOCUMENTS_LAYOUT_VIEWS,
|
||||
} from "@/lib/documents/documents-layout";
|
||||
|
||||
import { aiExtractionRefusals } from "./ai-extraction-refusals";
|
||||
import { aiRunAccepted, preferRespondAsyncParameter } from "./ai-run-accepted";
|
||||
@@ -44,6 +48,41 @@ import {
|
||||
} from "./shared";
|
||||
|
||||
const kindEnum = z.enum(INBOUND_DOCUMENT_KINDS);
|
||||
|
||||
// ─── Vault presentation (v1.42) ────────────────────────────────────────────
|
||||
|
||||
const documentsLayoutSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
view: z
|
||||
.enum(DOCUMENTS_LAYOUT_VIEWS)
|
||||
.describe(
|
||||
'`cards` renders the preview-tile grid, `list` one compact row per document. Default "cards".',
|
||||
),
|
||||
arrangement: z
|
||||
.enum(DOCUMENTS_LAYOUT_ARRANGEMENTS)
|
||||
.describe(
|
||||
'`stacked` gives every month its own block; `flow` runs the documents across the full width and wraps, with month names inline. Default "stacked".',
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "DocumentsLayout",
|
||||
description:
|
||||
"Per-user document vault presentation. Display-only; a client that does not render a vault ignores it.",
|
||||
});
|
||||
|
||||
const documentsLayoutPutBody = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
view: z.enum(DOCUMENTS_LAYOUT_VIEWS).optional(),
|
||||
arrangement: z.enum(DOCUMENTS_LAYOUT_ARRANGEMENTS).optional(),
|
||||
})
|
||||
.strict()
|
||||
.meta({
|
||||
id: "DocumentsLayoutPutBody",
|
||||
description:
|
||||
"Either field may be omitted; the stored value is kept for the one left out.",
|
||||
});
|
||||
const statusEnum = z.enum(INBOUND_DOCUMENT_STATUSES);
|
||||
|
||||
// ─── Chat about a document (P4) — response shapes ──────────────────────────
|
||||
@@ -719,6 +758,53 @@ export const inboundDocumentPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/documents/inbound/layout": {
|
||||
get: {
|
||||
tags: ["Documents"],
|
||||
summary: "Get the vault presentation",
|
||||
description:
|
||||
"The resolved card/list view and month arrangement for the vault, with defaults filled in when nothing has been chosen. Inside a shared record this answers the owner's choice.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The resolved presentation.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
documentsLayoutSchema,
|
||||
"DocumentsLayoutEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
put: {
|
||||
tags: ["Documents"],
|
||||
summary: "Change the vault presentation",
|
||||
description:
|
||||
"Preserve-when-absent: a body carrying only `view` keeps the stored arrangement and vice versa. Returns the full resolved presentation. Refused while acting inside somebody else's record.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { "application/json": { schema: documentsLayoutPutBody } },
|
||||
},
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The presentation as stored.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
documentsLayoutSchema,
|
||||
"DocumentsLayoutSavedEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/documents/inbound/bulk": {
|
||||
post: {
|
||||
tags: ["Documents"],
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The vault presentation switch: field-scoped PUT, optimistic cache flip,
|
||||
* rollback and a toast when the save fails. Exercised through the
|
||||
* dependency-injected `runSetDocumentsLayout`, without a React render.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
vi.mock("@/lib/api/api-fetch", () => ({
|
||||
apiGet: vi.fn(),
|
||||
apiPut: vi.fn(),
|
||||
}));
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
|
||||
}));
|
||||
|
||||
import { apiPut } from "@/lib/api/api-fetch";
|
||||
import { toast } from "sonner";
|
||||
import { runSetDocumentsLayout } from "@/lib/queries/use-documents-layout";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { DocumentsLayout } from "@/lib/documents/documents-layout";
|
||||
|
||||
const t = (key: string) => key;
|
||||
const key = queryKeys.documentsLayout();
|
||||
const STORED: DocumentsLayout = {
|
||||
version: 1,
|
||||
view: "cards",
|
||||
arrangement: "stacked",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("runSetDocumentsLayout", () => {
|
||||
it("sends only the field that changed and keeps the server's answer", async () => {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(key, STORED);
|
||||
const saved: DocumentsLayout = { ...STORED, arrangement: "flow" };
|
||||
vi.mocked(apiPut).mockResolvedValue(saved);
|
||||
|
||||
await runSetDocumentsLayout({
|
||||
patch: { arrangement: "flow" },
|
||||
queryClient,
|
||||
t,
|
||||
});
|
||||
|
||||
expect(apiPut).toHaveBeenCalledWith("/api/documents/inbound/layout", {
|
||||
version: 1,
|
||||
arrangement: "flow",
|
||||
});
|
||||
expect(queryClient.getQueryData(key)).toEqual(saved);
|
||||
});
|
||||
|
||||
it("flips the cache before the save lands", async () => {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(key, STORED);
|
||||
let settle: (value: DocumentsLayout) => void = () => {};
|
||||
vi.mocked(apiPut).mockReturnValue(
|
||||
new Promise<DocumentsLayout>((resolve) => {
|
||||
settle = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const run = runSetDocumentsLayout({
|
||||
patch: { view: "list" },
|
||||
queryClient,
|
||||
t,
|
||||
});
|
||||
expect(queryClient.getQueryData<DocumentsLayout>(key)?.view).toBe("list");
|
||||
settle({ ...STORED, view: "list" });
|
||||
await run;
|
||||
});
|
||||
|
||||
it("rolls back and says so when the save fails", async () => {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(key, STORED);
|
||||
vi.mocked(apiPut).mockRejectedValue(new Error("offline"));
|
||||
|
||||
await runSetDocumentsLayout({ patch: { view: "list" }, queryClient, t });
|
||||
|
||||
expect(queryClient.getQueryData(key)).toEqual(STORED);
|
||||
expect(toast.error).toHaveBeenCalledWith("documents.layout.saveFailed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type QueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { apiGet, apiPut } from "@/lib/api/api-fetch";
|
||||
import {
|
||||
DEFAULT_DOCUMENTS_LAYOUT,
|
||||
type DocumentsLayout,
|
||||
type DocumentsLayoutArrangement,
|
||||
type DocumentsLayoutView,
|
||||
} from "@/lib/documents/documents-layout";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
type Translator = (
|
||||
key: string,
|
||||
params?: Record<string, string | number>,
|
||||
) => string;
|
||||
|
||||
type LayoutPatch = {
|
||||
view?: DocumentsLayoutView;
|
||||
arrangement?: DocumentsLayoutArrangement;
|
||||
};
|
||||
|
||||
/**
|
||||
* Apply one field optimistically (the switch has to feel instant), then
|
||||
* persist it. The PUT is field-scoped, so a view change never resets the
|
||||
* arrangement and vice versa. On failure the cache rolls back and a calm
|
||||
* toast says so.
|
||||
*/
|
||||
export async function runSetDocumentsLayout(deps: {
|
||||
patch: LayoutPatch;
|
||||
queryClient: QueryClient;
|
||||
t: Translator;
|
||||
}): Promise<void> {
|
||||
const { patch, queryClient, t } = deps;
|
||||
const key = queryKeys.documentsLayout();
|
||||
const previous = queryClient.getQueryData<DocumentsLayout>(key);
|
||||
queryClient.setQueryData<DocumentsLayout>(key, {
|
||||
...(previous ?? DEFAULT_DOCUMENTS_LAYOUT),
|
||||
...patch,
|
||||
});
|
||||
try {
|
||||
const saved = await apiPut<DocumentsLayout>(
|
||||
"/api/documents/inbound/layout",
|
||||
{ version: 1, ...patch },
|
||||
);
|
||||
if (saved) queryClient.setQueryData(key, saved);
|
||||
} catch {
|
||||
queryClient.setQueryData(key, previous);
|
||||
toast.error(t("documents.layout.saveFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
/** The vault presentation, persisted per user. Defaults until the read lands. */
|
||||
export function useDocumentsLayout(enabled: boolean = true): {
|
||||
layout: DocumentsLayout;
|
||||
isLayoutLoading: boolean;
|
||||
setView: (view: DocumentsLayoutView) => Promise<void>;
|
||||
setArrangement: (arrangement: DocumentsLayoutArrangement) => Promise<void>;
|
||||
} {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: queryKeys.documentsLayout(),
|
||||
queryFn: () => apiGet<DocumentsLayout>("/api/documents/inbound/layout"),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
enabled,
|
||||
});
|
||||
|
||||
return {
|
||||
layout: data ?? DEFAULT_DOCUMENTS_LAYOUT,
|
||||
isLayoutLoading: enabled && isLoading,
|
||||
setView: (view) =>
|
||||
runSetDocumentsLayout({ patch: { view }, queryClient, t }),
|
||||
setArrangement: (arrangement) =>
|
||||
runSetDocumentsLayout({ patch: { arrangement }, queryClient, t }),
|
||||
};
|
||||
}
|
||||
@@ -30,6 +30,12 @@ export interface DocumentVaultFilters {
|
||||
|
||||
export const documentKeys = {
|
||||
documents: () => ["documents"] as const,
|
||||
/**
|
||||
* The vault presentation (view + month arrangement). Deliberately outside
|
||||
* the `["documents"]` prefix: a document write changes nothing about how
|
||||
* the vault is laid out, so it must not refetch this.
|
||||
*/
|
||||
documentsLayout: () => ["documents-layout"] as const,
|
||||
inboundDocuments: () => ["documents", "inbound"] as const,
|
||||
/**
|
||||
* The parameterised vault list (keyset-paginated via `useInfiniteQuery`).
|
||||
|
||||
@@ -2008,6 +2008,7 @@ const accountSettingsBackupSchema = z
|
||||
insightsLayoutJson: z.unknown().optional(),
|
||||
medicationListLayoutJson: z.unknown().optional(),
|
||||
moodTagLayoutJson: z.unknown().optional(),
|
||||
documentsLayoutJson: z.unknown().optional(),
|
||||
reportSelectionJson: z.unknown().optional(),
|
||||
globalExcludedInjectionSites: z.array(z.string()).optional(),
|
||||
healthKitConfigJson: z.unknown().optional(),
|
||||
|
||||
Reference in new issue
Block a user