mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
Merge branch 'fix/v1475-speed' into release/v1.47.5
# Conflicts: # src/__tests__/baselines/source-function-lines.json
This commit is contained in:
commit
b5e118d086
88 files changed
+1475
-337
No files matched your search
@@ -0,0 +1,113 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* The health status card reads two engines that walk every vital over up to
|
||||
* 180 days. The answer is kept in the record's analytics cell: a second open
|
||||
* of Insights serves it, and a write that sweeps the record's cells, or a
|
||||
* module switch, computes it again.
|
||||
*/
|
||||
|
||||
const computeCoincidentDeviation = vi.fn();
|
||||
const buildExtendedChangepointSignals = vi.fn();
|
||||
const resolveModuleMap = vi.fn();
|
||||
|
||||
vi.mock("@/lib/insights/derived/coincident-deviation", () => ({
|
||||
computeCoincidentDeviation: (...args: unknown[]) =>
|
||||
computeCoincidentDeviation(...args),
|
||||
}));
|
||||
vi.mock("@/lib/insights/derived/changepoint", () => ({
|
||||
buildExtendedChangepointSignals: (...args: unknown[]) =>
|
||||
buildExtendedChangepointSignals(...args),
|
||||
}));
|
||||
vi.mock("@/lib/insights/derived", () => ({
|
||||
loadBaselineProfile: vi.fn().mockResolvedValue({ ageYears: 40 }),
|
||||
}));
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
auditLog: { create: vi.fn() },
|
||||
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
|
||||
resolveModuleMap: (userId: string) => resolveModuleMap(userId),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkAnalyticsReadRateLimit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
|
||||
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
|
||||
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
|
||||
|
||||
const call = () => GET();
|
||||
|
||||
beforeEach(() => {
|
||||
__resetAllCachesForTests();
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
user: {
|
||||
id: "user-1",
|
||||
username: "testuser",
|
||||
role: "USER",
|
||||
timezone: "Europe/Berlin",
|
||||
},
|
||||
} as unknown as Awaited<ReturnType<typeof getSession>>);
|
||||
vi.mocked(checkAnalyticsReadRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
} as unknown as Awaited<ReturnType<typeof checkAnalyticsReadRateLimit>>);
|
||||
computeCoincidentDeviation
|
||||
.mockReset()
|
||||
.mockResolvedValue({ status: "insufficient" });
|
||||
buildExtendedChangepointSignals.mockReset().mockResolvedValue([]);
|
||||
resolveModuleMap.mockReset().mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe("GET /api/insights/health-status — the cached answer", () => {
|
||||
it("computes once for two opens", async () => {
|
||||
const first = await call();
|
||||
const second = await call();
|
||||
|
||||
expect(first.status).toBe(200);
|
||||
expect(second.status).toBe(200);
|
||||
expect(computeCoincidentDeviation).toHaveBeenCalledTimes(1);
|
||||
expect(buildExtendedChangepointSignals).toHaveBeenCalledTimes(1);
|
||||
expect((await second.json()).data).toEqual((await first.json()).data);
|
||||
});
|
||||
|
||||
it("computes again after a measurement write", async () => {
|
||||
await call();
|
||||
invalidateUserMeasurements("user-1", { evict: true });
|
||||
await call();
|
||||
|
||||
expect(computeCoincidentDeviation).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("computes again when a module is switched off", async () => {
|
||||
await call();
|
||||
resolveModuleMap.mockResolvedValue({ sleep: false });
|
||||
await call();
|
||||
|
||||
expect(buildExtendedChangepointSignals).toHaveBeenCalledTimes(2);
|
||||
expect(buildExtendedChangepointSignals).toHaveBeenLastCalledWith(
|
||||
"user-1",
|
||||
expect.any(Date),
|
||||
{ sleep: false },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -24,8 +24,10 @@ import { prisma } from "@/lib/db";
|
||||
import { loadBaselineProfile } from "@/lib/insights/derived";
|
||||
import { computeCoincidentDeviation } from "@/lib/insights/derived/coincident-deviation";
|
||||
import { buildExtendedChangepointSignals } from "@/lib/insights/derived/changepoint";
|
||||
import { resolveModuleMap } from "@/lib/modules/gate";
|
||||
import { MODULE_KEYS, resolveModuleMap } from "@/lib/modules/gate";
|
||||
import { summariseHealthStatus } from "@/lib/insights/health-status";
|
||||
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { DEFAULT_TIMEZONE, userDayKey } from "@/lib/tz/format";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -39,36 +41,56 @@ export const GET = apiHandler(async () => {
|
||||
return apiError("Too many analytics requests. Please retry later.", 429);
|
||||
}
|
||||
|
||||
// Both engines walk every vital over up to 180 days, so the answer goes
|
||||
// through the analytics cell its sibling reads use. Measurement and mood
|
||||
// writes sweep the record's cells; the reader's day and the switched-off
|
||||
// modules are part of the key, so a new day or a module switch never serves
|
||||
// the other answer.
|
||||
const modules = await resolveModuleMap(user.id);
|
||||
const modulesOff = MODULE_KEYS.filter((key) => modules[key] === false);
|
||||
const now = new Date();
|
||||
const profile = await loadBaselineProfile(prisma, user.id);
|
||||
|
||||
const coincident = await computeCoincidentDeviation(user.id, profile, {
|
||||
tz: user.timezone,
|
||||
now,
|
||||
});
|
||||
// v1.44 — the wider scan: every vital with a stable daily level over 180
|
||||
// days, a metric whose module is off left unread.
|
||||
const shifts = await buildExtendedChangepointSignals(
|
||||
user.id,
|
||||
now,
|
||||
await resolveModuleMap(user.id),
|
||||
const day = userDayKey(now, user.timezone ?? DEFAULT_TIMEZONE);
|
||||
const body = await cachedSwr(
|
||||
caches.analytics as ServerCache<HealthStatusBody>,
|
||||
`${user.id}|health-status|${day}|off:${modulesOff.join(",")}`,
|
||||
() => buildHealthStatus(user.id, user.timezone, now, modules),
|
||||
annotate,
|
||||
);
|
||||
|
||||
const vitals = coincident.status === "ok" ? coincident.value.vitals : [];
|
||||
const summary = summariseHealthStatus(vitals, shifts);
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.health-status.read" },
|
||||
meta: {
|
||||
deviations: summary.deviations.length,
|
||||
shifts: summary.shifts.length,
|
||||
deviations: body.deviations.length,
|
||||
shifts: body.shifts.length,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
return apiSuccess(body);
|
||||
});
|
||||
|
||||
type HealthStatusBody = Awaited<ReturnType<typeof buildHealthStatus>>;
|
||||
|
||||
async function buildHealthStatus(
|
||||
userId: string,
|
||||
timezone: string | undefined,
|
||||
now: Date,
|
||||
modules: Awaited<ReturnType<typeof resolveModuleMap>>,
|
||||
) {
|
||||
const profile = await loadBaselineProfile(prisma, userId);
|
||||
const coincident = await computeCoincidentDeviation(userId, profile, {
|
||||
tz: timezone,
|
||||
now,
|
||||
});
|
||||
// v1.44 — the wider scan: every vital with a stable daily level over 180
|
||||
// days, a metric whose module is off left unread.
|
||||
const shifts = await buildExtendedChangepointSignals(userId, now, modules);
|
||||
|
||||
const vitals = coincident.status === "ok" ? coincident.value.vitals : [];
|
||||
const summary = summariseHealthStatus(vitals, shifts);
|
||||
return {
|
||||
present: summary.present,
|
||||
deviations: summary.deviations,
|
||||
shifts: summary.shifts,
|
||||
generatedAt: now.toISOString(),
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import { NextRequest } from "next/server";
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
medication: { findUnique: vi.fn() },
|
||||
medicationIntakeEvent: { findMany: vi.fn() },
|
||||
medicationIntakeEvent: { findMany: vi.fn(), findFirst: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -567,3 +567,74 @@ describe("GET /api/medications/[id]/dose-history — slots before creation (#102
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The history reads the window's rows, not every intake the medication ever
|
||||
* had: for a medication taken for years each open of the tab read thousands
|
||||
* of rows to show at most a year. Of the rows before the window only the
|
||||
* latest take is read, because a rolling grid re-starts from it.
|
||||
*/
|
||||
describe("GET /api/medications/[id]/dose-history — the read is bounded to the window", () => {
|
||||
const FROM = new Date("2026-06-01T00:00:00Z");
|
||||
const TO = new Date("2026-06-15T00:00:00Z");
|
||||
const windowQuery = `?from=${encodeURIComponent(FROM.toISOString())}&to=${encodeURIComponent(TO.toISOString())}`;
|
||||
|
||||
it("asks only for rows anchored or taken in the window", async () => {
|
||||
await GET(getReq(windowQuery), ROUTE_PARAMS);
|
||||
|
||||
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
|
||||
.calls[0][0]?.where;
|
||||
expect(where).toMatchObject({
|
||||
OR: [{ scheduledFor: { gte: FROM } }, { takenAt: { gte: FROM } }],
|
||||
});
|
||||
const before = vi.mocked(prisma.medicationIntakeEvent.findFirst).mock
|
||||
.calls[0][0];
|
||||
expect(before?.where).toMatchObject({
|
||||
skipped: false,
|
||||
scheduledFor: { lt: FROM },
|
||||
takenAt: { lt: FROM },
|
||||
});
|
||||
});
|
||||
|
||||
it("re-starts a rolling grid from the latest take before the window", async () => {
|
||||
vi.mocked(prisma.medication.findUnique).mockResolvedValue({
|
||||
id: "med-1",
|
||||
startsOn: null,
|
||||
endsOn: null,
|
||||
oneShot: false,
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
schedules: [
|
||||
{
|
||||
id: "sched-1",
|
||||
windowStart: "08:00",
|
||||
windowEnd: "08:00",
|
||||
daysOfWeek: null,
|
||||
timesOfDay: ["08:00"],
|
||||
reminderGraceMinutes: null,
|
||||
rrule: null,
|
||||
rollingIntervalDays: 7,
|
||||
scheduleType: "SCHEDULED",
|
||||
cyclicOnWeeks: null,
|
||||
cyclicOffWeeks: null,
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
// Taken four days before the window opens, nothing since: the next dose
|
||||
// was due inside the window and reads as missed there.
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue({
|
||||
takenAt: new Date("2026-05-28T06:00:00Z"),
|
||||
} as never);
|
||||
|
||||
const res = await GET(getReq(windowQuery), ROUTE_PARAMS);
|
||||
expect(res.status).toBe(200);
|
||||
const rows = (await res.json()).data.rows as Array<{
|
||||
at: string;
|
||||
kind: string;
|
||||
status: string;
|
||||
}>;
|
||||
|
||||
expect(rows.map((r) => [r.at.slice(0, 10), r.kind, r.status])).toEqual([
|
||||
["2026-06-04", "slot", "missed"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -101,6 +101,61 @@ interface SerializedDoseHistoryRow {
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The intakes a window needs: the rows anchored in it or taken in it (a late
|
||||
* take on an older slot is an intake instant of the window), and of all the
|
||||
* rows before it only the latest take, the anchor a rolling grid re-starts
|
||||
* from and the last intake when none falls in the window. Earlier takes place
|
||||
* no slot in the window. The whole history used to be read on every open, so
|
||||
* a medication taken for years read thousands of rows to show at most a year.
|
||||
*/
|
||||
async function readWindowIntakes(
|
||||
medicationId: string,
|
||||
userId: string,
|
||||
from: Date,
|
||||
) {
|
||||
const [events, takenBefore] = await Promise.all([
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
medicationId,
|
||||
userId,
|
||||
deletedAt: null,
|
||||
OR: [{ scheduledFor: { gte: from } }, { takenAt: { gte: from } }],
|
||||
},
|
||||
orderBy: [{ scheduledFor: "desc" }, { id: "desc" }],
|
||||
select: {
|
||||
id: true,
|
||||
scheduledFor: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
autoMissed: true,
|
||||
// v1.15.20 — USER_PIN rows bind by anchor in the read ledger.
|
||||
attributionSource: true,
|
||||
// v1.16.4 — per-intake dose override for the ledger's deviation hint.
|
||||
doseTaken: true,
|
||||
// v1.32.8 (iOS #64) — write provenance so the client can label how
|
||||
// each dose was recorded (Web / API / Reminder / Import / AppleHealth).
|
||||
source: true,
|
||||
// v1.42.2 — the history labels an automatically recorded dose.
|
||||
autoRecorded: true,
|
||||
},
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findFirst({
|
||||
where: {
|
||||
medicationId,
|
||||
userId,
|
||||
deletedAt: null,
|
||||
skipped: false,
|
||||
scheduledFor: { lt: from },
|
||||
takenAt: { lt: from },
|
||||
},
|
||||
orderBy: [{ takenAt: "desc" }, { id: "desc" }],
|
||||
select: { takenAt: true },
|
||||
}),
|
||||
]);
|
||||
return { events, anchorBefore: takenBefore?.takenAt ?? null };
|
||||
}
|
||||
|
||||
export const GET = apiHandler(
|
||||
async (request: NextRequest, { params }: RouteParams) => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -165,26 +220,7 @@ export const GET = apiHandler(
|
||||
Math.max(requestedFrom.getTime(), spanFloor.getTime()),
|
||||
);
|
||||
|
||||
const events = await prisma.medicationIntakeEvent.findMany({
|
||||
where: { medicationId: id, userId: user.id, deletedAt: null },
|
||||
orderBy: [{ scheduledFor: "desc" }, { id: "desc" }],
|
||||
select: {
|
||||
id: true,
|
||||
scheduledFor: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
autoMissed: true,
|
||||
// v1.15.20 — USER_PIN rows bind by anchor in the read ledger.
|
||||
attributionSource: true,
|
||||
// v1.16.4 — per-intake dose override for the ledger's deviation hint.
|
||||
doseTaken: true,
|
||||
// v1.32.8 (iOS #64) — write provenance so the client can label how
|
||||
// each dose was recorded (Web / API / Reminder / Import / AppleHealth).
|
||||
source: true,
|
||||
// v1.42.2 — the history labels an automatically recorded dose.
|
||||
autoRecorded: true,
|
||||
},
|
||||
});
|
||||
const { events, anchorBefore } = await readWindowIntakes(id, user.id, from);
|
||||
|
||||
const mapped = events.map((e) => ({
|
||||
id: e.id,
|
||||
@@ -198,7 +234,10 @@ export const GET = apiHandler(
|
||||
autoRecorded: e.autoRecorded,
|
||||
}));
|
||||
|
||||
const lastIntakeAt = lastNonSkippedTakenAt(mapped);
|
||||
const lastIntakeAt = lastNonSkippedTakenAt([
|
||||
...mapped,
|
||||
...(anchorBefore ? [{ takenAt: anchorBefore, skipped: false }] : []),
|
||||
]);
|
||||
|
||||
// A dose may be recorded before its slot's own time: the dose window opens
|
||||
// up to two hours early, and a skip can be logged ahead. Such a row is
|
||||
@@ -263,6 +302,7 @@ export const GET = apiHandler(
|
||||
const intakeInstants = mapped
|
||||
.filter((e) => !e.skipped && e.takenAt !== null && e.takenAt <= to)
|
||||
.map((e) => e.takenAt as Date)
|
||||
.concat(anchorBefore ? [anchorBefore] : [])
|
||||
.sort((a, b) => a.getTime() - b.getTime());
|
||||
|
||||
const groups = buildBandsForSchedulesWithEras({
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Flame } from "lucide-react";
|
||||
|
||||
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
/**
|
||||
* v1.4.32 — `/insights/active-energy`.
|
||||
@@ -14,6 +15,7 @@ import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page
|
||||
* imports collapse cleanly via the v1.4.30 drain script.
|
||||
*/
|
||||
export default function InsightsActiveEnergyPage() {
|
||||
const { t } = useTranslations();
|
||||
return (
|
||||
<HealthKitMetricPage
|
||||
measurementType="ACTIVE_ENERGY_BURNED"
|
||||
@@ -27,7 +29,7 @@ export default function InsightsActiveEnergyPage() {
|
||||
yAxisUnit="kcal"
|
||||
emptyStateIcon={<Flame className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any active energy yet. What's a reasonable daily target, and how does it compare to total calories?"
|
||||
coachPrefill={t("insights.activeEnergy.coachPrefill")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsLaermereignissePage() {
|
||||
yAxisUnit=""
|
||||
emptyStateIcon={<Volume2 className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any loud-environment events yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -60,7 +60,6 @@ export default function InsightsBlutzuckerPage() {
|
||||
captureType="BLOOD_GLUCOSE"
|
||||
targetSummarySlug="blood-glucose"
|
||||
afterChart={<GlucoseClinicalPanel />}
|
||||
coachPrefill="I haven't logged any blood glucose yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -87,7 +87,7 @@ export default function InsightsBlutdruckPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I haven't recorded any blood pressure yet. Why does it matter, and what should I know before I start?"
|
||||
coachPrefill={t("insights.emptyState.bloodPressure.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -90,7 +90,7 @@ export default function InsightsBmiPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I haven't recorded any weight yet. Why does BMI matter for me, and what should I know before I start tracking it?"
|
||||
coachPrefill={t("insights.emptyState.bmi.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Thermometer } from "lucide-react";
|
||||
|
||||
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
/**
|
||||
* v1.4.32 — `/insights/body-temperature`.
|
||||
@@ -13,6 +14,7 @@ import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page
|
||||
* them on separate enum values per the v1.4.30 categorisation overlay.
|
||||
*/
|
||||
export default function InsightsBodyTemperaturePage() {
|
||||
const { t } = useTranslations();
|
||||
return (
|
||||
<HealthKitMetricPage
|
||||
measurementType="BODY_TEMPERATURE"
|
||||
@@ -24,7 +26,7 @@ export default function InsightsBodyTemperaturePage() {
|
||||
color="var(--chart-3)"
|
||||
emptyStateIcon={<Thermometer className="size-6" />}
|
||||
emptyStateCtaType="BODY_TEMPERATURE"
|
||||
coachPrefill="I haven't logged any body temperature yet. What's the healthy range, and what should I do if it drifts?"
|
||||
coachPrefill={t("insights.bodyTemperature.coachPrefill")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export default function InsightsKoerperwasserPage() {
|
||||
emptyStateIcon={<Droplet className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
captureType="TOTAL_BODY_WATER"
|
||||
coachPrefill="I haven't logged any total body water yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export default function InsightsKnochenmassePage() {
|
||||
emptyStateIcon={<Bone className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
captureType="BONE_MASS"
|
||||
coachPrefill="I haven't logged any bone mass yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function InsightsBreathingDisturbancesPage() {
|
||||
unitKey="insights.units.breathingEvents"
|
||||
emptyStateIcon={<Wind className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any sleep-breathing-disturbance data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -27,7 +27,6 @@ export default function InsightsCardioFitnessPage() {
|
||||
statIcon={Gauge}
|
||||
emptyStateIcon={<Gauge className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any cardio-fitness (VO₂ max) data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsCardioRecoveryPage() {
|
||||
yAxisUnit="bpm"
|
||||
emptyStateIcon={<HeartPulse className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any cardio-recovery data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsTageslichtPage() {
|
||||
yAxisUnit="min"
|
||||
emptyStateIcon={<Sun className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any time spent in daylight yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsDoppelstandphasePage() {
|
||||
yAxisUnit="%"
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any double support time yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsLaermbelastungPage() {
|
||||
yAxisUnit="dBA"
|
||||
emptyStateIcon={<Volume2 className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any environmental sound exposure yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { PersonStanding } from "lucide-react";
|
||||
|
||||
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
/**
|
||||
* v1.10.0 — `/insights/falls`.
|
||||
@@ -11,6 +12,7 @@ import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page
|
||||
* better. The series arrives from Apple Health sync — no manual-entry CTA.
|
||||
*/
|
||||
export default function InsightsFallsPage() {
|
||||
const { t } = useTranslations();
|
||||
return (
|
||||
<HealthKitMetricPage
|
||||
measurementType="FALL_COUNT"
|
||||
@@ -23,7 +25,7 @@ export default function InsightsFallsPage() {
|
||||
unitKey="insights.units.falls"
|
||||
emptyStateIcon={<PersonStanding className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any fall data yet. What does this metric tell me about my health, and how do I lower my fall risk?"
|
||||
coachPrefill={t("insights.falls.coachPrefill")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function InsightsFettfreieMassePage() {
|
||||
color="var(--chart-1)"
|
||||
emptyStateIcon={<Scale className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any fat-free mass yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function InsightsFettmassePage() {
|
||||
color="var(--chart-5)"
|
||||
emptyStateIcon={<Droplets className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any fat mass yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export default function InsightsStockwerkePage() {
|
||||
unitKey="insights.units.flights"
|
||||
emptyStateIcon={<TrendingUp className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any flights climbed yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsKopfhoererpegelPage() {
|
||||
yAxisUnit="dBA"
|
||||
emptyStateIcon={<Headphones className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any headphone audio exposure yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Activity } from "lucide-react";
|
||||
|
||||
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { EcgCrossLink } from "@/components/insights/ecg-cross-link";
|
||||
|
||||
/**
|
||||
@@ -20,6 +21,7 @@ import { EcgCrossLink } from "@/components/insights/ecg-cross-link";
|
||||
* own, labelled, because the two are not one measure.
|
||||
*/
|
||||
export default function InsightsHrvPage() {
|
||||
const { t } = useTranslations();
|
||||
return (
|
||||
<HealthKitMetricPage
|
||||
measurementType="HEART_RATE_VARIABILITY"
|
||||
@@ -37,7 +39,7 @@ export default function InsightsHrvPage() {
|
||||
yAxisUnit="ms"
|
||||
emptyStateIcon={<Activity className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any HRV data yet. What does heart-rate variability tell me, and how do I capture it?"
|
||||
coachPrefill={t("insights.hrv.coachPrefill")}
|
||||
// S10 / H1 — device-attributed pointer into the ECG viewer, in the
|
||||
// HRV / heart context. Self-gates to nothing without recordings.
|
||||
afterAssessment={<EcgCrossLink />}
|
||||
|
||||
@@ -24,7 +24,6 @@ export default function InsightsMagermassePage() {
|
||||
color="var(--chart-1)"
|
||||
emptyStateIcon={<Scale className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any lean body mass yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* Insights > Medications: the efficacy summary sits below every medication
|
||||
* card and asks one efficacy read per medication. On entry it holds its slot
|
||||
* with a sentinel and mounts only when scrolled near, so opening the page
|
||||
* sends the cards' reads and not the summary's.
|
||||
*/
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) =>
|
||||
queryKey[1] === "comprehensive"
|
||||
? {
|
||||
data: {
|
||||
medications: [
|
||||
{
|
||||
id: "m1",
|
||||
name: "Ramipril",
|
||||
dose: "5 mg",
|
||||
category: "BLOOD_PRESSURE",
|
||||
compliance7: 100,
|
||||
compliance30: 95,
|
||||
streak: 7,
|
||||
taken7: 7,
|
||||
skipped7: 0,
|
||||
missed7: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
}
|
||||
: { data: undefined, isLoading: false, isError: false },
|
||||
}));
|
||||
vi.mock("@/hooks/use-auth", () => ({
|
||||
useAuth: () => ({ isAuthenticated: true }),
|
||||
}));
|
||||
vi.mock("@/hooks/use-ai-capability", () => ({
|
||||
useAiCapability: () => ({ available: false }),
|
||||
useAiProviderState: () => ({ responseTimeoutMs: null }),
|
||||
}));
|
||||
vi.mock("@/components/insights/medication-efficacy-summary", () => ({
|
||||
MedicationEfficacySummary: () => <div data-slot="efficacy-summary-mounted" />,
|
||||
}));
|
||||
vi.mock("@/components/insights/sub-page-shell", () => ({
|
||||
SubPageShell: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
vi.mock("@/components/insights/glp1-substance-curve-summary", () => ({
|
||||
Glp1SubstanceCurveSummary: () => null,
|
||||
}));
|
||||
vi.mock("@/components/insights/metric-target-summary", () => ({
|
||||
MetricTargetSummary: () => null,
|
||||
}));
|
||||
vi.mock("@/components/insights/insight-status-card", () => ({
|
||||
InsightStatusCard: () => null,
|
||||
}));
|
||||
vi.mock("@/components/insights/coach-launch-button", () => ({
|
||||
CoachLaunchButton: () => null,
|
||||
}));
|
||||
vi.mock("@/components/charts/compliance-heatmap", () => ({
|
||||
ComplianceHeatmap: () => null,
|
||||
}));
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import InsightsMedikamentePage from "../page";
|
||||
|
||||
describe("/insights/medications on entry", () => {
|
||||
it("renders the cards and holds the efficacy summary until scrolled near", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">
|
||||
<InsightsMedikamentePage />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Ramipril");
|
||||
expect(html).toContain('data-deferred-section="medication-efficacy"');
|
||||
expect(html).not.toContain("efficacy-summary-mounted");
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,7 @@ import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
|
||||
import { InsightStatusCard } from "@/components/insights/insight-status-card";
|
||||
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
|
||||
import { MedicationEfficacySummary } from "@/components/insights/medication-efficacy-summary";
|
||||
import { DeferUntilNear } from "@/components/insights/defer-until-near";
|
||||
import { Glp1SubstanceCurveSummary } from "@/components/insights/glp1-substance-curve-summary";
|
||||
import { SubPageShell } from "@/components/insights/sub-page-shell";
|
||||
import { TileHeader } from "@/components/insights/tile-header";
|
||||
@@ -321,12 +322,12 @@ export default function InsightsMedikamentePage() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* v1.28 — compact efficacy summary: reuses the same server-computed
|
||||
efficacy DTO the detail-page "Wirkung" tab reads (never a second
|
||||
computation), association-only, linking through to the full view. */}
|
||||
<MedicationEfficacySummary
|
||||
medications={medications.map((m) => ({ id: m.id, name: m.name }))}
|
||||
/>
|
||||
{/* v1.28 — one efficacy read per medication, below every card: mounted when near. */}
|
||||
<DeferUntilNear id="medication-efficacy">
|
||||
<MedicationEfficacySummary
|
||||
medications={medications.map((m) => ({ id: m.id, name: m.name }))}
|
||||
/>
|
||||
</DeferUntilNear>
|
||||
|
||||
{/* v1.28.20 — estimated active-substance curve for GLP-1 medications
|
||||
(additive; renders nothing when the user has no GLP-1 medication). */}
|
||||
|
||||
@@ -132,7 +132,7 @@ export default function InsightsMoodPageClient() {
|
||||
<Link href="/mood">{t("insights.emptyState.mood.cta")}</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I haven't logged any mood entries yet. Why does mood tracking matter, and how should I start?"
|
||||
coachPrefill={t("insights.emptyState.mood.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -24,7 +24,6 @@ export default function InsightsMuskelmassePage() {
|
||||
color="var(--chart-1)"
|
||||
emptyStateIcon={<Dumbbell className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any muscle mass yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { ValueBand } from "@/lib/analytics/value-bands";
|
||||
|
||||
@@ -37,7 +38,9 @@ function bandsRendered(thresholds: unknown): ValueBand[] {
|
||||
}
|
||||
const html = renderToStaticMarkup(
|
||||
<QueryClientProvider client={client}>
|
||||
<InsightsOxygenSaturationPage />
|
||||
<I18nProvider initialLocale="en">
|
||||
<InsightsOxygenSaturationPage />
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const match = /<pre[^>]*>([^<]*)<\/pre>/.exec(html);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { Wind } from "lucide-react";
|
||||
|
||||
import { HealthKitMetricPage } from "@/components/insights/healthkit-metric-page";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { buildOxygenSaturationBands } from "@/lib/analytics/value-bands";
|
||||
import { useOwnTargetRange } from "@/lib/queries/use-own-target-range";
|
||||
|
||||
@@ -20,6 +21,7 @@ import { useOwnTargetRange } from "@/lib/queries/use-own-target-range";
|
||||
* `/targets`, and the clinical bands otherwise.
|
||||
*/
|
||||
export default function InsightsOxygenSaturationPage() {
|
||||
const { t } = useTranslations();
|
||||
const ownRange = useOwnTargetRange("OXYGEN_SATURATION");
|
||||
return (
|
||||
<HealthKitMetricPage
|
||||
@@ -38,7 +40,7 @@ export default function InsightsOxygenSaturationPage() {
|
||||
emptyStateIcon={<Wind className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
captureType="OXYGEN_SATURATION"
|
||||
coachPrefill="I haven't logged any oxygen-saturation data yet. What does SpO₂ tell me, and what range should I aim for?"
|
||||
coachPrefill={t("insights.oxygenSaturation.coachPrefill")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsPulswellengeschwindigkeitPage() {
|
||||
yAxisUnit="m/s"
|
||||
emptyStateIcon={<Activity className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any pulse wave velocity yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -115,7 +115,7 @@ export default function InsightsPulsPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I haven't recorded any resting pulse yet. Why does it matter, and what should I know before I start?"
|
||||
coachPrefill={t("insights.emptyState.pulse.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -25,7 +25,6 @@ export default function InsightsAtemfrequenzPage() {
|
||||
unitKey="insights.units.respiratoryRate"
|
||||
emptyStateIcon={<Wind className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any respiratory rate yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export default function InsightsSixMinuteWalkPage() {
|
||||
yAxisUnit="m"
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any six-minute-walk data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,6 @@ export default function InsightsHauttemperaturPage() {
|
||||
color="var(--chart-5)"
|
||||
emptyStateIcon={<Thermometer className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any skin temperature yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
afterChart={
|
||||
<ConnectedDeviceScoreTile
|
||||
type="BODY_TEMPERATURE_DEVIATION"
|
||||
|
||||
@@ -70,7 +70,7 @@ export default function InsightsSchlafPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I don't have any sleep data yet. Why does sleep tracking matter, and what should I know before I connect a source?"
|
||||
coachPrefill={t("insights.emptyState.sleep.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -25,7 +25,6 @@ export default function InsightsStairAscentSpeedPage() {
|
||||
yAxisUnit="m/s"
|
||||
emptyStateIcon={<Gauge className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any stair-ascent-speed data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -25,7 +25,6 @@ export default function InsightsStairDescentSpeedPage() {
|
||||
yAxisUnit="m/s"
|
||||
emptyStateIcon={<Gauge className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any stair-descent-speed data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsSchrittlaengePage() {
|
||||
yAxisUnit="m"
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking step length yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -40,7 +40,7 @@ export default function InsightsStepsPage() {
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
captureType="ACTIVITY_STEPS"
|
||||
coachPrefill="I haven't logged any steps yet. What's a reasonable daily step target, and how does walking more help my health?"
|
||||
coachPrefill={t("insights.steps.coachPrefill")}
|
||||
afterChart={
|
||||
calendarVisible ? (
|
||||
<CrossLinkCard
|
||||
|
||||
@@ -25,7 +25,6 @@ export default function InsightsGefaessalterPage() {
|
||||
unitKey="insights.units.years"
|
||||
emptyStateIcon={<HeartPulse className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any vascular age yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsViszeralfettPage() {
|
||||
yAxisUnit=""
|
||||
emptyStateIcon={<Droplets className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any visceral fat yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsGangasymmetriePage() {
|
||||
yAxisUnit="%"
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking asymmetry yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function InsightsGehstreckePage() {
|
||||
color="var(--chart-2)"
|
||||
emptyStateIcon={<Footprints className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking and running distance yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsGehpulsPage() {
|
||||
yAxisUnit="bpm"
|
||||
emptyStateIcon={<HeartPulse className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking heart rate average yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function InsightsGehgeschwindigkeitPage() {
|
||||
color="var(--chart-2)"
|
||||
emptyStateIcon={<Gauge className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking speed yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export default function InsightsGangstabilitaetPage() {
|
||||
yAxisUnit="%"
|
||||
emptyStateIcon={<Gauge className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any walking steadiness yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ export default function InsightsGewichtPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
coachPrefill="I haven't recorded any weight yet. Why does it matter, and what should I know before I start tracking?"
|
||||
coachPrefill={t("insights.emptyState.weight.coachPrefill")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -142,7 +142,7 @@ export default function InsightsWorkoutsPageClient() {
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
coachPrefill="I haven't logged any workouts yet. Why does tracking them matter, and what should I focus on first?"
|
||||
coachPrefill={t("insights.workouts.emptyState.coachPrefill")}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -24,7 +24,6 @@ export default function InsightsWristTemperaturePage() {
|
||||
color="var(--chart-5)"
|
||||
emptyStateIcon={<Thermometer className="size-6" />}
|
||||
emptyStateCtaType={null}
|
||||
coachPrefill="I haven't logged any wrist-temperature data yet. What does this metric tell me about my health, and how do I improve it?"
|
||||
/>
|
||||
);
|
||||
}
|
||||
+16
-2
@@ -8,6 +8,7 @@ import "./globals.css";
|
||||
import { Providers } from "@/components/providers";
|
||||
import { AuthShell } from "@/components/layout/auth-shell";
|
||||
import { MonitoringBootstrap } from "@/components/monitoring/bootstrap";
|
||||
import { getPublicMonitoringSettings } from "@/lib/monitoring-settings";
|
||||
import { WebVitalsReporter } from "@/components/monitoring/web-vitals-reporter";
|
||||
import { resolveInitialLocale } from "@/lib/i18n/resolve-initial-locale";
|
||||
import { isKeyMismatch } from "@/lib/boot/key-mismatch-state";
|
||||
@@ -86,7 +87,12 @@ export default async function RootLayout({
|
||||
? ((await headers()).get("x-nonce") ?? undefined)
|
||||
: undefined;
|
||||
|
||||
const initialLocale = await resolveInitialLocale();
|
||||
// The monitoring switches ride the document render instead of a request
|
||||
// from every page load; the key-mismatch page reads no data.
|
||||
const [initialLocale, monitoring] = await Promise.all([
|
||||
resolveInitialLocale(),
|
||||
isKeyMismatch() ? null : getPublicMonitoringSettings(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<html lang={initialLocale} suppressHydrationWarning>
|
||||
@@ -139,7 +145,15 @@ export default async function RootLayout({
|
||||
<KeyMismatchPage locale={initialLocale} />
|
||||
) : (
|
||||
<Providers initialLocale={initialLocale}>
|
||||
<MonitoringBootstrap />
|
||||
<MonitoringBootstrap
|
||||
settings={
|
||||
monitoring && {
|
||||
umamiEnabled: monitoring.umamiEnabled,
|
||||
umamiWebsiteId: monitoring.umamiWebsiteId,
|
||||
glitchtipEnabled: monitoring.glitchtipEnabled,
|
||||
}
|
||||
}
|
||||
/>
|
||||
<WebVitalsReporter />
|
||||
{/* `DEMO_MODE` is a server-only env var; the proxy uses it to
|
||||
block mutations. Resolve it here (server component) and
|
||||
|
||||
@@ -102,6 +102,19 @@ export default async function DashboardPage() {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(queryKeys.dashboardSnapshot(locale), wireBody);
|
||||
queryClient.setQueryData(queryKeys.dashboardWidgets(), wireBody.layout);
|
||||
// The mood chart's series rides the mood tile (same engine as
|
||||
// `/api/mood/analytics`); seeded with readings only, where the tile's
|
||||
// summary is the route's.
|
||||
const mood = (
|
||||
wireBody.tiles as
|
||||
{ mood?: { entries: unknown[]; summary: unknown } } | undefined
|
||||
)?.mood;
|
||||
if (mood?.summary && mood.entries.length > 0) {
|
||||
queryClient.setQueryData(queryKeys.moodAnalytics(), {
|
||||
entries: mood.entries,
|
||||
summary: mood.summary,
|
||||
});
|
||||
}
|
||||
|
||||
// Above-the-fold prefetch runs ONLY in snapshot mode: legacy mode derives
|
||||
// its chart-type list from analytics queries the RSC did not run, so there
|
||||
|
||||
Reference in new issue
Block a user