mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
Merge remote-tracking branch 'origin/work/parity-coherence' into release/v1.30.34
This commit is contained in:
commit
4c65949bac
21 files changed
+601
-61
No files matched your search
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* Copy-matches-behaviour guard.
|
||||
*
|
||||
* Three classes of copy that drifted away from the code they describe, each
|
||||
* pinned here so the pair fails loudly if either half moves again:
|
||||
*
|
||||
* 1. DELETE CONFIRMATIONS. A confirmation is the moment a user weighs the
|
||||
* consequence. Four dialogs promised permanence on surfaces that render
|
||||
* an Undo affordance (measurements bulk, mood bulk, labs, illness) — a
|
||||
* cautious user declines a safe delete, and the warning loses weight
|
||||
* where it is true. This test pins both directions: undo-able surfaces
|
||||
* must offer the undo sentence and must NOT claim finality; the
|
||||
* genuinely permanent ones must keep their warning.
|
||||
*
|
||||
* 2. SLEEP DEBT. v1.19.0 replaced the summed shortfall with a running
|
||||
* balance that credits surplus sleep. The labels still described the old
|
||||
* arithmetic, so the word contradicted the number for anyone who caught
|
||||
* up after a short night.
|
||||
*
|
||||
* 3. GLUCOSE REFERENCE BAND. The declared diabetes opt-in has a server
|
||||
* preference and a route; the copy for its web control must exist in
|
||||
* every locale, since a missing key silently degrades to the raw key on
|
||||
* a surface that makes a clinical-adjacent claim.
|
||||
*
|
||||
* Reversibility evidence for the undo-able set:
|
||||
* - measurements: `POST /api/measurements/restore`, undo toast in
|
||||
* `src/components/measurements/measurement-list.tsx`
|
||||
* - mood: `POST /api/mood-entries/restore`, undo toast in
|
||||
* `src/components/mood/mood-list.tsx`
|
||||
* - labs: `POST /api/labs/restore`, undo toast in
|
||||
* `src/components/labs/lab-history-list.tsx`
|
||||
* - illness: `POST /api/illness/episodes/[id]/restore`, undo toast in
|
||||
* `src/components/illness/episode-menu.tsx`
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const MESSAGES = join(__dirname, "../../messages");
|
||||
const LOCALES = ["de", "en", "es", "fr", "it", "pl"] as const;
|
||||
|
||||
function bundle(locale: string): Record<string, unknown> {
|
||||
return JSON.parse(readFileSync(join(MESSAGES, `${locale}.json`), "utf8"));
|
||||
}
|
||||
|
||||
function resolve(obj: Record<string, unknown>, path: string): string {
|
||||
let cur: unknown = obj;
|
||||
for (const seg of path.split(".")) {
|
||||
expect(cur, `${path} is missing at "${seg}"`).toBeTypeOf("object");
|
||||
cur = (cur as Record<string, unknown>)[seg];
|
||||
}
|
||||
expect(typeof cur, `${path} must resolve to a string`).toBe("string");
|
||||
return cur as string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-locale phrases that assert a deletion cannot be taken back. A dialog on
|
||||
* an undo-able surface must contain none of these.
|
||||
*/
|
||||
const FINALITY_PHRASES: Record<string, readonly string[]> = {
|
||||
en: ["cannot be undone", "can't be undone", "permanently", "permanent"],
|
||||
de: ["nicht rückgängig", "endgültig", "dauerhaft", "unwiderruflich"],
|
||||
es: ["no se puede deshacer", "permanente", "irreversible"],
|
||||
fr: [
|
||||
"irréversible",
|
||||
"définitivement",
|
||||
"définitive",
|
||||
"ne peut pas être annulé",
|
||||
],
|
||||
it: [
|
||||
"non può essere annullata",
|
||||
"definitivamente",
|
||||
"definitiva",
|
||||
"permanente",
|
||||
],
|
||||
pl: ["nie można cofnąć", "trwale", "nieodwracaln"],
|
||||
};
|
||||
|
||||
/** Per-locale phrase that promises the short undo window. */
|
||||
const UNDO_PHRASES: Record<string, string> = {
|
||||
en: "undo",
|
||||
de: "rückgängig",
|
||||
es: "deshacerlo",
|
||||
fr: "annuler cette action",
|
||||
it: "annullare",
|
||||
pl: "cofnąć",
|
||||
};
|
||||
|
||||
/** Confirmation bodies whose surface renders an Undo affordance. */
|
||||
const UNDOABLE_CONFIRM_KEYS = [
|
||||
"measurements.deleteConfirmDescription",
|
||||
"measurements.bulkDeleteConfirmBody",
|
||||
"mood.deleteConfirmDescription",
|
||||
"mood.bulkDeleteConfirmBody",
|
||||
"labs.deleteConfirmDescription",
|
||||
"illness.deleteConfirm.body",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Confirmation bodies whose delete really is unrecoverable for the user —
|
||||
* hard delete or a tombstone with no restore path. These MUST keep a
|
||||
* finality warning; softening them would be the mirror-image bug.
|
||||
*/
|
||||
const PERMANENT_CONFIRM_KEYS = [
|
||||
// hard delete + cascade of every recorded value
|
||||
"labs.biomarker.deleteConfirmDescription",
|
||||
// `?purge=true` hard-deletes the tag off every past entry
|
||||
"mood.manage.purgeBody",
|
||||
// GDPR Art. 17 account purge
|
||||
"settings.deleteAccountConfirmDescription",
|
||||
] as const;
|
||||
|
||||
describe("delete confirmations describe what the surface actually does", () => {
|
||||
for (const locale of LOCALES) {
|
||||
const msgs = bundle(locale);
|
||||
|
||||
describe(locale, () => {
|
||||
for (const key of UNDOABLE_CONFIRM_KEYS) {
|
||||
it(`${key} offers undo and claims no finality`, () => {
|
||||
const copy = resolve(msgs, key).toLowerCase();
|
||||
|
||||
for (const phrase of FINALITY_PHRASES[locale]) {
|
||||
expect(
|
||||
copy,
|
||||
`${locale}/${key} claims finality ("${phrase}") but the surface renders an Undo`,
|
||||
).not.toContain(phrase.toLowerCase());
|
||||
}
|
||||
|
||||
expect(
|
||||
copy,
|
||||
`${locale}/${key} should tell the user the delete can be undone`,
|
||||
).toContain(UNDO_PHRASES[locale].toLowerCase());
|
||||
});
|
||||
}
|
||||
|
||||
for (const key of PERMANENT_CONFIRM_KEYS) {
|
||||
it(`${key} keeps its finality warning`, () => {
|
||||
const copy = resolve(msgs, key).toLowerCase();
|
||||
const warns = FINALITY_PHRASES[locale].some((p) =>
|
||||
copy.includes(p.toLowerCase()),
|
||||
);
|
||||
expect(
|
||||
warns,
|
||||
`${locale}/${key} deletes irrecoverably — the copy must say so`,
|
||||
).toBe(true);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("sleep debt is labelled as a balance, not a summed deficit", () => {
|
||||
/**
|
||||
* The figure is a running balance: a short night adds, a long night pays it
|
||||
* down. Deficit/shortfall vocabulary describes the pre-v1.19.0 sum.
|
||||
*/
|
||||
const STALE_SUM_VOCABULARY: Record<string, readonly string[]> = {
|
||||
en: ["cumulative", "shortfall", "accumulated"],
|
||||
de: ["kumuliert", "defizit", "aufgelaufen"],
|
||||
es: ["acumulado", "acumulada", "déficit"],
|
||||
fr: ["cumulé", "cumulée", "déficit"],
|
||||
it: ["cumulato", "cumulata", "accumulato", "deficit"],
|
||||
pl: ["skumulowan", "niedobór", "niedoboru"],
|
||||
};
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
const msgs = bundle(locale);
|
||||
|
||||
it(`${locale} debt captions carry no summed-deficit wording`, () => {
|
||||
for (const key of [
|
||||
"insights.sleep.debt.caption",
|
||||
"insights.sleep.debt.clearCaption",
|
||||
]) {
|
||||
const copy = resolve(msgs, key).toLowerCase();
|
||||
for (const term of STALE_SUM_VOCABULARY[locale]) {
|
||||
expect(
|
||||
copy,
|
||||
`${locale}/${key} still describes the pre-v1.19.0 summed shortfall ("${term}")`,
|
||||
).not.toContain(term);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("the explainer states that catch-up sleep pays the balance down", () => {
|
||||
const copy = resolve(bundle("en"), "insights.sleep.debt.computedInfo");
|
||||
expect(copy.toLowerCase()).toContain("balance");
|
||||
expect(copy.toLowerCase()).toContain("catch-up");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the glucose reference band control is translated everywhere", () => {
|
||||
const KEYS = [
|
||||
"settings.glucoseReference.title",
|
||||
"settings.glucoseReference.description",
|
||||
"settings.glucoseReference.enable",
|
||||
"settings.glucoseReference.explainer",
|
||||
"settings.glucoseReference.disclaimer",
|
||||
"settings.glucoseReference.error",
|
||||
] as const;
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
it(`${locale} carries every key`, () => {
|
||||
const msgs = bundle(locale);
|
||||
for (const key of KEYS) {
|
||||
expect(resolve(msgs, key).length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("the disclaimer refuses the diagnosis reading (EN)", () => {
|
||||
const copy = resolve(
|
||||
bundle("en"),
|
||||
"settings.glucoseReference.disclaimer",
|
||||
).toLowerCase();
|
||||
expect(copy).toContain("not a diagnosis");
|
||||
expect(copy).toContain("never inferred");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* `GET /api/auth/passkeys` — the passkey management list.
|
||||
*
|
||||
* The management UI renders a "last used" column per credential, and a
|
||||
* passkey that reads "never used" is something a person acts on: they may
|
||||
* delete a working credential believing it is dead. So the field is part of
|
||||
* the route's contract, not an incidental select — dropping it from the
|
||||
* projection would silently turn every row into "never used" without any
|
||||
* type or lint failure.
|
||||
*
|
||||
* The write half (the stamp on a verified assertion) is pinned in
|
||||
* `src/lib/auth/__tests__/passkey.test.ts`.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: (fn: unknown) => fn,
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { passkey: { findMany: vi.fn() } },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { requireAuth } from "@/lib/api-handler";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const USER = { id: "user-1", username: "u", email: "u@example.com" };
|
||||
|
||||
const ROW = {
|
||||
id: "pk-1",
|
||||
name: "Phone",
|
||||
credentialDeviceType: "multiDevice",
|
||||
credentialBackedUp: true,
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
lastUsedAt: new Date("2026-07-01T10:00:00Z"),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(requireAuth).mockResolvedValue({ user: USER } as never);
|
||||
vi.mocked(prisma.passkey.findMany).mockResolvedValue([ROW] as never);
|
||||
});
|
||||
|
||||
describe("GET /api/auth/passkeys", () => {
|
||||
it("selects lastUsedAt, scoped to the calling user", async () => {
|
||||
await (GET as unknown as () => Promise<Response>)();
|
||||
|
||||
expect(prisma.passkey.findMany).toHaveBeenCalledTimes(1);
|
||||
const args = vi.mocked(prisma.passkey.findMany).mock.calls[0][0];
|
||||
|
||||
expect(args?.where).toEqual({ userId: USER.id });
|
||||
expect(args?.select).toMatchObject({ lastUsedAt: true });
|
||||
});
|
||||
|
||||
it("emits lastUsedAt in the response envelope", async () => {
|
||||
const res = await (GET as unknown as () => Promise<Response>)();
|
||||
const body = await res.json();
|
||||
|
||||
expect(body.error).toBeNull();
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0]).toHaveProperty("lastUsedAt");
|
||||
expect(new Date(body.data[0].lastUsedAt).toISOString()).toBe(
|
||||
"2026-07-01T10:00:00.000Z",
|
||||
);
|
||||
});
|
||||
|
||||
it("passes a never-used credential through as null, not as a missing key", async () => {
|
||||
vi.mocked(prisma.passkey.findMany).mockResolvedValue([
|
||||
{ ...ROW, lastUsedAt: null },
|
||||
] as never);
|
||||
|
||||
const res = await (GET as unknown as () => Promise<Response>)();
|
||||
const body = await res.json();
|
||||
|
||||
expect(Object.keys(body.data[0])).toContain("lastUsedAt");
|
||||
expect(body.data[0].lastUsedAt).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,8 @@
|
||||
* signals the Sleep page + the iOS client render off the SAME canonical night
|
||||
* reconstruction the Sleep Score uses:
|
||||
*
|
||||
* - `sleepDebt` — cumulative deficit over the rolling window, with a calm
|
||||
* - `sleepDebt` — outstanding balance over the rolling window (surplus
|
||||
* sleep pays it down), with a calm
|
||||
* `partial` state under the night threshold.
|
||||
* - `chronotype` — MCTQ MSF / MSFsc band + social jetlag, with a `learning`
|
||||
* state until enough free-day nights exist.
|
||||
|
||||
@@ -22,8 +22,11 @@ function hoursMinutes(totalMinutes: number): {
|
||||
/**
|
||||
* v1.17.0 — sleep-debt headline.
|
||||
*
|
||||
* The cumulative shortfall between sleep need and sleep obtained over the
|
||||
* rolling window. Under the night threshold it shows the calm `partial`
|
||||
* The outstanding balance between sleep need and sleep obtained over the
|
||||
* rolling window — a night below need adds to it, a night above need pays it
|
||||
* down (v1.19.0 replaced the summed shortfall with this running balance; the
|
||||
* copy follows the arithmetic). Under the night threshold it shows the calm
|
||||
* `partial`
|
||||
* state ("still learning — N more nights") and never asserts a total off thin
|
||||
* data. Mobile-first: a single readable figure + one line of grounded context.
|
||||
*/
|
||||
|
||||
@@ -267,6 +267,21 @@ describe("settings sections — SSR smoke", () => {
|
||||
expect(html).not.toContain("settings.sections.thresholds.");
|
||||
});
|
||||
|
||||
it("<ThresholdsSection> carries the glucose reference band control", () => {
|
||||
// The declared diabetes opt-in (`PATCH /api/auth/me/diabetes`) selects the
|
||||
// tighter glucose band and grounds the Coach, but shipped with no web
|
||||
// control at all — a web-only account could never reach it. It belongs on
|
||||
// Targets: same question ("which range judges my reading") as the editor
|
||||
// below it, and the copy must stay honest about being a reference band
|
||||
// rather than a diagnosis.
|
||||
const html = renderFramed("thresholds", <ThresholdsSection />);
|
||||
expect(html).toContain("Glucose reference band");
|
||||
expect(html).toContain("Use the diabetes goal band");
|
||||
expect(html).toContain("not a diagnosis");
|
||||
expect(html).toContain('data-slot="glucose-reference-disclaimer"');
|
||||
expect(html).not.toContain("settings.glucoseReference.");
|
||||
});
|
||||
|
||||
it("<ThresholdsSection> resolves the German title", () => {
|
||||
const html = renderFramed("thresholds", <ThresholdsSection />, "de");
|
||||
// v1.8.7.1 — German title is "Zielwerte" (Targets only).
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Droplet, Info } from "lucide-react";
|
||||
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { SettingsCard } from "@/components/settings/settings-card";
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { apiGet, apiPatch } from "@/lib/api/api-fetch";
|
||||
|
||||
/**
|
||||
* Glucose reference band — the web control for the declared diabetes opt-in
|
||||
* (`GET/PATCH /api/auth/me/diabetes`).
|
||||
*
|
||||
* WHY IT LIVES ON TARGETS
|
||||
* -----------------------
|
||||
* The flag answers exactly the question this page answers — "which range is my
|
||||
* reading judged against" — and the page already owns the four glucose target
|
||||
* rows. Putting it anywhere else would split one concept across two surfaces.
|
||||
* The card sits ABOVE the per-metric editor because the two controls are
|
||||
* ordered: this one picks the default band, a per-metric override below then
|
||||
* beats it (`src/lib/targets/glucose-targets.ts`).
|
||||
*
|
||||
* WHAT IT DOES NOT DO
|
||||
* -------------------
|
||||
* The flag is a display preference, never a diagnosis, and is never inferred
|
||||
* from a reading. It selects the band the glucose surfaces and the Coach's
|
||||
* reference grounding read; the app takes no clinical action on it. The copy
|
||||
* says so at the point of the switch rather than in a help page.
|
||||
*
|
||||
* Note: `GET /api/user/thresholds` (the editor below) reports the general
|
||||
* bands regardless of this flag — the flag resolves in the targets pipeline
|
||||
* (`src/lib/targets/build-response.ts`), which is why the mutation invalidates
|
||||
* `insightsTargets()` rather than `userThresholds()`.
|
||||
*/
|
||||
|
||||
interface DiabetesPrefShape {
|
||||
hasDiabetes: boolean;
|
||||
}
|
||||
|
||||
export function GlucoseReferenceCard() {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: queryKeys.diabetesPref(),
|
||||
queryFn: async () => apiGet<DiabetesPrefShape>("/api/auth/me/diabetes"),
|
||||
});
|
||||
|
||||
const toggle = useMutation({
|
||||
mutationFn: async (hasDiabetes: boolean) =>
|
||||
apiPatch<DiabetesPrefShape>("/api/auth/me/diabetes", { hasDiabetes }),
|
||||
onSuccess: (next) => {
|
||||
queryClient.setQueryData(queryKeys.diabetesPref(), next);
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.insightsTargets(),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const enabled = data?.hasDiabetes ?? false;
|
||||
|
||||
return (
|
||||
<SettingsCard>
|
||||
<SettingsCardHeader
|
||||
icon={Droplet}
|
||||
title={t("settings.glucoseReference.title")}
|
||||
description={t("settings.glucoseReference.description")}
|
||||
/>
|
||||
<div className="mt-4 space-y-4 pl-7">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<Label htmlFor="glucose-reference-diabetes" className="text-sm">
|
||||
{t("settings.glucoseReference.enable")}
|
||||
</Label>
|
||||
<Switch
|
||||
id="glucose-reference-diabetes"
|
||||
checked={enabled}
|
||||
disabled={toggle.isPending || data == null}
|
||||
onCheckedChange={(v) => toggle.mutate(v)}
|
||||
className="mt-0.5 shrink-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-sm">{t("settings.glucoseReference.explainer")}</p>
|
||||
|
||||
<div
|
||||
data-slot="glucose-reference-disclaimer"
|
||||
className="border-border bg-muted/40 flex items-start gap-2.5 rounded-lg border-l-2 p-3"
|
||||
>
|
||||
<Info
|
||||
className="text-muted-foreground mt-0.5 h-4 w-4 shrink-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<p className="text-foreground/80 text-xs leading-relaxed">
|
||||
{t("settings.glucoseReference.disclaimer")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{toggle.isError ? (
|
||||
<p className="text-destructive text-sm" role="alert">
|
||||
{t("settings.glucoseReference.error")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { GlucoseReferenceCard } from "@/components/settings/glucose-reference-card";
|
||||
import { ThresholdsEditorSection } from "@/components/settings/thresholds-editor-section";
|
||||
|
||||
/**
|
||||
@@ -31,6 +32,14 @@ import { ThresholdsEditorSection } from "@/components/settings/thresholds-editor
|
||||
* the names stop clashing.
|
||||
*/
|
||||
export function ThresholdsSection() {
|
||||
// Per-metric threshold ranges; the heading is supplied by the route frame.
|
||||
return <ThresholdsEditorSection id="thresholds" />;
|
||||
// The glucose reference band sits ABOVE the per-metric editor: it picks the
|
||||
// DEFAULT band a glucose reading is judged against, and a per-metric
|
||||
// override in the editor below then beats it. Same question, one page —
|
||||
// splitting the two across surfaces would hide the precedence.
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<GlucoseReferenceCard />
|
||||
<ThresholdsEditorSection id="thresholds" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -202,7 +202,7 @@ describe("getCoachSystemPrompt — DE", () => {
|
||||
// German coach can cite glucose + duration values with a valid token.
|
||||
expect(prompt).toMatch(/mg\/dL/);
|
||||
expect(prompt).toMatch(/mmol\/L/);
|
||||
expect(prompt).toMatch(/min[\s\S]*\(Schlafdefizit/);
|
||||
expect(prompt).toMatch(/min[\s\S]*\(Schlafschuld/);
|
||||
});
|
||||
|
||||
it("carries the v1.21.2 narrative-presence clauses (A4/A5/A6/A7)", () => {
|
||||
|
||||
@@ -157,7 +157,7 @@ interface SleepRhythmBlockContext {
|
||||
* ── v1.17.0 sleep-rhythm block (sleep-debt + chronotype) ──────────
|
||||
*
|
||||
* The two server-authoritative timing signals the Sleep page + the
|
||||
* dashboard summary render — cumulative sleep debt and the MCTQ
|
||||
* dashboard summary render — the outstanding sleep-debt balance and the MCTQ
|
||||
* chronotype band + social jetlag. Built from the SAME assembler the
|
||||
* dashboard route uses (`reconstructNights` → `computeSleepRhythmFromNights`),
|
||||
* over the rhythm's OWN fixed trailing-42-day rows, so the coach quotes the
|
||||
|
||||
@@ -361,8 +361,9 @@ ISO-week means.
|
||||
timing signals — the SAME values the Sleep page and dashboard show, so
|
||||
cite them as the user sees them and never recompute. It holds:
|
||||
- "sleepDebt": { state, debtMinutes, needMinutes }. "debtMinutes" is
|
||||
the cumulative deficit against the age-based nightly need over the
|
||||
trailing window, "needMinutes" the target per night — both in
|
||||
the OUTSTANDING BALANCE against the age-based nightly need over the
|
||||
trailing window — a short night adds to it, a long night pays it
|
||||
down, and it floors at 0 — "needMinutes" the target per night — both in
|
||||
MINUTES (convert to hours/minutes when you speak, e.g. 320 → "5h
|
||||
20m of sleep debt"). When "state" is "partial" the window is still
|
||||
short: treat the figure as still calibrating, not a firm number.
|
||||
@@ -980,7 +981,7 @@ Regeln:
|
||||
- "value" ist ein vorformatierter Anzeigestring ("138/85", "84,2",
|
||||
"4,1"). Stimmung als N/5 formatieren, wenn numerisch.
|
||||
- "unit" ist eines aus mmHg, kg, bpm, /5, %, mg/dL, mmol/L, min
|
||||
(Schlafdefizit / sozialer Jetlag).
|
||||
(Schlafschuld / sozialer Jetlag).
|
||||
- "window" ist eines aus last7days, last30days, last90days, allTime;
|
||||
bei Tages-Pins weglassen.
|
||||
- Lass den ganzen Block weg (KEINE ---KEYVALUES---Zeile, KEINE
|
||||
|
||||
@@ -137,3 +137,43 @@ describe("verifyAuthentication — Zod boundary (L-3)", () => {
|
||||
expect(out.verification.verified).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* "Last used" is a security-page fact people act on: a passkey that reads
|
||||
* "never used" invites deletion. The column is only ever written here, on a
|
||||
* verified assertion, so the stamp and the counter bump must stay one write.
|
||||
* The read half is pinned in
|
||||
* `src/app/api/auth/passkeys/__tests__/route.test.ts`.
|
||||
*/
|
||||
describe("verifyAuthentication — last-used stamp", () => {
|
||||
// The file-level `beforeEach` re-arms the mocks but does not clear their
|
||||
// call history, so the write assertions below need a clean ledger.
|
||||
beforeEach(() => {
|
||||
vi.mocked(prisma.passkey.update).mockClear();
|
||||
});
|
||||
|
||||
it("stamps lastUsedAt alongside the counter on a verified assertion", async () => {
|
||||
const before = Date.now();
|
||||
await verifyAuthentication("ch-1", VALID_BODY);
|
||||
|
||||
expect(prisma.passkey.update).toHaveBeenCalledTimes(1);
|
||||
const call = vi.mocked(prisma.passkey.update).mock.calls[0][0];
|
||||
|
||||
expect(call.where).toEqual({ id: "pk-1" });
|
||||
expect(call.data?.counter).toBe(BigInt(1));
|
||||
|
||||
const stamped = call.data?.lastUsedAt;
|
||||
expect(stamped).toBeInstanceOf(Date);
|
||||
expect((stamped as Date).getTime()).toBeGreaterThanOrEqual(before);
|
||||
});
|
||||
|
||||
it("does not stamp lastUsedAt when the assertion fails", async () => {
|
||||
vi.mocked(verifyAuthenticationResponse).mockResolvedValue({
|
||||
verified: false,
|
||||
} as never);
|
||||
|
||||
await verifyAuthentication("ch-1", VALID_BODY);
|
||||
|
||||
expect(prisma.passkey.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
* The one place that turns a user's raw `SLEEP_DURATION` rows into the two
|
||||
* timing signals the Sleep page + the iOS client + the dashboard render:
|
||||
*
|
||||
* - cumulative SLEEP DEBT over the rolling window (`computeSleepDebt`), and
|
||||
* - the outstanding SLEEP DEBT balance over the rolling window
|
||||
* (`computeSleepDebt`; surplus sleep pays it down), and
|
||||
* - MCTQ CHRONOTYPE + social jetlag (`computeChronotype`).
|
||||
*
|
||||
* ONE ENGINE, NO DUPLICATION
|
||||
|
||||
@@ -417,13 +417,15 @@ const sleepDebtResource = z.object({
|
||||
state: z
|
||||
.enum(["partial", "ready"])
|
||||
.describe(
|
||||
"`partial` until enough tracked nights exist (calm 'still learning'); `ready` once the rolling window can assert a cumulative debt.",
|
||||
"`partial` until enough tracked nights exist (calm 'still learning'); `ready` once the rolling window can assert a balance.",
|
||||
),
|
||||
debtMinutes: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.describe("Cumulative sleep debt over the window, in minutes, after caps."),
|
||||
.describe(
|
||||
"Outstanding sleep-debt balance over the window, in minutes, after caps. A night below need adds its shortfall; a night above need pays the balance down (floored at 0).",
|
||||
),
|
||||
needMinutes: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -513,7 +515,7 @@ const sleepRhythmResponse = z
|
||||
.meta({
|
||||
id: "SleepRhythmResource",
|
||||
description:
|
||||
"Server-authoritative sleep-rhythm read: cumulative sleep debt over the rolling window + MCTQ chronotype (MSF/MSFsc band, social jetlag). Free vs work nights default to weekend = free in the user's timezone (no work calendar). A view over existing per-stage SLEEP_DURATION rows — no schema, no new type.",
|
||||
"Server-authoritative sleep-rhythm read: the outstanding sleep-debt balance over the rolling window + MCTQ chronotype (MSF/MSFsc band, social jetlag). Free vs work nights default to weekend = free in the user's timezone (no work calendar). A view over existing per-stage SLEEP_DURATION rows — no schema, no new type.",
|
||||
});
|
||||
|
||||
// ── Time-series adapter (iOS chart source) ───────────────────────────
|
||||
@@ -1004,7 +1006,7 @@ export const measurementPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Measurements"],
|
||||
summary: "Sleep rhythm — sleep-debt + chronotype (v1.17.0)",
|
||||
description:
|
||||
"Returns the two server-authoritative sleep-timing signals the Sleep page + iOS render off the same canonical night reconstruction the Sleep Score uses: cumulative `sleepDebt` over the rolling window (calm `partial` state under the night threshold) and MCTQ `chronotype` (MSF/MSFsc band + social jetlag, `learning` state until enough free-day nights exist). Free vs work nights default to weekend = free in the user's timezone (no work calendar). A read-only view over existing per-stage SLEEP_DURATION rows — no schema, no new measurement type.",
|
||||
"Returns the two server-authoritative sleep-timing signals the Sleep page + iOS render off the same canonical night reconstruction the Sleep Score uses: the outstanding `sleepDebt` balance over the rolling window (calm `partial` state under the night threshold) and MCTQ `chronotype` (MSF/MSFsc band + social jetlag, `learning` state until enough free-day nights exist). Free vs work nights default to weekend = free in the user's timezone (no work calendar). A read-only view over existing per-stage SLEEP_DURATION rows — no schema, no new measurement type.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Sleep-debt + chronotype DTO.",
|
||||
|
||||
@@ -21,6 +21,14 @@ export const settingsKeys = {
|
||||
/** v1.8.5 — user-level injection-site preferences (global exclusion). */
|
||||
injectionSitePrefs: () => ["settings", "injection-site-prefs"] as const,
|
||||
|
||||
/**
|
||||
* The declared diabetes opt-in behind `GET/PATCH /api/auth/me/diabetes`.
|
||||
* Selects which reference band glucose readings are judged against, so the
|
||||
* toggle also invalidates `insightsTargets()` — the resolved band rides
|
||||
* on that payload.
|
||||
*/
|
||||
diabetesPref: () => ["settings", "diabetes"] as const,
|
||||
|
||||
/**
|
||||
* v1.18.0 — the per-user module enable/disable map behind
|
||||
* `GET/PATCH /api/auth/me/modules`. Used as the Module-hub mutation key;
|
||||
|
||||
Reference in new issue
Block a user