mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
chore(release): v1.4.42 — Knip enforcing, queryKey factory closed, iOS Workouts dedup, Withings off-response classification
Six touch-disjoint waves landed on develop before this release: - W1-KNIP — exports/types tiers flipped to enforcing-mode on main; 35 unused exports + 52 unused types triaged to 0/0; shadcn surface + zod-infer contract types scoped via knip.json ignore-block. - W2-ZOD-MULTI-ISSUE — `returnAllZodIssues` shared helper + `/api/dashboard/widgets` 422 now returns every Zod issue + worker audit-ledger breadcrumb. 41 sibling routes documented for v1.4.43. - W3-QUERYKEY-LONGTAIL — 40 settings/medications/admin/hooks files migrated to the queryKeys factory; 9 new factory entries; ESLint rule + test-guard scope extended in lockstep. - W4-ARCH-HYGIENE — BERLIN_DAY_FORMATTER consolidated across nine sites (seven status helpers + bucket-series + bp-in-target); Suspense double-comment consolidated; doctor-report sanitiser regex rewritten to escape-form so diffs are reviewable; pr-detection- worker soft-delete filter; offhost-backup DR-intent comment. - W5-IOS-WORKOUTS — `dedupeWorkoutBatch` write-time cross-source dedup helper for the v1.5 iOS HealthKit observer ingest; dashboard tile-strip placeholder parity with the live TrendCard chrome. - W6-WITHINGS-OFF + ENV-CHECK — Withings off-response classifier (transient/reauth/persistent) + WithingsApiError typed throw + the `pnpm check-env` CLI. APNs `allOrNone: true` closes the AP-2 silent-disable gap the wave was conceived to close. No migration, no env-var change, no API contract break for iOS v0.5.4. The new `/api/dashboard/widgets` 422 envelope is additively extended. pnpm test --run green at 4815 passing / 1 skipped. pnpm typecheck, pnpm lint, pnpm knip (no --include flag) green.
This commit is contained in:
1 parent
67207d725e
commit
9b6e237f5f
121 files changed
+6481
-590
No files matched your search
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* v1.4.42 W2 — multi-issue 422 envelope on PUT.
|
||||
*
|
||||
* Until v1.4.41 this route returned `parsed.error.issues[0].message`,
|
||||
* which dropped every issue past the first. iOS contract debugging
|
||||
* needed one round-trip per wrong field. The route now returns every
|
||||
* issue under `details.issues` AND writes a
|
||||
* `dashboard.widgets.validation-failed` audit-ledger row so the
|
||||
* operator can grep `/api/admin/audit` for the same trail.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
},
|
||||
toJson: (v: unknown) => v,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({
|
||||
getSession: 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 "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
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: "tester",
|
||||
role: "USER" as const,
|
||||
displayName: null,
|
||||
},
|
||||
};
|
||||
|
||||
const callPut = PUT as unknown as (req: NextRequest) => Promise<Response>;
|
||||
|
||||
function makeReq(body: unknown): NextRequest {
|
||||
return new NextRequest("http://localhost/api/dashboard/widgets", {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
__resetAllCachesForTests();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
describe("PUT /api/dashboard/widgets — 422 multi-issue envelope (v1.4.42 W2)", () => {
|
||||
it("surfaces TWO simultaneous validation errors under details.issues", async () => {
|
||||
// version=2 (literal mismatch) + widgets=[] (min(1) violation).
|
||||
const res = await callPut(makeReq({ version: 2, widgets: [] }));
|
||||
expect(res.status).toBe(422);
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: null;
|
||||
error: string;
|
||||
details: {
|
||||
issues: Array<{ path: string; code: string; message: string }>;
|
||||
};
|
||||
};
|
||||
expect(body.data).toBeNull();
|
||||
expect(body.error).toBe("Validation failed");
|
||||
expect(body.details.issues.length).toBe(2);
|
||||
const paths = body.details.issues.map((i) => i.path).sort();
|
||||
expect(paths).toEqual(["version", "widgets"]);
|
||||
|
||||
// Every issue carries exactly path / code / message — issue.params
|
||||
// never leaks (it may echo the offending user input for some codes).
|
||||
for (const issue of body.details.issues) {
|
||||
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("surfaces THREE simultaneous validation errors", async () => {
|
||||
const res = await callPut(
|
||||
makeReq({
|
||||
version: 99,
|
||||
widgets: [],
|
||||
comparisonBaseline: "tomorrow",
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as {
|
||||
details: { issues: Array<{ path: string; code: string }> };
|
||||
};
|
||||
expect(body.details.issues.length).toBe(3);
|
||||
const paths = body.details.issues.map((i) => i.path).sort();
|
||||
expect(paths).toEqual(["comparisonBaseline", "version", "widgets"]);
|
||||
});
|
||||
|
||||
it("writes one audit-ledger row keyed dashboard.widgets.validation-failed", async () => {
|
||||
const res = await callPut(makeReq({ version: 2, widgets: [] }));
|
||||
expect(res.status).toBe(422);
|
||||
|
||||
// The audit row is fire-and-forget — let the microtask queue drain.
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
|
||||
expect(prisma.auditLog.create).toHaveBeenCalledTimes(1);
|
||||
const call = vi.mocked(prisma.auditLog.create).mock.calls[0]?.[0] as {
|
||||
data: { userId: string; action: string; details: string };
|
||||
};
|
||||
expect(call.data.userId).toBe("user-1");
|
||||
expect(call.data.action).toBe("dashboard.widgets.validation-failed");
|
||||
const details = JSON.parse(call.data.details) as {
|
||||
issues: Array<{ path: string; code: string; message: string }>;
|
||||
};
|
||||
expect(details.issues.length).toBe(2);
|
||||
for (const issue of details.issues) {
|
||||
// Audit row carries the same sanitised shape — issue.params never
|
||||
// hits the ledger either.
|
||||
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not block the 422 response when the audit-row write rejects", async () => {
|
||||
vi.mocked(prisma.auditLog.create).mockRejectedValueOnce(
|
||||
new Error("db down"),
|
||||
);
|
||||
|
||||
const res = await callPut(makeReq({ version: 2, widgets: [] }));
|
||||
// The response is the contract — the audit row is best-effort.
|
||||
expect(res.status).toBe(422);
|
||||
const body = (await res.json()) as {
|
||||
details: { issues: Array<unknown> };
|
||||
};
|
||||
expect(body.details.issues.length).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,12 @@
|
||||
* to default.
|
||||
*/
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import {
|
||||
apiSuccess,
|
||||
safeJson,
|
||||
returnAllZodIssues,
|
||||
sanitiseZodIssues,
|
||||
} from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { prisma, toJson } from "@/lib/db";
|
||||
import {
|
||||
@@ -126,7 +131,31 @@ export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
const parsed = layoutSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return apiError(parsed.error.issues[0].message, 422);
|
||||
// v1.4.42 W2 — the legacy `issues[0].message` envelope dropped
|
||||
// every issue past the first. iOS contract debugging hit one
|
||||
// round-trip per wrong field; the new helper surfaces every
|
||||
// issue under `details.issues`. We additionally emit an
|
||||
// append-only audit-ledger row so the operator can grep
|
||||
// `/api/admin/audit` for these without combing the iOS dev
|
||||
// console.
|
||||
const issues = sanitiseZodIssues(parsed.error.issues);
|
||||
annotate({
|
||||
action: { name: "dashboard.widgets.validation-failed" },
|
||||
meta: { issue_count: issues.length },
|
||||
});
|
||||
// Best-effort breadcrumb — never block the 422 on a write miss.
|
||||
prisma.auditLog
|
||||
.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
action: "dashboard.widgets.validation-failed",
|
||||
details: JSON.stringify({ issues }),
|
||||
},
|
||||
})
|
||||
.catch(() => {
|
||||
/* swallow — validation response is the contract, audit row is best-effort */
|
||||
});
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
// v1.4.18 — preserve any per-chart overlay prefs that the client
|
||||
|
||||
@@ -225,8 +225,17 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
|
||||
const res = await POST(
|
||||
makeRequest({
|
||||
workouts: [
|
||||
// Two distinct runs separated by 2 h so the v1.4.42 W5
|
||||
// write-time canonical-row picker treats them as separate
|
||||
// workouts. Without the spacing the picker would collapse
|
||||
// them to one survivor (same userId + sportType + startedAt
|
||||
// inside the 90 s dedup window) and the envelope-count
|
||||
// assertion would mask the per-entry status pin.
|
||||
validWorkout("uuid-fresh-1"),
|
||||
validWorkout("uuid-fresh-2"),
|
||||
validWorkout("uuid-fresh-2", {
|
||||
startedAt: "2026-05-14T08:30:00.000Z",
|
||||
endedAt: "2026-05-14T09:15:00.000Z",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -253,8 +262,14 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
|
||||
const res = await POST(
|
||||
makeRequest({
|
||||
workouts: [
|
||||
// Same spacing rationale as the prior test — keep the two
|
||||
// entries' `startedAt` outside the W5 dedup window so the
|
||||
// pre-`createMany` pass doesn't collapse them.
|
||||
validWorkout("uuid-existing"),
|
||||
validWorkout("uuid-fresh"),
|
||||
validWorkout("uuid-fresh", {
|
||||
startedAt: "2026-05-14T08:30:00.000Z",
|
||||
endedAt: "2026-05-14T09:15:00.000Z",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -284,8 +299,15 @@ describe("POST /api/workouts/batch — per-entry status envelope", () => {
|
||||
const res = await POST(
|
||||
makeRequest({
|
||||
workouts: [
|
||||
// Same spacing rationale as the per-entry tests — keep both
|
||||
// entries outside the W5 dedup window so the race-reconcile
|
||||
// contract is exercised directly without the write-time
|
||||
// canonical-picker absorbing one of the rows first.
|
||||
validWorkout("uuid-race-1"),
|
||||
validWorkout("uuid-race-2"),
|
||||
validWorkout("uuid-race-2", {
|
||||
startedAt: "2026-05-14T08:30:00.000Z",
|
||||
endedAt: "2026-05-14T09:15:00.000Z",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -68,7 +68,8 @@ import {
|
||||
createBatchWorkoutSchema,
|
||||
MAX_WORKOUTS_PER_BATCH,
|
||||
} from "@/lib/validations/workout";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { dedupeWorkoutBatch } from "@/lib/workouts/canonical-rows";
|
||||
import { Prisma, type MeasurementSource } from "@/generated/prisma/client";
|
||||
|
||||
// v1.4.25 W16c — push-suppression threshold for workout PRs. A batch
|
||||
// larger than this fires the detection job with `silent: true` so a
|
||||
@@ -254,11 +255,56 @@ async function postBatch(request: NextRequest): Promise<Response> {
|
||||
};
|
||||
});
|
||||
|
||||
// v1.4.42 W5 — write-time cross-source dedup. The v1.5 iOS app
|
||||
// drains a HealthKit observer queue that frequently carries the
|
||||
// SAME logical workout from two paired sensors (Apple Watch +
|
||||
// Withings ScanWatch). Without this pass, both rows persist (their
|
||||
// `externalId`s differ → the `(userId, source, externalId)` unique
|
||||
// index never fires) and the read-time canonical-picker has to
|
||||
// carry the duplicate forward on every dashboard render.
|
||||
//
|
||||
// The helper is pure (no Prisma, no user lookups). It groups by
|
||||
// `(userId, activityType, startedAt ± 90 s)`, prefers the canonical
|
||||
// source ladder (APPLE_HEALTH > WITHINGS > MANUAL > IMPORT), and
|
||||
// breaks ties on calories > earliest createdAt > input order. Rows
|
||||
// dropped here surface to the iOS client as `duplicate` so the
|
||||
// sync cursor advances past them identically to the externalId
|
||||
// case below.
|
||||
const canonicalPrepared = dedupeWorkoutBatch(
|
||||
prepared.map((p) => ({
|
||||
userId: p.row.userId,
|
||||
activityType: p.row.sportType,
|
||||
startedAt: p.row.startedAt as Date,
|
||||
// Zod's `measurementSourceEnum.optional().default("MANUAL")`
|
||||
// guarantees `source` is set post-parse, but Prisma's
|
||||
// `WorkoutCreateManyInput` types it optional. Default through
|
||||
// the same fallback the validator uses so the picker's source
|
||||
// ladder still resolves on the rare row where TypeScript
|
||||
// can't prove the union.
|
||||
source: (p.row.source ?? "MANUAL") as MeasurementSource,
|
||||
caloriesKcal: p.row.totalEnergyKcal ?? null,
|
||||
// No createdAt yet — the row is pre-insert; the tie-breaker
|
||||
// falls through to input order via the `index` field below.
|
||||
index: p.index,
|
||||
})),
|
||||
);
|
||||
const survivingIndices = new Set(canonicalPrepared.map((r) => r.index ?? -1));
|
||||
const droppedByWriteDedup: number[] = [];
|
||||
for (const p of prepared) {
|
||||
if (!survivingIndices.has(p.index)) {
|
||||
results[p.index] = { index: p.index, status: "duplicate" };
|
||||
droppedByWriteDedup.push(p.index);
|
||||
}
|
||||
}
|
||||
const survivors = prepared.filter((p) => survivingIndices.has(p.index));
|
||||
let duplicateCount = droppedByWriteDedup.length;
|
||||
let insertedCount = 0;
|
||||
let duplicateCount = 0;
|
||||
|
||||
if (prepared.length > 0) {
|
||||
const dedupCandidates = prepared
|
||||
if (survivors.length > 0) {
|
||||
// v1.4.42 W5 — only the write-time dedup survivors are probed
|
||||
// against existing rows; the dropped twins already carry a
|
||||
// `duplicate` status and never reach the DB.
|
||||
const dedupCandidates = survivors
|
||||
.map((p) => p.dedupKey)
|
||||
.filter((k): k is { source: string; externalId: string } => k !== null);
|
||||
|
||||
@@ -280,7 +326,7 @@ async function postBatch(request: NextRequest): Promise<Response> {
|
||||
);
|
||||
|
||||
const toInsert: Prepared[] = [];
|
||||
for (const p of prepared) {
|
||||
for (const p of survivors) {
|
||||
const keyTuple = p.dedupKey
|
||||
? `${p.dedupKey.source}::${p.dedupKey.externalId}`
|
||||
: null;
|
||||
@@ -461,7 +507,10 @@ async function postBatch(request: NextRequest): Promise<Response> {
|
||||
const racedDuplicates = toInsert.length - insertedCount;
|
||||
if (racedDuplicates > 0) {
|
||||
let downgraded = 0;
|
||||
for (const p of prepared) {
|
||||
// v1.4.42 W5 — walk `survivors` (not `prepared`) so the
|
||||
// already-downgraded-by-write-dedup losers don't get
|
||||
// double-counted toward the race-reconcile budget.
|
||||
for (const p of survivors) {
|
||||
if (downgraded >= racedDuplicates) break;
|
||||
if (results[p.index]?.status === "inserted") {
|
||||
results[p.index] = { index: p.index, status: "duplicate" };
|
||||
|
||||
@@ -13,6 +13,7 @@ import { IntakeHistoryListV2 } from "@/components/medications/intake-history-lis
|
||||
import { ArrowLeft, Loader2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
export default function IntakeHistoryPage({
|
||||
params,
|
||||
@@ -31,7 +32,7 @@ export default function IntakeHistoryPage({
|
||||
}, [authLoading, isAuthenticated, router]);
|
||||
|
||||
const { data: medication, isLoading: medLoading } = useQuery({
|
||||
queryKey: ["medications", id],
|
||||
queryKey: queryKeys.medicationDetail(id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${id}`);
|
||||
if (!res.ok) throw new Error("Failed to fetch");
|
||||
|
||||
@@ -4,7 +4,11 @@ import { useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
invalidateKeys,
|
||||
medicationDependentKeys,
|
||||
queryKeys,
|
||||
} from "@/lib/query-keys";
|
||||
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { MedicationForm } from "@/components/medications/medication-form";
|
||||
import { MedicationCard } from "@/components/medications/medication-card";
|
||||
@@ -90,7 +94,7 @@ export default function MedicationsPage() {
|
||||
isError,
|
||||
refetch: refetchMedications,
|
||||
} = useQuery({
|
||||
queryKey: ["medications"],
|
||||
queryKey: queryKeys.medications(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/medications");
|
||||
if (!res.ok) throw new Error("Failed to fetch");
|
||||
|
||||
+6
-18
@@ -1400,32 +1400,20 @@ export default function DashboardPage() {
|
||||
{trendCards.map((entry) => (
|
||||
<div key={entry.id} className="flex min-w-0">
|
||||
{/*
|
||||
* v1.4.40 W-RSC — per-tile `<Suspense>` boundary.
|
||||
* The tile body is synchronous today (every tile
|
||||
* reads from the merged `data` memo which already
|
||||
* gates on the slim/thick analytics queries on the
|
||||
* parent), so this fallback never paints in the
|
||||
* current composition. The structural boundary
|
||||
* matches the chart-row layer below so the entire
|
||||
* dashboard composition reads as a streaming-ready
|
||||
* grid of independently suspending cells — and
|
||||
* future RSC hoists of any tile slot won't need a
|
||||
* second pass to add the fallback infrastructure.
|
||||
*/}
|
||||
{/*
|
||||
* v1.4.41 W-FRONTEND-FACTORY (UX M1) — swap the
|
||||
* `null` fallback for a layout-stable placeholder
|
||||
* that mirrors the trend-card chrome. The body
|
||||
* stays synchronous today so the fallback rarely
|
||||
* Per-tile `<Suspense>` boundary with a layout-stable
|
||||
* placeholder that mirrors the trend-card chrome. Tile
|
||||
* bodies are synchronous today so the fallback rarely
|
||||
* paints, but a future RSC hoist of any tile slot
|
||||
* would otherwise leave the grid track empty and
|
||||
* trigger CLS as the cell paints in.
|
||||
*
|
||||
* v1.4.40 W-RSC — boundary added; v1.4.41 W-FRONTEND-FACTORY — fallback hoisted to layout-stable placeholder.
|
||||
*/}
|
||||
<Suspense
|
||||
fallback={
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="bg-card border-border h-full w-full rounded-xl border p-4 md:p-6"
|
||||
className="bg-card border-border flex h-full min-h-[6rem] w-full min-w-0 flex-col rounded-xl border p-4 md:p-6"
|
||||
/>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { AlertCircle, Loader2 } from "lucide-react";
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { convertGlucose, resolveGlucoseUnit } from "@/lib/glucose";
|
||||
import {
|
||||
@@ -46,9 +47,8 @@ interface TargetsResponse {
|
||||
/**
|
||||
* v1.4.25 W3e — provider-chain status used to gate the per-card Coach
|
||||
* CTA. Returns true when at least one provider is configured AND
|
||||
* enabled. The Settings → AI surface owns the same query
|
||||
* (`useQuery({ queryKey: ["insights", "provider-chain"] })`) so the
|
||||
* cache is shared.
|
||||
* enabled. The Settings → AI surface owns the same query (via
|
||||
* `queryKeys.insightsProviderChain()`) so the cache is shared.
|
||||
*/
|
||||
interface ProviderChainStatus {
|
||||
activeProvider: string | null;
|
||||
@@ -132,7 +132,7 @@ export default function TargetsPage() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["insights", "targets"],
|
||||
queryKey: queryKeys.insightsTargets(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/insights/targets");
|
||||
if (!res.ok) throw new Error(t("targets.loadError"));
|
||||
@@ -146,7 +146,7 @@ export default function TargetsPage() {
|
||||
// user has no configured provider, `activeProvider` is null and the
|
||||
// per-card Coach CTA hides entirely (no broken-button state).
|
||||
const { data: chainStatus } = useQuery({
|
||||
queryKey: ["insights", "provider-chain"],
|
||||
queryKey: queryKeys.insightsProviderChain(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/insights/provider-chain");
|
||||
if (!res.ok) return null;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { toast } from "sonner";
|
||||
import { Cpu, Fingerprint, Globe, KeyRound } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { PasswordInput as SharedPasswordInput } from "@/components/ui/password-input";
|
||||
|
||||
/**
|
||||
@@ -225,7 +226,7 @@ export function SettingsToggle({
|
||||
|
||||
export function useAdminSettings() {
|
||||
return useQuery({
|
||||
queryKey: ["admin", "settings"],
|
||||
queryKey: queryKeys.adminSettings(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/settings");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -249,7 +250,7 @@ export function useUpdateSettings() {
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "settings"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminSettings() });
|
||||
toast.success(t("common.saved"));
|
||||
},
|
||||
onError: (err) => {
|
||||
@@ -523,7 +524,7 @@ export function auditLogCsvHeaderLabels(
|
||||
|
||||
export function useSystemStatus() {
|
||||
return useQuery({
|
||||
queryKey: ["admin", "status"],
|
||||
queryKey: queryKeys.adminStatus(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Sparkles, Loader2 } from "lucide-react";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface FeedbackBucket {
|
||||
severity: string;
|
||||
@@ -63,7 +64,7 @@ export function AiQualitySection() {
|
||||
const fmt = useFormatters();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "ai-quality"],
|
||||
queryKey: queryKeys.adminAiQuality(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/ai-quality");
|
||||
const json = (await res.json()) as AiQualityResponse;
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import { formatDate, formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { type ApiTokenInfo } from "./_shared";
|
||||
|
||||
/**
|
||||
@@ -147,7 +148,7 @@ export function ApiTokenOverviewSection() {
|
||||
// one card the toggle hides the entire surface. the maintainer reported it
|
||||
// as "sinnlos" — gone.
|
||||
const { data: tokens, isLoading } = useQuery({
|
||||
queryKey: ["admin", "tokens"],
|
||||
queryKey: queryKeys.adminTokens(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/tokens");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { WideEvent, LogLevel } from "@/lib/logging/types";
|
||||
|
||||
type RangePreset = "15m" | "1h" | "6h" | "all";
|
||||
@@ -100,7 +101,7 @@ export function AppLogPreviewSection() {
|
||||
}, [traceId, actionFilter, level, range]);
|
||||
|
||||
const { data, isLoading, refetch, isFetching } = useQuery({
|
||||
queryKey: ["admin", "app-logs", traceId, actionFilter, level, range],
|
||||
queryKey: queryKeys.adminAppLogs(traceId, actionFilter, level, range),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/admin/app-logs?${params.toString()}`);
|
||||
if (!res.ok) throw new Error("Failed to load app logs");
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Sparkles } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { SettingsToggle, getApiErrorMessage } from "./_shared";
|
||||
|
||||
/**
|
||||
@@ -45,7 +46,7 @@ interface AssistantFlagsResponse {
|
||||
|
||||
function useAssistantFlags() {
|
||||
return useQuery({
|
||||
queryKey: ["admin", "settings", "assistant-flags"],
|
||||
queryKey: queryKeys.adminAssistantFlags(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/settings/assistant-flags");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -73,12 +74,12 @@ function useUpdateAssistantFlags() {
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
client.setQueryData(
|
||||
["admin", "settings", "assistant-flags"],
|
||||
queryKeys.adminAssistantFlags(),
|
||||
data,
|
||||
);
|
||||
// Bust the runtime `/api/feature-flags` cache so the operator
|
||||
// sees the toggled surface react within the same session.
|
||||
client.invalidateQueries({ queryKey: ["feature-flags"] });
|
||||
client.invalidateQueries({ queryKey: queryKeys.featureFlags() });
|
||||
toast.success(t("common.saved"));
|
||||
},
|
||||
onError: (err) => {
|
||||
@@ -88,7 +89,7 @@ function useUpdateAssistantFlags() {
|
||||
: t("admin.settingsSaveError"),
|
||||
);
|
||||
client.invalidateQueries({
|
||||
queryKey: ["admin", "settings", "assistant-flags"],
|
||||
queryKey: queryKeys.adminAssistantFlags(),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -41,6 +41,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { BackupRow, BackupsList } from "@/types/backups";
|
||||
import { getApiErrorMessage } from "./_shared";
|
||||
|
||||
@@ -172,7 +173,7 @@ export function BackupsSection() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["admin", "backups"],
|
||||
queryKey: queryKeys.adminBackups(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/backups");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -194,7 +195,7 @@ export function BackupsSection() {
|
||||
// shows up without leaving the user wondering whether the click
|
||||
// did anything.
|
||||
setTimeout(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "backups"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminBackups() });
|
||||
}, 2000);
|
||||
},
|
||||
onError: (err) => {
|
||||
@@ -245,7 +246,7 @@ export function BackupsSection() {
|
||||
toast.success(
|
||||
t("admin.section.backups.uploadSuccess", { count: String(total) }),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "backups"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminBackups() });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
@@ -290,7 +291,7 @@ export function BackupsSection() {
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(t("admin.section.backups.restoreSuccess"));
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "backups"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminBackups() });
|
||||
// Restore touches every personal-data table; nuke the broader
|
||||
// cache so dashboards / lists rebuild against the new state.
|
||||
queryClient.invalidateQueries();
|
||||
|
||||
@@ -22,6 +22,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { Loader2, Sparkles } from "lucide-react";
|
||||
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface CoachFeedbackBucket {
|
||||
promptVersion: string;
|
||||
@@ -55,7 +56,7 @@ export function CoachFeedbackSection() {
|
||||
const fmt = useFormatters();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "coach-feedback"],
|
||||
queryKey: queryKeys.adminCoachFeedback(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/ai-quality");
|
||||
const json = (await res.json()) as CoachFeedbackResponse;
|
||||
|
||||
@@ -30,6 +30,7 @@ import { Label } from "@/components/ui/label";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
FEEDBACK_STATUS_TABS,
|
||||
type FeedbackCategoryType,
|
||||
@@ -50,7 +51,7 @@ export function FeedbackInboxSection() {
|
||||
const [selected, setSelected] = useState<FeedbackItem | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["admin", "feedback", activeStatus],
|
||||
queryKey: queryKeys.adminFeedback(activeStatus),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(
|
||||
`/api/admin/feedback?status=${activeStatus}&limit=100`,
|
||||
@@ -63,7 +64,7 @@ export function FeedbackInboxSection() {
|
||||
const counts = data?.meta?.countsByStatus ?? {};
|
||||
|
||||
function refresh() {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "feedback"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminFeedbackRoot() });
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
} from "recharts";
|
||||
import { useMemo } from "react";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface HostMetricsApiSample {
|
||||
capturedAt: string;
|
||||
@@ -130,7 +131,7 @@ export function HostMetricsChart() {
|
||||
const fmt = useFormatters();
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["admin", "host-metrics", "2h"],
|
||||
queryKey: queryKeys.adminHostMetrics("2h"),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/host-metrics?since=2h");
|
||||
if (!res.ok) throw new Error("Failed to load host metrics");
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@/components/ui/select";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { toCSV } from "@/lib/export";
|
||||
import { formatInUserTz, DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
@@ -114,10 +115,7 @@ export function LoginOverviewSection() {
|
||||
}, [page, perPage, actor, actionFilter, target, range]);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [
|
||||
"admin",
|
||||
"audit-log",
|
||||
"filtered",
|
||||
queryKey: queryKeys.adminAuditLogFiltered({
|
||||
filter,
|
||||
page,
|
||||
perPage,
|
||||
@@ -125,7 +123,7 @@ export function LoginOverviewSection() {
|
||||
actionFilter,
|
||||
target,
|
||||
range,
|
||||
],
|
||||
}),
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams(queryParams);
|
||||
// Quick-filter pill stacks on top of the new filters.
|
||||
@@ -140,7 +138,7 @@ export function LoginOverviewSection() {
|
||||
|
||||
// Distinct actions for the dropdown — populated lazily.
|
||||
const { data: actionsData } = useQuery({
|
||||
queryKey: ["admin", "audit-log", "actions"],
|
||||
queryKey: queryKeys.adminAuditActions(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/audit-log/actions");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { EmptyState } from "@/components/ui/empty-state";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { type AdminAuditEntry, useAuthActionLabels } from "./_shared";
|
||||
|
||||
const PREVIEW_LIMIT = 10;
|
||||
@@ -34,7 +35,7 @@ export function RecentAuditPreview() {
|
||||
const { t } = useTranslations();
|
||||
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["admin", "audit-log", "overview-preview"],
|
||||
queryKey: queryKeys.adminAuditOverview(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(
|
||||
`/api/admin/audit-log?limit=${PREVIEW_LIMIT}&filter=auth`,
|
||||
|
||||
@@ -22,6 +22,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { StatusItem, useSystemStatus } from "./_shared";
|
||||
|
||||
interface VersionResponse {
|
||||
@@ -33,7 +34,7 @@ interface VersionResponse {
|
||||
|
||||
function useOfflineGeoState() {
|
||||
return useQuery({
|
||||
queryKey: ["public", "version"],
|
||||
queryKey: queryKeys.publicVersion(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/version");
|
||||
if (!res.ok) throw new Error("Failed to load version");
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { StatusItem, useSystemStatus } from "./_shared";
|
||||
|
||||
interface VersionResponse {
|
||||
@@ -36,7 +37,7 @@ interface VersionResponse {
|
||||
|
||||
function useVersion() {
|
||||
return useQuery({
|
||||
queryKey: ["public", "version"],
|
||||
queryKey: queryKeys.publicVersion(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/version");
|
||||
if (!res.ok) throw new Error("Failed to load version");
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { type AdminUser, PasswordInput } from "./_shared";
|
||||
|
||||
/**
|
||||
@@ -49,7 +50,7 @@ export function UserManagementSection() {
|
||||
const [logoutTarget, setLogoutTarget] = useState<AdminUser | null>(null);
|
||||
|
||||
const { data: users } = useQuery({
|
||||
queryKey: ["admin", "users"],
|
||||
queryKey: queryKeys.adminUsers(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/users");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -81,7 +82,7 @@ export function UserManagementSection() {
|
||||
if (!res.ok) throw new Error(json.error || t("common.error"));
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.adminUsers() });
|
||||
setEditingUser(null);
|
||||
toast.success(t("common.saved"));
|
||||
},
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
computeOneCompartment,
|
||||
type DoseEvent,
|
||||
@@ -129,7 +130,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
|
||||
|
||||
const { data: researchMode, isLoading: rmLoading } =
|
||||
useQuery<ResearchModeStatus | null>({
|
||||
queryKey: ["research-mode"],
|
||||
queryKey: queryKeys.researchMode(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/auth/me/research-mode");
|
||||
if (!res.ok) return null;
|
||||
@@ -146,7 +147,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
|
||||
|
||||
const { data: details, isLoading: detailsLoading } =
|
||||
useQuery<Glp1DetailsResponse | null>({
|
||||
queryKey: ["medications", medication.id, "glp1-details"],
|
||||
queryKey: queryKeys.medicationGlp1Details(medication.id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${medication.id}/glp1`);
|
||||
if (!res.ok) return null;
|
||||
@@ -160,7 +161,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
|
||||
});
|
||||
|
||||
const { data: intakeEnvelope, isLoading: intakeLoading } = useQuery({
|
||||
queryKey: ["medications", medication.id, "intake", "drug-level-chart"],
|
||||
queryKey: queryKeys.medicationIntakeDrugLevelChart(medication.id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(
|
||||
`/api/medications/${medication.id}/intake?limit=20&sortBy=takenAt&sortDir=desc`,
|
||||
|
||||
@@ -45,6 +45,7 @@ import { AlertTriangle, BookOpenCheck, Loader2 } from "lucide-react";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
export interface ResearchModeAcknowledgmentDialogProps {
|
||||
open: boolean;
|
||||
@@ -94,7 +95,7 @@ export function ResearchModeAcknowledgmentDialog({
|
||||
onSuccess: () => {
|
||||
setErrorMessage(null);
|
||||
toast.success(t("medications.researchMode.dialog.successToast"));
|
||||
queryClient.invalidateQueries({ queryKey: ["research-mode"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.researchMode() });
|
||||
onAcknowledged?.();
|
||||
onOpenChange(false);
|
||||
},
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Loader2, BellRing, BellOff, Pencil } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
|
||||
|
||||
/**
|
||||
@@ -92,7 +93,7 @@ export function SchedulingSection({
|
||||
const fmt = useFormatters();
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["medications", medicationId, "cadence"],
|
||||
queryKey: queryKeys.medicationCadence(medicationId),
|
||||
queryFn: async (): Promise<CadenceResponse> => {
|
||||
const res = await fetch(
|
||||
`/api/medications/${medicationId}/cadence?days=30`,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { Loader2, ExternalLink } from "lucide-react";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
|
||||
|
||||
/**
|
||||
@@ -62,7 +63,7 @@ export function TitrationSection({ medicationId }: TitrationSectionProps) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["medications", medicationId, "titration"],
|
||||
queryKey: queryKeys.medicationTitration(medicationId),
|
||||
queryFn: async (): Promise<TitrationResponse> => {
|
||||
const res = await fetch(`/api/medications/${medicationId}/titration`);
|
||||
if (!res.ok) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { IntakeHistoryListV2 } from "@/components/medications/intake-history-list-v2";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
/**
|
||||
* v1.4.36 W4a — IntakeHistoryListV2 SSR smoke tests.
|
||||
@@ -62,16 +63,17 @@ function seedIntake(
|
||||
const limit = opts.limit ?? 25;
|
||||
const offset = opts.offset ?? 0;
|
||||
// v1.4.37 W3 — the component pins `status:"completed"` on the
|
||||
// server-side query and threads it through the cache key, so the
|
||||
// seed mirrors that shape verbatim.
|
||||
// server-side query and threads it through the cache key. The seed
|
||||
// routes through the canonical factory so the params shape stays in
|
||||
// lockstep with the component's read.
|
||||
client.setQueryData(
|
||||
[
|
||||
"medications",
|
||||
medId,
|
||||
"intake",
|
||||
"list",
|
||||
{ sortBy, sortDir, limit, offset, status: "completed" },
|
||||
],
|
||||
queryKeys.medicationIntakeList(medId, {
|
||||
sortBy,
|
||||
sortDir,
|
||||
limit,
|
||||
offset,
|
||||
status: "completed",
|
||||
}),
|
||||
{ events: rows, meta: { total, limit, offset } },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,12 +29,15 @@ import {
|
||||
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
invalidateKeys,
|
||||
medicationDependentKeys,
|
||||
queryKeys,
|
||||
} from "@/lib/query-keys";
|
||||
import { formatDateTime, formatTime } from "@/lib/format";
|
||||
import { formatTimeWindowRange } from "@/lib/time-window-format";
|
||||
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
|
||||
import {
|
||||
describeInjectionSite,
|
||||
nextInjectionSite,
|
||||
type InjectionSiteKey,
|
||||
} from "@/lib/medications/injection-sites";
|
||||
@@ -179,7 +182,7 @@ export function Glp1MedicationCard({
|
||||
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
|
||||
|
||||
const { data: compliance } = useQuery({
|
||||
queryKey: ["medications", medication.id, "compliance"],
|
||||
queryKey: queryKeys.medicationCompliance(medication.id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${medication.id}/compliance`);
|
||||
if (!res.ok) return null;
|
||||
@@ -194,7 +197,7 @@ export function Glp1MedicationCard({
|
||||
// medication card so the take-now / overdue / very-overdue pill
|
||||
// tiers identically on both surfaces.
|
||||
const { data: thresholds } = useQuery({
|
||||
queryKey: ["settings", "reminder-thresholds"],
|
||||
queryKey: queryKeys.settingsReminderThresholds(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/reminder-thresholds");
|
||||
if (!res.ok) return null;
|
||||
@@ -208,7 +211,7 @@ export function Glp1MedicationCard({
|
||||
// pen inventory). Lives behind a dedicated endpoint so the standard
|
||||
// medications grid loads in parallel without paying for it.
|
||||
const { data: details } = useQuery({
|
||||
queryKey: ["medications", medication.id, "glp1-details"],
|
||||
queryKey: queryKeys.medicationGlp1Details(medication.id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${medication.id}/glp1`);
|
||||
if (!res.ok) return null;
|
||||
@@ -587,6 +590,3 @@ function siteSuffix(site: InjectionSiteKey): string {
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Re-export so the parent doesn't need to import describeInjectionSite. */
|
||||
export { describeInjectionSite };
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -111,13 +112,13 @@ export function IntakeHistoryListV2({
|
||||
const offset = page * pageSize;
|
||||
|
||||
const { data, isLoading, isError } = useQuery<IntakeListResponse>({
|
||||
queryKey: [
|
||||
"medications",
|
||||
medicationId,
|
||||
"intake",
|
||||
"list",
|
||||
{ sortBy, sortDir, limit: pageSize, offset, status: STATUS_FILTER },
|
||||
],
|
||||
queryKey: queryKeys.medicationIntakeList(medicationId, {
|
||||
sortBy,
|
||||
sortDir,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
status: STATUS_FILTER,
|
||||
}),
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams({
|
||||
sortBy,
|
||||
|
||||
@@ -29,7 +29,11 @@ import {
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
invalidateKeys,
|
||||
medicationDependentKeys,
|
||||
queryKeys,
|
||||
} from "@/lib/query-keys";
|
||||
|
||||
interface Schedule {
|
||||
id: string;
|
||||
@@ -128,7 +132,7 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
|
||||
const [intakeLoading, setIntakeLoading] = useState<string | null>(null);
|
||||
|
||||
const { data: compliance } = useQuery({
|
||||
queryKey: ["medications", medication.id, "compliance"],
|
||||
queryKey: queryKeys.medicationCompliance(medication.id),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${medication.id}/compliance`);
|
||||
if (!res.ok) return null;
|
||||
@@ -141,7 +145,7 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
|
||||
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
|
||||
|
||||
const { data: thresholds } = useQuery({
|
||||
queryKey: ["settings", "reminder-thresholds"],
|
||||
queryKey: queryKeys.settingsReminderThresholds(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/reminder-thresholds");
|
||||
if (!res.ok) return null;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface PhaseConfigData {
|
||||
greenValue: number;
|
||||
@@ -76,7 +77,7 @@ export function PhaseConfigDialog({
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["phase-config", medicationId],
|
||||
queryKey: queryKeys.medicationPhaseConfig(medicationId),
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/api/medications/${medicationId}/phase-config`);
|
||||
const json = await res.json();
|
||||
@@ -101,7 +102,7 @@ export function PhaseConfigDialog({
|
||||
onSuccess: () => {
|
||||
setLocalForm(null);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["phase-config", medicationId],
|
||||
queryKey: queryKeys.medicationPhaseConfig(medicationId),
|
||||
});
|
||||
setStatusMessage(t("medications.phaseSaved"));
|
||||
setTimeout(() => setStatusMessage(null), 2000);
|
||||
@@ -119,7 +120,7 @@ export function PhaseConfigDialog({
|
||||
onSuccess: () => {
|
||||
setLocalForm(null);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["phase-config", medicationId],
|
||||
queryKey: queryKeys.medicationPhaseConfig(medicationId),
|
||||
});
|
||||
setStatusMessage(t("medications.phaseReset"));
|
||||
setTimeout(() => setStatusMessage(null), 2000);
|
||||
|
||||
@@ -44,6 +44,7 @@ import { formatDate } from "@/lib/format";
|
||||
import { locales, localeLabels, type Locale } from "@/lib/i18n/config";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { describePasskeyError } from "@/lib/passkey-errors";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { TimezonePicker } from "@/components/settings/timezone-picker";
|
||||
import { detectBrowserTimezone, DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
|
||||
@@ -726,7 +727,7 @@ function PasskeyListSection({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
const [deleteMsg, setDeleteMsg] = useState<string | null>(null);
|
||||
|
||||
const { data: passkeys } = useQuery({
|
||||
queryKey: ["passkeys"],
|
||||
queryKey: queryKeys.passkeys(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/auth/passkeys");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -742,7 +743,7 @@ function PasskeyListSection({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
if (!res.ok) throw new Error(json.error || t("common.error"));
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["passkeys"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.passkeys() });
|
||||
setDeleteMsg(null);
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { ResearchModeAcknowledgmentDialog } from "@/components/medications/ResearchModeAcknowledgmentDialog";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
type ResearchModeStatus,
|
||||
researchModeGateState,
|
||||
@@ -102,7 +103,7 @@ function ResearchModeCard() {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const { data: status, isLoading } = useQuery<ResearchModeStatus | null>({
|
||||
queryKey: ["research-mode"],
|
||||
queryKey: queryKeys.researchMode(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/auth/me/research-mode");
|
||||
if (!res.ok) return null;
|
||||
@@ -140,7 +141,7 @@ function ResearchModeCard() {
|
||||
setErrorMessage(t("settings.researchMode.disableError"));
|
||||
return;
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ["research-mode"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.researchMode() });
|
||||
} catch {
|
||||
setErrorMessage(t("settings.researchMode.disableError"));
|
||||
} finally {
|
||||
|
||||
@@ -37,6 +37,7 @@ import { PasswordInput } from "@/components/ui/password-input";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface InsightsSettings {
|
||||
codexStatus: string;
|
||||
@@ -186,7 +187,7 @@ function AiInsightsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const { data: insightsSettings } = useQuery({
|
||||
queryKey: ["insights", "settings"],
|
||||
queryKey: queryKeys.insightsSettings(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/insights/settings");
|
||||
if (!res.ok) return null;
|
||||
@@ -197,7 +198,7 @@ function AiInsightsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
});
|
||||
|
||||
const { data: userProvider } = useQuery({
|
||||
queryKey: ["user", "ai-provider"],
|
||||
queryKey: queryKeys.userAiProvider(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/user/ai-provider");
|
||||
if (!res.ok) return null;
|
||||
@@ -208,7 +209,7 @@ function AiInsightsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
});
|
||||
|
||||
const { data: chainData } = useQuery({
|
||||
queryKey: ["insights", "provider-chain"],
|
||||
queryKey: queryKeys.insightsProviderChain(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/insights/provider-chain");
|
||||
if (!res.ok) return null;
|
||||
@@ -296,10 +297,10 @@ function AiInsightsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
privacyMode={insightsSettings?.privacyMode ?? "aggregated"}
|
||||
lastInsightAt={insightsSettings?.lastInsightAt ?? null}
|
||||
onRegenerated={() =>
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] })
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() })
|
||||
}
|
||||
onPrivacyChanged={() =>
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] })
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
@@ -479,7 +480,7 @@ function CodexProviderForm({
|
||||
url.searchParams.delete("codex_error");
|
||||
window.history.replaceState({}, "", url.toString());
|
||||
if (oauthOutcome.kind === "connected") {
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
}
|
||||
}, [oauthOutcome, queryClient]);
|
||||
|
||||
@@ -536,7 +537,7 @@ function CodexProviderForm({
|
||||
setDevicePolling(false);
|
||||
setMsg(t("settings.codexConnected"));
|
||||
setMsgType("success");
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
return;
|
||||
}
|
||||
if (!cancelled) setTimeout(tick, intervalMs);
|
||||
@@ -575,7 +576,7 @@ function CodexProviderForm({
|
||||
}
|
||||
setMsg(t("settings.codexDisconnected"));
|
||||
setMsgType("success");
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
} catch (err) {
|
||||
setMsg(err instanceof Error ? err.message : t("settings.savingError"));
|
||||
setMsgType("error");
|
||||
@@ -793,8 +794,8 @@ function OpenAIProviderForm({
|
||||
setOk(true);
|
||||
setMsg(t("settings.ai.saved"));
|
||||
setApiKey("");
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "ai-provider"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.userAiProvider() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
},
|
||||
onError: (e) => {
|
||||
setOk(false);
|
||||
@@ -979,8 +980,8 @@ function AnthropicProviderForm({
|
||||
setOk(true);
|
||||
setMsg(t("settings.ai.saved"));
|
||||
setApiKey("");
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "ai-provider"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.userAiProvider() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
},
|
||||
onError: (e) => {
|
||||
setOk(false);
|
||||
@@ -1135,8 +1136,8 @@ function LocalProviderForm({
|
||||
setOk(true);
|
||||
setMsg(t("settings.ai.saved"));
|
||||
setApiKey("");
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "ai-provider"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.userAiProvider() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
},
|
||||
onError: (e) => {
|
||||
setOk(false);
|
||||
@@ -1323,7 +1324,7 @@ function FallbackChainCard({
|
||||
onSuccess: () => {
|
||||
setOk(true);
|
||||
setMsg(t("settings.ai.providerChain.saved"));
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
},
|
||||
onError: (e) => {
|
||||
setOk(false);
|
||||
|
||||
@@ -21,6 +21,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { formatDate, formatDateTime } from "@/lib/format";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface ApiTokenInfo {
|
||||
id: string;
|
||||
@@ -166,7 +167,7 @@ function ApiTokensCard() {
|
||||
const [showRevokedTokens, setShowRevokedTokens] = useState(false);
|
||||
|
||||
const { data: tokens } = useQuery({
|
||||
queryKey: ["tokens"],
|
||||
queryKey: queryKeys.tokens(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/tokens");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -191,7 +192,7 @@ function ApiTokensCard() {
|
||||
if (res.ok) {
|
||||
setNewToken(json.data.token);
|
||||
setNewName("");
|
||||
queryClient.invalidateQueries({ queryKey: ["tokens"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tokens() });
|
||||
} else {
|
||||
setTokenMsg(json.error || t("common.error"));
|
||||
}
|
||||
@@ -205,7 +206,7 @@ function ApiTokensCard() {
|
||||
async function handleRevoke(tokenId: string) {
|
||||
const res = await fetch(`/api/tokens/${tokenId}`, { method: "DELETE" });
|
||||
if (res.ok) {
|
||||
queryClient.invalidateQueries({ queryKey: ["tokens"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.tokens() });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,11 @@ import { IntegrationStatusPill } from "@/components/settings/integration-status-
|
||||
import type { IntegrationPillState } from "@/components/settings/integration-status-pill";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { invalidateKeys, measurementDependentKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
invalidateKeys,
|
||||
measurementDependentKeys,
|
||||
queryKeys,
|
||||
} from "@/lib/query-keys";
|
||||
|
||||
interface MoodLogStatus {
|
||||
configured: boolean;
|
||||
@@ -91,7 +95,7 @@ interface IntegrationStatusEnvelope {
|
||||
*/
|
||||
function useIntegrationStatuses(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: ["integrations", "status"],
|
||||
queryKey: queryKeys.integrationsStatus(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/integrations/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -155,7 +159,7 @@ export function IntegrationsSection() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
const { data: globalServices } = useQuery({
|
||||
queryKey: ["settings", "global-services"],
|
||||
queryKey: queryKeys.settingsGlobalServices(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/global-services");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -219,7 +223,7 @@ function WithingsCard({
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: status } = useQuery({
|
||||
queryKey: ["withings", "status"],
|
||||
queryKey: queryKeys.withingsStatus(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/withings/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -247,8 +251,8 @@ function WithingsCard({
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["withings"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.withings() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.integrationsStatus() });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -273,7 +277,7 @@ function WithingsCard({
|
||||
);
|
||||
setSyncMsgType("success");
|
||||
void invalidateKeys(queryClient, measurementDependentKeys);
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.integrationsStatus() });
|
||||
} else {
|
||||
setSyncMsg(json.error || t("settings.withingsSyncFailed"));
|
||||
setSyncMsgType("error");
|
||||
@@ -307,7 +311,7 @@ function WithingsCard({
|
||||
setCredsMsgType("success");
|
||||
setClientId("");
|
||||
setClientSecret("");
|
||||
queryClient.invalidateQueries({ queryKey: ["withings"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.withings() });
|
||||
} else {
|
||||
try {
|
||||
const json = await res.json();
|
||||
@@ -601,7 +605,7 @@ function MoodLogCard({
|
||||
const [msgType, setMsgType] = useState<"success" | "error" | null>(null);
|
||||
|
||||
const { data: status, refetch: refetchStatus } = useQuery({
|
||||
queryKey: ["moodlog-status"],
|
||||
queryKey: queryKeys.moodlogStatus(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/integrations/moodlog/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -624,7 +628,7 @@ function MoodLogCard({
|
||||
setUrl("");
|
||||
setApiKey("");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.integrationsStatus() });
|
||||
} else {
|
||||
const json = await res.json();
|
||||
setMsg(json.error || t("settings.savingError"));
|
||||
@@ -652,7 +656,7 @@ function MoodLogCard({
|
||||
);
|
||||
setMsgType("success");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.integrationsStatus() });
|
||||
} else {
|
||||
setMsg(t("settings.moodLogSyncFailed"));
|
||||
setMsgType("error");
|
||||
@@ -670,7 +674,7 @@ function MoodLogCard({
|
||||
setMsg(t("settings.moodLogDisconnected"));
|
||||
setMsgType("success");
|
||||
await refetchStatus();
|
||||
queryClient.invalidateQueries({ queryKey: ["integrations", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.integrationsStatus() });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { SmilePlus } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface ProfileShape {
|
||||
moodReminderEnabled: boolean;
|
||||
@@ -25,7 +26,7 @@ export function MoodReminderCard({
|
||||
const [msgType, setMsgType] = useState<"success" | "error" | null>(null);
|
||||
|
||||
const { data: profile } = useQuery({
|
||||
queryKey: ["user", "profile"],
|
||||
queryKey: queryKeys.userProfile(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/user/profile");
|
||||
if (!res.ok) throw new Error("Failed to load profile");
|
||||
@@ -55,7 +56,7 @@ export function MoodReminderCard({
|
||||
: t("notifications.moodReminder.disabledToast"),
|
||||
);
|
||||
setMsgType("success");
|
||||
await queryClient.invalidateQueries({ queryKey: ["user", "profile"] });
|
||||
await queryClient.invalidateQueries({ queryKey: queryKeys.userProfile() });
|
||||
setOptimistic(null);
|
||||
} else {
|
||||
setOptimistic(null);
|
||||
|
||||
@@ -33,6 +33,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
type ChannelType = "TELEGRAM" | "NTFY" | "WEB_PUSH";
|
||||
|
||||
@@ -69,7 +70,7 @@ export function NotificationStatusCard() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["notifications", "status"],
|
||||
queryKey: queryKeys.notificationsStatus(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/notifications/status");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -90,7 +91,7 @@ export function NotificationStatusCard() {
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.notificationsStatus() });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -103,7 +104,7 @@ export function NotificationStatusCard() {
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["notifications", "status"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.notificationsStatus() });
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ChevronRight } from "lucide-react";
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { MoodReminderCard } from "@/components/settings/mood-reminder-card";
|
||||
import { NotificationStatusCard } from "@/components/settings/notification-status-card";
|
||||
import { NtfyCard } from "@/components/settings/ntfy-card";
|
||||
@@ -25,7 +26,7 @@ export function NotificationsSection() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
const { data: globalServices } = useQuery({
|
||||
queryKey: ["settings", "global-services"],
|
||||
queryKey: queryKeys.settingsGlobalServices(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/global-services");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { PasswordInput } from "@/components/ui/password-input";
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface NtfySettings {
|
||||
enabled: boolean;
|
||||
@@ -31,7 +32,7 @@ export function NtfyCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
);
|
||||
|
||||
const { data: settings } = useQuery({
|
||||
queryKey: ["settings", "ntfy"],
|
||||
queryKey: queryKeys.settingsNtfy(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/ntfy");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -70,7 +71,7 @@ export function NtfyCard({ isAuthenticated }: { isAuthenticated: boolean }) {
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["settings", "ntfy"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.settingsNtfy() });
|
||||
setSaveMsg(t("settings.saved"));
|
||||
setSaveMsgType("success");
|
||||
setAuthToken("");
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { PasswordInput } from "@/components/ui/password-input";
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
interface TelegramSettings {
|
||||
enabled: boolean;
|
||||
@@ -34,7 +35,7 @@ export function TelegramCard({
|
||||
const [msgType, setMsgType] = useState<"success" | "error" | null>(null);
|
||||
|
||||
const { data: settings } = useQuery({
|
||||
queryKey: ["telegram", "settings"],
|
||||
queryKey: queryKeys.telegramSettings(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/settings/telegram");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
@@ -78,7 +79,7 @@ export function TelegramCard({
|
||||
setMsg(t("settings.telegramSaved"));
|
||||
setMsgType("success");
|
||||
setBotToken("");
|
||||
queryClient.invalidateQueries({ queryKey: ["telegram"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.telegram() });
|
||||
} else {
|
||||
const json = await res.json();
|
||||
setMsg(json.error || t("settings.savingError"));
|
||||
|
||||
@@ -62,7 +62,7 @@ export function ThresholdsEditorSection({ id }: { id: string }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["user", "thresholds"],
|
||||
queryKey: queryKeys.userThresholds(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/user/thresholds");
|
||||
if (!res.ok) throw new Error("failed");
|
||||
@@ -86,10 +86,10 @@ export function ThresholdsEditorSection({ id }: { id: string }) {
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "thresholds"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.userThresholds() });
|
||||
// Every chart/band depends on these thresholds — invalidate everything.
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
toast.success(t("thresholds.saveSuccess"));
|
||||
},
|
||||
onError: (err) =>
|
||||
@@ -107,9 +107,9 @@ export function ThresholdsEditorSection({ id }: { id: string }) {
|
||||
if (!res.ok) throw new Error("reset failed");
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "thresholds"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.userThresholds() });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
|
||||
queryClient.invalidateQueries({ queryKey: ["insights"] });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.insightsRoot() });
|
||||
toast.success(t("thresholds.resetSuccess"));
|
||||
},
|
||||
onError: () => toast.error(t("thresholds.saveError")),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
DEFAULT_COACH_PREFS,
|
||||
type CoachPrefs,
|
||||
@@ -24,7 +25,7 @@ import {
|
||||
*/
|
||||
export function useCoachPrefs(opts?: { enabled?: boolean }) {
|
||||
return useQuery<CoachPrefs>({
|
||||
queryKey: ["coach-prefs"],
|
||||
queryKey: queryKeys.coachPrefs(),
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/auth/me/coach-prefs");
|
||||
if (!res.ok) return DEFAULT_COACH_PREFS;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { useContext } from "react";
|
||||
import { QueryClientContext, useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
/**
|
||||
* v1.4.31 — Client-side accessor for the operator's assistant
|
||||
* feature-flag matrix. Mirrors `GET /api/feature-flags`'s response
|
||||
@@ -86,7 +88,7 @@ export function useFeatureFlags(): AssistantFlagSet {
|
||||
|
||||
function useFeatureFlagsQuery(): AssistantFlagSet {
|
||||
const query = useQuery({
|
||||
queryKey: ["feature-flags"],
|
||||
queryKey: queryKeys.featureFlags(),
|
||||
queryFn: fetchFeatureFlags,
|
||||
staleTime: 60_000,
|
||||
gcTime: 300_000,
|
||||
|
||||
@@ -13,7 +13,8 @@ import type { SubPageAnalyticsData } from "@/types/analytics";
|
||||
* `schlaf`) each used to declare:
|
||||
*
|
||||
* - a private `AnalyticsData` interface,
|
||||
* - a `useQuery({ queryKey: ["analytics"], staleTime: 60_000 })` block,
|
||||
* - a `useQuery` block keyed on `["analytics"]` with a 60-second
|
||||
* `staleTime`,
|
||||
* - an `if (isAuthenticated && analytics && !hasMetricData(...)) { … }`
|
||||
* short-circuit that rendered a sub-page-specific empty state.
|
||||
*
|
||||
|
||||
@@ -92,10 +92,12 @@ export function useWorkouts(opts: UseWorkoutsOptions = {}): UseWorkoutsResult {
|
||||
const { isAuthenticated } = useAuth();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: [
|
||||
...queryKeys.workoutsRecent(),
|
||||
{ limit: opts.limit, offset: opts.offset, since: opts.since, sportType: opts.sportType },
|
||||
] as const,
|
||||
queryKey: queryKeys.workoutsRecentList({
|
||||
limit: opts.limit,
|
||||
offset: opts.offset,
|
||||
since: opts.since,
|
||||
sportType: opts.sportType,
|
||||
}),
|
||||
queryFn: () => fetchWorkouts(opts),
|
||||
enabled: isAuthenticated,
|
||||
staleTime: 60 * 1000,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { z } from "zod/v4";
|
||||
import {
|
||||
returnAllZodIssues,
|
||||
sanitiseZodIssues,
|
||||
} from "../api-response";
|
||||
|
||||
// v1.4.42 W2 — every Zod-validated route historically returned
|
||||
// `parsed.error.issues[0].message`, dropping every issue past the first.
|
||||
// `returnAllZodIssues` is the additive replacement: clients that only
|
||||
// read `error` keep working, new callers branch on `details.issues`.
|
||||
|
||||
const schema = z.object({
|
||||
version: z.literal(1),
|
||||
widgets: z.array(z.object({ id: z.string() })).min(1),
|
||||
comparisonBaseline: z.enum(["none", "lastMonth", "lastYear"]).optional(),
|
||||
});
|
||||
|
||||
describe("returnAllZodIssues", () => {
|
||||
it("returns 422 by default with a sanitised issue list", async () => {
|
||||
const parsed = schema.safeParse({});
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) return;
|
||||
|
||||
const response = returnAllZodIssues(parsed.error);
|
||||
expect(response.status).toBe(422);
|
||||
|
||||
const body = (await response.json()) as {
|
||||
data: null;
|
||||
error: string;
|
||||
details: { issues: Array<{ path: string; code: string; message: string }> };
|
||||
};
|
||||
expect(body.data).toBeNull();
|
||||
expect(body.error).toBe("Validation failed");
|
||||
expect(body.details.issues.length).toBeGreaterThanOrEqual(2);
|
||||
expect(body.details.issues[0]).toMatchObject({
|
||||
code: expect.any(String),
|
||||
message: expect.any(String),
|
||||
path: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces TWO simultaneous validation errors", async () => {
|
||||
const parsed = schema.safeParse({ version: 2, widgets: [] });
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) return;
|
||||
|
||||
const response = returnAllZodIssues(parsed.error);
|
||||
const body = (await response.json()) as {
|
||||
details: { issues: Array<{ path: string; code: string }> };
|
||||
};
|
||||
expect(body.details.issues.length).toBe(2);
|
||||
const paths = body.details.issues.map((i) => i.path).sort();
|
||||
expect(paths).toEqual(["version", "widgets"]);
|
||||
});
|
||||
|
||||
it("surfaces THREE simultaneous validation errors", async () => {
|
||||
const parsed = schema.safeParse({
|
||||
version: 2,
|
||||
widgets: [],
|
||||
comparisonBaseline: "yesterday",
|
||||
});
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) return;
|
||||
|
||||
const response = returnAllZodIssues(parsed.error);
|
||||
const body = (await response.json()) as {
|
||||
details: { issues: Array<{ path: string; code: string }> };
|
||||
};
|
||||
expect(body.details.issues.length).toBe(3);
|
||||
const paths = body.details.issues.map((i) => i.path).sort();
|
||||
expect(paths).toEqual(["comparisonBaseline", "version", "widgets"]);
|
||||
});
|
||||
|
||||
it("flattens nested paths with dots", async () => {
|
||||
const nested = z.object({ outer: z.object({ inner: z.string() }) });
|
||||
const parsed = nested.safeParse({ outer: { inner: 5 } });
|
||||
if (parsed.success) throw new Error("expected failure");
|
||||
|
||||
const sanitised = sanitiseZodIssues(parsed.error.issues);
|
||||
expect(sanitised[0].path).toBe("outer.inner");
|
||||
});
|
||||
|
||||
it("does NOT echo issue.params (privacy: may contain user input)", async () => {
|
||||
const parsed = schema.safeParse({
|
||||
version: 99,
|
||||
widgets: [{ id: "x" }],
|
||||
});
|
||||
if (parsed.success) throw new Error("expected failure");
|
||||
|
||||
const response = returnAllZodIssues(parsed.error);
|
||||
const body = (await response.json()) as {
|
||||
details: { issues: Array<Record<string, unknown>> };
|
||||
};
|
||||
for (const issue of body.details.issues) {
|
||||
expect(issue).not.toHaveProperty("params");
|
||||
// Only path / code / message survive the sanitiser.
|
||||
expect(Object.keys(issue).sort()).toEqual(["code", "message", "path"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("respects a custom status code", async () => {
|
||||
const parsed = schema.safeParse({});
|
||||
if (parsed.success) throw new Error("expected failure");
|
||||
const response = returnAllZodIssues(parsed.error, 400);
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
|
||||
it("forwards meta.errorCode and headers like apiError", async () => {
|
||||
const parsed = schema.safeParse({});
|
||||
if (parsed.success) throw new Error("expected failure");
|
||||
|
||||
const response = returnAllZodIssues(parsed.error, 422, {
|
||||
errorCode: "dashboard.widgets.invalid",
|
||||
headers: { "X-Test": "yes" },
|
||||
});
|
||||
expect(response.headers.get("X-Test")).toBe("yes");
|
||||
const body = (await response.json()) as {
|
||||
meta?: { errorCode?: string; headers?: unknown };
|
||||
};
|
||||
expect(body.meta?.errorCode).toBe("dashboard.widgets.invalid");
|
||||
// Headers are consumed by the NextResponse constructor and stripped
|
||||
// from the JSON envelope, matching apiError's contract.
|
||||
expect(body.meta?.headers).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -100,6 +100,81 @@ describe("queryKeys factory", () => {
|
||||
"dashboard-medication-compliance",
|
||||
);
|
||||
});
|
||||
|
||||
// v1.4.42 W3-QUERYKEY-LONGTAIL — pin the shapes of the new factory
|
||||
// entries so a future rename can't drift the cache layout silently.
|
||||
it("exposes the per-medication sub-keys under the medications prefix", () => {
|
||||
expect(queryKeys.medicationCompliance("med1")).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"compliance",
|
||||
]);
|
||||
expect(queryKeys.medicationTitration("med1")).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"titration",
|
||||
]);
|
||||
expect(queryKeys.medicationCadence("med1")).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"cadence",
|
||||
]);
|
||||
expect(queryKeys.medicationGlp1Details("med1")).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"glp1-details",
|
||||
]);
|
||||
expect(queryKeys.medicationIntakeDrugLevelChart("med1")).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"intake",
|
||||
"drug-level-chart",
|
||||
]);
|
||||
const listKey = queryKeys.medicationIntakeList("med1", {
|
||||
sortBy: "takenAt",
|
||||
sortDir: "desc",
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
status: "completed",
|
||||
});
|
||||
expect(listKey).toEqual([
|
||||
"medications",
|
||||
"med1",
|
||||
"intake",
|
||||
"list",
|
||||
"takenAt",
|
||||
"desc",
|
||||
25,
|
||||
0,
|
||||
"completed",
|
||||
]);
|
||||
});
|
||||
|
||||
it("exposes withingsStatus under the withings prefix", () => {
|
||||
expect(queryKeys.withingsStatus()).toEqual(["withings", "status"]);
|
||||
});
|
||||
|
||||
it("packs adminAuditLogFiltered params into a stable filtered shape", () => {
|
||||
const key = queryKeys.adminAuditLogFiltered({
|
||||
filter: "all",
|
||||
page: 1,
|
||||
perPage: 50,
|
||||
actor: "",
|
||||
actionFilter: "",
|
||||
target: "",
|
||||
range: "7d",
|
||||
});
|
||||
expect(key[0]).toBe("admin");
|
||||
expect(key[1]).toBe("audit-log");
|
||||
expect(key[2]).toBe("filtered");
|
||||
expect(key.length).toBe(10);
|
||||
});
|
||||
|
||||
it("packs workoutsRecentList opts under the workouts-recent prefix", () => {
|
||||
const key = queryKeys.workoutsRecentList({ limit: 3 });
|
||||
expect(key[0]).toBe("workouts");
|
||||
expect(key[1]).toBe("recent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dependent-key bundles", () => {
|
||||
@@ -195,11 +270,19 @@ describe("queryKey factory enforcement", () => {
|
||||
join(repoRoot, "src", "app", "page.tsx"),
|
||||
join(repoRoot, "src", "hooks", "use-auth.ts"),
|
||||
// v1.4.41 W-FRONTEND-FACTORY — auth, notifications, and the
|
||||
// about-section migrated to the factory. Future waves extend
|
||||
// this list as they migrate their own surface.
|
||||
// about-section migrated to the factory.
|
||||
join(repoRoot, "src", "app", "auth"),
|
||||
join(repoRoot, "src", "app", "notifications"),
|
||||
join(repoRoot, "src", "components", "settings", "about-section.tsx"),
|
||||
// v1.4.42 W3-QUERYKEY-LONGTAIL — settings / medications /
|
||||
// admin / hooks now route every read through the factory.
|
||||
join(repoRoot, "src", "components", "settings"),
|
||||
join(repoRoot, "src", "components", "medications"),
|
||||
join(repoRoot, "src", "components", "admin"),
|
||||
join(repoRoot, "src", "hooks"),
|
||||
join(repoRoot, "src", "app", "medications", "page.tsx"),
|
||||
join(repoRoot, "src", "app", "medications", "[id]", "history", "page.tsx"),
|
||||
join(repoRoot, "src", "app", "targets", "page.tsx"),
|
||||
];
|
||||
|
||||
function collect(): string[] {
|
||||
|
||||
@@ -97,8 +97,6 @@ export const coachChatRequestSchema = z.object({
|
||||
scope: coachScopeSchema.optional(),
|
||||
});
|
||||
|
||||
export type CoachChatRequest = z.infer<typeof coachChatRequestSchema>;
|
||||
|
||||
/**
|
||||
* SSE event shapes emitted by the streaming endpoint.
|
||||
*
|
||||
|
||||
@@ -67,8 +67,6 @@ export const metricSourceSchema = z.object({
|
||||
n: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
|
||||
export type MetricSource = z.infer<typeof metricSourceSchema>;
|
||||
|
||||
/**
|
||||
* Set of valid `referenceId` values, derived from
|
||||
* `MEDICAL_REFERENCES` so the two cannot drift. Validated lazily
|
||||
@@ -118,10 +116,6 @@ export const aiRecommendationRationaleSchema = z.object({
|
||||
deviation: z.string().min(1, "rationale.deviation required"),
|
||||
});
|
||||
|
||||
export type AIRecommendationRationale = z.infer<
|
||||
typeof aiRecommendationRationaleSchema
|
||||
>;
|
||||
|
||||
export const aiRecommendationSchema = z
|
||||
.object({
|
||||
/**
|
||||
@@ -191,8 +185,6 @@ export const aiRecommendationSchema = z
|
||||
}
|
||||
});
|
||||
|
||||
export type AIRecommendation = z.infer<typeof aiRecommendationSchema>;
|
||||
|
||||
export const aiCitationSchema = z.object({
|
||||
/** Snapshot key being cited. */
|
||||
type: z.string().min(1, "citation.type required"),
|
||||
@@ -202,8 +194,6 @@ export const aiCitationSchema = z.object({
|
||||
summary: z.string().min(1, "citation.summary required"),
|
||||
});
|
||||
|
||||
export type AICitation = z.infer<typeof aiCitationSchema>;
|
||||
|
||||
export const aiWarningSchema = z.object({
|
||||
/** Topic — "blood_pressure", "pulse", etc. */
|
||||
topic: z.string().min(1, "warning.topic required"),
|
||||
@@ -213,8 +203,6 @@ export const aiWarningSchema = z.object({
|
||||
severity: recommendationSeveritySchema.optional(),
|
||||
});
|
||||
|
||||
export type AIWarning = z.infer<typeof aiWarningSchema>;
|
||||
|
||||
/**
|
||||
* v1.4.20 phase B1 — Daily Briefing block.
|
||||
*
|
||||
@@ -419,8 +407,6 @@ export const storyboardAnnotationSchema = z.object({
|
||||
.max(400, "storyboardAnnotation.detail must be <= 400 chars"),
|
||||
});
|
||||
|
||||
export type StoryboardAnnotation = z.infer<typeof storyboardAnnotationSchema>;
|
||||
|
||||
export const storyboardAnnotationsSchema = z
|
||||
.array(storyboardAnnotationSchema)
|
||||
.max(20, "storyboardAnnotations can hold at most 20 entries");
|
||||
|
||||
@@ -99,7 +99,6 @@ export const insightResultSchema = z.object({
|
||||
});
|
||||
|
||||
export type InsightResult = z.infer<typeof insightResultSchema>;
|
||||
export type InsightFinding = z.infer<typeof insightFindingSchema>;
|
||||
|
||||
// ─── Provider Types ────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -60,17 +60,7 @@ export interface BpReading {
|
||||
const SYS_HYPOTENSION_FLOOR = 90;
|
||||
const DIA_HYPOTENSION_FLOOR = 50;
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
// en-CA gives us the YYYY-MM-DD shape directly.
|
||||
return BERLIN_DAY_FORMATTER.format(date);
|
||||
}
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
/**
|
||||
* Pair a systolic reading with its closest diastolic by absolute time
|
||||
|
||||
@@ -42,13 +42,6 @@ export type ThresholdMetric =
|
||||
| "BONE_MASS"
|
||||
| "OXYGEN_SATURATION";
|
||||
|
||||
export interface ThresholdOverride {
|
||||
min: number;
|
||||
max: number;
|
||||
/** Set true when the value was entered by the user (not the computed default). */
|
||||
isOverride?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape persisted in User.thresholdsJson. Any metric missing = use default.
|
||||
*/
|
||||
|
||||
+89
-17
@@ -1,10 +1,97 @@
|
||||
import { isIP } from "node:net";
|
||||
import { NextResponse } from "next/server";
|
||||
import type { ZodError, ZodIssue } from "zod/v4";
|
||||
|
||||
export function apiSuccess<T>(data: T, status = 200) {
|
||||
return NextResponse.json({ data, error: null }, { status });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitised view of a single Zod issue. We surface `path`, `code` and
|
||||
* `message` only — `issue.params` may echo the offending user input
|
||||
* (e.g. a too-long string, a regex source) and we do not want that
|
||||
* round-tripped to mobile callers or persisted into the audit ledger.
|
||||
*/
|
||||
export interface SanitisedZodIssue {
|
||||
path: string;
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.42 W2 — multi-issue Zod error envelope.
|
||||
*
|
||||
* Historic pattern was `apiError(parsed.error.issues[0].message, 422)`
|
||||
* which dropped every issue past the first. The iOS contract debug
|
||||
* loop hit this hard: a single PUT with three wrong fields produced
|
||||
* one error, the client fixed it, re-sent, hit the next error, and
|
||||
* so on — three round-trips for one stack of mistakes.
|
||||
*
|
||||
* Shape kept additive with `apiError` so existing clients that only
|
||||
* read `error` keep working; new callers branch on `details.issues`.
|
||||
*
|
||||
* Privacy: only `path`, `code` and `message` are echoed. `issue.params`
|
||||
* (which can carry the raw rejected value for some Zod issue codes)
|
||||
* stays server-side.
|
||||
*/
|
||||
export function sanitiseZodIssues(
|
||||
issues: readonly ZodIssue[],
|
||||
): SanitisedZodIssue[] {
|
||||
return issues.map((issue) => ({
|
||||
path: issue.path.join("."),
|
||||
code: issue.code,
|
||||
message: issue.message,
|
||||
}));
|
||||
}
|
||||
|
||||
type ErrorMeta = {
|
||||
errorCode?: string;
|
||||
headers?: Record<string, string>;
|
||||
} & Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* Shared builder for every `{ data: null, error, ... }` JSON envelope.
|
||||
* Strips `headers` from the meta passthrough (it lands on the
|
||||
* NextResponse constructor, not in the JSON body) and omits the `meta`
|
||||
* key entirely when no non-header fields remain — so the unchanged
|
||||
* `{ data: null, error: <string> }` envelope still serialises byte-
|
||||
* identically when the caller passes no extras.
|
||||
*/
|
||||
function buildJsonErrorResponse(
|
||||
body: Record<string, unknown>,
|
||||
status: number,
|
||||
meta: ErrorMeta | undefined,
|
||||
): NextResponse {
|
||||
const { headers, ...rest } = meta ?? {};
|
||||
const metaKeys = Object.keys(rest);
|
||||
return NextResponse.json(
|
||||
{
|
||||
...body,
|
||||
...(metaKeys.length > 0 ? { meta: rest } : {}),
|
||||
},
|
||||
{
|
||||
status,
|
||||
...(headers ? { headers } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function returnAllZodIssues(
|
||||
error: ZodError,
|
||||
status: number = 422,
|
||||
meta?: ErrorMeta,
|
||||
): NextResponse {
|
||||
return buildJsonErrorResponse(
|
||||
{
|
||||
data: null,
|
||||
error: "Validation failed",
|
||||
details: { issues: sanitiseZodIssues(error.issues) },
|
||||
},
|
||||
status,
|
||||
meta,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `meta` is additive — clients that ignore it see the unchanged
|
||||
* `{ data: null, error: <string> }` envelope. New callers can pass
|
||||
@@ -21,24 +108,9 @@ export function apiSuccess<T>(data: T, status = 200) {
|
||||
export function apiError(
|
||||
message: string,
|
||||
status = 400,
|
||||
meta?: {
|
||||
errorCode?: string;
|
||||
headers?: Record<string, string>;
|
||||
} & Record<string, unknown>,
|
||||
meta?: ErrorMeta,
|
||||
) {
|
||||
const { headers, ...rest } = meta ?? {};
|
||||
const metaKeys = Object.keys(rest);
|
||||
return NextResponse.json(
|
||||
{
|
||||
data: null,
|
||||
error: message,
|
||||
...(metaKeys.length > 0 ? { meta: rest } : {}),
|
||||
},
|
||||
{
|
||||
status,
|
||||
...(headers ? { headers } : {}),
|
||||
},
|
||||
);
|
||||
return buildJsonErrorResponse({ data: null, error: message }, status, meta);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -21,8 +21,6 @@ const extendedProfileSchema = profileSchema.extend({
|
||||
moodReminderEnabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type ApplyProfileInput = z.infer<typeof extendedProfileSchema>;
|
||||
|
||||
export interface ApplyProfileResult {
|
||||
ok: true;
|
||||
user: {
|
||||
|
||||
@@ -185,13 +185,3 @@ export async function destroyAllSessions(userId: string): Promise<void> {
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Require an authenticated admin user.
|
||||
* Returns user if admin, null otherwise.
|
||||
*/
|
||||
export async function requireAdmin(): Promise<User | null> {
|
||||
const sessionData = await getSession();
|
||||
if (!sessionData) return null;
|
||||
if (sessionData.user.role !== "ADMIN") return null;
|
||||
return sessionData.user;
|
||||
}
|
||||
@@ -15,21 +15,3 @@
|
||||
|
||||
/** Full-size trend-card body height (non-mini chart cards on the dashboard). */
|
||||
export const CHART_HEIGHT_PX = 240;
|
||||
|
||||
/**
|
||||
* Range-preset options for charts that expose a 7d / 30d / 90d / All
|
||||
* range selector. Each entry carries the i18n keys for the visible
|
||||
* label + sr-only title, plus a `points` count used by the underlying
|
||||
* `HealthChart` query window. `points: 0` denotes "all data".
|
||||
*
|
||||
* Re-used by the GLP-1 dashboard tile so its range strip stays in
|
||||
* lockstep with the rest of the trend strip.
|
||||
*/
|
||||
export const CHART_RANGE_PRESETS = [
|
||||
{ labelKey: "charts.points7Label", titleKey: "charts.points7Title", points: 7 },
|
||||
{ labelKey: "charts.points30Label", titleKey: "charts.points30Title", points: 30 },
|
||||
{ labelKey: "charts.points90Label", titleKey: "charts.points90Title", points: 90 },
|
||||
{ labelKey: "charts.pointsAllLabel", titleKey: "charts.pointsAllTitle", points: 0 },
|
||||
] as const;
|
||||
|
||||
export type ChartRangePreset = (typeof CHART_RANGE_PRESETS)[number];
|
||||
Binary file not shown.
@@ -19,7 +19,7 @@ export const localeLabels: Record<Locale, string> = {
|
||||
* know to expect rough edges and where to contribute fixes. Promoting
|
||||
* a locale here turns the banner off.
|
||||
*/
|
||||
export const MAINTAINED_LOCALES: ReadonlySet<Locale> = new Set(["de", "en"]);
|
||||
const MAINTAINED_LOCALES: ReadonlySet<Locale> = new Set(["de", "en"]);
|
||||
|
||||
export function isMaintainedLocale(locale: Locale): boolean {
|
||||
return MAINTAINED_LOCALES.has(locale);
|
||||
|
||||
@@ -30,29 +30,10 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -15,29 +15,10 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -16,12 +16,7 @@
|
||||
* does not produce 360 zero-rows of noise.
|
||||
*/
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinYmd as toBerlinYmdStrings } from "@/lib/tz/resolver";
|
||||
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -65,14 +60,12 @@ interface BerlinYmd {
|
||||
}
|
||||
|
||||
function toBerlinYmd(date: Date): BerlinYmd {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = Number(parts.find((p) => p.type === "year")?.value);
|
||||
const month = Number(parts.find((p) => p.type === "month")?.value);
|
||||
const day = Number(parts.find((p) => p.type === "day")?.value);
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin Y-M-D");
|
||||
}
|
||||
return { year, month, day };
|
||||
const parts = toBerlinYmdStrings(date);
|
||||
return {
|
||||
year: Number(parts.year),
|
||||
month: Number(parts.month),
|
||||
day: Number(parts.day),
|
||||
};
|
||||
}
|
||||
|
||||
/** UTC midnight of the Berlin calendar day containing `date`. */
|
||||
|
||||
@@ -205,10 +205,3 @@ export function tokenToMetric(token: ChartToken): string {
|
||||
return token.slice("metric:".length);
|
||||
}
|
||||
|
||||
/** Token kinds the renderer needs to distinguish. MeasurementType tokens
|
||||
* feed `<HealthChart>`; `metric:MOOD` mounts the dedicated, self-fetching
|
||||
* `<MoodChart>` instead. */
|
||||
export function tokenKind(token: ChartToken): "measurement" | "mood" {
|
||||
if (token === "metric:MOOD") return "mood";
|
||||
return "measurement";
|
||||
}
|
||||
@@ -20,13 +20,7 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
@@ -34,19 +28,6 @@ type SupportedLocale = "de" | "en";
|
||||
// in the AI general-status fetch (V3 audit: enum drift cousins).
|
||||
const MEASUREMENT_TYPES = measurementTypeEnum.options;
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -20,18 +20,12 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
// 360 daily days + 24 monthly windows ≈ 1080 days of intake history.
|
||||
const COMPLIANCE_HISTORY_DAYS = 360 + 24 * 30;
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
interface MedicationSummaryItem {
|
||||
@@ -39,19 +33,6 @@ interface MedicationSummaryItem {
|
||||
text: string;
|
||||
}
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -22,29 +22,10 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -21,29 +21,10 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
// `gewicht`, `bmi`, `schlaf`, `stimmung`, `medikamente`, `workouts`)
|
||||
// stay flat — they predate v1.4.32 and the maintainer's audit kept
|
||||
// them as direct entries.
|
||||
export const SUB_PAGE_METRIC = {
|
||||
const SUB_PAGE_METRIC = {
|
||||
// ── vitals ──
|
||||
blutdruck: ["BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA", "PULSE"],
|
||||
puls: ["PULSE"],
|
||||
|
||||
@@ -25,29 +25,10 @@ import {
|
||||
} from "@/lib/insights/with-timeout";
|
||||
import { persistTimeoutStubAndReturn } from "@/lib/insights/persist-timeout-stub";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
import { toBerlinDayKey } from "@/lib/tz/resolver";
|
||||
|
||||
type SupportedLocale = "de" | "en";
|
||||
|
||||
function toBerlinDayKey(date: Date): string {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function round(value: number, digits = 1): number {
|
||||
const factor = 10 ** digits;
|
||||
return Math.round(value * factor) / factor;
|
||||
|
||||
@@ -269,6 +269,68 @@ describe("recordSyncFailure — reauth_required", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordSyncFailure — persistent (v1.4.42 W6)", () => {
|
||||
it("marks state=error_transient (next sync still runs) and audits with kind=persistent", async () => {
|
||||
// Contract-mismatch failures (Withings 293 invalid params) MUST
|
||||
// surface in the audit log with kind=persistent so operations can
|
||||
// grep for upstream contract bugs, but they MUST NOT park the
|
||||
// integration — the next sync should still run because the
|
||||
// mismatch can be one-sided (e.g. Withings introducing a new
|
||||
// required field that the client release fixes).
|
||||
vi.mocked(prisma.integrationStatus.upsert).mockResolvedValueOnce({
|
||||
consecutiveFailures: 1,
|
||||
} as never);
|
||||
await recordSyncFailure({
|
||||
userId: "u1",
|
||||
integration: "withings",
|
||||
kind: "persistent",
|
||||
message: "Withings measure error: 293 - invalid params",
|
||||
errorCode: "293",
|
||||
});
|
||||
const upsertArgs = vi.mocked(prisma.integrationStatus.upsert).mock
|
||||
.calls[0][0];
|
||||
expect(upsertArgs.update).toMatchObject({ state: "error_transient" });
|
||||
expect(auditLog).toHaveBeenCalledWith(
|
||||
"integrations.sync.failed",
|
||||
expect.objectContaining({
|
||||
details: expect.objectContaining({
|
||||
kind: "persistent",
|
||||
errorCode: "293",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("at threshold, the admin alert message includes the 'persistent error' label", async () => {
|
||||
vi.mocked(prisma.integrationStatus.upsert).mockResolvedValueOnce({
|
||||
consecutiveFailures: 3,
|
||||
alertedAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValueOnce({
|
||||
email: "user@example.com",
|
||||
} as never);
|
||||
vi.mocked(prisma.user.findMany).mockResolvedValueOnce([
|
||||
{ id: "admin-1" },
|
||||
] as never);
|
||||
vi.mocked(prisma.integrationStatus.update).mockResolvedValueOnce(
|
||||
{} as never,
|
||||
);
|
||||
|
||||
await recordSyncFailure({
|
||||
userId: "u1",
|
||||
integration: "withings",
|
||||
kind: "persistent",
|
||||
message: "Withings activity error: 293",
|
||||
errorCode: "293",
|
||||
});
|
||||
|
||||
expect(dispatchNotification).toHaveBeenCalledOnce();
|
||||
const payload = vi.mocked(dispatchNotification).mock.calls[0][0];
|
||||
expect(payload.message).toContain("persistent error");
|
||||
expect(payload.message).toContain("Action: investigate the upstream contract");
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordSyncFailure — admin Telegram skipped silently when no admins", () => {
|
||||
it("logs a wide-event warning but does NOT throw when no admin users exist", async () => {
|
||||
vi.mocked(prisma.integrationStatus.upsert).mockResolvedValueOnce({
|
||||
|
||||
@@ -162,7 +162,26 @@ export async function recordSyncSuccess(
|
||||
});
|
||||
}
|
||||
|
||||
export type FailureKind = "transient" | "reauth_required";
|
||||
/**
|
||||
* Failure kinds carried into `recordSyncFailure`.
|
||||
*
|
||||
* - `transient` : retry on the next sync; user not blocked.
|
||||
* - `reauth_required` : permanent revoke / invalid_grant; park at
|
||||
* `error_reauth` until the user reconnects.
|
||||
* - `persistent` : contract mismatch (invalid params, missing
|
||||
* field, unknown action). Surfaces in the
|
||||
* integration-status card AND audit log so an
|
||||
* operator can investigate, but does NOT skip
|
||||
* future sync attempts — those may succeed once
|
||||
* the upstream side resolves.
|
||||
*
|
||||
* v1.4.42 W6 extended this union from `transient | reauth_required` to
|
||||
* the three-state taxonomy above; the state-mapping function turns
|
||||
* `persistent` into `error_transient` for now (a Withings 293 still
|
||||
* lets the next sync run), but the audit detail carries the explicit
|
||||
* kind so operations can filter.
|
||||
*/
|
||||
export type FailureKind = "transient" | "reauth_required" | "persistent";
|
||||
|
||||
export interface RecordSyncFailureInput {
|
||||
userId: string;
|
||||
@@ -193,6 +212,12 @@ export async function recordSyncFailure(
|
||||
): Promise<void> {
|
||||
const { userId, integration, kind, message, errorCode } = input;
|
||||
const now = new Date();
|
||||
// State mapping:
|
||||
// reauth_required → error_reauth (sync entry-point short-circuits)
|
||||
// transient → error_transient (next sync still runs)
|
||||
// persistent → error_transient (next sync still runs, but the
|
||||
// audit detail carries `kind: "persistent"` so
|
||||
// operations can grep for contract-bug bursts)
|
||||
const newState: IntegrationState =
|
||||
kind === "reauth_required" ? "error_reauth" : "error_transient";
|
||||
|
||||
@@ -477,6 +502,30 @@ export interface AlertInput {
|
||||
* 4096 characters but our envelope (title + summary + action line)
|
||||
* eats ~150 chars so we keep a comfortable margin.
|
||||
*/
|
||||
/**
|
||||
* Reason + action copy keyed off `FailureKind`. Adding a new failure
|
||||
* kind is a one-row table edit instead of two more arms in two
|
||||
* different ternary stacks (the style-guide forbids nested ternaries).
|
||||
*/
|
||||
const FAILURE_KIND_COPY: Record<
|
||||
FailureKind,
|
||||
{ reason: string; action: string }
|
||||
> = {
|
||||
reauth_required: {
|
||||
reason: "re-auth required",
|
||||
action: "ask the user to reconnect the integration.",
|
||||
},
|
||||
persistent: {
|
||||
reason: "persistent error",
|
||||
action:
|
||||
"investigate the upstream contract — params/scope/action likely mismatched.",
|
||||
},
|
||||
transient: {
|
||||
reason: "transient error",
|
||||
action: "investigate the upstream service.",
|
||||
},
|
||||
};
|
||||
|
||||
export function formatAdminAlertPayload(input: AlertInput): {
|
||||
title: string;
|
||||
message: string;
|
||||
@@ -485,8 +534,8 @@ export function formatAdminAlertPayload(input: AlertInput): {
|
||||
const integrationLabel =
|
||||
input.integration === "withings" ? "Withings" : "moodLog";
|
||||
const subjectLabel = input.subjectLabel ?? input.userId;
|
||||
const reasonLabel =
|
||||
input.kind === "reauth_required" ? "re-auth required" : "transient error";
|
||||
const { reason: reasonLabel, action: actionLabel } =
|
||||
FAILURE_KIND_COPY[input.kind];
|
||||
const codeLabel = input.errorCode ? ` (${input.errorCode})` : "";
|
||||
const trimmed =
|
||||
input.message.length > 280
|
||||
@@ -497,7 +546,7 @@ export function formatAdminAlertPayload(input: AlertInput): {
|
||||
const message =
|
||||
`${integrationLabel} sync has failed ${input.consecutiveFailures} times in a row for ${subjectLabel}.\n` +
|
||||
`Last error: ${reasonLabel}${codeLabel} — ${trimmed}\n` +
|
||||
`Action: ${input.kind === "reauth_required" ? "ask the user to reconnect the integration." : "investigate the upstream service."}`;
|
||||
`Action: ${actionLabel}`;
|
||||
|
||||
return {
|
||||
title,
|
||||
|
||||
@@ -216,6 +216,9 @@ export async function runOffhostBackup(
|
||||
try {
|
||||
const [measurements, medications, intakeEvents, moodEntries] =
|
||||
await Promise.all([
|
||||
// includes soft-deleted rows because this is the DR snapshot,
|
||||
// not a user-facing export — see
|
||||
// `/api/export/full-backup/route.ts` for the symmetric exclusion.
|
||||
prisma.measurement.findMany({ where: { userId: user.id } }),
|
||||
prisma.medication.findMany({
|
||||
where: { userId: user.id },
|
||||
|
||||
@@ -33,17 +33,3 @@ export async function withBackgroundEvent<T>(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire-and-forget Variante: schluckt Fehler und loggt sie nur.
|
||||
* Fuer Webhook-Sends, Achievement-Checks, etc.
|
||||
*/
|
||||
export async function withBackgroundEventSafe(
|
||||
taskName: string,
|
||||
fn: (evt: WideEventBuilder) => Promise<void>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await withBackgroundEvent(taskName, fn);
|
||||
} catch {
|
||||
// Fehler wurde bereits ins Event geschrieben und emittiert
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ export { WideEventBuilder } from "./event-builder";
|
||||
export { eventStorage, getEvent, annotate } from "./context";
|
||||
export { shouldEmit } from "./sampler";
|
||||
export { emitEvent, emitIfSampled } from "./transports";
|
||||
export { withBackgroundEvent, withBackgroundEventSafe } from "./background";
|
||||
export { withBackgroundEvent } from "./background";
|
||||
export {
|
||||
appendLogEvent,
|
||||
readLogBuffer,
|
||||
|
||||
@@ -148,7 +148,7 @@ interface MutableTypeStat {
|
||||
}
|
||||
|
||||
/** Tick frequency for the live `ImportJob.progress` write. */
|
||||
export const PROGRESS_TICK_RECORDS = 1_000;
|
||||
const PROGRESS_TICK_RECORDS = 1_000;
|
||||
const SPOT_FLUSH_BATCH = 500;
|
||||
const WORKOUT_FLUSH_BATCH = 100;
|
||||
|
||||
|
||||
@@ -73,5 +73,3 @@ export const listSideEffectsSchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(200).optional().default(50),
|
||||
});
|
||||
|
||||
export type CreateSideEffectInput = z.infer<typeof createSideEffectSchema>;
|
||||
export type ListSideEffectsInput = z.infer<typeof listSideEffectsSchema>;
|
||||
@@ -71,22 +71,6 @@ export interface NtfyChannelConfig {
|
||||
authToken?: string;
|
||||
}
|
||||
|
||||
export type WebPushChannelConfig = Record<string, never>;
|
||||
|
||||
/**
|
||||
* APNs channel config is empty by design — the per-device APNs token +
|
||||
* environment live on the `Device` model, not on the channel row. The
|
||||
* channel row exists so per-event preference toggles in
|
||||
* `NotificationPreference` apply uniformly across all four channels.
|
||||
*/
|
||||
export type ApnsChannelConfig = Record<string, never>;
|
||||
|
||||
export type ChannelConfig =
|
||||
| TelegramChannelConfig
|
||||
| NtfyChannelConfig
|
||||
| WebPushChannelConfig
|
||||
| ApnsChannelConfig;
|
||||
|
||||
// ── Notification payload ──
|
||||
|
||||
export interface NotificationPayload {
|
||||
|
||||
@@ -217,7 +217,7 @@ export async function detectPersonalRecordsForUser(
|
||||
// Warm-up gate. Cheap count first so we don't pull a 30k-row
|
||||
// scan on a brand-new account.
|
||||
const sampleCount = await prisma.measurement.count({
|
||||
where: { userId, type: metricType },
|
||||
where: { userId, type: metricType, deletedAt: null },
|
||||
});
|
||||
if (sampleCount < PR_DETECTION_WARMUP_THRESHOLD) continue;
|
||||
|
||||
@@ -400,7 +400,7 @@ async function findBestMeasurement(
|
||||
direction: PersonalRecordDirection,
|
||||
): Promise<MeasurementCandidate | null> {
|
||||
const row = await prisma.measurement.findFirst({
|
||||
where: { userId, type },
|
||||
where: { userId, type, deletedAt: null },
|
||||
orderBy:
|
||||
direction === PersonalRecordDirection.MAX
|
||||
? { value: "desc" }
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useQuery, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { DataSummary } from "@/lib/analytics/trends";
|
||||
import type { SubPageAnalyticsData } from "@/types/analytics";
|
||||
|
||||
/**
|
||||
* v1.4.33 IW2 — single TanStack-Query wrapper for `/api/analytics`.
|
||||
@@ -39,15 +38,6 @@ import type { SubPageAnalyticsData } from "@/types/analytics";
|
||||
* stubbed on the slim path per the IW1 follow-up.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Strict structural subset shared between the slim slice and the thick
|
||||
* default payload. Consumers that only read `summaries` should type
|
||||
* the hook return as `AnalyticsSlicePayload` (or import
|
||||
* `SubPageAnalyticsData` directly — same shape, kept aliased for
|
||||
* call-site clarity).
|
||||
*/
|
||||
export type AnalyticsSlicePayload = SubPageAnalyticsData;
|
||||
|
||||
/**
|
||||
* Discriminator for the server-side slice. `undefined` (the default)
|
||||
* routes onto the thick payload; `"summaries"` routes onto IW1's
|
||||
|
||||
@@ -73,6 +73,49 @@ export const queryKeys = {
|
||||
medicationDetail: (id: string) => ["medications", id] as const,
|
||||
medicationComplianceChart: (medicationId: string) =>
|
||||
["compliance-chart-inline", medicationId] as const,
|
||||
/**
|
||||
* v1.4.42 W3-QUERYKEY-LONGTAIL — per-medication compliance KPI used
|
||||
* by `medication-card` + `glp1-medication-card`. Centralising lets
|
||||
* the intake mutation invalidate every compliance read through the
|
||||
* `["medications"]` prefix instead of one bare-literal at a time.
|
||||
*/
|
||||
medicationCompliance: (medicationId: string) =>
|
||||
["medications", medicationId, "compliance"] as const,
|
||||
medicationTitration: (medicationId: string) =>
|
||||
["medications", medicationId, "titration"] as const,
|
||||
medicationCadence: (medicationId: string) =>
|
||||
["medications", medicationId, "cadence"] as const,
|
||||
medicationGlp1Details: (medicationId: string) =>
|
||||
["medications", medicationId, "glp1-details"] as const,
|
||||
medicationIntakeDrugLevelChart: (medicationId: string) =>
|
||||
["medications", medicationId, "intake", "drug-level-chart"] as const,
|
||||
/**
|
||||
* v1.4.42 — intake-history list with sort / paging / status filter.
|
||||
* The opaque params object lives at index 4 so the
|
||||
* `["medications", id, "intake", "list"]` prefix invalidates every
|
||||
* sort/page combination on an intake mutation.
|
||||
*/
|
||||
medicationIntakeList: (
|
||||
medicationId: string,
|
||||
params: {
|
||||
sortBy: string;
|
||||
sortDir: string;
|
||||
limit: number;
|
||||
offset: number;
|
||||
status: string;
|
||||
},
|
||||
) =>
|
||||
[
|
||||
"medications",
|
||||
medicationId,
|
||||
"intake",
|
||||
"list",
|
||||
params.sortBy,
|
||||
params.sortDir,
|
||||
params.limit,
|
||||
params.offset,
|
||||
params.status,
|
||||
] as const,
|
||||
/**
|
||||
* v1.4.40 W-RSC — the dashboard-level compliance chart (aggregate
|
||||
* across every scheduled medication) was a bare `["medication-
|
||||
@@ -143,11 +186,44 @@ export const queryKeys = {
|
||||
["admin", "host-metrics", window] as const,
|
||||
adminAuditActions: () => ["admin", "audit-log", "actions"] as const,
|
||||
adminAuditOverview: () => ["admin", "audit-log", "overview-preview"] as const,
|
||||
/**
|
||||
* v1.4.42 W3-QUERYKEY-LONGTAIL — paginated + filtered audit-log
|
||||
* read used by the login-overview admin section. The `filtered`
|
||||
* discriminator at index 2 keeps the no-arg `adminAuditLog(filter)`
|
||||
* cache slot byte-distinct so its consumers don't collide.
|
||||
*/
|
||||
adminAuditLogFiltered: (params: {
|
||||
filter: string;
|
||||
page: number;
|
||||
perPage: number;
|
||||
actor: string;
|
||||
actionFilter: string;
|
||||
target: string;
|
||||
range: string;
|
||||
}) =>
|
||||
[
|
||||
"admin",
|
||||
"audit-log",
|
||||
"filtered",
|
||||
params.filter,
|
||||
params.page,
|
||||
params.perPage,
|
||||
params.actor,
|
||||
params.actionFilter,
|
||||
params.target,
|
||||
params.range,
|
||||
] as const,
|
||||
|
||||
tokens: () => ["tokens"] as const,
|
||||
telegram: () => ["telegram"] as const,
|
||||
telegramSettings: () => ["telegram", "settings"] as const,
|
||||
withings: () => ["withings"] as const,
|
||||
/**
|
||||
* v1.4.42 W3-QUERYKEY-LONGTAIL — the per-card Withings status read.
|
||||
* Shares the `["withings"]` prefix with `withings()` so a disconnect
|
||||
* mutation invalidates both at once.
|
||||
*/
|
||||
withingsStatus: () => ["withings", "status"] as const,
|
||||
|
||||
// v1.4.32 — workout list + detail caches. `workouts()` is the
|
||||
// root key invalidated by the batch-ingest mutation; the recent +
|
||||
@@ -155,6 +231,18 @@ export const queryKeys = {
|
||||
// detail page share a cache slot with the list page.
|
||||
workouts: () => ["workouts"] as const,
|
||||
workoutsRecent: () => ["workouts", "recent"] as const,
|
||||
/**
|
||||
* v1.4.42 W3-QUERYKEY-LONGTAIL — the `useWorkouts` hook used to
|
||||
* spread `workoutsRecent()` and append an opts object inline. The
|
||||
* factory now owns the full shape so the hook never reaches for a
|
||||
* literal-array wrapper.
|
||||
*/
|
||||
workoutsRecentList: (opts: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
since?: string;
|
||||
sportType?: string;
|
||||
}) => ["workouts", "recent", opts] as const,
|
||||
workoutDetail: (id: string) => ["workouts", id] as const,
|
||||
|
||||
adminSettings: () => ["admin", "settings"] as const,
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
* v1.5.0 — read-side helpers that aggregate the persistent rollup
|
||||
* table into the same `DataSummary` shape the live aggregator
|
||||
* returns. The reader-side surfaces (`summaries-slice`,
|
||||
* `comprehensive-aggregator`, the analytics route) call
|
||||
* `readDataSummariesFromRollups` before falling through to live SQL;
|
||||
* on rollup miss / stale they call `recomputeUserRollups` once to
|
||||
* persist the buckets, then re-read.
|
||||
* `comprehensive-aggregator`, the analytics route) re-aggregate the
|
||||
* trailing DAY buckets directly via `readRollupBuckets` and feed the
|
||||
* resulting rows into `aggregateBuckets` below.
|
||||
*
|
||||
* The 90-day window is reconstructed from DAY buckets by:
|
||||
* - sum(count_i) → window count
|
||||
@@ -20,8 +19,6 @@
|
||||
* rollup-read path delegates to live SQL so the byte-shape parity with
|
||||
* the v1.4.34.1 / 4.5 aggregator survives.
|
||||
*/
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { readRollupBuckets } from "@/lib/rollups/measurement-rollups";
|
||||
|
||||
export interface DailyMeanRow {
|
||||
day: Date;
|
||||
@@ -31,26 +28,6 @@ export interface DailyMeanRow {
|
||||
maxValue: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the trailing DAY buckets for `(userId, type)` over `[from, to)`
|
||||
* and return them as a normalised list.
|
||||
*/
|
||||
export async function readDailyMeans(
|
||||
userId: string,
|
||||
type: MeasurementType,
|
||||
from: Date,
|
||||
to: Date,
|
||||
): Promise<DailyMeanRow[]> {
|
||||
const rows = await readRollupBuckets(userId, type, "DAY", from, to);
|
||||
return rows.map((r) => ({
|
||||
day: r.bucketStart,
|
||||
count: r.count,
|
||||
mean: r.mean,
|
||||
minValue: r.minValue,
|
||||
maxValue: r.maxValue,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine DAY buckets into the linearly-composable window stats —
|
||||
* `count`, `min`, `max`, `mean`. SD / slope / R² are intentionally
|
||||
|
||||
@@ -23,10 +23,9 @@
|
||||
*
|
||||
* Reads:
|
||||
* - `readRollupBuckets` returns the persisted rows. The reader
|
||||
* side (`analytics`, `comprehensive`, `summaries-slice`) calls
|
||||
* `isRollupFresh` first to decide whether to fall through to the
|
||||
* live aggregator + persist-on-miss. Cheap heuristic — one
|
||||
* indexed query for the newest measurement's `measuredAt`.
|
||||
* side (`analytics`, `comprehensive`, `summaries-slice`) decides
|
||||
* whether to fall through to the live aggregator + persist-on-miss
|
||||
* via its own per-tier freshness probe.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
|
||||
@@ -303,42 +302,6 @@ export async function readRollupBuckets(
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap freshness heuristic — one indexed query against
|
||||
* `measurements` for the newest row per (user, type). Returns true
|
||||
* when the persisted rollup covers every measurement currently in
|
||||
* the DB, false when there's a newer measurement than the freshest
|
||||
* rollup row (the rollup needs a recompute).
|
||||
*
|
||||
* `null` newest measurement means the user has no rows of this type,
|
||||
* in which case the rollups are trivially fresh (empty == empty).
|
||||
*/
|
||||
export async function isRollupFresh(
|
||||
userId: string,
|
||||
type: MeasurementType,
|
||||
granularity: RollupGranularity,
|
||||
newestComputedAt: Date | null,
|
||||
): Promise<boolean> {
|
||||
const newest = await prisma.measurement.findFirst({
|
||||
where: { userId, type, deletedAt: null },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { measuredAt: true, updatedAt: true },
|
||||
});
|
||||
if (!newest) {
|
||||
// No measurements at all — empty rollup set is fresh by definition.
|
||||
return true;
|
||||
}
|
||||
if (!newestComputedAt) {
|
||||
// We have measurements but no rollup rows — definitely stale.
|
||||
return false;
|
||||
}
|
||||
// Stale when the latest row was written / updated after the most
|
||||
// recent rollup `computed_at` for this `(user, type, granularity)`.
|
||||
const watermark =
|
||||
newest.updatedAt > newest.measuredAt ? newest.updatedAt : newest.measuredAt;
|
||||
return watermark <= newestComputedAt;
|
||||
}
|
||||
|
||||
// ─── internals ────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
+47
-1
@@ -48,13 +48,59 @@ export {
|
||||
DEFAULT_TIMEZONE,
|
||||
isValidTimezone,
|
||||
isNearUtc,
|
||||
listSupportedTimezones,
|
||||
detectBrowserTimezone,
|
||||
formatInUserTz,
|
||||
userDayKey,
|
||||
type FormatInUserTzShape,
|
||||
} from "./format";
|
||||
|
||||
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "Europe/Berlin",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
|
||||
/**
|
||||
* Format a Date as `YYYY-MM-DD` in `Europe/Berlin`. The seven Insight
|
||||
* status helpers (`bmi`, `blood-pressure`, `weight`, `pulse`, `mood`,
|
||||
* `medication-compliance`, `general`) all key their per-day cache on
|
||||
* this — Marc's primary tenant runs in Berlin and the cache action
|
||||
* row reads identically across helpers when the formatter lives here.
|
||||
*
|
||||
* For per-user surfaces, prefer `userDayKey(date, tz)` from `./format`.
|
||||
* This helper exists for the cache-key path where the day-bucket is
|
||||
* intentionally Berlin-anchored regardless of the requesting user's
|
||||
* stored zone.
|
||||
*/
|
||||
export function toBerlinDayKey(date: Date): string {
|
||||
const { year, month, day } = toBerlinYmd(date);
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same formatter, but returns the numeric `{year, month, day}` parts
|
||||
* instead of the reassembled string. Used by `bucket-series.ts` for
|
||||
* `Date.UTC(year, month - 1, day)` arithmetic where parsing the string
|
||||
* back would be wasted work.
|
||||
*/
|
||||
export function toBerlinYmd(date: Date): {
|
||||
year: string;
|
||||
month: string;
|
||||
day: string;
|
||||
} {
|
||||
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
|
||||
if (!year || !month || !day) {
|
||||
throw new Error("Could not derive Berlin day key");
|
||||
}
|
||||
|
||||
return { year, month, day };
|
||||
}
|
||||
|
||||
const TTL_MS = 60_000;
|
||||
|
||||
interface CacheEntry {
|
||||
|
||||
@@ -2,11 +2,14 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
MEASURE_TYPE_MAP,
|
||||
WITHINGS_OAUTH_SCOPE,
|
||||
exchangeCode,
|
||||
fetchMeasurements,
|
||||
hasActivityScope,
|
||||
parseWithingsScope,
|
||||
refreshAccessToken,
|
||||
subscribeWebhook,
|
||||
} from "../client";
|
||||
import { WithingsApiError } from "../response-classifier";
|
||||
import { WITHINGS_NOTIFY_APPLIS } from "../sync";
|
||||
|
||||
/**
|
||||
@@ -376,3 +379,142 @@ describe("fetchMeasurements — pulse-wave velocity + vascular age", () => {
|
||||
expect(out[0]).toMatchObject({ type: "VASCULAR_AGE", value: 42 });
|
||||
});
|
||||
});
|
||||
|
||||
// ── v1.4.42 W6 — off-response classifier wire-through ──
|
||||
//
|
||||
// Each client entrypoint must throw `WithingsApiError` carrying the
|
||||
// classification verdict, NOT a plain `new Error("Withings ... error:
|
||||
// <status>")`. Downstream catch-blocks read `err.classification`; the
|
||||
// regex-fallback in `classifyError` covers serialised retries but the
|
||||
// typed-throw is the contract.
|
||||
|
||||
describe("client off-response handling — refreshAccessToken", () => {
|
||||
const creds = { clientId: "id", clientSecret: "secret" };
|
||||
|
||||
it("throws WithingsApiError(classification: 'reauth_required') on Withings 101", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 101, error: "Invalid token" }),
|
||||
})),
|
||||
);
|
||||
|
||||
await expect(refreshAccessToken("rt", creds)).rejects.toMatchObject({
|
||||
name: "WithingsApiError",
|
||||
classification: "reauth_required",
|
||||
withingsStatus: 101,
|
||||
});
|
||||
});
|
||||
|
||||
it("throws WithingsApiError(classification: 'transient') on HTTP 503", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 503,
|
||||
json: async () => ({ status: 0 }),
|
||||
})),
|
||||
);
|
||||
|
||||
const err = await refreshAccessToken("rt", creds).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(WithingsApiError);
|
||||
expect((err as WithingsApiError).classification).toBe("transient");
|
||||
expect((err as WithingsApiError).reason).toBe("http_503");
|
||||
});
|
||||
});
|
||||
|
||||
describe("client off-response handling — exchangeCode", () => {
|
||||
const creds = { clientId: "id", clientSecret: "secret" };
|
||||
|
||||
it("classifies Withings 100 (Authentication failed) as reauth_required", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 100, error: "Authentication failed" }),
|
||||
})),
|
||||
);
|
||||
const err = await exchangeCode("auth-code", creds).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(WithingsApiError);
|
||||
expect((err as WithingsApiError).classification).toBe("reauth_required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("client off-response handling — fetchMeasurements", () => {
|
||||
it("throws WithingsApiError(classification: 'transient') on Withings 601 (rate-limit)", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 601 }),
|
||||
})),
|
||||
);
|
||||
const err = await fetchMeasurements("token").catch((e) => e);
|
||||
expect(err).toBeInstanceOf(WithingsApiError);
|
||||
expect((err as WithingsApiError).classification).toBe("transient");
|
||||
expect((err as WithingsApiError).withingsStatus).toBe(601);
|
||||
});
|
||||
|
||||
it("throws WithingsApiError(classification: 'persistent') on Withings 293 (invalid params)", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 293 }),
|
||||
})),
|
||||
);
|
||||
const err = await fetchMeasurements("token").catch((e) => e);
|
||||
expect(err).toBeInstanceOf(WithingsApiError);
|
||||
expect((err as WithingsApiError).classification).toBe("persistent");
|
||||
});
|
||||
|
||||
it("returns the empty list on a healthy but empty body (status 0, no measuregrps)", async () => {
|
||||
// Off-response edge case: a healthy connection that has no data
|
||||
// in the requested window is NOT a failure — it's success with
|
||||
// zero rows.
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 0, body: { measuregrps: [] } }),
|
||||
})),
|
||||
);
|
||||
const out = await fetchMeasurements("token");
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("client off-response handling — subscribeWebhook 294 idempotency", () => {
|
||||
it("does NOT throw when Withings replies status 294 (already-subscribed)", async () => {
|
||||
// 294 at the subscribe call-site is documented idempotent success;
|
||||
// every other endpoint sees it as `persistent`, but here we
|
||||
// downgrade to success so reconnect flows don't fail.
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 294 }),
|
||||
})),
|
||||
);
|
||||
await expect(
|
||||
subscribeWebhook("token", "https://example.com/webhook", 1),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws WithingsApiError(classification: 'transient') when Withings replies status 2554 (notify-subscribe busy)", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => ({
|
||||
status: 200,
|
||||
json: async () => ({ status: 2554 }),
|
||||
})),
|
||||
);
|
||||
const err = await subscribeWebhook(
|
||||
"token",
|
||||
"https://example.com/webhook",
|
||||
1,
|
||||
).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(WithingsApiError);
|
||||
expect((err as WithingsApiError).classification).toBe("transient");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* v1.4.42 W6 — Withings off-response classifier.
|
||||
*
|
||||
* The classifier turns a `(httpStatus, body)` pair into a verdict of
|
||||
* `success / transient / reauth_required / persistent`. Every other
|
||||
* Withings code path branches on the verdict; this suite pins the
|
||||
* three-way taxonomy plus the "off-spec response" edge cases the
|
||||
* legacy client treated as silent no-data.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
WithingsApiError,
|
||||
classifyError,
|
||||
classifyWithingsResponse,
|
||||
} from "../response-classifier";
|
||||
|
||||
describe("classifyWithingsResponse — success branch", () => {
|
||||
it("treats HTTP 200 + status 0 as success", () => {
|
||||
const v = classifyWithingsResponse(200, { status: 0 });
|
||||
expect(v.classification).toBe("success");
|
||||
expect(v.withingsStatus).toBe(0);
|
||||
expect(v.reason).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyWithingsResponse — transient branch", () => {
|
||||
it("HTTP 503 → transient (upstream outage)", () => {
|
||||
const v = classifyWithingsResponse(503, null);
|
||||
expect(v.classification).toBe("transient");
|
||||
expect(v.reason).toBe("http_503");
|
||||
});
|
||||
|
||||
it("HTTP 502 → transient", () => {
|
||||
expect(classifyWithingsResponse(502, null).classification).toBe(
|
||||
"transient",
|
||||
);
|
||||
});
|
||||
|
||||
it("HTTP 429 → transient (rate-limit)", () => {
|
||||
const v = classifyWithingsResponse(429, null);
|
||||
expect(v.classification).toBe("transient");
|
||||
expect(v.reason).toBe("http_429");
|
||||
});
|
||||
|
||||
it("Withings status 503 (service unavailable) → transient", () => {
|
||||
const v = classifyWithingsResponse(200, { status: 503 });
|
||||
expect(v.classification).toBe("transient");
|
||||
expect(v.withingsStatus).toBe(503);
|
||||
});
|
||||
|
||||
it("Withings status 601 (rate-limited) → transient", () => {
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 601 }).classification,
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("Withings status 2554 (notify-subscribe transient) → transient", () => {
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 2554 }).classification,
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("off-spec body without a `status` field → transient (one-off CDN page)", () => {
|
||||
const v = classifyWithingsResponse(200, {});
|
||||
expect(v.classification).toBe("transient");
|
||||
expect(v.reason).toBe("no_status_field");
|
||||
});
|
||||
|
||||
it("unknown Withings status defaults to transient (admin-alert ladder catches recurrence)", () => {
|
||||
const v = classifyWithingsResponse(200, { status: 9999 });
|
||||
expect(v.classification).toBe("transient");
|
||||
expect(v.reason).toBe("withings_9999_unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyWithingsResponse — reauth_required branch", () => {
|
||||
it.each([100, 101, 102])(
|
||||
"Withings status %i → reauth_required (permanent revoke)",
|
||||
(status) => {
|
||||
const v = classifyWithingsResponse(200, { status });
|
||||
expect(v.classification).toBe("reauth_required");
|
||||
expect(v.withingsStatus).toBe(status);
|
||||
},
|
||||
);
|
||||
|
||||
it("Withings 200 (invalid_grant boundary) → reauth_required", () => {
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 200 }).classification,
|
||||
).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("Withings 250 (mid-range invalid_grant) → reauth_required", () => {
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 250 }).classification,
|
||||
).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("Withings 299 (invalid_grant upper boundary) → reauth_required", () => {
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 299 }).classification,
|
||||
).toBe("reauth_required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyWithingsResponse — persistent branch", () => {
|
||||
it("Withings status 293 (invalid params) → persistent", () => {
|
||||
const v = classifyWithingsResponse(200, { status: 293 });
|
||||
expect(v.classification).toBe("persistent");
|
||||
expect(v.withingsStatus).toBe(293);
|
||||
});
|
||||
|
||||
it("Withings status 294 (already-subscribed) → persistent (callers downgrade for subscribe)", () => {
|
||||
// 294 is idempotent-success at the subscribeWebhook call-site;
|
||||
// the classifier still surfaces it as persistent so any OTHER
|
||||
// endpoint that sees 294 is loud about the contract bug.
|
||||
expect(
|
||||
classifyWithingsResponse(200, { status: 294 }).classification,
|
||||
).toBe("persistent");
|
||||
});
|
||||
|
||||
it("HTTP 400 (unexpected from Withings) → persistent", () => {
|
||||
const v = classifyWithingsResponse(400, null);
|
||||
expect(v.classification).toBe("persistent");
|
||||
expect(v.reason).toBe("http_400");
|
||||
});
|
||||
|
||||
it("HTTP 404 → persistent", () => {
|
||||
expect(classifyWithingsResponse(404, null).classification).toBe(
|
||||
"persistent",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WithingsApiError", () => {
|
||||
it("carries the classification + status on the typed error", () => {
|
||||
const err = new WithingsApiError({
|
||||
verb: "refresh",
|
||||
classification: "reauth_required",
|
||||
withingsStatus: 100,
|
||||
reason: "withings_100",
|
||||
upstreamError: "Authentication failed",
|
||||
});
|
||||
expect(err.classification).toBe("reauth_required");
|
||||
expect(err.withingsStatus).toBe(100);
|
||||
expect(err.reason).toBe("withings_100");
|
||||
expect(err.verb).toBe("refresh");
|
||||
expect(err.name).toBe("WithingsApiError");
|
||||
});
|
||||
|
||||
it("preserves the legacy `Withings <verb> error: <status> - <error>` message shape", () => {
|
||||
const err = new WithingsApiError({
|
||||
verb: "measure",
|
||||
classification: "transient",
|
||||
withingsStatus: 503,
|
||||
reason: "withings_503",
|
||||
upstreamError: "service unavailable",
|
||||
});
|
||||
// Legacy regex consumers (extractWithingsStatus, etc.) expect
|
||||
// exactly this shape.
|
||||
expect(err.message).toBe(
|
||||
"Withings measure error: 503 - service unavailable",
|
||||
);
|
||||
expect(/Withings\s+\w+\s+error:\s*(\d+)/.exec(err.message)?.[1]).toBe(
|
||||
"503",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the dash-segment when upstreamError is absent", () => {
|
||||
const err = new WithingsApiError({
|
||||
verb: "subscribe",
|
||||
classification: "persistent",
|
||||
withingsStatus: 293,
|
||||
reason: "withings_293",
|
||||
});
|
||||
expect(err.message).toBe("Withings subscribe error: 293");
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyError", () => {
|
||||
it("reads the verdict directly off a WithingsApiError instance", () => {
|
||||
const err = new WithingsApiError({
|
||||
verb: "refresh",
|
||||
classification: "reauth_required",
|
||||
withingsStatus: 101,
|
||||
reason: "withings_101",
|
||||
});
|
||||
expect(classifyError(err)).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("falls back to the message regex when the prototype was lost (pg-boss round-trip)", () => {
|
||||
// pg-boss serializes job errors to JSON and re-throws as plain Error
|
||||
// on retry — the WithingsApiError prototype does NOT survive.
|
||||
const rehydrated = new Error("Withings refresh error: 102 - User does not exist");
|
||||
expect(classifyError(rehydrated)).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("classifies a recovered Withings 503 transient via the regex fallback", () => {
|
||||
const rehydrated = new Error("Withings measure error: 503");
|
||||
expect(classifyError(rehydrated)).toBe("transient");
|
||||
});
|
||||
|
||||
it("classifies a recovered Withings 293 persistent via the regex fallback", () => {
|
||||
const rehydrated = new Error("Withings activity error: 293");
|
||||
expect(classifyError(rehydrated)).toBe("persistent");
|
||||
});
|
||||
|
||||
it("defaults to transient for unrelated errors (network drop, timeout)", () => {
|
||||
expect(classifyError(new Error("ECONNRESET"))).toBe("transient");
|
||||
expect(classifyError("string error")).toBe("transient");
|
||||
expect(classifyError(null)).toBe("transient");
|
||||
});
|
||||
});
|
||||
+61
-19
@@ -3,6 +3,10 @@
|
||||
* Docs: https://developer.withings.com/api-reference
|
||||
*/
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
import {
|
||||
WithingsApiError,
|
||||
classifyWithingsResponse,
|
||||
} from "./response-classifier";
|
||||
|
||||
const WITHINGS_OAUTH_URL =
|
||||
"https://account.withings.com/oauth2_user/authorize2";
|
||||
@@ -112,15 +116,22 @@ export async function exchangeCode(
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: "exchangeCode",
|
||||
duration_ms: Math.round(performance.now() - start),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
throw new Error(`Withings token error: ${json.status} - ${json.error}`);
|
||||
if (verdict.classification !== "success") {
|
||||
throw new WithingsApiError({
|
||||
verb: "token",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
return json.body as WithingsTokenResponse;
|
||||
}
|
||||
@@ -148,15 +159,22 @@ export async function refreshAccessToken(
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: "refreshAccessToken",
|
||||
duration_ms: Math.round(performance.now() - start),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
throw new Error(`Withings refresh error: ${json.status} - ${json.error}`);
|
||||
if (verdict.classification !== "success") {
|
||||
throw new WithingsApiError({
|
||||
verb: "refresh",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
return json.body as WithingsTokenResponse;
|
||||
}
|
||||
@@ -261,15 +279,22 @@ export async function fetchMeasurements(
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: `fetchMeasurements(page=${pageCount})`,
|
||||
duration_ms: Math.round(performance.now() - pageStart),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
throw new Error(`Withings measure error: ${json.status}`);
|
||||
if (verdict.classification !== "success") {
|
||||
throw new WithingsApiError({
|
||||
verb: "measure",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const body = json.body ?? {};
|
||||
@@ -331,19 +356,29 @@ export async function subscribeWebhook(
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
// 294 = already-subscribed is idempotent success at the subscribe
|
||||
// call-site (Withings preserves the existing subscription). The
|
||||
// classifier surfaces it as `persistent` because any OTHER endpoint
|
||||
// receiving 294 is a contract bug; here we explicitly downgrade it.
|
||||
const isAlreadySubscribed = json?.status === 294;
|
||||
const treatAsSuccess =
|
||||
verdict.classification === "success" || isAlreadySubscribed;
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: "subscribeWebhook",
|
||||
duration_ms: Math.round(performance.now() - start),
|
||||
status: res.status,
|
||||
error:
|
||||
json.status !== 0 && json.status !== 294
|
||||
? `status=${json.status}`
|
||||
: undefined,
|
||||
error: treatAsSuccess ? undefined : verdict.reason,
|
||||
});
|
||||
// Status 0 = success, 294 = already subscribed (both OK)
|
||||
if (json.status !== 0 && json.status !== 294) {
|
||||
throw new Error(`Withings subscribe error: ${json.status}`);
|
||||
if (!treatAsSuccess) {
|
||||
throw new WithingsApiError({
|
||||
verb: "subscribe",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,14 +407,21 @@ export async function unsubscribeWebhook(
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: "unsubscribeWebhook",
|
||||
duration_ms: Math.round(performance.now() - start),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
getEvent()?.addWarning(`Withings unsubscribe warning: ${json.status}`);
|
||||
// Unsubscribe is best-effort — a stale subscription will eventually
|
||||
// be garbage-collected by Withings, so we never throw here. We do
|
||||
// bubble the verdict into a warning so the audit-log path still
|
||||
// sees the off-response.
|
||||
if (verdict.classification !== "success") {
|
||||
getEvent()?.addWarning(
|
||||
`Withings unsubscribe warning: ${verdict.reason}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
/**
|
||||
* Off-response classifier for Withings API replies.
|
||||
*
|
||||
* The Withings API has three failure shapes the legacy client treated
|
||||
* uniformly as "throw with a message":
|
||||
*
|
||||
* 1. HTTP 5xx — upstream outage, retry on the next sync.
|
||||
* 2. HTTP 200 + `status: <non-zero>` — Withings returns its semantic
|
||||
* error code in the JSON body, with HTTP 200. The status code
|
||||
* taxonomy is documented at
|
||||
* https://developer.withings.com/api-reference/#section/Response-status .
|
||||
* 3. HTTP 200 + `status: 0` + empty `measuregrps` — no data, but the
|
||||
* connection is healthy. Not a failure at all.
|
||||
*
|
||||
* Pre-v1.4.42 the sync path inferred reauth-vs-transient from the error
|
||||
* MESSAGE via a regex (`isWithingsRefreshReauthFailure` in sync.ts).
|
||||
* That worked because the only failure shape the client threw was
|
||||
* `Withings <verb> error: <status>`, but it tightly coupled the
|
||||
* classifier to the literal message format and meant rate-limit
|
||||
* responses (601) and quota responses (293) were silently bucketed as
|
||||
* transient errors that never escalated even when they kept recurring.
|
||||
*
|
||||
* This module introduces an explicit classifier:
|
||||
*
|
||||
* - `classifyWithingsResponse(httpStatus, body)` — pure function,
|
||||
* returns a `WithingsClassification`.
|
||||
* - `WithingsApiError` — typed Error subclass carrying the
|
||||
* classification so downstream catch-blocks don't need to re-parse
|
||||
* a string.
|
||||
*
|
||||
* Classification buckets:
|
||||
*
|
||||
* - `success` → HTTP 200 + body.status === 0
|
||||
* - `transient` → retryable: HTTP 5xx, 429, Withings status 503
|
||||
* (upstream unavailable), 601 (rate-limited),
|
||||
* 2554 (too many subscriptions in flight),
|
||||
* 3xx network/CDN glitches
|
||||
* - `reauth_required` → permanent revoke: Withings 100, 101, 102,
|
||||
* 200–299 (invalid grant family). The user has
|
||||
* to redo OAuth.
|
||||
* - `persistent` → operator-attention error: invalid params
|
||||
* (293), missing scope (293 with body.scope_hint),
|
||||
* unknown action (294 outside subscribeWebhook).
|
||||
* These should NOT be retried silently — they
|
||||
* indicate a contract mismatch.
|
||||
*
|
||||
* The classifier is deliberately conservative: anything it doesn't
|
||||
* recognise defaults to `transient` so we don't hard-fail an integration
|
||||
* over a Withings status we've never seen. The audit log + admin-alert
|
||||
* ladder in `recordSyncFailure` already catches the "this keeps
|
||||
* happening" case for unknown transients.
|
||||
*/
|
||||
|
||||
/** Outcome buckets for a Withings response. */
|
||||
export type WithingsClassification =
|
||||
| "success"
|
||||
| "transient"
|
||||
| "reauth_required"
|
||||
| "persistent";
|
||||
|
||||
export interface ClassifiedResponse {
|
||||
classification: WithingsClassification;
|
||||
/** The Withings body status code (or undefined if HTTP-only failure). */
|
||||
withingsStatus: number | undefined;
|
||||
/** Short human-readable label for logs / audit details. */
|
||||
reason: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The minimum body shape we read. Withings adds many additional fields
|
||||
* (`body`, `error`, `scope_hint`, `more`, `measuregrps`, …); callers
|
||||
* keep their own typed views — we only need `status` and (optionally)
|
||||
* `error` for the reason string.
|
||||
*/
|
||||
export interface WithingsBodyLike {
|
||||
status?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Withings status codes that map to a permanent-revoke (user MUST
|
||||
* redo OAuth). See https://developer.withings.com/api-reference for
|
||||
* the full table — these are the values both Withings' own SDKs and
|
||||
* the existing HealthLog code treated as terminal.
|
||||
*/
|
||||
const REAUTH_CODES = new Set<number>([100, 101, 102]);
|
||||
|
||||
/**
|
||||
* Withings status codes that map to a transient / retryable error.
|
||||
* Conservative on purpose — 503 is the documented "service unavailable"
|
||||
* response, 601 is rate-limit, 2554/2555/2556 are notify-subscribe
|
||||
* transients.
|
||||
*/
|
||||
const TRANSIENT_CODES = new Set<number>([503, 601, 2554, 2555, 2556]);
|
||||
|
||||
/**
|
||||
* Withings status codes that indicate a persistent contract mismatch —
|
||||
* the request itself is malformed or the integration is missing a
|
||||
* required field. Retrying without operator intervention will not
|
||||
* succeed; the audit log surfaces these.
|
||||
*
|
||||
* - 293 = "invalid params" / "missing required field"
|
||||
* - 294 = "already subscribed" (subscribeWebhook treats it as success;
|
||||
* any OTHER endpoint receiving 294 is a contract bug)
|
||||
*
|
||||
* Note: 294 is intentionally listed here. `subscribeWebhook` overrides
|
||||
* the classification for its own call site (already-subscribed is
|
||||
* idempotent there); every other client call that sees 294 surfaces it
|
||||
* as a persistent failure so the bug doesn't hide.
|
||||
*/
|
||||
const PERSISTENT_CODES = new Set<number>([293, 294]);
|
||||
|
||||
/**
|
||||
* Classify a single Withings API response.
|
||||
*
|
||||
* @param httpStatus The HTTP status code from fetch (200 for the
|
||||
* happy path, 5xx for upstream outages).
|
||||
* @param body The parsed JSON body. Only `status` (and
|
||||
* optionally `error`) are read.
|
||||
*/
|
||||
export function classifyWithingsResponse(
|
||||
httpStatus: number,
|
||||
body: WithingsBodyLike | null | undefined,
|
||||
): ClassifiedResponse {
|
||||
// HTTP layer first — a 503 / 502 / 504 from Withings means we never
|
||||
// got to the JSON envelope.
|
||||
if (httpStatus >= 500 && httpStatus < 600) {
|
||||
return {
|
||||
classification: "transient",
|
||||
withingsStatus: undefined,
|
||||
reason: `http_${httpStatus}`,
|
||||
};
|
||||
}
|
||||
if (httpStatus === 429) {
|
||||
return {
|
||||
classification: "transient",
|
||||
withingsStatus: undefined,
|
||||
reason: "http_429",
|
||||
};
|
||||
}
|
||||
// 4xx outside 429 is unexpected from Withings — they always reply 200
|
||||
// even on auth failures, embedding the real status in the body. We
|
||||
// bucket as persistent so a regression to a 4xx-throwing upstream
|
||||
// surfaces in audit logs rather than retrying forever.
|
||||
if (httpStatus >= 400 && httpStatus < 500) {
|
||||
return {
|
||||
classification: "persistent",
|
||||
withingsStatus: undefined,
|
||||
reason: `http_${httpStatus}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Body status — Withings' own taxonomy.
|
||||
const status = body?.status;
|
||||
if (status === 0) {
|
||||
return {
|
||||
classification: "success",
|
||||
withingsStatus: 0,
|
||||
reason: "ok",
|
||||
};
|
||||
}
|
||||
if (typeof status !== "number") {
|
||||
// Off-spec body — no `status` field at all. The legacy client
|
||||
// would have crashed reading `json.status`; we treat it as a
|
||||
// transient so the retry catches a one-off CDN error page.
|
||||
return {
|
||||
classification: "transient",
|
||||
withingsStatus: undefined,
|
||||
reason: "no_status_field",
|
||||
};
|
||||
}
|
||||
|
||||
// Explicit lists take precedence over ranges so a contract-mismatch
|
||||
// code (293, 294) that happens to live inside the 200..299 OAuth
|
||||
// range stays classified as persistent rather than reauth.
|
||||
if (PERSISTENT_CODES.has(status)) {
|
||||
return {
|
||||
classification: "persistent",
|
||||
withingsStatus: status,
|
||||
reason: `withings_${status}`,
|
||||
};
|
||||
}
|
||||
if (TRANSIENT_CODES.has(status)) {
|
||||
return {
|
||||
classification: "transient",
|
||||
withingsStatus: status,
|
||||
reason: `withings_${status}`,
|
||||
};
|
||||
}
|
||||
if (REAUTH_CODES.has(status)) {
|
||||
return {
|
||||
classification: "reauth_required",
|
||||
withingsStatus: status,
|
||||
reason: `withings_${status}`,
|
||||
};
|
||||
}
|
||||
// The 200..299 invalid_grant family — Withings uses this range for
|
||||
// OAuth grant failures. Membership is by range rather than an
|
||||
// explicit list because individual codes in there can shift between
|
||||
// Withings firmware revisions. Explicit persistent/transient codes
|
||||
// above this check are deliberate exemptions.
|
||||
if (status >= 200 && status <= 299) {
|
||||
return {
|
||||
classification: "reauth_required",
|
||||
withingsStatus: status,
|
||||
reason: `withings_${status}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Default: anything we don't recognise becomes transient. The
|
||||
// 3-strike admin alert ladder in `recordSyncFailure` already catches
|
||||
// the "keeps happening" case, and silently degrading to "no data"
|
||||
// (the legacy behaviour) is strictly worse than a retry.
|
||||
return {
|
||||
classification: "transient",
|
||||
withingsStatus: status,
|
||||
reason: `withings_${status}_unknown`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Typed Error subclass that carries the classification verdict so
|
||||
* `try/catch` blocks downstream can branch without re-parsing the
|
||||
* message.
|
||||
*
|
||||
* The `message` field still uses the legacy
|
||||
* `"Withings <verb> error: <status> - <error>"` format so the existing
|
||||
* regex-based `extractWithingsStatus` / `isWithingsRefreshReauthFailure`
|
||||
* helpers in sync.ts continue to work for callers that haven't been
|
||||
* migrated yet. Callers that import the new class can read
|
||||
* `err.classification` directly.
|
||||
*/
|
||||
export class WithingsApiError extends Error {
|
||||
readonly classification: WithingsClassification;
|
||||
readonly withingsStatus: number | undefined;
|
||||
readonly reason: string;
|
||||
readonly verb: string;
|
||||
|
||||
constructor(opts: {
|
||||
verb: string;
|
||||
classification: WithingsClassification;
|
||||
withingsStatus: number | undefined;
|
||||
reason: string;
|
||||
upstreamError?: string;
|
||||
}) {
|
||||
const statusLabel =
|
||||
typeof opts.withingsStatus === "number" ? opts.withingsStatus : "?";
|
||||
const errSegment = opts.upstreamError ? ` - ${opts.upstreamError}` : "";
|
||||
super(`Withings ${opts.verb} error: ${statusLabel}${errSegment}`);
|
||||
this.name = "WithingsApiError";
|
||||
this.verb = opts.verb;
|
||||
this.classification = opts.classification;
|
||||
this.withingsStatus = opts.withingsStatus;
|
||||
this.reason = opts.reason;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the classification from any caught error. Returns
|
||||
* `transient` for non-`WithingsApiError` inputs so existing call
|
||||
* sites that surface a plain `Error` continue to retry rather than
|
||||
* permanently disabling the integration.
|
||||
*
|
||||
* Falls back to message-regex parsing so callers that wrap
|
||||
* `WithingsApiError` in `new Error(`... ${err.message}`)` (e.g.
|
||||
* pg-boss job retries that lose the original prototype) still
|
||||
* classify correctly.
|
||||
*/
|
||||
export function classifyError(err: unknown): WithingsClassification {
|
||||
if (err instanceof WithingsApiError) return err.classification;
|
||||
|
||||
// Best-effort regex fallback for unwrapped messages — same shape
|
||||
// sync.ts's `extractWithingsStatus` reads.
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const m = /Withings\s+\w+\s+error:\s*(\d+)/.exec(msg);
|
||||
if (!m) return "transient";
|
||||
const status = Number.parseInt(m[1]!, 10);
|
||||
if (!Number.isFinite(status)) return "transient";
|
||||
// Run the body classifier with a synthetic HTTP-200 envelope.
|
||||
return classifyWithingsResponse(200, { status }).classification;
|
||||
}
|
||||
@@ -44,6 +44,10 @@ import {
|
||||
} from "@/lib/rollups/measurement-rollups";
|
||||
|
||||
import { hasActivityScope } from "./client";
|
||||
import {
|
||||
WithingsApiError,
|
||||
classifyWithingsResponse,
|
||||
} from "./response-classifier";
|
||||
import {
|
||||
extractWithingsStatus,
|
||||
isWithingsRefreshReauthFailure,
|
||||
@@ -157,15 +161,22 @@ export async function fetchWithingsActivity(
|
||||
body: params.toString(),
|
||||
});
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: `fetchWithingsActivity(page=${pageCount})`,
|
||||
duration_ms: Math.round(performance.now() - pageStart),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
throw new Error(`Withings activity error: ${json.status}`);
|
||||
if (verdict.classification !== "success") {
|
||||
throw new WithingsApiError({
|
||||
verb: "activity",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const body = json.body ?? {};
|
||||
|
||||
@@ -42,6 +42,10 @@ import {
|
||||
} from "@/lib/rollups/measurement-rollups";
|
||||
|
||||
import { hasActivityScope } from "./client";
|
||||
import {
|
||||
WithingsApiError,
|
||||
classifyWithingsResponse,
|
||||
} from "./response-classifier";
|
||||
import {
|
||||
extractWithingsStatus,
|
||||
isWithingsRefreshReauthFailure,
|
||||
@@ -127,15 +131,22 @@ export async function fetchWithingsSleep(
|
||||
body: params.toString(),
|
||||
});
|
||||
const json = await res.json();
|
||||
const verdict = classifyWithingsResponse(res.status, json);
|
||||
getEvent()?.addExternalCall({
|
||||
service: "withings",
|
||||
method: "fetchWithingsSleep",
|
||||
duration_ms: Math.round(performance.now() - pageStart),
|
||||
status: res.status,
|
||||
error: json.status !== 0 ? `status=${json.status}` : undefined,
|
||||
error: verdict.classification === "success" ? undefined : verdict.reason,
|
||||
});
|
||||
if (json.status !== 0) {
|
||||
throw new Error(`Withings sleep error: ${json.status}`);
|
||||
if (verdict.classification !== "success") {
|
||||
throw new WithingsApiError({
|
||||
verb: "sleep",
|
||||
classification: verdict.classification,
|
||||
withingsStatus: verdict.withingsStatus,
|
||||
reason: verdict.reason,
|
||||
upstreamError: typeof json?.error === "string" ? json.error : undefined,
|
||||
});
|
||||
}
|
||||
const series: WithingsSleepSegment[] = json.body?.series ?? [];
|
||||
return series;
|
||||
|
||||
+66
-24
@@ -17,7 +17,13 @@ import {
|
||||
isReauthRequired,
|
||||
recordSyncFailure,
|
||||
recordSyncSuccess,
|
||||
type FailureKind,
|
||||
} from "@/lib/integrations/status";
|
||||
import {
|
||||
classifyError,
|
||||
WithingsApiError,
|
||||
type WithingsClassification,
|
||||
} from "./response-classifier";
|
||||
import {
|
||||
collapseToTypeDayKeys,
|
||||
recomputeBucketsForMeasurement,
|
||||
@@ -109,20 +115,7 @@ export async function getValidToken(userId: string): Promise<{
|
||||
};
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(`Token refresh failed for user ${userId}: ${err}`);
|
||||
// Withings refresh failures expose the upstream `status` code in
|
||||
// the error message (see refreshAccessToken). We treat any of the
|
||||
// documented permanent-revoke statuses (100, 101, 102, 200..299
|
||||
// for invalid_grant) as reauth-required and everything else as a
|
||||
// transient retryable failure.
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const isReauth = isWithingsRefreshReauthFailure(message);
|
||||
await recordSyncFailure({
|
||||
userId,
|
||||
integration: "withings",
|
||||
kind: isReauth ? "reauth_required" : "transient",
|
||||
message,
|
||||
errorCode: extractWithingsStatus(message),
|
||||
});
|
||||
await recordWithingsSyncFailure(userId, err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -184,16 +177,7 @@ export async function syncUserMeasurements(
|
||||
try {
|
||||
measures = await fetchMeasurements(tokenInfo.accessToken, startDate);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
await recordSyncFailure({
|
||||
userId,
|
||||
integration: "withings",
|
||||
kind: isWithingsRefreshReauthFailure(message)
|
||||
? "reauth_required"
|
||||
: "transient",
|
||||
message,
|
||||
errorCode: extractWithingsStatus(message),
|
||||
});
|
||||
await recordWithingsSyncFailure(userId, err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -287,6 +271,57 @@ export async function syncUserMeasurements(
|
||||
return imported;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a Withings response classification onto the `FailureKind` carried
|
||||
* into `recordSyncFailure`. Pure function — no IO, no state.
|
||||
*
|
||||
* `success` → not a failure; callers must not invoke this.
|
||||
* `transient` → `transient` (retry next sync)
|
||||
* `reauth_required` → `reauth_required` (park at `error_reauth`)
|
||||
* `persistent` → `persistent` (audited; next sync still runs)
|
||||
*/
|
||||
/**
|
||||
* v1.4.42 — shared failure-recording shape for the two Withings sync
|
||||
* catch-blocks. The typed `WithingsApiError` carries the classification
|
||||
* verdict directly; `classifyError`'s regex fallback handles plain
|
||||
* `Error` instances (e.g. a pg-boss job retry that lost the prototype
|
||||
* during the JSON round-trip).
|
||||
*/
|
||||
async function recordWithingsSyncFailure(
|
||||
userId: string,
|
||||
err: unknown,
|
||||
): Promise<void> {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
await recordSyncFailure({
|
||||
userId,
|
||||
integration: "withings",
|
||||
kind: classificationToFailureKind(classifyError(err)),
|
||||
message,
|
||||
errorCode:
|
||||
err instanceof WithingsApiError
|
||||
? err.withingsStatus?.toString()
|
||||
: extractWithingsStatus(message),
|
||||
});
|
||||
}
|
||||
|
||||
export function classificationToFailureKind(
|
||||
classification: WithingsClassification,
|
||||
): FailureKind {
|
||||
switch (classification) {
|
||||
case "reauth_required":
|
||||
return "reauth_required";
|
||||
case "persistent":
|
||||
return "persistent";
|
||||
case "transient":
|
||||
return "transient";
|
||||
case "success":
|
||||
// Defensive: a caller asking for the FailureKind of a success
|
||||
// is a contract bug. Default to `transient` so the audit log
|
||||
// still surfaces the bug rather than silently ignoring it.
|
||||
return "transient";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Withings status codes that indicate a permanent-revoke condition
|
||||
* (the refresh_token will not work again — the user has to redo OAuth).
|
||||
@@ -302,6 +337,13 @@ export async function syncUserMeasurements(
|
||||
*
|
||||
* The error message format from `refreshAccessToken()` is
|
||||
* "Withings refresh error: <status> - <error>".
|
||||
*
|
||||
* v1.4.42 W6 — superseded for new code paths by
|
||||
* `classifyError`/`classifyWithingsResponse` in `response-classifier.ts`.
|
||||
* Kept for the W17b/c sync-activity + sync-sleep catch-blocks that
|
||||
* haven't yet been migrated; both paths now also benefit from the
|
||||
* typed-error throw upstream because `classifyError` falls back to the
|
||||
* same regex.
|
||||
*/
|
||||
export function isWithingsRefreshReauthFailure(message: string): boolean {
|
||||
const status = extractWithingsStatus(message);
|
||||
|
||||
@@ -43,10 +43,6 @@ const WITHINGS_SLEEP_APPLI = 44;
|
||||
const WITHINGS_ACTIVITY_QUEUE = "withings-activity-sync";
|
||||
const WITHINGS_SLEEP_QUEUE = "withings-sleep-sync";
|
||||
|
||||
export type WithingsWebhookAuthOutcome =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: "missing_secret" | "mismatch" | "not_configured" };
|
||||
|
||||
/**
|
||||
* Constant-time comparison helper. Returns false unless both inputs have
|
||||
* the same byte length AND match exactly.
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* v1.4.42 W5 — write-time canonical-row picker tests.
|
||||
*
|
||||
* Pairs with `src/lib/workouts/canonical-rows.ts`. The helper is the
|
||||
* pre-`createMany` dedup pass invoked by `POST /api/workouts/batch`
|
||||
* when the v1.5 iOS sprint posts a batch carrying both an Apple Watch
|
||||
* row and a Withings ScanWatch row for the same Sunday-morning run.
|
||||
* The tests pin the algorithm contract so a future tightening of the
|
||||
* window or a tie-breaker tweak surfaces a failing assertion rather
|
||||
* than a silent regression in the duplicate-drop count.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
dedupeWorkoutBatch,
|
||||
WORKOUT_DEDUP_WINDOW_MS,
|
||||
type WorkoutRow,
|
||||
} from "../canonical-rows";
|
||||
|
||||
import type { MeasurementSource } from "@/generated/prisma/client";
|
||||
|
||||
interface TestRow extends WorkoutRow {
|
||||
/** Marker so the test can assert which input row survived. */
|
||||
id: string;
|
||||
}
|
||||
|
||||
function row(partial: Partial<TestRow> & { id: string }): TestRow {
|
||||
return {
|
||||
id: partial.id,
|
||||
userId: partial.userId ?? "user-1",
|
||||
activityType: partial.activityType ?? "running",
|
||||
startedAt: partial.startedAt ?? new Date("2026-05-21T08:00:00Z"),
|
||||
source: partial.source ?? "APPLE_HEALTH",
|
||||
caloriesKcal: partial.caloriesKcal ?? null,
|
||||
createdAt: partial.createdAt ?? null,
|
||||
index: partial.index,
|
||||
};
|
||||
}
|
||||
|
||||
describe("dedupeWorkoutBatch", () => {
|
||||
it("returns an empty array on empty input", () => {
|
||||
expect(dedupeWorkoutBatch([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("collapses exact duplicates from the same source", () => {
|
||||
// Two rows from the SAME source at the SAME instant: a re-posted
|
||||
// batch with the externalId differing (e.g. the iOS app split the
|
||||
// workout into two HKWorkout entries by mistake) would otherwise
|
||||
// double-count. The helper keeps one survivor — the higher-cal /
|
||||
// earliest-createdAt row.
|
||||
const a = row({
|
||||
id: "a",
|
||||
source: "APPLE_HEALTH",
|
||||
caloriesKcal: 420,
|
||||
createdAt: new Date("2026-05-21T08:30:00Z"),
|
||||
});
|
||||
const b = row({
|
||||
id: "b",
|
||||
source: "APPLE_HEALTH",
|
||||
caloriesKcal: 420,
|
||||
createdAt: new Date("2026-05-21T08:31:00Z"),
|
||||
});
|
||||
|
||||
const out = dedupeWorkoutBatch([a, b]);
|
||||
expect(out).toHaveLength(1);
|
||||
// Same calories → earliest createdAt wins (`a`).
|
||||
expect(out[0]!.id).toBe("a");
|
||||
});
|
||||
|
||||
it("prefers the higher-priority source on a cross-source overlap inside the window", () => {
|
||||
// Apple Watch + Withings ScanWatch both record the same run. The
|
||||
// window is satisfied (rows are 60 s apart, well under the 90 s
|
||||
// ceiling) and the activityType matches → group dedups to one
|
||||
// survivor. APPLE_HEALTH outranks WITHINGS per the ladder.
|
||||
const apple = row({
|
||||
id: "apple",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
caloriesKcal: 400,
|
||||
});
|
||||
const withings = row({
|
||||
id: "withings",
|
||||
source: "WITHINGS",
|
||||
startedAt: new Date("2026-05-21T08:01:00Z"),
|
||||
caloriesKcal: 500,
|
||||
});
|
||||
|
||||
const out = dedupeWorkoutBatch([apple, withings]);
|
||||
expect(out).toHaveLength(1);
|
||||
// Source-axis wins outright — APPLE_HEALTH beats WITHINGS even
|
||||
// when WITHINGS has higher calories. The calories tie-break only
|
||||
// fires WITHIN a single source tier.
|
||||
expect(out[0]!.id).toBe("apple");
|
||||
});
|
||||
|
||||
it("returns every row unchanged when no overlap exists", () => {
|
||||
// Two runs 10 min apart from the SAME source — well outside the
|
||||
// 90 s window. Both must survive; the helper is not a generic
|
||||
// "one run per day" filter.
|
||||
const first = row({
|
||||
id: "first",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
const second = row({
|
||||
id: "second",
|
||||
startedAt: new Date("2026-05-21T08:10:00Z"),
|
||||
});
|
||||
|
||||
const out = dedupeWorkoutBatch([first, second]);
|
||||
expect(out.map((r) => r.id)).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it("returns rows from different users untouched even on identical timestamps", () => {
|
||||
// A multi-user batch (theoretically possible from an admin path)
|
||||
// must never collapse rows across `userId`. The window check
|
||||
// includes the userId in the grouping key.
|
||||
const u1 = row({
|
||||
id: "u1",
|
||||
userId: "user-1",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
const u2 = row({
|
||||
id: "u2",
|
||||
userId: "user-2",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
|
||||
const out = dedupeWorkoutBatch([u1, u2]);
|
||||
expect(out.map((r) => r.id).sort()).toEqual(["u1", "u2"]);
|
||||
});
|
||||
|
||||
it("returns rows of different activity types untouched at the same instant", () => {
|
||||
// A user opens a "Walk" workout on the Watch and a "Strength"
|
||||
// workout on the iPhone at the same instant. The window matches
|
||||
// but the activityType doesn't — two distinct rows, both survive.
|
||||
const walk = row({
|
||||
id: "walk",
|
||||
activityType: "walking",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
const strength = row({
|
||||
id: "strength",
|
||||
activityType: "strength",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
|
||||
const out = dedupeWorkoutBatch([walk, strength]);
|
||||
expect(out.map((r) => r.id).sort()).toEqual(["strength", "walk"]);
|
||||
});
|
||||
|
||||
it("uses caloriesKcal as the tie-breaker when sources tie", () => {
|
||||
// Apple Watch in the bag (no HR contact, calories=200) vs Apple
|
||||
// Watch on the wrist (full HR series, calories=500). Same source,
|
||||
// same instant, same activityType — calories wins.
|
||||
const lo = row({
|
||||
id: "lo",
|
||||
source: "APPLE_HEALTH",
|
||||
caloriesKcal: 200,
|
||||
});
|
||||
const hi = row({
|
||||
id: "hi",
|
||||
source: "APPLE_HEALTH",
|
||||
caloriesKcal: 500,
|
||||
// Stamp a later createdAt to prove the calories axis wins
|
||||
// over the createdAt fallback.
|
||||
createdAt: new Date("2026-05-21T09:00:00Z"),
|
||||
});
|
||||
const loWithEarlierCreated = row({
|
||||
id: "lo-early",
|
||||
source: "APPLE_HEALTH",
|
||||
caloriesKcal: 200,
|
||||
createdAt: new Date("2026-05-21T08:30:00Z"),
|
||||
});
|
||||
|
||||
// Pair 1: hi vs lo → hi wins on calories.
|
||||
expect(dedupeWorkoutBatch([lo, hi]).map((r) => r.id)).toEqual(["hi"]);
|
||||
|
||||
// Pair 2: hi vs lo-early → hi STILL wins because calories trump
|
||||
// createdAt.
|
||||
expect(
|
||||
dedupeWorkoutBatch([loWithEarlierCreated, hi]).map((r) => r.id),
|
||||
).toEqual(["hi"]);
|
||||
});
|
||||
|
||||
it("falls back to earliest createdAt when source + calories both tie", () => {
|
||||
// Marc's ScanWatch on the wrist + ScanWatch in a desk drawer:
|
||||
// unrealistic, but the case isolates the tie-breaker hierarchy.
|
||||
const early = row({
|
||||
id: "early",
|
||||
source: "WITHINGS",
|
||||
caloriesKcal: 350,
|
||||
createdAt: new Date("2026-05-21T08:30:00Z"),
|
||||
});
|
||||
const late = row({
|
||||
id: "late",
|
||||
source: "WITHINGS",
|
||||
caloriesKcal: 350,
|
||||
createdAt: new Date("2026-05-21T08:45:00Z"),
|
||||
});
|
||||
|
||||
expect(dedupeWorkoutBatch([late, early]).map((r) => r.id)).toEqual([
|
||||
"early",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps determinism via input order when every field ties", () => {
|
||||
// Two manually-entered "running" workouts at the same instant
|
||||
// with no calories and no createdAt — the helper falls back to
|
||||
// the original input ordinal so re-running over the same input
|
||||
// always picks the same survivor.
|
||||
const first = row({ id: "first", source: "MANUAL" });
|
||||
const second = row({ id: "second", source: "MANUAL" });
|
||||
|
||||
expect(dedupeWorkoutBatch([first, second]).map((r) => r.id)).toEqual([
|
||||
"first",
|
||||
]);
|
||||
// Reversed input → reversed survivor. Confirms the tie-breaker
|
||||
// genuinely consults input order rather than a hidden field
|
||||
// (e.g. `id` lexicographic).
|
||||
expect(dedupeWorkoutBatch([second, first]).map((r) => r.id)).toEqual([
|
||||
"second",
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats a row exactly at the ±90 s boundary as in-window", () => {
|
||||
// The window is inclusive (`<=`). A row landing on the boundary
|
||||
// joins the group; one millisecond past stays separate.
|
||||
const anchor = row({
|
||||
id: "anchor",
|
||||
source: "APPLE_HEALTH",
|
||||
startedAt: new Date("2026-05-21T08:00:00Z"),
|
||||
});
|
||||
const onBoundary = row({
|
||||
id: "boundary",
|
||||
source: "WITHINGS",
|
||||
startedAt: new Date(
|
||||
anchor.startedAt.getTime() + WORKOUT_DEDUP_WINDOW_MS,
|
||||
),
|
||||
});
|
||||
const justOutside = row({
|
||||
id: "outside",
|
||||
source: "WITHINGS",
|
||||
startedAt: new Date(
|
||||
anchor.startedAt.getTime() + WORKOUT_DEDUP_WINDOW_MS + 1,
|
||||
),
|
||||
});
|
||||
|
||||
// anchor + onBoundary → one group; APPLE_HEALTH wins.
|
||||
expect(
|
||||
dedupeWorkoutBatch([anchor, onBoundary]).map((r) => r.id),
|
||||
).toEqual(["anchor"]);
|
||||
|
||||
// anchor + justOutside → two distinct groups, both survive.
|
||||
expect(
|
||||
dedupeWorkoutBatch([anchor, justOutside]).map((r) => r.id),
|
||||
).toEqual(["anchor", "outside"]);
|
||||
});
|
||||
|
||||
it("walks the full source ladder (APPLE_HEALTH > WITHINGS > MANUAL > IMPORT)", () => {
|
||||
const sources: MeasurementSource[] = [
|
||||
"IMPORT",
|
||||
"MANUAL",
|
||||
"WITHINGS",
|
||||
"APPLE_HEALTH",
|
||||
];
|
||||
const rows = sources.map((source, idx) =>
|
||||
row({
|
||||
id: source,
|
||||
source,
|
||||
// Stagger by 10 s so each row sits inside the 90 s window
|
||||
// relative to the anchor (the first row inserted).
|
||||
startedAt: new Date(
|
||||
new Date("2026-05-21T08:00:00Z").getTime() + idx * 10_000,
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(dedupeWorkoutBatch(rows).map((r) => r.id)).toEqual([
|
||||
"APPLE_HEALTH",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not mutate caller rows", () => {
|
||||
// The picker is pure — the caller's array reference and row
|
||||
// identity survive the call so a future audit-overlay can
|
||||
// re-inspect the dropped rows.
|
||||
const a = row({ id: "a", source: "APPLE_HEALTH", caloriesKcal: 100 });
|
||||
const b = row({ id: "b", source: "WITHINGS", caloriesKcal: 100 });
|
||||
const before = JSON.stringify([a, b]);
|
||||
dedupeWorkoutBatch([a, b]);
|
||||
expect(JSON.stringify([a, b])).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* v1.4.42 W5 — write-time cross-source canonical-row picker for
|
||||
* incoming `Workout` ingest payloads.
|
||||
*
|
||||
* Why this exists alongside the read-time helper
|
||||
* ──────────────────────────────────────────────
|
||||
*
|
||||
* Two related-but-distinct dedup paths exist in the codebase:
|
||||
*
|
||||
* - `pickCanonicalWorkoutRows()` in `src/lib/measurements/` (v1.4.30)
|
||||
* — READ-time picker invoked by `GET /api/workouts` /
|
||||
* `GET /api/workouts/[id]`. It walks DB rows, looks up the user's
|
||||
* persisted `sourcePriorityJson`, buckets by 5-minute slot, and
|
||||
* filters the read result so the dashboard tile shows one row per
|
||||
* logical workout.
|
||||
*
|
||||
* - This helper (`dedupeWorkoutBatch`, v1.4.42) — WRITE-time picker
|
||||
* invoked by `POST /api/workouts/batch` BEFORE
|
||||
* `prisma.workout.createMany`. The name intentionally diverges
|
||||
* from the read-time picker to make the auto-completion path
|
||||
* unambiguous (write-time payload-internal dedup vs. read-time
|
||||
* cross-batch dedup with user-priority resolution).
|
||||
* The v1.5 iOS sprint will ingest `HKWorkoutType` data in batches
|
||||
* against `/api/workouts/batch`; Apple Watch + Withings ScanWatch
|
||||
* paired to the same iPhone frequently capture the same workout
|
||||
* simultaneously (e.g. a Sunday-morning run) and the iOS app may
|
||||
* post both rows in one batch. Without write-time dedup, both
|
||||
* rows would persist (their `externalId`s differ, so the
|
||||
* `(userId, source, externalId)` unique index doesn't fire) and
|
||||
* the read-time picker would carry the duplicate forward at every
|
||||
* downstream read.
|
||||
*
|
||||
* The two pickers are layered, not redundant:
|
||||
* - Write-time picker drops PAYLOAD-internal duplicates inside a
|
||||
* single batch so we don't pay the storage cost.
|
||||
* - Read-time picker still runs to collapse cross-batch duplicates
|
||||
* (e.g. Apple Watch row from Monday's batch + ScanWatch row from
|
||||
* Tuesday's backfill batch).
|
||||
*
|
||||
* Algorithm
|
||||
* ─────────
|
||||
*
|
||||
* 1. Group by `(userId, activityType, startedAt ± 90 s window)`.
|
||||
* The 90-second window is tighter than the read-time picker's
|
||||
* 5-minute slot because a single batch from one iOS client has
|
||||
* no cross-device clock skew to absorb — both rows are stamped
|
||||
* with HealthKit's `startDate`, which Apple aggregates to the
|
||||
* same instant across paired sensors. A 90-second cushion
|
||||
* covers HK's documented ±60s smoothing plus a small buffer.
|
||||
* 2. Within each group, prefer in order:
|
||||
* `APPLE_HEALTH ≻ WITHINGS ≻ MANUAL ≻ IMPORT`. The literal
|
||||
* source ladder is sourced from `DEFAULT_WORKOUT_SOURCE_PRIORITY`
|
||||
* in `src/lib/sources/pick-canonical-workout.ts` (the v1.4.25
|
||||
* W16a scaffolding) so both pickers consult a single source of
|
||||
* truth — adding a new source enum value is a one-place change.
|
||||
* Per the scope memo the legacy `STRAVA_IMPORT` reference maps
|
||||
* to the actual `IMPORT` enum value (the codebase has no
|
||||
* separate Strava source today; Strava XML imports ride the
|
||||
* generic `IMPORT` bucket).
|
||||
* 3. Tie-breaker: higher `caloriesKcal` (more sensor data — a row
|
||||
* with HR-derived calories beats a row with a zero / null
|
||||
* total). Then earliest `createdAt` so re-running the picker
|
||||
* with the same inputs picks the same survivor every time.
|
||||
*
|
||||
* Purity contract
|
||||
* ───────────────
|
||||
*
|
||||
* Zero Prisma imports, zero IO, zero user lookups. The helper takes
|
||||
* an array, returns an array. Testable in isolation; safely invoked
|
||||
* from a hot ingest path with no DB round-trip cost.
|
||||
*
|
||||
* Source-priority divergence vs the read-time picker
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* The read-time picker resolves the per-user `sourcePriorityJson`
|
||||
* (from `User.sourcePriorityJson`) for every read so a user who
|
||||
* promoted MANUAL above APPLE_HEALTH in Settings → Sources sees
|
||||
* their Manual rows surface above the Apple Watch ones. The
|
||||
* write-time helper deliberately does NOT consult that preference:
|
||||
* it uses the canonical `DEFAULT_WORKOUT_SOURCE_PRIORITY` constant
|
||||
* unconditionally, so a customized user's preferred row can still
|
||||
* be dropped at write-time before the read-time picker ever sees
|
||||
* it. Scope-narrow today — `DEFAULT_SOURCE_PRIORITY.steps` is the
|
||||
* Apple-first default and most paired users never override it —
|
||||
* but the moment a user customises, this helper silently
|
||||
* overrides them.
|
||||
*
|
||||
* The architecturally correct fix (v1.4.43 candidate) is option
|
||||
* (b) from the v1.4.42 senior-dev QA M1: accept the small ingest-
|
||||
* path cost of one indexed `User.sourcePriorityJson` lookup and
|
||||
* thread the user's ladder into the picker. The batch route
|
||||
* already has the userId per row; the lookup is one
|
||||
* `prisma.user.findUnique({ where: { id }, select:
|
||||
* { sourcePriorityJson: true }})`. Until that lands, this
|
||||
* docstring is the load-bearing operator notice.
|
||||
*/
|
||||
|
||||
import { DEFAULT_WORKOUT_SOURCE_PRIORITY } from "@/lib/sources/pick-canonical-workout";
|
||||
import type { MeasurementSource } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Minimum row shape consulted by the picker. Field names mirror the
|
||||
* batch-route's prepared `Prisma.WorkoutCreateManyInput` plus a
|
||||
* `createdAt` slot for the deterministic tie-breaker. Anything else
|
||||
* the caller carried alongside the row (route geometry, HR series,
|
||||
* metadata) survives untouched — the picker filters but never
|
||||
* mutates and is generic in `T` so call sites keep their own
|
||||
* carrier type.
|
||||
*
|
||||
* Naming aligned with the v1.5 iOS contract:
|
||||
* - `activityType` — the sport type (`"running"`, `"cycling"`,
|
||||
* ...). Matches `Workout.sportType` at the DB layer and
|
||||
* `WorkoutSportType` at the validator layer; cross-source
|
||||
* overlap requires identical sport so a "Walking" + "Running"
|
||||
* pair at the same instant stays as two distinct rows.
|
||||
* - `caloriesKcal` — the active-energy aggregate. The v1.5 iOS
|
||||
* contract uses `caloriesKcal` for parity with HealthKit's
|
||||
* `HKQuantityTypeIdentifierActiveEnergyBurned`; the server's
|
||||
* write path maps it to `Workout.totalEnergyKcal`.
|
||||
* - `createdAt` — when the row was minted. The batch path doesn't
|
||||
* have this yet (it's set by Prisma's `@default(now())` at
|
||||
* insert), so the helper falls back to insertion order via the
|
||||
* `index` field when `createdAt` is undefined on every member.
|
||||
*/
|
||||
export interface WorkoutRow {
|
||||
userId: string;
|
||||
activityType: string;
|
||||
startedAt: Date;
|
||||
source: MeasurementSource;
|
||||
caloriesKcal?: number | null;
|
||||
/**
|
||||
* Optional row-mint timestamp. The write-time picker is called
|
||||
* BEFORE `createMany`, so prepared rows usually have no
|
||||
* `createdAt` yet — undefined falls through to the next
|
||||
* tie-breaker (insertion order via the `index` field).
|
||||
*/
|
||||
createdAt?: Date | null;
|
||||
/**
|
||||
* Stable per-batch ordinal. Set by the caller (e.g. the position
|
||||
* of the entry in the inbound payload) so two rows with identical
|
||||
* priority + calories + createdAt still resolve deterministically.
|
||||
* Optional; defaults to 0 so single-row groups never need it.
|
||||
*/
|
||||
index?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-source dedup window. Within a single ingest batch from one
|
||||
* iOS client, two rows whose `startedAt` falls within ±90 s AND
|
||||
* share the same `activityType` AND belong to the same user are
|
||||
* treated as the same logical workout. The window is symmetric:
|
||||
* the comparison uses `|a.startedAt - b.startedAt| ≤ 90 000 ms`.
|
||||
*/
|
||||
export const WORKOUT_DEDUP_WINDOW_MS = 90 * 1000;
|
||||
|
||||
/**
|
||||
* Source-priority rank lookup. Lower rank = higher priority. A
|
||||
* source absent from the ladder gets a rank past the end of the
|
||||
* array — the picker still keeps that row when no ladder-listed
|
||||
* row competes for the slot (single-source group), but loses to
|
||||
* any ladder-listed competitor.
|
||||
*/
|
||||
function sourceRank(source: MeasurementSource): number {
|
||||
const idx = DEFAULT_WORKOUT_SOURCE_PRIORITY.indexOf(source);
|
||||
return idx === -1 ? DEFAULT_WORKOUT_SOURCE_PRIORITY.length : idx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparator: returns negative when `a` should win over `b`.
|
||||
* Priority order: source rank → higher calories → earliest
|
||||
* createdAt → earliest input index.
|
||||
*/
|
||||
function compareCandidates<T extends WorkoutRow>(a: T, b: T): number {
|
||||
const sourceDelta = sourceRank(a.source) - sourceRank(b.source);
|
||||
if (sourceDelta !== 0) return sourceDelta;
|
||||
|
||||
// Tie-breaker 1 — higher caloriesKcal wins (more sensor data).
|
||||
// `null` / `undefined` calories sort below any numeric value.
|
||||
const aCal = a.caloriesKcal ?? -1;
|
||||
const bCal = b.caloriesKcal ?? -1;
|
||||
if (aCal !== bCal) return bCal - aCal;
|
||||
|
||||
// Tie-breaker 2 — earliest `createdAt` wins (stable across
|
||||
// re-runs). Undefined sorts below any concrete date so a
|
||||
// pre-insert row (no createdAt yet) doesn't beat an already-
|
||||
// persisted row carrying a real timestamp.
|
||||
const aCreated = a.createdAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
||||
const bCreated = b.createdAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
||||
if (aCreated !== bCreated) return aCreated - bCreated;
|
||||
|
||||
// Tie-breaker 3 — input order. Guarantees determinism even when
|
||||
// every other field ties (rare; same source, same calories,
|
||||
// same / no createdAt). Default of 0 keeps single-row groups
|
||||
// untouched.
|
||||
return (a.index ?? 0) - (b.index ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick canonical rows across sources for an inbound ingest batch.
|
||||
*
|
||||
* Group by `(userId, activityType, startedAt ± 90 s)`; within each
|
||||
* group the comparator selects one survivor (the rest drop). No
|
||||
* cross-source overlap → the row passes through. The returned
|
||||
* array preserves the input order of the surviving rows so a
|
||||
* caller that pre-sorted by `startedAt ASC` keeps that ordering
|
||||
* downstream.
|
||||
*
|
||||
* Implementation walks the input once with a union-find-style
|
||||
* pass: each row joins an existing group whose anchor falls
|
||||
* within the dedup window AND matches `(userId, activityType)`,
|
||||
* or seeds a new group. The anchor is the FIRST row that landed
|
||||
* in the group; subsequent rows compare against the anchor so the
|
||||
* window can't drift across an arbitrarily long chain of
|
||||
* within-window-of-neighbour rows. This is O(n²) worst case but
|
||||
* a typical batch is ≤ 100 entries so the constant is fine.
|
||||
*/
|
||||
export function dedupeWorkoutBatch<T extends WorkoutRow>(
|
||||
rows: readonly T[],
|
||||
): T[] {
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
// Stamp each input with its original index so the comparator
|
||||
// has a stable tie-breaker without mutating the caller's row.
|
||||
type Tagged = { row: T; origIndex: number };
|
||||
const tagged: Tagged[] = rows.map((row, origIndex) => ({ row, origIndex }));
|
||||
|
||||
// Group anchors: each group is a list of (row, origIndex). The
|
||||
// anchor row sets the window comparison reference.
|
||||
const groups: Tagged[][] = [];
|
||||
|
||||
for (const entry of tagged) {
|
||||
let placed = false;
|
||||
for (const group of groups) {
|
||||
const anchor = group[0]!.row;
|
||||
if (
|
||||
anchor.userId === entry.row.userId &&
|
||||
anchor.activityType === entry.row.activityType &&
|
||||
Math.abs(anchor.startedAt.getTime() - entry.row.startedAt.getTime()) <=
|
||||
WORKOUT_DEDUP_WINDOW_MS
|
||||
) {
|
||||
group.push(entry);
|
||||
placed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!placed) {
|
||||
groups.push([entry]);
|
||||
}
|
||||
}
|
||||
|
||||
// Pick one survivor per group, then re-emit in original input
|
||||
// order. The comparator sees `index` via the original input
|
||||
// ordinal (overrides any caller-supplied `index` so the helper
|
||||
// is self-contained — but a caller who set `index` explicitly
|
||||
// still wins because we layer the explicit value on top below).
|
||||
const survivors: Tagged[] = [];
|
||||
for (const group of groups) {
|
||||
if (group.length === 1) {
|
||||
survivors.push(group[0]!);
|
||||
continue;
|
||||
}
|
||||
// Annotate each member with its origIndex as the row's `index`
|
||||
// for the comparator, but only when the caller didn't already
|
||||
// set one. Caller-supplied indices outrank insertion order so
|
||||
// a deliberate "I want this row first" hint survives.
|
||||
const annotated = group.map((entry) => ({
|
||||
...entry,
|
||||
row: {
|
||||
...entry.row,
|
||||
index: entry.row.index ?? entry.origIndex,
|
||||
} as T,
|
||||
}));
|
||||
annotated.sort((a, b) => compareCandidates(a.row, b.row));
|
||||
// Preserve the picker's input-order survival by remembering the
|
||||
// ORIGINAL row reference (not the annotated copy) so the caller
|
||||
// gets back exactly what it passed in.
|
||||
const winner = annotated[0]!;
|
||||
const original = group.find((g) => g.origIndex === winner.origIndex)!;
|
||||
survivors.push(original);
|
||||
}
|
||||
|
||||
survivors.sort((a, b) => a.origIndex - b.origIndex);
|
||||
return survivors.map((entry) => entry.row);
|
||||
}
|
||||
Reference in new issue
Block a user