perf(i18n,shell): ship one locale and stop blocking the first paint

The client bundle carries only the active locale — resolved on the
server and handed to the provider with no hydration flash, halving the
dashboard route to under a megabyte parsed (288 KiB gzip). The auth
shell renders the app chrome immediately instead of a spinner while the
session resolves in parallel, the widgets request folds into the
snapshot it duplicated, and insight pills prefetch their sub-pages —
a first visit to a sub-page lands in about ninety milliseconds instead
of nearly a second.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 02:19:27 +02:00
1 parent 9445d89b76
commit 3b480b9885
284 files changed
+6058 -5398

No files matched your search

@@ -9,7 +9,7 @@ import { join } from "node:path";
* thick `/api/analytics` envelope; every per-type tile waited on the
* heavy fan-out before paint. Mood and medication tiles arrived first
* (separate routes) and then every other tile arrived as one burst,
* which Marc reported as "etwas nervig" in the v1.4.39.1 post-deploy
* which the maintainer reported as "etwas nervig" in the v1.4.39.1 post-deploy
* trace.
*
* Post-fix the dashboard mounts TWO `useAnalyticsQuery` calls in
@@ -70,19 +70,19 @@ describe("GET /api/admin/audit-log — extended filters", () => {
});
it("filters by `actor` against userId OR user.username", async () => {
await GET(req("actor=marc"));
await GET(req("actor=testuser"));
const call = vi.mocked(prisma.auditLog.findMany).mock.calls[0][0]!;
const where = call.where as Record<string, unknown>;
// Expect an OR clause covering userId + user.username (contains)
expect(where.OR).toBeDefined();
const or = where.OR as Array<Record<string, unknown>>;
const matchesUserId = or.some((c) => c.userId === "marc");
const matchesUserId = or.some((c) => c.userId === "testuser");
const matchesUsername = or.some(
(c) =>
typeof c.user === "object" &&
c.user !== null &&
// user: { username: { contains: "marc", mode: "insensitive" } }
JSON.stringify(c).toLowerCase().includes("marc"),
// user: { username: { contains: "testuser", mode: "insensitive" } }
JSON.stringify(c).toLowerCase().includes("testuser"),
);
expect(matchesUserId).toBe(true);
expect(matchesUsername).toBe(true);
@@ -60,7 +60,7 @@ import { getSession } from "@/lib/auth/session";
const ADMIN_SESSION = {
session: { id: "sess-admin", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "admin-1", username: "marc", role: "ADMIN" as const },
user: { id: "admin-1", username: "testuser", role: "ADMIN" as const },
};
const USER_SESSION = {
session: { id: "sess-user", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -4,7 +4,7 @@ import { annotate, getEvent } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { dispatchLocalisedNotification } from "@/lib/notifications/dispatch-localised";
import { getUserTodayBounds, getDayOfWeekInTz } from "@/lib/timezone";
import { getUserTodayBounds, getDayOfWeekInTz } from "@/lib/tz/local-day";
export const dynamic = "force-dynamic";
@@ -33,7 +33,7 @@ import { prisma } from "@/lib/db";
const ADMIN_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "admin-1", username: "marc", role: "ADMIN" as const },
user: { id: "admin-1", username: "testuser", role: "ADMIN" as const },
};
const USER_OK = {
session: { id: "sess-2", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -71,7 +71,7 @@ describe("PUT /api/admin/users/[id]", () => {
new HttpError(401, "Not authenticated"),
);
await expect(
PUT(jsonReq({ username: "marc" }), params("u1")),
PUT(jsonReq({ username: "testuser" }), params("u1")),
).rejects.toThrow("Not authenticated");
});
@@ -80,7 +80,7 @@ describe("PUT /api/admin/users/[id]", () => {
new HttpError(403, "Admin access required"),
);
await expect(
PUT(jsonReq({ username: "marc" }), params("u1")),
PUT(jsonReq({ username: "testuser" }), params("u1")),
).rejects.toThrow("Admin access required");
});
@@ -97,7 +97,7 @@ describe("PUT /api/admin/users/[id]", () => {
it("returns 404 when target user does not exist", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
const res = await PUT(jsonReq({ username: "marc" }), params("u-missing"));
const res = await PUT(jsonReq({ username: "testuser" }), params("u-missing"));
expect(res.status).toBe(404);
expect(vi.mocked(prisma.user.update)).not.toHaveBeenCalled();
});
@@ -102,7 +102,7 @@ describe("POST /api/auth/check-user — audit-log row (M-1)", () => {
_count: { passkeys: 2 },
} as never);
const res = await POST(makeRequest({ identifier: "marc" }));
const res = await POST(makeRequest({ identifier: "testuser" }));
expect(res.status).toBe(200);
expect(auditLog).toHaveBeenCalledTimes(1);
@@ -111,7 +111,7 @@ describe("POST /api/auth/check-user — audit-log row (M-1)", () => {
ipAddress: "203.0.113.1",
details: {
branch: "passkey_only",
identifier_hash: expectedHash("marc"),
identifier_hash: expectedHash("testuser"),
},
});
});
@@ -123,13 +123,13 @@ describe("POST /api/auth/check-user — audit-log row (M-1)", () => {
_count: { passkeys: 0 },
} as never);
const res = await POST(makeRequest({ identifier: "marc@example.com" }));
const res = await POST(makeRequest({ identifier: "user@example.com" }));
expect(res.status).toBe(200);
const args = vi.mocked(auditLog).mock.calls[0];
expect(args[1]?.details).toEqual({
branch: "email_fallback",
identifier_hash: expectedHash("marc@example.com"),
identifier_hash: expectedHash("user@example.com"),
});
expect(args[1]?.userId).toBe("user-2");
});
@@ -75,8 +75,8 @@ import { createSession } from "@/lib/auth/session";
const FAKE_USER = {
id: "user-1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
passwordHash: "$argon2id$...",
};
@@ -88,7 +88,7 @@ function makeRequest(headers: Record<string, string> = {}): NextRequest {
...headers,
},
body: JSON.stringify({
email: "marc@example.com",
email: "user@example.com",
password: "supersecret",
}),
});
@@ -48,7 +48,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(): NextRequest {
@@ -35,7 +35,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(deviceIdHeader?: string): NextRequest {
@@ -47,7 +47,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPatch(body: unknown): Request {
@@ -39,7 +39,7 @@ import { DEFAULT_DOCTOR_REPORT_PREFS } from "@/lib/validations/doctor-report-pre
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPut(body: unknown): Request {
@@ -69,7 +69,7 @@ describe("GET /api/auth/me/doctor-report-prefs", () => {
data: typeof DEFAULT_DOCTOR_REPORT_PREFS;
};
expect(env.data).toEqual(DEFAULT_DOCTOR_REPORT_PREFS);
expect(env.data.mood).toBe(false); // privacy default per Marc
expect(env.data.mood).toBe(false); // privacy default per the maintainer
});
});
@@ -145,7 +145,7 @@ describe("PUT /api/auth/me/doctor-report-prefs", () => {
});
// ── Case 4 — unauthenticated cross-user request ────────────────────
// Marc's spec mentions "cross-user 404" — the route layer returns 401
// the maintainer's spec mentions "cross-user 404" — the route layer returns 401
// when there is no session at all, which is the only "you are not the
// right user" surface available before requireAuth() resolves an
// identity. `prisma.user.update` must NOT fire in this case.
@@ -48,7 +48,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPatch(body: unknown): Request {
@@ -48,7 +48,7 @@ import { RESEARCH_MODE_DISCLAIMER_VERSION } from "@/lib/medications/glp1-pk";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPost(body: unknown): Request {
@@ -37,7 +37,7 @@ import { auditLog } from "@/lib/auth/audit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPut(body: unknown): Request {
@@ -38,7 +38,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkReq(body: unknown): NextRequest {
@@ -46,7 +46,7 @@ import { auditLog } from "@/lib/auth/audit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function mkPatch(body: unknown): Request {
@@ -60,8 +60,8 @@ import {
const FAKE_USER = {
id: "user-1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
};
function makeRequest(headers: Record<string, string> = {}): NextRequest {
@@ -41,7 +41,7 @@ import { auditLog } from "@/lib/auth/audit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(body: unknown): NextRequest {
@@ -41,7 +41,7 @@ import { auditLog } from "@/lib/auth/audit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -65,7 +65,7 @@ const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "marc",
username: "testuser",
role: "USER" as const,
displayName: null,
},
@@ -134,7 +134,7 @@ describe("GET /api/dashboard/summary", () => {
metrics: Array<{ id: string; kind: string; sparkline: number[] }>;
};
};
expect(body.data.greeting.salutation).toBe("Hi, marc");
expect(body.data.greeting.salutation).toBe("Hi, testuser");
expect(body.data.streak.currentDays).toBe(0);
expect(body.data.compliance.scheduledToday).toBe(0);
// REG-11 (v1.4.44): weight is the only always-emitted base metric.
@@ -48,7 +48,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(): NextRequest {
+1 -1
View File
@@ -59,7 +59,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(body: unknown): NextRequest {
@@ -72,7 +72,7 @@ function setEmptyDataMocks() {
);
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
username: "marc",
username: "testuser",
dateOfBirth: null,
gender: null,
heightCm: null,
@@ -3,7 +3,7 @@
*
* Returns one boolean per toggleable section so the dialog can hide
* checkboxes for data types that have zero rows in the user-selected
* date range (Marc's "hide-when-empty" rule). Pure presence check —
* date range (the maintainer's "hide-when-empty" rule). Pure presence check —
* `count` queries on small indexed tables — so this is cheap enough to
* run on every date-range change in the dialog without driving cost.
*
@@ -36,7 +36,7 @@ import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(): NextRequest {
@@ -43,7 +43,7 @@ const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "marc",
username: "testuser",
role: "USER" as const,
createdAt: new Date("2026-03-01T00:00:00.000Z"),
heightCm: null,
@@ -43,7 +43,7 @@ const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "marc",
username: "testuser",
role: "USER" as const,
createdAt: new Date("2026-03-01T00:00:00.000Z"),
heightCm: null,
@@ -37,7 +37,7 @@ import { getSession } from "@/lib/auth/session";
const OWNER_SESSION = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
const OTHER_SESSION = {
session: { id: "sess-2", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -45,7 +45,7 @@ const OTHER_SESSION = {
};
const ADMIN_SESSION = {
session: { id: "sess-a", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "admin-1", username: "marc-admin", role: "ADMIN" as const },
user: { id: "admin-1", username: "test-admin", role: "ADMIN" as const },
};
const NOW = new Date("2026-05-15T10:00:00.000Z");
@@ -58,7 +58,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -45,7 +45,7 @@ import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -41,7 +41,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -97,7 +97,7 @@ const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-comp-1",
username: "marc",
username: "testuser",
role: "USER" as const,
locale: "en",
},
@@ -45,7 +45,7 @@ import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
+2 -2
View File
@@ -21,7 +21,7 @@ import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { prisma } from "@/lib/db";
import { getLocalDateParts } from "@/lib/timezone";
import { wallClockInTz } from "@/lib/tz/wall-clock";
import type { MeasurementType } from "@/generated/prisma/client";
import {
discoverCorrelations,
@@ -39,7 +39,7 @@ const WINDOW_DAYS = 180;
/** Day key (YYYY-MM-DD) for an instant in the user's display timezone. */
function tzDayKey(at: Date, tz: string): string {
const { year, month, day } = getLocalDateParts(at, tz);
const { year, month, day } = wallClockInTz(at, tz);
const mm = String(month).padStart(2, "0");
const dd = String(day).padStart(2, "0");
return `${year}-${mm}-${dd}`;
@@ -64,7 +64,7 @@ import { computeDerivedMetric } from "@/lib/insights/derived";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -54,7 +54,7 @@ import { computeDerivedMetric } from "@/lib/insights/derived";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -268,7 +268,7 @@ describe("POST /api/insights/generate — provider error mapping", () => {
});
// v1.4.16 A7.1: rate limit raised from 2 → 10/h, env-configurable.
// the maintainer reported the previous 2/h was too aggressive when iterating on
// The maintainer reported the previous 2/h was too aggressive when iterating on
// settings. The 10/h ceiling is the new default; the env override lets
// operators on a tight LLM budget dial it back without a rebuild.
describe("POST /api/insights/generate — rate limit (v1.4.16 A7.1)", () => {
@@ -47,7 +47,7 @@ import { generateMetricStatus } from "@/lib/insights/metric-status";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -46,7 +46,7 @@ import { enqueueForceWarm } from "@/lib/jobs/insight-pregenerate-shared";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callPost = POST as unknown as (req: NextRequest) => Promise<Response>;
@@ -41,7 +41,7 @@ import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
user: { id: "user-1", username: "testuser", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -85,7 +85,7 @@ import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_USER = {
id: "user-targets-1",
username: "marc",
username: "testuser",
role: "USER" as const,
timezone: "Europe/Berlin",
heightCm: 180,
@@ -37,7 +37,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -28,7 +28,7 @@ import { MEASUREMENT_CATEGORIES } from "@/lib/measurements/categories";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(): NextRequest {
@@ -36,7 +36,7 @@ import { Prisma } from "@/generated/prisma/client";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function putRequest(id: string, body: Record<string, unknown>): NextRequest {
@@ -350,7 +350,7 @@ describe("GET /api/measurements — all-time semantics (SD-H1)", () => {
});
it("source=rollup folds the partition inline and re-reads when the rollup is under-converged (v1.4.39.2)", async () => {
// Marc's pre-fix production trace: 30-day BP_SYS window returned
// The maintainer's pre-fix production trace: 30-day BP_SYS window returned
// `total: 2` from the rollup branch even though `measurements`
// carried ~30 distinct days. The chart tripped its `< 3 daily
// points` empty-state because the route short-circuited on
@@ -60,7 +60,7 @@ import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function makeRequest(body: unknown): NextRequest {
@@ -0,0 +1,177 @@
/**
* v1.16.4 — POST /api/measurements/restore.
*
* Asserts the ownership-scoped un-tombstone contract that backs the
* delete-Undo toast: only owned, currently-tombstoned rows are touched;
* a forged / foreign / never-deleted id is a silent no-op (no 404
* existence leak); the rollup recompute collapses to the unique
* `(type, day)` set; the >200-id cap returns 422.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: {
findMany: vi.fn(),
updateMany: vi.fn(),
},
auditLog: { create: vi.fn() },
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/idempotency", () => ({
withIdempotency:
<Args extends unknown[]>(fn: (...args: Args) => Promise<Response>) =>
(...args: Args) =>
fn(...args),
}));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserMeasurements: vi.fn(),
}));
vi.mock("@/lib/insights/comprehensive-generate", () => ({
invalidateStatusInsightsForTypes: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rollups/measurement-rollups", async () => {
const actual = await vi.importActual<
typeof import("@/lib/rollups/measurement-rollups")
>("@/lib/rollups/measurement-rollups");
return {
// keep the real collapse so the test exercises the actual fan-out logic
collapseToTypeDayKeys: actual.collapseToTypeDayKeys,
recomputeBucketsForMeasurement: vi.fn().mockResolvedValue(undefined),
};
});
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 { POST } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import { recomputeBucketsForMeasurement } from "@/lib/rollups/measurement-rollups";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "tester", role: "USER" as const },
};
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/measurements/restore", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(recomputeBucketsForMeasurement).mockResolvedValue(undefined);
vi.mocked(invalidateStatusInsightsForTypes).mockResolvedValue(undefined);
});
describe("POST /api/measurements/restore", () => {
it("un-tombstones only owned, tombstoned rows and returns that count", async () => {
// Caller asked for 3 ids but only 2 are owned + tombstoned.
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T08:00:00Z") },
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T20:00:00Z") },
] as never);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({
count: 2,
} as never);
const res = await POST(postReq({ ids: ["m1", "m2", "foreign"] }));
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { restored: number } };
expect(body.data.restored).toBe(2);
// updateMany is ownership-scoped + only touches tombstones — a
// forged / live id never 404s, it's just excluded from the count.
const call = vi.mocked(prisma.measurement.updateMany).mock.calls[0][0];
expect(call.where).toMatchObject({
id: { in: ["m1", "m2", "foreign"] },
userId: "user-1",
deletedAt: { not: null },
});
expect(call.data).toMatchObject({
deletedAt: null,
syncVersion: { increment: 1 },
});
expect(invalidateUserMeasurements).toHaveBeenCalledWith("user-1");
});
it("collapses the rollup recompute to the unique (type, day) set, not per-row", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T08:00:00Z") },
{ type: "WEIGHT", measuredAt: new Date("2026-01-01T20:00:00Z") },
{ type: "WEIGHT", measuredAt: new Date("2026-01-02T09:00:00Z") },
{ type: "PULSE", measuredAt: new Date("2026-01-01T10:00:00Z") },
] as never);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({
count: 4,
} as never);
await POST(postReq({ ids: ["a", "b", "c", "d"] }));
// 4 rows in, 3 distinct (type, day) recomputes out.
expect(recomputeBucketsForMeasurement).toHaveBeenCalledTimes(3);
});
it("is a no-op (restored: 0) when no id is owned + tombstoned — no rollup, no invalidate", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({
count: 0,
} as never);
const res = await POST(postReq({ ids: ["foreign-1", "live-1"] }));
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { restored: number } };
expect(body.data.restored).toBe(0);
expect(invalidateUserMeasurements).not.toHaveBeenCalled();
expect(recomputeBucketsForMeasurement).not.toHaveBeenCalled();
});
it("rejects a batch over the 200-id cap with 422", async () => {
const ids = Array.from({ length: 201 }, (_, i) => `m${i}`);
const res = await POST(postReq({ ids }));
expect(res.status).toBe(422);
expect(prisma.measurement.updateMany).not.toHaveBeenCalled();
});
it("rejects an empty id array with 422", async () => {
const res = await POST(postReq({ ids: [] }));
expect(res.status).toBe(422);
});
it("429s when the rate limit is exceeded", async () => {
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: false } as never);
const res = await POST(postReq({ ids: ["m1"] }));
expect(res.status).toBe(429);
expect(prisma.measurement.updateMany).not.toHaveBeenCalled();
});
});
+144
View File
@@ -0,0 +1,144 @@
/**
* `POST /api/measurements/restore` — un-tombstone for the management
* list's delete-Undo affordance (v1.16.4).
*
* Body:
* { ids: string[] } — 1..200 measurement ids, scoped to the caller.
*
* Clears `deletedAt` (+ bumps `syncVersion`) on every owned,
* currently-tombstoned row in one `updateMany`, so the row re-surfaces
* in normal reads and the `/api/sync/changes` delta feed carries it as
* an upsert to paired clients. A forged / foreign / not-deleted id is a
* silent no-op (never a 404 existence leak): the mutation `where` pins
* `userId` so it only ever touches the caller's rows.
*
* Response (200):
* { restored: <number of rows un-tombstoned> }
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import {
recomputeBucketsForMeasurement,
collapseToTypeDayKeys,
} from "@/lib/rollups/measurement-rollups";
import type { MeasurementType } from "@/generated/prisma/client";
const MAX_IDS_PER_BATCH = 200;
const RATE_LIMIT_MAX = 60;
const RATE_LIMIT_WINDOW_MS = 60 * 1000;
const restoreSchema = z.object({
ids: z.array(z.string().min(1)).min(1).max(MAX_IDS_PER_BATCH),
});
export const POST = apiHandler(withIdempotency<[NextRequest]>(postRestore));
async function postRestore(request: NextRequest): Promise<Response> {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`measurements:restore:${user.id}`,
RATE_LIMIT_MAX,
RATE_LIMIT_WINDOW_MS,
);
if (!rl.allowed) {
return apiError("Too many restore requests, try again later", 429);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 256 * 1024,
});
if (jsonError) return jsonError;
const parsed = restoreSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "measurement.restore.invalid",
});
}
const { ids } = parsed.data;
// Read the soon-to-be-restored rows first so we know which
// `(type, day)` buckets need a rollup recompute and which types need
// a status-insight cache drop. Ownership-scoped + `deletedAt != null`
// so a forged / foreign / never-deleted id is excluded here exactly as
// it is from the mutation below — no existence leak.
const affected = await prisma.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
select: { type: true, measuredAt: true },
});
// Un-tombstone in one statement. The `where` pins `userId` so a forged
// id for another user is silently a no-op; `deletedAt: { not: null }`
// keeps the count honest (a live row doesn't re-count).
const { count } = await prisma.measurement.updateMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
data: { deletedAt: null, syncVersion: { increment: 1 } },
});
await auditLog("measurement.restore", {
userId: user.id,
ipAddress: getClientIp(request),
details: { count },
});
annotate({
action: { name: "measurement.restore" },
meta: { count },
});
if (count > 0) {
// Bust per-user analytics + achievements + workouts caches so
// subsequent reads reflect the restored rows.
invalidateUserMeasurements(user.id);
// Collapse the restored rows to the unique `(type, day)` set BEFORE
// recomputing — mirrors the bulk-delete path. Best-effort: a
// populator hiccup never fails the user's restore.
const keys = collapseToTypeDayKeys(
affected.map((row) => ({
type: row.type as MeasurementType,
measuredAt: row.measuredAt,
})),
);
try {
for (const k of keys) {
await recomputeBucketsForMeasurement(user.id, k.type, k.measuredAt);
}
} catch (err) {
console.warn("[measurements] restore rollup recompute failed", err);
}
// Drop the cached per-metric assessment rows the restore dirties so
// the next mount / nightly warm pass regenerates against the
// restored history. Fire-and-forget: never blocks the restore.
const affectedTypes = Array.from(new Set(keys.map((k) => k.type)));
if (affectedTypes.length > 0) {
invalidateStatusInsightsForTypes(user.id, affectedTypes).catch((err) => {
console.warn(
"[measurements] restore status-insight invalidate failed",
err,
);
});
}
}
return apiSuccess({ restored: count });
}
+2 -2
View File
@@ -319,7 +319,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
// `GET /api/measurements?type=…&aggregate=daily&limit=5000` requests
// (BP_SYS / BP_DIA / WEIGHT). The legacy `date_trunc('day', …)`
// path scanned the measurements table each time — a full year window
// on Marc's account hit 3 × ~3 s on the v1.4.35 HAR. Reading from
// on the maintainer's account hit 3 × ~3 s on the v1.4.35 HAR. Reading from
// the persistent `measurement_rollups` DAY buckets drops each call
// to a small indexed read against the ~5 k-row rollup table.
//
@@ -398,7 +398,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
// window) and finishes well inside the request budget.
//
// The probe runs only on suspicious rollups so the covered-tenant
// happy path stays a single indexed read. Marc's tenant on a 30-day
// happy path stays a single indexed read. The maintainer's tenant on a 30-day
// BP_SYS window pre-fix returned 2 rollup rows and hit `total: 2`
// in the live trace; post-fix the probe finds ~30 distinct days in
// `measurements`, folds them, and the chart paints all 30.
@@ -55,7 +55,7 @@ import { annotate } from "@/lib/logging/context";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(query: string): NextRequest {
@@ -39,7 +39,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -73,7 +73,7 @@ import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { cached } from "@/lib/cache/server-cache";
import { checkRateLimit } from "@/lib/rate-limit";
import { getUserTodayBounds } from "@/lib/timezone";
import { getUserTodayBounds } from "@/lib/tz/local-day";
import { userDayKey } from "@/lib/tz/format";
// UTC keeps the half-open day slice (`[dayStart, dayEnd)`) and the
@@ -84,7 +84,7 @@ const TZ = "UTC";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, timezone: TZ },
user: { id: "user-1", username: "testuser", role: "USER" as const, timezone: TZ },
};
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
@@ -58,14 +58,14 @@ import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
import { checkRateLimit } from "@/lib/rate-limit";
import { localHmAsUtc } from "@/lib/timezone";
import { localHmAsUtc } from "@/lib/tz/local-day";
const TZ = "Europe/Berlin";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "marc",
username: "testuser",
role: "USER" as const,
timezone: TZ,
},
@@ -62,7 +62,7 @@ import { assertMedicationOwnership } from "@/lib/medications/route-guards";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
const MED_OK = { id: "med-1", userId: "user-1" };
@@ -260,7 +260,7 @@ describe("PUT /api/medications/[id]/intake/[eventId] — one-shot reconcile on s
// v1.15.18 — PUT re-runs window-band slot attribution on a takenAt change
// ────────────────────────────────────────────────────────────────────
import { localHmAsUtc } from "@/lib/timezone";
import { localHmAsUtc } from "@/lib/tz/local-day";
const TZ = "Europe/Berlin";
const SESSION_TZ = {
@@ -98,7 +98,7 @@ const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "marc",
username: "testuser",
role: "USER" as const,
// Pin the user timezone so slot-instant resolution is deterministic
// regardless of the host TZ (CI runs in UTC, local in Europe/Berlin).
@@ -90,7 +90,7 @@ import {
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
@@ -52,7 +52,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
const MED_OK = { id: "med-1", userId: "user-1" };
+1 -1
View File
@@ -31,7 +31,7 @@ import {
recomputeMedicationComplianceForDay,
} from "@/lib/rollups/medication-compliance-rollups";
import { assertMedicationOwnership } from "@/lib/medications/route-guards";
import { getUserTodayBounds } from "@/lib/timezone";
import { getUserTodayBounds } from "@/lib/tz/local-day";
import { NextRequest } from "next/server";
type RouteParams = { params: Promise<{ id: string }> };
@@ -5,7 +5,7 @@
* - hard delete; the row is user-owned, non-clinical, and the
* audit log captures enough state to reconstruct it if needed.
*
* Marc-decision (from the W19d brief): allow delete at any time
* maintainer decision (from the W19d brief): allow delete at any time
* rather than a 24-hour retraction window. Side-effect rows are not
* a clinical record; the user owns them and a stale mis-entry should
* never be undeletable. The audit trail preserves "what was deleted
@@ -60,7 +60,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
const MED_OK = { id: "med-1", userId: "user-1" };
@@ -38,7 +38,7 @@ vi.mock("@/lib/medication-category", () => ({
getMedicationCategories: vi.fn().mockResolvedValue({}),
setMedicationCategory: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/timezone", () => ({
vi.mock("@/lib/tz/local-day", () => ({
getUserTodayBounds: vi
.fn()
.mockReturnValue({ start: new Date(), end: new Date() }),
@@ -66,7 +66,7 @@ import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
+1 -1
View File
@@ -34,7 +34,7 @@ import {
expectedSlotCountForDay,
lastNonSkippedTakenAt,
} from "@/lib/analytics/compliance";
import { getUserTodayBounds } from "@/lib/timezone";
import { getUserTodayBounds } from "@/lib/tz/local-day";
import { projectTodayIntakesAndRecompute } from "@/lib/medications/scheduling/project-today-intakes";
import {
applyCanonicalSlotWrite,
+1 -1
View File
@@ -19,7 +19,7 @@ import {
computeDisplayDue,
OVERDUE_LOOKBACK_MS,
} from "@/lib/medications/scheduling/next-due";
import { getUserTodayBounds } from "@/lib/timezone";
import { getUserTodayBounds } from "@/lib/tz/local-day";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { NextRequest } from "next/server";
@@ -0,0 +1,161 @@
/**
* v1.16.4 — POST /api/mood-entries/restore.
*
* Asserts the ownership-scoped un-tombstone contract that backs the
* delete-Undo toast: only owned, currently-tombstoned rows are touched;
* a forged / foreign / never-deleted id is a silent no-op (no 404
* existence leak); the mood rollup recompute collapses to the unique
* day set; the >200-id cap returns 422.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
moodEntry: {
findMany: vi.fn(),
updateMany: vi.fn(),
},
auditLog: { create: vi.fn() },
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/idempotency", () => ({
withIdempotency:
<Args extends unknown[]>(fn: (...args: Args) => Promise<Response>) =>
(...args: Args) =>
fn(...args),
}));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserMood: vi.fn(),
}));
vi.mock("@/lib/rollups/mood-rollups", () => ({
recomputeMoodBucketsForEntry: vi.fn().mockResolvedValue(undefined),
}));
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 { POST } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMood } from "@/lib/cache/invalidate";
import { recomputeMoodBucketsForEntry } from "@/lib/rollups/mood-rollups";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "tester", role: "USER" as const },
};
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/mood-entries/restore", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(recomputeMoodBucketsForEntry).mockResolvedValue(undefined as never);
});
describe("POST /api/mood-entries/restore", () => {
it("un-tombstones only owned, tombstoned rows and returns that count", async () => {
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([
{ moodLoggedAt: new Date("2026-01-01T08:00:00Z") },
{ moodLoggedAt: new Date("2026-01-01T20:00:00Z") },
] as never);
vi.mocked(prisma.moodEntry.updateMany).mockResolvedValue({
count: 2,
} as never);
const res = await POST(postReq({ ids: ["e1", "e2", "foreign"] }));
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { restored: number } };
expect(body.data.restored).toBe(2);
const call = vi.mocked(prisma.moodEntry.updateMany).mock.calls[0][0];
expect(call.where).toMatchObject({
id: { in: ["e1", "e2", "foreign"] },
userId: "user-1",
deletedAt: { not: null },
});
expect(call.data).toMatchObject({
deletedAt: null,
syncVersion: { increment: 1 },
});
expect(invalidateUserMood).toHaveBeenCalledWith("user-1");
});
it("collapses the mood rollup recompute to the unique day set, not per-row", async () => {
// 3 restored rows across 2 distinct UTC days → 2 recomputes.
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([
{ moodLoggedAt: new Date("2026-01-01T08:00:00Z") },
{ moodLoggedAt: new Date("2026-01-01T20:00:00Z") },
{ moodLoggedAt: new Date("2026-01-02T09:00:00Z") },
] as never);
vi.mocked(prisma.moodEntry.updateMany).mockResolvedValue({
count: 3,
} as never);
await POST(postReq({ ids: ["a", "b", "c"] }));
expect(recomputeMoodBucketsForEntry).toHaveBeenCalledTimes(2);
});
it("is a no-op (restored: 0) when no id is owned + tombstoned", async () => {
vi.mocked(prisma.moodEntry.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.moodEntry.updateMany).mockResolvedValue({
count: 0,
} as never);
const res = await POST(postReq({ ids: ["foreign-1", "live-1"] }));
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { restored: number } };
expect(body.data.restored).toBe(0);
expect(invalidateUserMood).not.toHaveBeenCalled();
expect(recomputeMoodBucketsForEntry).not.toHaveBeenCalled();
});
it("rejects a batch over the 200-id cap with 422", async () => {
const ids = Array.from({ length: 201 }, (_, i) => `e${i}`);
const res = await POST(postReq({ ids }));
expect(res.status).toBe(422);
expect(prisma.moodEntry.updateMany).not.toHaveBeenCalled();
});
it("rejects an empty id array with 422", async () => {
const res = await POST(postReq({ ids: [] }));
expect(res.status).toBe(422);
});
it("429s when the rate limit is exceeded", async () => {
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: false } as never);
const res = await POST(postReq({ ids: ["e1"] }));
expect(res.status).toBe(429);
expect(prisma.moodEntry.updateMany).not.toHaveBeenCalled();
});
});
+133
View File
@@ -0,0 +1,133 @@
/**
* `POST /api/mood-entries/restore` — un-tombstone for the mood list's
* delete-Undo affordance (v1.16.4).
*
* Body:
* { ids: string[] } — 1..200 mood-entry ids, scoped to the caller.
*
* Clears `deletedAt` (+ bumps `syncVersion`) on every owned,
* currently-tombstoned row in one `updateMany`, so the row re-surfaces
* in normal reads and the `/api/sync/changes` delta feed carries it as
* an upsert to paired clients. A forged / foreign / not-deleted id is a
* silent no-op (never a 404 existence leak): the mutation `where` pins
* `userId` so it only ever touches the caller's rows.
*
* Response (200):
* { restored: <number of rows un-tombstoned> }
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { invalidateUserMood } from "@/lib/cache/invalidate";
import { recomputeMoodBucketsForEntry } from "@/lib/rollups/mood-rollups";
const MAX_IDS_PER_BATCH = 200;
const RATE_LIMIT_MAX = 60;
const RATE_LIMIT_WINDOW_MS = 60 * 1000;
const restoreSchema = z.object({
ids: z.array(z.string().min(1)).min(1).max(MAX_IDS_PER_BATCH),
});
export const POST = apiHandler(withIdempotency<[NextRequest]>(postRestore));
async function postRestore(request: NextRequest): Promise<Response> {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`mood-entries:restore:${user.id}`,
RATE_LIMIT_MAX,
RATE_LIMIT_WINDOW_MS,
);
if (!rl.allowed) {
return apiError("Too many restore requests, try again later", 429);
}
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 256 * 1024,
});
if (jsonError) return jsonError;
const parsed = restoreSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "mood.restore.invalid",
});
}
const { ids } = parsed.data;
// Read the soon-to-be-restored rows first so we know which days need
// a mood-rollup recompute. Ownership-scoped + `deletedAt != null` so a
// forged / foreign / never-deleted id is excluded here exactly as it
// is from the mutation below — no existence leak.
const affected = await prisma.moodEntry.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
select: { moodLoggedAt: true },
});
// Un-tombstone in one statement. The `where` pins `userId` so a forged
// id for another user is silently a no-op; `deletedAt: { not: null }`
// keeps the count honest (a live row doesn't re-count).
const { count } = await prisma.moodEntry.updateMany({
where: { id: { in: ids }, userId: user.id, deletedAt: { not: null } },
data: { deletedAt: null, syncVersion: { increment: 1 } },
});
await auditLog("mood.restore", {
userId: user.id,
ipAddress: getClientIp(request),
details: { count },
});
annotate({
action: { name: "mood.restore" },
meta: { count },
});
if (count > 0) {
// Bust per-user mood + achievements + analytics caches.
invalidateUserMood(user.id);
// Collapse the restored rows to the unique `(user, dayStart)` set
// BEFORE recomputing — mirrors the bulk-delete path. Best-effort: a
// populator hiccup never fails the user's restore.
const touchedDayStarts = new Set<number>();
for (const row of affected) {
const d = row.moodLoggedAt;
touchedDayStarts.add(
Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()),
);
}
try {
await Promise.all(
Array.from(touchedDayStarts).map((t) =>
recomputeMoodBucketsForEntry(user.id, new Date(t)),
),
);
} catch (rollupErr) {
annotate({
meta: {
mood_rollup_write_failed: true,
mood_rollup_write_error:
rollupErr instanceof Error ? rollupErr.message : String(rollupErr),
},
});
}
}
return apiSuccess({ restored: count });
}
@@ -70,7 +70,7 @@ import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_USER = {
id: "user-mood-1",
username: "marc",
username: "testuser",
role: "USER" as const,
timezone: "Europe/Berlin",
heightCm: 180,
@@ -58,7 +58,7 @@ import { EVENT_TYPES } from "@/lib/notifications/types";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -63,7 +63,7 @@ import { checkRateLimit } from "@/lib/rate-limit";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(body: unknown): NextRequest {
@@ -36,7 +36,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(url: string): NextRequest {
@@ -46,7 +46,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function req(query: string): NextRequest {
@@ -34,7 +34,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
beforeEach(() => {
@@ -56,9 +56,9 @@ describe("GET /api/user/profile", () => {
it("returns flattened iOS-style fields", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
username: "marc",
username: "testuser",
displayName: "Alex T.",
email: "marc@example.com",
email: "user@example.com",
dateOfBirth: new Date("1985-03-12T00:00:00.000Z"),
gender: "MALE",
heightCm: 180,
@@ -76,7 +76,7 @@ describe("GET /api/user/profile", () => {
locale: string | null;
};
};
expect(body.data.username).toBe("marc");
expect(body.data.username).toBe("testuser");
expect(body.data.displayName).toBe("Alex T.");
expect(body.data.heightCm).toBe(180);
expect(body.data.locale).toBe("de");
@@ -85,7 +85,7 @@ describe("GET /api/user/profile", () => {
it("echoes the insurer IK number on GET", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
username: "marc",
username: "testuser",
displayName: null,
email: null,
dateOfBirth: null,
@@ -136,7 +136,7 @@ describe("PATCH /api/user/profile", () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
vi.mocked(prisma.user.update).mockResolvedValue({
id: "user-1",
username: "marc",
username: "testuser",
displayName: "Alex T.",
email: null,
role: "USER",
@@ -165,7 +165,7 @@ describe("PATCH /api/user/profile", () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
vi.mocked(prisma.user.update).mockResolvedValue({
id: "user-1",
username: "marc",
username: "testuser",
displayName: null,
email: null,
role: "USER",
@@ -209,7 +209,7 @@ describe("PATCH /api/user/profile", () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
vi.mocked(prisma.user.update).mockResolvedValue({
id: "user-1",
username: "marc",
username: "testuser",
displayName: null,
email: null,
role: "USER",
@@ -76,7 +76,7 @@ import { enqueuePrDetection } from "@/lib/jobs/pr-detection";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function makeRequest(
@@ -52,7 +52,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function makeRequest(query = ""): NextRequest {
@@ -50,7 +50,7 @@ import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
user: { id: "user-1", username: "testuser", role: "USER" as const },
};
function makeRequest(): NextRequest {
+34 -44
View File
@@ -13,6 +13,7 @@ import { Separator } from "@/components/ui/separator";
import { describePasskeyError } from "@/lib/passkey-errors";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiGet, apiPost } from "@/lib/api/api-fetch";
export default function LoginPage() {
const router = useRouter();
@@ -33,12 +34,16 @@ export default function LoginPage() {
const { data: registrationEnabled } = useQuery({
queryKey: queryKeys.authRegistrationStatus(),
queryFn: async () => {
const res = await fetch("/api/auth/registration-status", {
cache: "no-store",
});
if (!res.ok) return true;
const json = await res.json();
return Boolean(json.data?.registrationEnabled ?? true);
try {
const data = await apiGet<{ registrationEnabled?: boolean }>(
"/api/auth/registration-status",
{ cache: "no-store" },
);
return Boolean(data?.registrationEnabled ?? true);
} catch {
// Fail open, exactly as the raw `if (!res.ok) return true` did.
return true;
}
},
staleTime: 60 * 1000,
});
@@ -58,38 +63,30 @@ export default function LoginPage() {
setLoading(true);
try {
const optRes = await fetch("/api/auth/passkey/login-options", {
method: "POST",
});
const optJson = await optRes.json();
if (!optRes.ok) {
setError(optJson.error);
setLoading(false);
return;
}
const { options, challengeId } = optJson.data;
const { startAuthentication } = await import("@simplewebauthn/browser");
const { options, challengeId } = await apiPost<{
options: Parameters<typeof startAuthentication>[0]["optionsJSON"];
challengeId: string;
}>("/api/auth/passkey/login-options");
const credential = await startAuthentication({ optionsJSON: options });
const verifyRes = await fetch("/api/auth/passkey/login-verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ challengeId, credential }),
await apiPost("/api/auth/passkey/login-verify", {
challengeId,
credential,
});
const verifyJson = await verifyRes.json();
if (!verifyRes.ok) {
setError(verifyJson.error || t("auth.loginFailed"));
setLoading(false);
return;
}
await queryClient.invalidateQueries({ queryKey: queryKeys.auth() });
router.push(getRedirectTarget());
} catch (err) {
const { key, params } = describePasskeyError(err);
setError(t(key, params));
// Route rejections carry the envelope error verbatim; everything
// else (WebAuthn ceremony failures) keeps the descriptive mapping.
if (err instanceof ApiError) {
setError(err.message || t("auth.loginFailed"));
} else {
const { key, params } = describePasskeyError(err);
setError(t(key, params));
}
} finally {
setLoading(false);
}
@@ -101,23 +98,16 @@ export default function LoginPage() {
setLoading(true);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
await apiPost("/api/auth/login", { email, password });
await queryClient.invalidateQueries({ queryKey: queryKeys.auth() });
router.push(getRedirectTarget());
} catch {
setError(t("auth.loginFailed"));
} catch (err) {
setError(
err instanceof ApiError && err.message
? err.message
: t("auth.loginFailed"),
);
} finally {
setLoading(false);
}
+13 -19
View File
@@ -13,6 +13,7 @@ import { PasswordStrength } from "@/components/ui/password-strength";
import { useTranslations } from "@/lib/i18n/context";
import { detectBrowserTimezone } from "@/lib/tz/format";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiPost } from "@/lib/api/api-fetch";
export default function RegisterPage() {
const router = useRouter();
@@ -47,29 +48,22 @@ export default function RegisterPage() {
// bogus, so a tampered or proxied request can never poison
// the user's stored zone.
const timezone = detectBrowserTimezone();
const res = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email,
username,
password,
timezone,
...(inviteToken ? { inviteToken } : {}),
}),
await apiPost("/api/auth/register", {
email,
username,
password,
timezone,
...(inviteToken ? { inviteToken } : {}),
});
const json = await res.json();
if (!res.ok) {
setError(json.error);
setLoading(false);
return;
}
await queryClient.invalidateQueries({ queryKey: queryKeys.auth() });
router.push("/");
} catch {
setError(t("auth.registerFailed"));
} catch (err) {
setError(
err instanceof ApiError && err.message
? err.message
: t("auth.registerFailed"),
);
} finally {
setLoading(false);
}
+23 -33
View File
@@ -17,6 +17,7 @@ import {
import { Loader2, CheckCircle2, Bug, GitPullRequest, Info } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiGet, apiPost } from "@/lib/api/api-fetch";
interface BugReportStatus {
configured: boolean;
@@ -49,10 +50,7 @@ export default function BugReportPage() {
const { data: status } = useQuery({
queryKey: queryKeys.bugreportStatus(),
queryFn: async () => {
const res = await fetch("/api/bugreport/status");
if (!res.ok) throw new Error("Failed to load status");
const json = await res.json();
return json.data as BugReportStatus;
return apiGet<BugReportStatus>("/api/bugreport/status");
},
enabled: isAuthenticated,
});
@@ -63,36 +61,28 @@ export default function BugReportPage() {
setLoading(true);
try {
const res = await fetch("/api/feedback", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category,
subject: subject || description.slice(0, 60),
description,
metadata: {
locale,
userAgent:
typeof navigator !== "undefined" ? navigator.userAgent : null,
url:
typeof window !== "undefined" ? window.location.pathname : null,
},
}),
await apiPost("/api/feedback", {
category,
subject: subject || description.slice(0, 60),
description,
metadata: {
locale,
userAgent:
typeof navigator !== "undefined" ? navigator.userAgent : null,
url: typeof window !== "undefined" ? window.location.pathname : null,
},
});
setResult({ type: "success", message: t("bugreport.success") });
setSubject("");
setDescription("");
} catch (err) {
setResult({
type: "error",
message:
err instanceof ApiError
? err.message || t("bugreport.errorCreating")
: t("common.networkError"),
});
const json = await res.json();
if (res.ok) {
setResult({ type: "success", message: t("bugreport.success") });
setSubject("");
setDescription("");
} else {
setResult({
type: "error",
message: json.error || t("bugreport.errorCreating"),
});
}
} catch {
setResult({ type: "error", message: t("common.networkError") });
} finally {
setLoading(false);
}
+12 -15
View File
@@ -19,6 +19,7 @@ import { InsightStatusCard } from "@/components/insights/insight-status-card";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { TileHeader } from "@/components/insights/tile-header";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.25 W4 — `/insights/medications`.
@@ -93,10 +94,7 @@ export default function InsightsMedikamentePage() {
const { data: comprehensive, isLoading: isComprehensiveLoading } = useQuery({
queryKey: queryKeys.insightsComprehensive(),
queryFn: async () => {
const res = await fetch("/api/insights/comprehensive");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as ComprehensiveMedicationData;
return apiGet<ComprehensiveMedicationData>("/api/insights/comprehensive");
},
enabled: isAuthenticated,
});
@@ -110,13 +108,7 @@ export default function InsightsMedikamentePage() {
MED_STATUS_TIMEOUT_MS,
);
try {
const res = await fetch(
`/api/insights/medication-compliance-status?locale=${locale}`,
{ signal: controller.signal },
);
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as MedicationComplianceStatusData;
return apiGet<MedicationComplianceStatusData>(`/api/insights/medication-compliance-status?locale=${locale}`, { signal: controller.signal });
} finally {
clearTimeout(timeoutHandle);
}
@@ -313,10 +305,15 @@ function MedicationComplianceCalendar({
const { data, isLoading } = useQuery({
queryKey: queryKeys.medicationComplianceChart(medicationId),
queryFn: async () => {
const res = await fetch(`/api/medications/${medicationId}/compliance`);
if (!res.ok) return null;
const json = await res.json();
return json.data as MedicationComplianceDailyResponse;
try {
return await apiGet<MedicationComplianceDailyResponse>(
`/api/medications/${medicationId}/compliance`,
);
} catch {
// The calendar simply doesn't render — same as the raw
// `if (!res.ok) return null` did.
return null;
}
},
enabled: !!medicationId,
staleTime: 60 * 1000,
+2 -4
View File
@@ -16,6 +16,7 @@ import { MetricTargetSummary } from "@/components/insights/metric-target-summary
import { MoodInsightsSections } from "@/components/insights/mood/mood-insights-sections";
import { SlugInsightStatusCard } from "@/components/insights/slug-insight-status-card";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.4.25 W4 — `/insights/mood`.
@@ -49,10 +50,7 @@ export default function InsightsStimmungPage() {
const { data: comprehensive } = useQuery({
queryKey: queryKeys.insightsComprehensive(),
queryFn: async () => {
const res = await fetch("/api/insights/comprehensive");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as ComprehensiveMoodData;
return apiGet<ComprehensiveMoodData>("/api/insights/comprehensive");
},
enabled: isAuthenticated,
});
+7 -5
View File
@@ -8,6 +8,7 @@ import { RefreshCw, SlidersHorizontal, TrendingUp } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useFeatureFlags } from "@/hooks/use-feature-flags";
import { useInsightsLayoutQuery } from "@/hooks/use-insights-layout";
import {
@@ -202,7 +203,7 @@ const CycleRingTile = dynamic(
* cards moved onto the metric pages they belong to (Weight owns
* weight × weekday, Pulse owns mood × pulse, …), so the overview
* no longer renders a duplicate correlation row.
* - The CoachDrawer is mounted in the mother-page body only (Marc
* - The CoachDrawer is mounted in the mother-page body only (the maintainer
* directive). Navigating to a sub-page unmounts the drawer.
*
* The per-section status cards (BP/Weight/Pulse/etc.) and their
@@ -250,10 +251,11 @@ export default function InsightsPage() {
const { data, isLoading, isFetched, isError, refetch } = useQuery({
queryKey: queryKeys.insightsComprehensive(),
queryFn: async () => {
const res = await fetch("/api/insights/comprehensive");
if (!res.ok) throw new Error(t("insights.loadError"));
const json = await res.json();
return json.data as ComprehensiveData;
try {
return await apiGet<ComprehensiveData>("/api/insights/comprehensive");
} catch {
throw new Error(t("insights.loadError"));
}
},
enabled: isAuthenticated,
});
+9 -1
View File
@@ -8,6 +8,7 @@ import { MonitoringBootstrap } from "@/components/monitoring/bootstrap";
import { WebVitalsReporter } from "@/components/monitoring/web-vitals-reporter";
import { parseLocaleFromAcceptLanguage } from "@/lib/format-locale";
import { locales, type Locale } from "@/lib/i18n/config";
import { allMessages } from "@/lib/i18n/shared-resolve";
async function resolveInitialLocale(): Promise<Locale> {
// Both cookies() and headers() can throw (DynamicServerError, etc.) —
@@ -106,6 +107,13 @@ export default async function RootLayout({
: undefined;
const initialLocale = await resolveInitialLocale();
// RSC handoff for the i18n bundle split: only EN ships statically in
// the client chunk, so a non-EN first paint needs its bundle inlined
// into the payload here — that is what keeps the split free of the
// EN→DE hydration flash. EN passes nothing (the client already holds
// the static fallback floor).
const initialMessages =
initialLocale === "en" ? undefined : allMessages[initialLocale];
return (
<html lang={initialLocale} suppressHydrationWarning>
@@ -117,7 +125,7 @@ export default async function RootLayout({
/>
</head>
<body className={`${inter.variable} font-sans antialiased`}>
<Providers initialLocale={initialLocale}>
<Providers initialLocale={initialLocale} initialMessages={initialMessages}>
<MonitoringBootstrap />
<WebVitalsReporter />
{/* `DEMO_MODE` is a server-only env var; the proxy uses it to
+2 -3
View File
@@ -28,6 +28,7 @@ import {
MedicationDetailTabs,
type MedicationDetailSnapshot,
} from "@/components/medications/detail/MedicationDetailTabs";
import { apiGet } from "@/lib/api/api-fetch";
export default function MedicationDetailPage({
params,
@@ -52,9 +53,7 @@ export default function MedicationDetailPage({
} = useQuery<MedicationDetailSnapshot>({
queryKey: queryKeys.medicationDetail(id),
queryFn: async () => {
const res = await fetch(`/api/medications/${id}`);
if (!res.ok) throw new Error("medication_detail_failed");
return (await res.json()).data as MedicationDetailSnapshot;
return apiGet<MedicationDetailSnapshot>(`/api/medications/${id}`);
},
// v1.15.20 — deliberately NOT gated on `isAuthenticated`: the session
// cookie rides the fetch either way, so waiting for `/api/auth/me`
+2 -4
View File
@@ -21,6 +21,7 @@ import {
import { EmptyState } from "@/components/ui/empty-state";
import { Skeleton } from "@/components/ui/skeleton";
import { CheckCircle2, Loader2, Pill, Plus } from "lucide-react";
import { apiGet } from "@/lib/api/api-fetch";
interface Schedule {
id: string;
@@ -149,10 +150,7 @@ export default function MedicationsPage() {
} = useQuery({
queryKey: queryKeys.medications(),
queryFn: async () => {
const res = await fetch("/api/medications");
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
return json.data as Medication[];
return apiGet<Medication[]>("/api/medications");
},
enabled: isAuthenticated,
});
+3 -11
View File
@@ -19,6 +19,7 @@ import {
type EventType,
} from "@/lib/notifications/types";
import { queryKeys } from "@/lib/query-keys";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
interface ChannelInfo {
id: string;
@@ -91,10 +92,7 @@ export default function NotificationsPage() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.notificationsPreferences(),
queryFn: async () => {
const res = await fetch("/api/notifications/preferences");
if (!res.ok) throw new Error("Failed to load preferences");
const json = await res.json();
return json.data as PreferencesData;
return apiGet<PreferencesData>("/api/notifications/preferences");
},
enabled: isAuthenticated,
});
@@ -105,13 +103,7 @@ export default function NotificationsPage() {
eventType: string;
enabled: boolean;
}) => {
const res = await fetch("/api/notifications/preferences", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
});
if (!res.ok) throw new Error("Failed to update preference");
return res.json();
return apiPut("/api/notifications/preferences", params);
},
onMutate: async ({ channelId, eventType, enabled }) => {
await queryClient.cancelQueries({
+1 -1
View File
@@ -89,7 +89,7 @@ export default async function OnboardingStepPage({ params }: PageProps) {
// Welcome (step 0)
// * Fresh user → value-prop carousel.
// * Returning user (onboarding already completed) → welcome-back
// banner with "Open dashboard" CTA. Marc note 2026-05-14: the
// banner with "Open dashboard" CTA. The maintainer note 2026-05-14: the
// "restart onboarding" affordance lives in Settings → Account in
// v1.4.26; for now the banner is informational only.
if (requested === 0) {
+7 -12
View File
@@ -96,6 +96,7 @@ import {
getAgeFromDateOfBirth,
getPersonalizedPulseTarget,
} from "@/lib/analytics/pulse-targets";
import { apiGet } from "@/lib/api/api-fetch";
/**
* v1.7.0 — first-paint gate for the dashboard tile strip.
@@ -148,7 +149,7 @@ export default function DashboardPage() {
// (thick slice) blocked every per-type tile until the heavy fan-out
// resolved. Mood and medication tiles paint from their own dedicated
// endpoints and arrived first; the per-type measurement tiles then
// arrived as one burst once the full slice landed — Marc reported
// arrived as one burst once the full slice landed — the maintainer reported
// this "blocked-then-burst" pattern as "etwas nervig".
//
// Post-fix: two parallel queries. The slim slice (`?slice=summaries`)
@@ -205,7 +206,7 @@ export default function DashboardPage() {
// coverage. Pre-fix the inline `slim?.summaries ?? thick?.summaries`
// short-circuited on a truthy-but-empty `{}` from the slim slice
// and blanked the tile strip even when thick carried the full
// payload — the regression Marc's v1.4.39.3 e2e CI flagged across
// payload — the regression the maintainer's v1.4.39.3 e2e CI flagged across
// eight dashboard / chart specs. The helper falls back to thick
// when slim resolves with no content and otherwise keeps the
// v1.4.39.2 slim-wins-first progressive-paint contract.
@@ -237,10 +238,7 @@ export default function DashboardPage() {
const { data: layoutDataLegacy } = useQuery({
queryKey: queryKeys.dashboardWidgets(),
queryFn: async () => {
const res = await fetch("/api/dashboard/widgets");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as DashboardLayout;
return apiGet<DashboardLayout>("/api/dashboard/widgets");
},
enabled: !snapshotEnabled && isAuthenticated,
...DASHBOARD_QUERY_OPTS,
@@ -252,13 +250,10 @@ export default function DashboardPage() {
const { data: moodDataLegacy } = useQuery({
queryKey: queryKeys.moodAnalytics(),
queryFn: async () => {
const res = await fetch("/api/mood/analytics");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as {
return apiGet<{
entries: Array<{ date: string; score: number; samples: number }>;
summary: DataSummary;
};
}>("/api/mood/analytics");
},
enabled: !snapshotEnabled && isAuthenticated,
...DASHBOARD_QUERY_OPTS,
@@ -1362,7 +1357,7 @@ export default function DashboardPage() {
return (
<>
{/* v1.4: dashboard tiles are *always* a single row.
* maintainer-explicit (per feedback_dashboard_one_row.md): a 2-row
* Maintainer-explicit (per feedback_dashboard_one_row.md): a 2-row
* tile strip breaks the visual hierarchy and reads like an
* Excel grid. Total width caps at the parent container —
* exactly the chart-width below. When the active tile count
+5 -4
View File
@@ -245,10 +245,11 @@ describe("<PrivacyPage>", () => {
// email address attaches the actual contact.
expect(html).toContain("mailto:mbombeck@gmail.com");
expect(html).toContain("github.com/MBombeck/HealthLog/issues");
// Marc-Voice rule: no personal name in user-facing artefacts. The
// policy speaks in terms of "the operator" / "the controller"
// not Marc's full name. Only the bare email address attaches the
// contact route.
// Project-voice rule: no personal name in user-facing artefacts.
// The policy speaks in terms of "the operator" / "the controller",
// never a person's full name. Only the bare email address attaches
// the contact route. The regexes pin the operator's given-name /
// surname fragments so a regression cannot reintroduce them.
expect(html).not.toMatch(/Marc[- ]?Andr/i);
expect(html).not.toMatch(/\bBombeck\s+[A-Z]/);
});
@@ -58,7 +58,7 @@ describe("<AiQualitySection>", () => {
mockQueryState.isError = false;
const html = render(<AiQualitySection />);
// v1.4.33 IW7 — admin section renamed from "AI Quality" to
// "Insights Quality" per the Marc-Voice rule.
// "Insights Quality" per the project-voice rule.
expect(html).toContain("Insights Quality");
expect(html).toContain("No feedback yet");
});
@@ -35,8 +35,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -30,7 +30,7 @@ const sampleTokens = [
expiresAt: null,
createdAt: "2026-05-01T08:00:00Z",
revoked: false,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
@@ -54,8 +54,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -107,7 +107,7 @@ describe("ApiTokenOverviewSection — responsive", () => {
// All data points the desktop table shows must also appear in the
// mobile cards. Token name + username + a permission badge + the
// last-used/created labels are all present.
expect(html).toContain("marc"); // username
expect(html).toContain("testuser"); // username
expect(html).toContain("iOS app"); // token name
// F-19 (v1.4.19): the wildcard `*` permission renders as the
// human-readable "All" with a tooltip explaining the semantics,
@@ -4,7 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.19 A7 — `/admin/api-tokens` 4th-attempt scrollbar fix.
*
* the maintainer reported a "minimaler Scrollbar" still painting at the
* The maintainer reported a "minimaler Scrollbar" still painting at the
* bottom-right of the api-tokens page, even after the v1.4.18 phase
* A2 mobile-strip `no-scrollbar` fix. The remaining culprits are
* inside the section card itself: long token names, long usernames,
@@ -37,7 +37,7 @@ const sampleTokens = [
revoked: false,
user: {
id: "u1",
username: "marc-the-very-long-username-that-overflows",
username: "user-the-very-long-username-that-overflows",
},
},
];
@@ -62,8 +62,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -51,8 +51,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -35,7 +35,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "ADMIN" },
user: { id: "u1", username: "testuser", role: "ADMIN" },
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
@@ -108,7 +108,7 @@ describe("CoachFeedbackSection", () => {
expect(html).toContain('role="alert"');
});
// v1.4.25 W8 regression — Marc reported a layout shift on
// v1.4.25 W8 regression — the maintainer reported a layout shift on
// /admin/coach-feedback. Root cause was the title only rendering in the
// empty + data branches, so the section grew taller (loading → data)
// and snapped down. Lock the heading + outer-card structure across
@@ -64,8 +64,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -15,7 +15,7 @@ import { toCSV } from "@/lib/export";
* `createdAt` string, which Excel/LibreOffice misread once the `Z`
* suffix was stripped. This test pins:
*
* - The column order Marc requested:
* - The column order the maintainer requested:
* `timestamp → user → IP → location → provider → outcome` (email
* is absent from the audit-log API so it's intentionally skipped)
* followed by `action` + `details` for triage completeness.
@@ -80,7 +80,7 @@ function deterministicFormatter(iso: string): string {
}
describe("buildAuditLogCsvRecords", () => {
it("emits Marc's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
it("emits the maintainer's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
const entries: AuditCsvEntry[] = [
{
createdAt: "2026-05-11T09:05:00.000Z",
@@ -88,7 +88,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const [record] = buildAuditLogCsvRecords(
@@ -119,7 +119,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: null,
location: null,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -220,7 +220,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -234,12 +234,12 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
"Zeitpunkt,Benutzer,IP,Standort,Mobilfunkanbieter,Anbieter,Ergebnis,Aktion,Details",
);
expect(lines[1]).toBe(
'2026-05-11T09:05:00+00:00,marc,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
'2026-05-11T09:05:00+00:00,testuser,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
);
});
it("folds the GeoLite2 organisation string to the short DACH carrier label", () => {
// Marc's spec: the verbose MMDB org strings get a glanceable chip.
// The maintainer's spec: the verbose MMDB org strings get a glanceable chip.
// The CSV column carries the same folded text so a downstream
// spreadsheet matches what the admin overview screen renders.
const entries: AuditCsvEntry[] = [
@@ -251,7 +251,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Deutsche Telekom AG",
asn: 3320,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -261,7 +261,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Vodafone GmbH",
asn: 3209,
details: null,
user: { id: "u2", username: "marc" },
user: { id: "u2", username: "testuser" },
},
{
createdAt: "2026-05-11T09:07:00.000Z",
@@ -271,7 +271,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "1&1 Versatel GmbH",
asn: 8881,
details: null,
user: { id: "u3", username: "marc" },
user: { id: "u3", username: "testuser" },
},
{
createdAt: "2026-05-11T09:08:00.000Z",
@@ -281,7 +281,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Telefónica Germany GmbH & Co. OHG",
asn: 6805,
details: null,
user: { id: "u4", username: "marc" },
user: { id: "u4", username: "testuser" },
},
{
createdAt: "2026-05-11T09:09:00.000Z",
@@ -291,7 +291,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Google LLC",
asn: 15169,
details: null,
user: { id: "u5", username: "marc" },
user: { id: "u5", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -37,8 +37,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
timezone: "Europe/Berlin",
},
Loaded 100 of 284 files, more files were not shown because too many files have changed in this diff. Show more