mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
chore(release): v1.4.28
Bug-fix and consistency follow-through after the v1.4.27 mobile sweep. The headline is a tighter dashboard and insights surface: six widgets retire from code entirely (GLP-1 tile, dashboard `<DrugLevelChart>` mount, GLP-1 detail-page intake history + inventory, the `<InsightAdvisorCard>` block and its regeneration affordance, the weekly-report route), four broken edges close (workout-edit duplicate- timestamp 409, BD-Zielbereich tile rebuilt on the shared `<TrendCard>` primitive, `/insights/puls` chart timeout fallback, sticky tab-strip scroll lock), and one consistency contract lands per maintainer directive: every medication-list row, every medication- detail section header, every trend tile, every Coach launch glyph, every chart-height contract reads on one shape. The HealthScore card grows to fill its column, gains an accessible `?` tooltip explaining the delta, and drops the placeholder "Wochenbericht erstellen" button. iOS contracts are intact; the only `/api/*` evolution is additive (the `aggregate=monthly` grain on `/api/measurements` and an internal-only `/api/internal/web-vitals` beacon route).
This commit is contained in:
1 parent
4f09c3f862
commit
2d111fcb24
136 files changed
+5731
-8462
No files matched your search
@@ -1,203 +0,0 @@
|
||||
/**
|
||||
* GET /api/dashboard/glp1 — v1.4.25 W6
|
||||
*
|
||||
* Powers the dashboard's `<Glp1Tile>`. Returns the user's active GLP-1
|
||||
* medications (treatmentClass = "GLP1"), each enriched with a tiny
|
||||
* weight series + the dates the user logged an injection. Returns
|
||||
* `null` data when the user has no active GLP-1 medication — the tile
|
||||
* then suppresses itself per Marc's empty-state hide rule.
|
||||
*
|
||||
* Bridge layer: the heavy lifting (current dose / last + next injection
|
||||
* / titration history / inventory math) is delegated to
|
||||
* `buildGlp1SnapshotBlock` so the Coach's GLP-1-aware reply path and
|
||||
* this dashboard tile read from the exact same shape. The extras we
|
||||
* add on top here are purely UI-facing:
|
||||
* - weightSeries[] — daily aggregates since the first dose change
|
||||
* (or 90 days back, whichever is later) for
|
||||
* the mini-chart on the tile
|
||||
* - weightDeltaKg — convenience caption value (current − start);
|
||||
* the tile renders "−4.2 kg seit Beginn" off
|
||||
* this number, with `null` when either side
|
||||
* is missing
|
||||
* - injectionDates[] — `YYYY-MM-DD` keys for every recorded intake
|
||||
* event so the chart can paint the vertical
|
||||
* injection-day markers Marc wants
|
||||
*/
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { buildGlp1SnapshotBlock } from "@/lib/ai/coach/glp1-snapshot";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
|
||||
const WEIGHT_LOOKBACK_DAYS = 90;
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
function isoDate(d: Date): string {
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucket raw weight measurements into one daily average so the mini-
|
||||
* chart doesn't render the noisy raw stream. Same `YYYY-MM-DD` keying
|
||||
* the dashboard chart layer uses (UTC-noon anchor — DST-safe).
|
||||
*/
|
||||
function bucketDaily(
|
||||
rows: Array<{ measuredAt: Date; value: number }>,
|
||||
): Array<{ date: string; weight: number }> {
|
||||
const sums = new Map<string, { sum: number; count: number }>();
|
||||
for (const row of rows) {
|
||||
const key = isoDate(row.measuredAt);
|
||||
const slot = sums.get(key) ?? { sum: 0, count: 0 };
|
||||
slot.sum += row.value;
|
||||
slot.count += 1;
|
||||
sums.set(key, slot);
|
||||
}
|
||||
return Array.from(sums.entries())
|
||||
.map(([date, { sum, count }]) => ({
|
||||
date,
|
||||
weight: Math.round((sum / count) * 100) / 100,
|
||||
}))
|
||||
.sort((a, b) => (a.date < b.date ? -1 : 1));
|
||||
}
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const userTz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
const now = new Date();
|
||||
|
||||
const snapshot = await buildGlp1SnapshotBlock(user.id, now);
|
||||
// No active GLP-1 medication → the tile suppresses itself. We still
|
||||
// return 200 + `data: null` so the client doesn't have to special-
|
||||
// case the 404 path.
|
||||
if (!snapshot) {
|
||||
annotate({
|
||||
action: { name: "dashboard.glp1" },
|
||||
meta: { active: 0 },
|
||||
});
|
||||
return apiSuccess(null);
|
||||
}
|
||||
|
||||
// Anchor the weight series to the earliest meaningful date: the user
|
||||
// wants to see the trend SINCE THEY STARTED the GLP-1, not just the
|
||||
// last 90 days. We pick the earlier of:
|
||||
// - the first dose-change `effectiveFrom` across all GLP-1 meds
|
||||
// - 90 days back from today (so brand-new accounts still get a
|
||||
// reasonable window when they only just logged their first dose)
|
||||
let anchor = new Date(now.getTime() - WEIGHT_LOOKBACK_DAYS * MS_PER_DAY);
|
||||
for (const med of snapshot.medications) {
|
||||
if (med.doseHistory.length === 0) continue;
|
||||
const firstDose = med.doseHistory[0].effectiveFrom;
|
||||
const firstDoseMs = Date.parse(`${firstDose}T00:00:00Z`);
|
||||
if (Number.isFinite(firstDoseMs) && firstDoseMs < anchor.getTime()) {
|
||||
anchor = new Date(firstDoseMs);
|
||||
}
|
||||
}
|
||||
|
||||
const [weights, intakeRows] = await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
type: "WEIGHT",
|
||||
measuredAt: { gte: anchor },
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { measuredAt: true, value: true },
|
||||
}),
|
||||
prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
takenAt: { not: null, gte: anchor },
|
||||
medication: { treatmentClass: "GLP1" },
|
||||
},
|
||||
orderBy: { takenAt: "asc" },
|
||||
select: {
|
||||
medicationId: true,
|
||||
takenAt: true,
|
||||
medication: { select: { name: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const weightSeries = bucketDaily(weights);
|
||||
|
||||
// Per-med injection date set — used by the chart's vertical markers.
|
||||
// Multiple injection events on the same day collapse to a single
|
||||
// marker so the chart doesn't paint stacked overlapping lines.
|
||||
const injectionDatesByMed = new Map<string, Set<string>>();
|
||||
for (const ev of intakeRows) {
|
||||
if (!ev.takenAt) continue;
|
||||
const set = injectionDatesByMed.get(ev.medicationId) ?? new Set<string>();
|
||||
set.add(isoDate(ev.takenAt));
|
||||
injectionDatesByMed.set(ev.medicationId, set);
|
||||
}
|
||||
|
||||
// We also need to know the medication id per snapshot entry. The
|
||||
// snapshot exposes name + genericName but not the id; re-fetch the
|
||||
// id list ordered by `createdAt: desc` (matches the snapshot
|
||||
// ordering) and zip the two lists. Cheap re-query — already in cache
|
||||
// from the snapshot's first hit.
|
||||
const idsForOrder = await prisma.medication.findMany({
|
||||
where: { userId: user.id, treatmentClass: "GLP1", active: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
|
||||
// Build the enriched per-med payload. `startWeight` = the first daily
|
||||
// bucket on/after the med's first dose-change date; `currentWeight`
|
||||
// = the most recent daily bucket. Both `null` when no weight data
|
||||
// exists in the window — the tile suppresses the delta caption then.
|
||||
const medications = snapshot.medications.map((med, idx) => {
|
||||
const medId = idsForOrder[idx]?.id ?? null;
|
||||
|
||||
let startWeight: number | null = null;
|
||||
let currentWeight: number | null = null;
|
||||
let medSeries: Array<{ date: string; weight: number }> = [];
|
||||
|
||||
if (weightSeries.length > 0) {
|
||||
const firstDoseDate =
|
||||
med.doseHistory.length > 0 ? med.doseHistory[0].effectiveFrom : null;
|
||||
// Filter the series to "since the user started this medication".
|
||||
// If we don't have a dose-change row (legacy data) we fall back
|
||||
// to the whole 90-day window so the chart isn't empty.
|
||||
medSeries = firstDoseDate
|
||||
? weightSeries.filter((p) => p.date >= firstDoseDate)
|
||||
: weightSeries.slice();
|
||||
startWeight = medSeries[0]?.weight ?? null;
|
||||
currentWeight = medSeries[medSeries.length - 1]?.weight ?? null;
|
||||
}
|
||||
|
||||
const weightDeltaKg =
|
||||
startWeight !== null && currentWeight !== null
|
||||
? Math.round((currentWeight - startWeight) * 100) / 100
|
||||
: null;
|
||||
|
||||
const injectionDates = medId
|
||||
? Array.from(injectionDatesByMed.get(medId) ?? []).sort()
|
||||
: [];
|
||||
|
||||
return {
|
||||
...med,
|
||||
medicationId: medId,
|
||||
startWeight,
|
||||
currentWeight,
|
||||
weightDeltaKg,
|
||||
weightSeries: medSeries,
|
||||
injectionDates,
|
||||
};
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "dashboard.glp1" },
|
||||
meta: {
|
||||
active: medications.length,
|
||||
tz: userTz,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
active: snapshot.active,
|
||||
medications,
|
||||
});
|
||||
});
|
||||
@@ -274,7 +274,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// block to the user prompt when the active GLP-1 medication has been
|
||||
// on a stable dose for ≥21 days with weight delta within ±0.5 kg.
|
||||
// The block instructs the model to emit a glp1_plateau keyFinding
|
||||
// framed observationally (no dose recommendation per GROUND RULE 14).
|
||||
// framed observationally (no dose recommendation per GROUND RULE 13).
|
||||
// Returns null when no GLP-1 is active OR no plateau condition;
|
||||
// 99% of users land in the null branch and pay zero token cost.
|
||||
const plateauContext = await detectGlp1Plateau(userId);
|
||||
@@ -298,7 +298,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
params: {
|
||||
// The strict prompt (PROMPT_VERSION 4.20.x) carries GROUND RULE 8
|
||||
// — emit a top-level `dailyBriefing` block when the snapshot has
|
||||
// analysable signal — plus the trendAnnotations / weeklyReport /
|
||||
// analysable signal — plus the trendAnnotations and
|
||||
// storyboardAnnotations rules. The legacy `getInsightsSystemPrompt`
|
||||
// returned the v1.4.5 `{changed, stable, drivers, …}` shape and
|
||||
// never asked the model for dailyBriefing, so the hero strip's
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* v1.4.28 R4-CODE-C3 / Security H-1 / SD-C2 — the web-vitals beacon
|
||||
* is unauthenticated by design (browser fires before any session) but
|
||||
* MUST gate the surface so a peer cannot flood the wide-event log nor
|
||||
* inject arbitrary strings.
|
||||
*
|
||||
* Contract:
|
||||
*
|
||||
* - Zod schema rejects unknown `name`, non-finite `value`, oversized
|
||||
* `id` → 400. Raw body never enters the log.
|
||||
* - Per-IP rate-limit (60/min) → 429 with `X-RateLimit-*` headers on
|
||||
* overflow.
|
||||
* - Valid payload → 204 No Content (sendBeacon shape — never retry).
|
||||
*/
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi.fn(),
|
||||
rateLimitHeaders: () => ({}),
|
||||
}));
|
||||
|
||||
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 { POST } from "../route";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
function postRequest(body: unknown, init?: { referer?: string }): NextRequest {
|
||||
return new NextRequest("http://localhost/api/internal/web-vitals", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...(init?.referer ? { referer: init.referer } : {}),
|
||||
},
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 59,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
// NEXT_PUBLIC_APP_URL unset in the unit harness — the same-origin
|
||||
// gate is skipped (dev-friendly default).
|
||||
delete process.env.NEXT_PUBLIC_APP_URL;
|
||||
});
|
||||
|
||||
describe("POST /api/internal/web-vitals", () => {
|
||||
it("returns 204 on a valid payload", async () => {
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
name: "LCP",
|
||||
value: 1234.5,
|
||||
id: "v1-1700000000-7",
|
||||
delta: 12.3,
|
||||
rating: "good",
|
||||
navigationType: "navigate",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(204);
|
||||
});
|
||||
|
||||
it("returns 400 when the name is not in the documented set", async () => {
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
name: "ARBITRARY_LOG_STRING",
|
||||
value: 0,
|
||||
id: "x",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 when value is non-finite", async () => {
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
name: "CLS",
|
||||
value: Number.NaN,
|
||||
id: "x",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 when id exceeds the 50-char cap", async () => {
|
||||
const res = await POST(
|
||||
postRequest({
|
||||
name: "INP",
|
||||
value: 12,
|
||||
id: "a".repeat(51),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 on malformed JSON without logging the raw payload", async () => {
|
||||
const res = await POST(postRequest("not-json"));
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 429 when the rate-limit fires", async () => {
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
});
|
||||
const res = await POST(
|
||||
postRequest({ name: "CLS", value: 0.1, id: "x" }),
|
||||
);
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
|
||||
it("rejects a cross-origin Referer when NEXT_PUBLIC_APP_URL is configured", async () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = "https://healthlog.example.com";
|
||||
const res = await POST(
|
||||
postRequest(
|
||||
{ name: "LCP", value: 1000, id: "x" },
|
||||
{ referer: "https://malicious.example.org/probe" },
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(204);
|
||||
// The beacon was silently dropped (no log line); the rate-limiter
|
||||
// was never even consulted for a cross-site request.
|
||||
expect(checkRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a same-origin Referer when NEXT_PUBLIC_APP_URL is configured", async () => {
|
||||
process.env.NEXT_PUBLIC_APP_URL = "https://healthlog.example.com";
|
||||
const res = await POST(
|
||||
postRequest(
|
||||
{ name: "LCP", value: 1000, id: "x" },
|
||||
{ referer: "https://healthlog.example.com/insights" },
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(204);
|
||||
expect(checkRateLimit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* v1.4.28 R3d — Web Vitals beacon.
|
||||
*
|
||||
* Next 16 exposes `reportWebVitals` from the root layout; the client
|
||||
* POSTs every measurement to this internal route, which logs to the
|
||||
* shared wide-event pipeline so ops can see CLS / FCP / FID / LCP /
|
||||
* TTFB / INP / FCP histograms in the same place the rest of the
|
||||
* request flow surfaces.
|
||||
*
|
||||
* Why a route + not the front-end alone:
|
||||
*
|
||||
* - `console.log` from the client is invisible to the server-side
|
||||
* observability stack (HealthLog ships logs through the
|
||||
* `WideEventBuilder` in `src/lib/logging/context.ts`). Funnelling
|
||||
* metrics through a thin route reuses the existing pipeline.
|
||||
* - Persisting elsewhere (Postgres, S3) would be a wasted spend —
|
||||
* this is a beacon. We log and forget.
|
||||
*
|
||||
* Authentication: none. Web Vitals fire from the document lifecycle
|
||||
* (including the very first navigation that pre-dates auth), so an
|
||||
* auth gate would silently drop the most informative samples. The
|
||||
* route compensates by gating on:
|
||||
*
|
||||
* 1. Same-origin Referer header (when `NEXT_PUBLIC_APP_URL` is
|
||||
* configured) — fails closed on cross-site dispatch.
|
||||
* 2. Per-IP `checkRateLimit` (60 req / minute) — same shape as the
|
||||
* deploy-webhook. A real client sends ≤ 7 beacons per page;
|
||||
* anything past 60 is a flood.
|
||||
* 3. Zod schema — `name` is locked to the documented web-vitals
|
||||
* identifier set; `value` / `delta` / `id` are size-bounded.
|
||||
* Only validated fields enter the wide-event meta — the raw
|
||||
* payload is NEVER logged, so a hostile client cannot inject
|
||||
* arbitrary text into the observability sink.
|
||||
*
|
||||
* Always returns 204 No Content on a successful enqueue (no body so
|
||||
* `sendBeacon` never retries). 400 on schema reject; 429 on rate-limit
|
||||
* hit. The client never reads either — the beacon is fire-and-forget.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { getClientIp } from "@/lib/api-response";
|
||||
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
|
||||
|
||||
const webVitalsBodySchema = z.object({
|
||||
// Locked to the web-vitals library's documented metric identifiers.
|
||||
// FCP is included for parity with the iOS WebView client; INP super-
|
||||
// sedes FID under the new Core Web Vitals contract.
|
||||
name: z.enum(["CLS", "LCP", "FID", "INP", "TTFB", "FCP"]),
|
||||
value: z.number().finite(),
|
||||
// Web Vitals client builds `id` from `${navigation-uuid}-${index}`
|
||||
// — bounded length keeps a hostile peer from logging arbitrary text
|
||||
// under the identifier slot.
|
||||
id: z.string().max(50),
|
||||
delta: z.number().finite().optional(),
|
||||
rating: z.enum(["good", "needs-improvement", "poor"]).optional(),
|
||||
navigationType: z
|
||||
.enum(["navigate", "reload", "back-forward", "back-forward-cache", "prerender"])
|
||||
.optional(),
|
||||
});
|
||||
|
||||
function isSameOriginReferer(request: NextRequest): boolean {
|
||||
// When `NEXT_PUBLIC_APP_URL` is unset (test / unconfigured dev) skip
|
||||
// the check — the rate-limit + schema still bound the surface, and
|
||||
// gating on a missing env would dead-lock the beacon in dev.
|
||||
const expectedOrigin = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (!expectedOrigin) return true;
|
||||
|
||||
const referer = request.headers.get("referer");
|
||||
if (!referer) return false;
|
||||
|
||||
try {
|
||||
const refererOrigin = new URL(referer).origin;
|
||||
const expected = new URL(expectedOrigin).origin;
|
||||
return refererOrigin === expected;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// Same-origin gate. Fails closed on cross-site dispatch.
|
||||
if (!isSameOriginReferer(request)) {
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
// Per-IP rate-limit. 60 req / minute is well above a real client's
|
||||
// ≤ 7 beacons / page-load and well below a flood. 429 on hit; the
|
||||
// beacon contract still accepts 4xx without retry on the client.
|
||||
const ip = getClientIp(request);
|
||||
const rl = await checkRateLimit(
|
||||
`web-vitals:${ip ?? "unknown"}`,
|
||||
60,
|
||||
60_000,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "rate_limited" },
|
||||
{ status: 429, headers: rateLimitHeaders(rl) },
|
||||
);
|
||||
}
|
||||
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await request.json();
|
||||
} catch {
|
||||
// Malformed payload — 400 so the beacon never retries. Crucially:
|
||||
// we do NOT log the raw body (log-injection defence).
|
||||
return NextResponse.json({ error: "invalid_body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const parsed = webVitalsBodySchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "invalid_body" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Log only the validated fields. The raw payload never enters the
|
||||
// observability pipeline, so a hostile peer cannot smuggle text
|
||||
// into the wide-event log via unrecognised keys.
|
||||
const { name, value, id, delta, rating, navigationType } = parsed.data;
|
||||
annotate({
|
||||
meta: {
|
||||
"web_vitals.name": name,
|
||||
"web_vitals.value": value,
|
||||
"web_vitals.id": id,
|
||||
"web_vitals.delta": delta ?? null,
|
||||
"web_vitals.rating": rating ?? null,
|
||||
"web_vitals.navigation_type": navigationType ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { updateMeasurementSchema } from "@/lib/validations/measurement";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
@@ -62,14 +63,35 @@ export const PUT = apiHandler(
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const measurement = await prisma.measurement.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.value !== undefined && { value: data.value }),
|
||||
...(data.measuredAt !== undefined && { measuredAt: data.measuredAt }),
|
||||
...(data.notes !== undefined && { notes: data.notes }),
|
||||
},
|
||||
});
|
||||
let measurement;
|
||||
try {
|
||||
measurement = await prisma.measurement.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(data.value !== undefined && { value: data.value }),
|
||||
...(data.measuredAt !== undefined && { measuredAt: data.measuredAt }),
|
||||
...(data.notes !== undefined && { notes: data.notes }),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
// v1.4.28 FB-B1 — re-pointing `measuredAt` onto an existing
|
||||
// `(userId, type, measuredAt, source, sleepStage)` tuple raises
|
||||
// `P2002`. Mirror the POST handler's catch so the row-edit Sheet
|
||||
// surfaces a clean 409 with a translatable `errorCode` instead of
|
||||
// the bare 500 the UI used to render as the generic save-error
|
||||
// toast.
|
||||
if (
|
||||
err instanceof Prisma.PrismaClientKnownRequestError &&
|
||||
err.code === "P2002"
|
||||
) {
|
||||
return apiError(
|
||||
"A measurement with this timestamp already exists",
|
||||
409,
|
||||
{ errorCode: "measurement.duplicate_timestamp" },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
await auditLog("measurement.update", {
|
||||
userId: user.id,
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
|
||||
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 { PUT } from "../[id]/route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
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 },
|
||||
};
|
||||
|
||||
function putRequest(id: string, body: Record<string, unknown>): NextRequest {
|
||||
return new NextRequest(`http://localhost/api/measurements/${id}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("PUT /api/measurements/[id] — duplicate-timestamp handling", () => {
|
||||
it("returns 409 when re-pointing measuredAt onto an existing tuple", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.findUnique).mockResolvedValue({
|
||||
id: "m-2",
|
||||
userId: "user-1",
|
||||
type: "ACTIVITY_STEPS",
|
||||
value: 1234,
|
||||
measuredAt: new Date("2026-05-10T10:00:00.000Z"),
|
||||
source: "MANUAL",
|
||||
sleepStage: null,
|
||||
notes: null,
|
||||
unit: "count",
|
||||
} as never);
|
||||
|
||||
// Mirror what Prisma raises on a unique-constraint collision.
|
||||
const p2002 = new Prisma.PrismaClientKnownRequestError(
|
||||
"Unique constraint failed",
|
||||
{
|
||||
code: "P2002",
|
||||
clientVersion: "x",
|
||||
meta: { target: ["userId", "type", "measuredAt", "source", "sleepStage"] },
|
||||
},
|
||||
);
|
||||
vi.mocked(prisma.measurement.update).mockRejectedValue(p2002);
|
||||
|
||||
const res = await PUT(
|
||||
putRequest("m-2", { measuredAt: "2026-05-10T09:00:00.000Z" }),
|
||||
{ params: Promise.resolve({ id: "m-2" }) },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const json = (await res.json()) as { error: string; meta?: { errorCode?: string } };
|
||||
expect(json.error).toMatch(/already exists|duplicate/i);
|
||||
expect(json.meta?.errorCode).toBe("measurement.duplicate_timestamp");
|
||||
});
|
||||
|
||||
it("re-throws any non-P2002 Prisma error", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.findUnique).mockResolvedValue({
|
||||
id: "m-3",
|
||||
userId: "user-1",
|
||||
type: "WEIGHT",
|
||||
value: 75,
|
||||
measuredAt: new Date(),
|
||||
source: "MANUAL",
|
||||
sleepStage: null,
|
||||
notes: null,
|
||||
unit: "kg",
|
||||
} as never);
|
||||
|
||||
const otherError = new Prisma.PrismaClientKnownRequestError(
|
||||
"Record not found",
|
||||
{ code: "P2025", clientVersion: "x" },
|
||||
);
|
||||
vi.mocked(prisma.measurement.update).mockRejectedValue(otherError);
|
||||
|
||||
const res = await PUT(
|
||||
putRequest("m-3", { value: 76 }),
|
||||
{ params: Promise.resolve({ id: "m-3" }) },
|
||||
);
|
||||
|
||||
// apiHandler converts uncaught errors to 500.
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 409 on a sport-style measurement edit (FB-B1)", async () => {
|
||||
// v1.4.28 FB-B1 — the maintainer's "Sport edit + save → error"
|
||||
// report maps onto measurement-typed sport rows (Apple Health
|
||||
// ingests workouts as ACTIVE_ENERGY_BURNED / FLIGHTS_CLIMBED /
|
||||
// WALKING_RUNNING_DISTANCE samples, all of which route through
|
||||
// /api/measurements/[id] for edits). No separate /api/workouts/[id]
|
||||
// PUT exists — workouts are ingested via POST /api/workouts/batch
|
||||
// only. The 409 handler must therefore fire for sport-typed rows.
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.findUnique).mockResolvedValue({
|
||||
id: "m-sport",
|
||||
userId: "user-1",
|
||||
type: "ACTIVE_ENERGY_BURNED",
|
||||
value: 320,
|
||||
measuredAt: new Date("2026-05-10T10:00:00.000Z"),
|
||||
source: "APPLE_HEALTH",
|
||||
sleepStage: null,
|
||||
notes: null,
|
||||
unit: "kcal",
|
||||
} as never);
|
||||
|
||||
const p2002 = new Prisma.PrismaClientKnownRequestError(
|
||||
"Unique constraint failed",
|
||||
{
|
||||
code: "P2002",
|
||||
clientVersion: "x",
|
||||
meta: { target: ["userId", "type", "measuredAt", "source", "sleepStage"] },
|
||||
},
|
||||
);
|
||||
vi.mocked(prisma.measurement.update).mockRejectedValue(p2002);
|
||||
|
||||
const res = await PUT(
|
||||
putRequest("m-sport", { measuredAt: "2026-05-10T09:00:00.000Z" }),
|
||||
{ params: Promise.resolve({ id: "m-sport" }) },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const json = (await res.json()) as {
|
||||
error: string;
|
||||
meta?: { errorCode?: string };
|
||||
};
|
||||
expect(json.meta?.errorCode).toBe("measurement.duplicate_timestamp");
|
||||
});
|
||||
|
||||
it("returns the updated measurement on the 200 happy path", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.measurement.findUnique).mockResolvedValue({
|
||||
id: "m-4",
|
||||
userId: "user-1",
|
||||
type: "WEIGHT",
|
||||
value: 75,
|
||||
measuredAt: new Date("2026-05-10T10:00:00.000Z"),
|
||||
source: "MANUAL",
|
||||
sleepStage: null,
|
||||
notes: null,
|
||||
unit: "kg",
|
||||
} as never);
|
||||
vi.mocked(prisma.measurement.update).mockResolvedValue({
|
||||
id: "m-4",
|
||||
userId: "user-1",
|
||||
type: "WEIGHT",
|
||||
value: 76,
|
||||
measuredAt: new Date("2026-05-10T10:00:00.000Z"),
|
||||
source: "MANUAL",
|
||||
sleepStage: null,
|
||||
notes: null,
|
||||
unit: "kg",
|
||||
} as never);
|
||||
|
||||
const res = await PUT(
|
||||
putRequest("m-4", { value: 76 }),
|
||||
{ params: Promise.resolve({ id: "m-4" }) },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as { data: { id: string; value: number } };
|
||||
expect(json.data.id).toBe("m-4");
|
||||
expect(json.data.value).toBe(76);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* v1.4.28 R4-CODE-C1 / C2 — the `/api/measurements` route must
|
||||
* aggregate via Postgres `date_trunc` BEFORE applying the bucket cap.
|
||||
* The legacy code path `findMany({ take: limit })` then in-memory
|
||||
* bucketised — a 1-year `aggregate=daily` window would silently truncate
|
||||
* to the first N raw rows and surface only a handful of buckets.
|
||||
*
|
||||
* The route now runs a `$queryRaw` with `GROUP BY type, date_trunc(...)`
|
||||
* so the cap (`BUCKET_CAP[grain]`) applies after the bucket count is
|
||||
* known. C2 — the aggregation must NOT auto-fire on iOS callers; the
|
||||
* `aggregate` param is required to opt in.
|
||||
*/
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
},
|
||||
$queryRaw: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
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 { prisma } from "@/lib/db";
|
||||
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: "test-user", role: "USER" as const },
|
||||
};
|
||||
|
||||
function getRequest(query: string): NextRequest {
|
||||
return new NextRequest(`http://localhost/api/measurements?${query}`, {
|
||||
method: "GET",
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
});
|
||||
|
||||
describe("GET /api/measurements — aggregation gate (C2)", () => {
|
||||
it("returns raw rows when `aggregate` is omitted, even on a wide window", async () => {
|
||||
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "m-1",
|
||||
userId: "user-1",
|
||||
type: "PULSE",
|
||||
value: 60,
|
||||
measuredAt: new Date("2026-01-01T10:00:00.000Z"),
|
||||
source: "MANUAL",
|
||||
notes: null,
|
||||
unit: "bpm",
|
||||
},
|
||||
] as never);
|
||||
vi.mocked(prisma.measurement.count).mockResolvedValue(1 as never);
|
||||
|
||||
// A 1-year window with no `aggregate` must NOT trigger the
|
||||
// aggregation branch — iOS contract safety (R4-CODE-C2).
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=PULSE&from=2025-05-15T00:00:00Z&to=2026-05-15T00:00:00Z&limit=500",
|
||||
),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { measurements: Array<unknown>; meta: { aggregate?: string } };
|
||||
};
|
||||
expect(prisma.$queryRaw).not.toHaveBeenCalled();
|
||||
expect(prisma.measurement.findMany).toHaveBeenCalledTimes(1);
|
||||
expect(json.data.meta.aggregate).toBeUndefined();
|
||||
});
|
||||
|
||||
it("runs SQL aggregation when `aggregate=daily` is set and returns bucketed rows", async () => {
|
||||
// Simulate 365 daily buckets returned from the date_trunc query.
|
||||
const buckets = Array.from({ length: 365 }, (_, i) => ({
|
||||
type: "PULSE",
|
||||
bucket_start: new Date(
|
||||
Date.UTC(2025, 4, 15 + i, 0, 0, 0) - i * 0, // placeholder, monotonic
|
||||
),
|
||||
avg: 60 + (i % 10),
|
||||
cnt: 1440, // a minute-by-minute pulse account
|
||||
}));
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue(buckets as never);
|
||||
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=PULSE&from=2025-05-15T00:00:00Z&to=2026-05-15T00:00:00Z&aggregate=daily&limit=5000",
|
||||
),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: {
|
||||
measurements: Array<{ type: string; value: number; count: number }>;
|
||||
meta: { aggregate?: string; limit: number };
|
||||
};
|
||||
};
|
||||
expect(prisma.$queryRaw).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
|
||||
// C1 — the response carries one bucket per calendar day, NOT
|
||||
// `min(limit, count)/grain`. The raw-data density (1440 rows/day)
|
||||
// is summarised in the `count` field.
|
||||
expect(json.data.measurements.length).toBe(365);
|
||||
expect(json.data.measurements[0].count).toBe(1440);
|
||||
expect(json.data.meta.aggregate).toBe("daily");
|
||||
// Bucket cap for daily is 365.
|
||||
expect(json.data.meta.limit).toBe(365);
|
||||
});
|
||||
|
||||
it("caps monthly grain at the BUCKET_CAP ceiling", async () => {
|
||||
const buckets = Array.from({ length: 24 }, (_, i) => ({
|
||||
type: "WEIGHT",
|
||||
bucket_start: new Date(Date.UTC(2024, i, 1, 0, 0, 0)),
|
||||
avg: 75 + i * 0.1,
|
||||
cnt: 30,
|
||||
}));
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue(buckets as never);
|
||||
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=WEIGHT&from=2024-01-01T00:00:00Z&to=2026-01-01T00:00:00Z&aggregate=monthly&limit=5000",
|
||||
),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { meta: { limit: number; aggregate?: string } };
|
||||
};
|
||||
expect(json.data.meta.limit).toBe(24);
|
||||
expect(json.data.meta.aggregate).toBe("monthly");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/measurements — all-time semantics (SD-H1)", () => {
|
||||
it("returns a sensible monthly series for a multi-year all-time window", async () => {
|
||||
// Simulate four years of monthly weight rollups. The fixture mirrors
|
||||
// what `date_trunc('month', measured_at)` produces server-side and
|
||||
// proves the route hands back the full history (capped at the
|
||||
// monthly BUCKET_CAP of 24 — the chart paints the most recent 24
|
||||
// months when "All time" exceeds the cap).
|
||||
const buckets = Array.from({ length: 24 }, (_, i) => ({
|
||||
type: "WEIGHT",
|
||||
bucket_start: new Date(Date.UTC(2024, i, 1, 0, 0, 0)),
|
||||
avg: 80 - i * 0.05,
|
||||
cnt: 30,
|
||||
}));
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue(buckets as never);
|
||||
|
||||
// "All time" client call: oldest measurement → today, monthly grain.
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=WEIGHT&from=2020-01-01T00:00:00Z&to=2026-05-15T00:00:00Z&aggregate=monthly&limit=5000",
|
||||
),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: {
|
||||
measurements: Array<{ measuredAt: string; count: number }>;
|
||||
meta: { aggregate?: string; total: number };
|
||||
};
|
||||
};
|
||||
// The response is monthly-bucketed (NOT a truncated 365-day slice).
|
||||
expect(json.data.meta.aggregate).toBe("monthly");
|
||||
expect(json.data.measurements.length).toBe(24);
|
||||
// Buckets cover distinct calendar months — a 365-day slice could
|
||||
// not span more than 13 months.
|
||||
const months = new Set(
|
||||
json.data.measurements.map((m) => m.measuredAt.slice(0, 7)),
|
||||
);
|
||||
expect(months.size).toBe(24);
|
||||
});
|
||||
|
||||
it("returns a weekly series when the all-time window is under two years", async () => {
|
||||
// Three months past one year → falls in the weekly grain band.
|
||||
const weeks = Array.from({ length: 60 }, (_, i) => ({
|
||||
type: "PULSE",
|
||||
bucket_start: new Date(Date.UTC(2025, 0, 6 + i * 7, 0, 0, 0)),
|
||||
avg: 60 + (i % 5),
|
||||
cnt: 7 * 24 * 60,
|
||||
}));
|
||||
vi.mocked(prisma.$queryRaw).mockResolvedValue(weeks as never);
|
||||
|
||||
const res = await GET(
|
||||
getRequest(
|
||||
"type=PULSE&from=2024-12-15T00:00:00Z&to=2026-05-15T00:00:00Z&aggregate=weekly&limit=5000",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as {
|
||||
data: { meta: { aggregate?: string }; measurements: Array<unknown> };
|
||||
};
|
||||
expect(json.data.meta.aggregate).toBe("weekly");
|
||||
expect(json.data.measurements.length).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
listMeasurementsSchema,
|
||||
getUnitForType,
|
||||
} from "@/lib/validations/measurement";
|
||||
import {
|
||||
BUCKET_CAP,
|
||||
type AggregateGrain,
|
||||
} from "@/lib/measurements/range-aggregation";
|
||||
import { withIdempotency } from "@/lib/idempotency";
|
||||
import { NextRequest } from "next/server";
|
||||
import type {
|
||||
@@ -32,7 +36,8 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
}
|
||||
|
||||
const { type, from, to, limit, offset, sortBy, sortDir } = parsed.data;
|
||||
const { type, from, to, limit, offset, sortBy, sortDir, aggregate } =
|
||||
parsed.data;
|
||||
|
||||
const where = {
|
||||
userId: user.id,
|
||||
@@ -47,6 +52,68 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
: {}),
|
||||
};
|
||||
|
||||
// v1.4.28 FB-D2 — server-side aggregation. Gated on an explicit
|
||||
// `aggregate` param so the iOS contract (raw `MeasurementWireDTO`
|
||||
// shape on `GET /api/measurements`) is byte-stable for any caller
|
||||
// that omits the new query parameter. The chart-data client opts
|
||||
// in; iOS does not.
|
||||
//
|
||||
// R4-CODE-C1 — `take` no longer applies BEFORE bucketising. The
|
||||
// aggregation runs in Postgres via `date_trunc`, the bucket cap is
|
||||
// applied AFTER, so a 1-year `aggregate=daily` window walks every
|
||||
// row in the window and returns up to 365 buckets per type instead
|
||||
// of truncating to the first N raw rows.
|
||||
//
|
||||
// SD-H1 — "All time" range semantics. When the chart's "All" tab
|
||||
// is active, the client passes `from` = the user's earliest
|
||||
// measurement (or a sentinel like 1970-01-01) plus `to` = now plus
|
||||
// `aggregate=monthly` (or `weekly` when full history < 2 years).
|
||||
// The route's response is bounded by the `BUCKET_CAP` ceiling per
|
||||
// grain (monthly: 24, weekly: 105, daily: 365) so a multi-decade
|
||||
// account never paints an unbounded series.
|
||||
if (aggregate && aggregate !== "raw" && from && to) {
|
||||
const grain: AggregateGrain = aggregate;
|
||||
const cap = Math.min(limit, BUCKET_CAP[grain]);
|
||||
const truncUnit = grain === "daily" ? "day" : grain;
|
||||
const buckets = await prisma.$queryRaw<
|
||||
Array<{ type: string; bucket_start: Date; avg: number; cnt: number }>
|
||||
>`
|
||||
SELECT
|
||||
m."type"::text AS type,
|
||||
date_trunc(${truncUnit}, m."measured_at") AS bucket_start,
|
||||
AVG(m."value")::double precision AS avg,
|
||||
COUNT(*)::int AS cnt
|
||||
FROM measurements m
|
||||
WHERE m."user_id" = ${user.id}
|
||||
AND m."measured_at" >= ${from}
|
||||
AND m."measured_at" <= ${to}
|
||||
${type ? Prisma.sql`AND m."type" = ${type}::"MeasurementType"` : Prisma.empty}
|
||||
GROUP BY m."type", bucket_start
|
||||
ORDER BY bucket_start ASC
|
||||
LIMIT ${cap}
|
||||
`;
|
||||
|
||||
const measurements = buckets.map((b) => ({
|
||||
type: b.type,
|
||||
value: Number(b.avg),
|
||||
measuredAt: b.bucket_start.toISOString(),
|
||||
count: Number(b.cnt),
|
||||
}));
|
||||
annotate({
|
||||
action: { name: "measurement.list" },
|
||||
meta: { total: measurements.length, type, aggregate: grain },
|
||||
});
|
||||
return apiSuccess({
|
||||
measurements,
|
||||
meta: {
|
||||
total: measurements.length,
|
||||
limit: cap,
|
||||
offset: 0,
|
||||
aggregate: grain,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const [measurements, total] = await Promise.all([
|
||||
prisma.measurement.findMany({
|
||||
where,
|
||||
|
||||
Reference in new issue
Block a user