Answer the native client's open server asks

- Publish timezone, glucoseUnit and a features block on the account
  payload; glucoseUnit reads as the closed pair the contract names, and
  features.trackIntake tells a separately released client that
  medications take the record-only switch.
- Refuse a new dose for a record-only medication with
  medication.intake.notTracked on every dose-writing route; the bulk
  route reports it per entry as intake_not_tracked, and correcting an
  already resolved event stays open.
- Answer passkey sign-in failures by name instead of a 500:
  passkey.challenge.expired, passkey.unknown, passkey.response.invalid
  and passkey.verification.failed, each with an audit row.
- Carry one account-wide adherence figure in meta.aggregate on the
  batched compliance read, weighted by expected doses, and accept
  ?days=30|60|90|180|365 for a report window.
- Accept ?days=30|90|180|365 on the mood insights read so stability
  covers the period shown, and name the window it covers.
- Keep only the reminder that announces a dose off APNs when the phone
  owns medication reminders; follow-ups for a dose still open are
  pushed again, marked by a followUp flag the reminder cron sets.
- Document which batch validation issues belong to an entry and pin it
  with a test that splits and resends a batch; publish rejectedFields
  items as ValidationIssue.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 10:32:11 +02:00
1 parent 7bcb6f71d9
commit bb563b6506
50 files changed
+1789 -142

No files matched your search

@@ -0,0 +1,86 @@
/**
* `GET /api/mood/insights?days=N` serves the stability score for the period
* a client shows. The aggregate is cached once per user with every window in
* it; the route picks one, names it, and keeps the per-window map off the
* wire.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/modules/gate", () => ({
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
}));
vi.mock("@/lib/cache/server-cache", () => ({
cachedSwr: vi.fn(),
caches: { moodInsights: {} },
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
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 { cachedSwr } from "@/lib/cache/server-cache";
import { requireModuleEnabled } from "@/lib/modules/gate";
const year = { score: 40, stdDev: 0.9, band: "variable", days: 300 };
const month = { score: 90, stdDev: 0.2, band: "verySteady", days: 28 };
const AGGREGATE = {
summary: { totalEntries: 300 },
heatmap: { windowDays: 365, cells: [] },
tags: [],
stability: year,
stabilityByWindow: { 30: month, 90: null, 180: year, 365: year },
};
const call = (query = "") =>
(GET as (req: Request) => Promise<Response>)(
new Request(`http://localhost/api/mood/insights${query}`),
);
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue({
session: { id: "s", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "u", role: "USER", timezone: "UTC" },
} as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true } as never);
vi.mocked(cachedSwr).mockResolvedValue(AGGREGATE as never);
});
describe("GET /api/mood/insights — stability per period", () => {
it("serves the whole year by default and names the window", async () => {
const body = await (await call()).json();
expect(body.data.stability).toEqual(year);
expect(body.data.stabilityWindowDays).toBe(365);
expect(body.data).not.toHaveProperty("stabilityByWindow");
});
it("serves the chosen window as stability on ?days=30", async () => {
const body = await (await call("?days=30")).json();
expect(body.data.stability).toEqual(month);
expect(body.data.stabilityWindowDays).toBe(30);
});
it("answers null, not the year's score, when the window has too few days", async () => {
const body = await (await call("?days=90")).json();
expect(body.data.stability).toBeNull();
expect(body.data.stabilityWindowDays).toBe(90);
});
it("refuses a window it does not offer", async () => {
const res = await call("?days=45");
expect(res.status).toBe(422);
expect(cachedSwr).not.toHaveBeenCalled();
});
});
+38 -3
View File
@@ -1,10 +1,14 @@
import { apiSuccess } from "@/lib/api-response";
import { z } from "zod/v4";
import { apiSuccess, returnAllZodIssues } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
import {
fetchMoodAggregates,
MOOD_STABILITY_WINDOWS,
type MoodAggregates,
type MoodStabilityWindow,
} from "@/lib/insights/mood-aggregates";
import { requireModuleEnabled } from "@/lib/modules/gate";
@@ -26,9 +30,28 @@ export const dynamic = "force-dynamic";
* aggregate is served immediately and a single background recompute
* warms a fresh one, so an active logger never re-pays the cold compute.
*/
export const GET = apiHandler(async () => {
/**
* `?days=N` cuts `stability` to the trailing N days, so a period picker shows
* the steadiness of the period it shows. Without it the score covers the
* whole year, as it always has; `stabilityWindowDays` names the window the
* served score covers either way.
*/
const querySchema = z.object({
days: z
.enum(MOOD_STABILITY_WINDOWS.map(String) as [string, ...string[]])
.transform((v) => Number(v) as MoodStabilityWindow)
.optional(),
});
export const GET = apiHandler(async (request: Request) => {
const { user } = await requireAuth();
const query = querySchema.safeParse(
Object.fromEntries(new URL(request.url).searchParams),
);
if (!query.success) return returnAllZodIssues(query.error, 422);
const stabilityWindowDays: MoodStabilityWindow = query.data.days ?? 365;
// Per-domain gate: the mood-insights aggregate surface only serves the
// mood module's analysis page, so it must be gated on the mood module
// (mirrors `/api/insights/mood-status`). Disabled ⇒ 403 module.disabled.
@@ -51,5 +74,17 @@ export const GET = apiHandler(async () => {
},
});
return apiSuccess(result);
// 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.
const { stabilityByWindow, ...wire } = result;
return apiSuccess({
...wire,
stability:
stabilityWindowDays === 365
? result.stability
: (stabilityByWindow?.[stabilityWindowDays] ?? null),
stabilityWindowDays,
});
});