Publish the resolved cycle verdict instead of letting each client work it out

The cycle ring's day count, its phase arcs, and the judgement that a period
is late all used to be worked out in web client code, including the
fourteen-day grace window that decides when the count stops being an
observed fact. Anything else that wanted the same answer had to reproduce
that rule, and a second copy of it is how a ring ends up showing someone a
cycle day their record does not hold.

GET /api/cycle/calendar now carries a verdict: the state, the cycle day,
the ring's arcs, the cycle start, how many days until the next period, and
when the period is late, how late. It is resolved against the user's own
timezone day, which a browser in another zone cannot do. The web wheel,
the wellness-strip tile, the insights teaser and the temperature chart all
render it, the grace constant is gone from the components directory, and
the spec says the field is required.

The overdue caption now names the number of days instead of only saying
later than usual.
This commit is contained in:
Marc-André Bombeck committed 2026-08-01 10:37:18 +02:00
1 parent 6c87c96fa6
commit dbecbbcbdb
21 files changed
+702 -554

No files matched your search

@@ -41,6 +41,7 @@ describe("<BbtChart>", () => {
<BbtChart
days={days}
today={today}
cycleStartDate="2026-06-01"
predictedOvulation={null}
rawChartMode={false}
/>,
@@ -60,6 +61,7 @@ describe("<BbtChart>", () => {
<BbtChart
days={days}
today={today}
cycleStartDate="2026-06-01"
predictedOvulation="2026-06-08"
rawChartMode={false}
/>,
@@ -25,7 +25,7 @@ vi.mock("@/hooks/use-unit-display", async () => {
});
import { I18nProvider } from "@/lib/i18n/context";
import type { CalendarResponse } from "../types";
import type { CalendarResponse, CycleVerdict } from "../types";
import type { CycleInsightsResponse } from "../use-cycle";
import type { CyclePhaseCrosstabRow } from "../cycle-phase-crosstab";
@@ -80,8 +80,6 @@ vi.mock("../use-cycle", async () => {
...actual,
useCycleCalendar: () => calendarState.current,
useCycleInsights: () => insightsState.current,
// The card now reads the profile lengths for the low-data idealized ring.
useCycleProfile: () => ({ data: undefined }),
};
});
@@ -93,9 +91,39 @@ function render(node: React.ReactNode) {
);
}
/** Build a calendar read where `today` sits on a LUTEAL day at day-of-cycle 3
* (a short MENSTRUAL run → LUTEAL today, so `deriveWheelState` resolves a
* phase + day). */
/** The verdict the server would resolve for that grid: LUTEAL, cycle day 3. */
const LUTEAL_VERDICT: CycleVerdict = {
state: "IN_CYCLE",
dayOfCycle: 3,
cycleLength: 28,
phase: "LUTEAL",
spans: [
{ phase: "MENSTRUAL", fraction: 5 / 28 },
{ phase: "FOLLICULAR", fraction: 7 / 28 },
{ phase: "OVULATORY", fraction: 2 / 28 },
{ phase: "LUTEAL", fraction: 14 / 28 },
],
cycleStartDate: null,
overdueDays: null,
daysUntilNext: null,
fertileWindow: { start: null, end: null, active: false },
};
/** The verdict for an account with nothing to say about today. */
const NO_CYCLE_VERDICT: CycleVerdict = {
state: "INSUFFICIENT_DATA",
dayOfCycle: null,
cycleLength: null,
phase: null,
spans: [],
cycleStartDate: null,
overdueDays: null,
daysUntilNext: null,
fertileWindow: { start: null, end: null, active: false },
};
/** A calendar read whose SERVER-RESOLVED verdict puts today on LUTEAL, day 3.
* The card renders the verdict; it no longer derives anything from `days`. */
function lutealCalendar(today: string): CalendarResponse {
// Three consecutive days ending today: MENSTRUAL, FOLLICULAR, LUTEAL.
const days = [
@@ -107,6 +135,7 @@ function lutealCalendar(today: string): CalendarResponse {
days: days as unknown as CalendarResponse["days"],
profile: {} as CalendarResponse["profile"],
prediction: null,
verdict: LUTEAL_VERDICT,
} as CalendarResponse;
}
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import type { CalendarResponse } from "../types";
import type { CalendarResponse, CycleVerdict } from "../types";
/**
* v1.15.3 — the compact cycle ring as a wellness-strip tile.
@@ -10,7 +10,7 @@ import type { CalendarResponse } from "../types";
* The tile is mounted ONLY when `user.cycleTrackingEnabled` is true (a
* page-level gate the Insights page owns, mirroring the summary card); these
* tests cover the tile's own behaviour given that gate: it sources the phase +
* cycle day from the SAME calendar read + `deriveWheelState` the wheel uses,
* cycle day from the SAME server-resolved `verdict` the wheel reads,
* renders the cycle ring labelled, deep-links to the cycle page, and stays
* silent while resolving / on a hard error / when there is no active cycle so
* the wellness strip never shows a half-painted dial (no gap, no placeholder).
@@ -49,9 +49,6 @@ vi.mock("../use-cycle", async () => {
return {
...actual,
useCycleCalendar: () => calendarState.current,
// The tile now reads the profile lengths for the low-data idealized ring.
// Mock it at the hook boundary too so the SSR snapshot needs no QueryClient.
useCycleProfile: () => ({ data: undefined }),
};
});
@@ -63,7 +60,38 @@ function render(node: React.ReactNode) {
);
}
/** A calendar read where `today` sits on a LUTEAL day at day-of-cycle 3. */
/** The verdict the server would resolve for that grid: LUTEAL, cycle day 3. */
const LUTEAL_VERDICT: CycleVerdict = {
state: "IN_CYCLE",
dayOfCycle: 3,
cycleLength: 28,
phase: "LUTEAL",
spans: [
{ phase: "MENSTRUAL", fraction: 5 / 28 },
{ phase: "FOLLICULAR", fraction: 7 / 28 },
{ phase: "OVULATORY", fraction: 2 / 28 },
{ phase: "LUTEAL", fraction: 14 / 28 },
],
cycleStartDate: null,
overdueDays: null,
daysUntilNext: null,
fertileWindow: { start: null, end: null, active: false },
};
/** The verdict for an account with nothing to say about today. */
const NO_CYCLE_VERDICT: CycleVerdict = {
state: "INSUFFICIENT_DATA",
dayOfCycle: null,
cycleLength: null,
phase: null,
spans: [],
cycleStartDate: null,
overdueDays: null,
daysUntilNext: null,
fertileWindow: { start: null, end: null, active: false },
};
/** A calendar read whose SERVER-RESOLVED verdict puts today on LUTEAL, day 3. */
function lutealCalendar(today: string): CalendarResponse {
const days = [
{ date: shift(today, -2), phase: "MENSTRUAL" as const },
@@ -74,6 +102,7 @@ function lutealCalendar(today: string): CalendarResponse {
days: days as unknown as CalendarResponse["days"],
profile: {} as CalendarResponse["profile"],
prediction: null,
verdict: LUTEAL_VERDICT,
} as CalendarResponse;
}
@@ -138,6 +167,7 @@ describe("<CycleRingTile>", () => {
days: [] as unknown as CalendarResponse["days"],
profile: {} as CalendarResponse["profile"],
prediction: null,
verdict: NO_CYCLE_VERDICT,
} as CalendarResponse;
calendarState.current = { data: empty, isLoading: false, isError: false };
expect(render(<CycleRingTile />)).toBe("");
@@ -1,191 +0,0 @@
import { describe, it, expect } from "vitest";
import { deriveWheelState, currentCycleStartDate } from "../wheel-state";
import type { CalendarDay } from "../types";
function day(date: string, phase: CalendarDay["phase"]): CalendarDay {
return {
date,
phase,
isPredictedPeriod: false,
isFertileWindow: false,
isPredictedOvulation: false,
isPeriodLogged: phase === "MENSTRUAL",
flow: null,
hasSymptoms: false,
confidence: 1,
basalBodyTempC: null,
ovulationTest: null,
cervicalMucus: null,
};
}
describe("deriveWheelState", () => {
it("returns a null state when today carries no phase", () => {
const days = [day("2026-06-01", null), day("2026-06-02", null)];
const w = deriveWheelState(days, "2026-06-02");
expect(w.dayOfCycle).toBeNull();
expect(w.phase).toBeNull();
expect(w.spans).toEqual([]);
});
it("counts the day-of-cycle from the most recent menstrual start", () => {
// A run starting 2026-06-01 (menstrual) → today 2026-06-05 is cycle day 5.
const days = [
day("2026-05-30", "LUTEAL"),
day("2026-06-01", "MENSTRUAL"),
day("2026-06-02", "MENSTRUAL"),
day("2026-06-03", "FOLLICULAR"),
day("2026-06-04", "FOLLICULAR"),
day("2026-06-05", "FOLLICULAR"),
];
const w = deriveWheelState(days, "2026-06-05");
expect(w.dayOfCycle).toBe(5);
expect(w.phase).toBe("FOLLICULAR");
});
it("builds proportional phase spans summing to ~1", () => {
// A well-populated run (>= 7 labelled days spanning all four phases) keeps
// the OBSERVED-share spans. Eight forward-labelled days exercise the
// observed path (above the sparse threshold).
const days = [
day("2026-06-01", "MENSTRUAL"),
day("2026-06-02", "MENSTRUAL"),
day("2026-06-03", "MENSTRUAL"),
day("2026-06-04", "FOLLICULAR"),
day("2026-06-05", "FOLLICULAR"),
day("2026-06-06", "OVULATORY"),
day("2026-06-07", "LUTEAL"),
day("2026-06-08", "LUTEAL"),
];
const w = deriveWheelState(days, "2026-06-05");
const total = w.spans.reduce((s, x) => s + x.fraction, 0);
expect(total).toBeCloseTo(1, 5);
// All four observed phases are emitted, and the observed cycle length
// matches the labelled run (8 days) — NOT the idealized fallback length.
expect(w.spans.map((s) => s.phase).sort()).toEqual([
"FOLLICULAR",
"LUTEAL",
"MENSTRUAL",
"OVULATORY",
]);
expect(w.cycleLength).toBe(8);
});
it("falls back to canonical four-phase spans for a low-data tracker", () => {
// Only the first few days of a first-ever cycle are logged — a 2-day
// menstrual run. The observed-share path would normalise this so MENSTRUAL
// filled (nearly) the whole ring. The low-data fallback instead draws the
// canonical four phases from the profile lengths.
const days = [
day("2026-06-01", "MENSTRUAL"),
day("2026-06-02", "MENSTRUAL"),
];
const w = deriveWheelState(days, "2026-06-02", {
typicalCycleLength: 28,
typicalPeriodLength: 5,
lutealPhaseLength: 14,
});
// The marker read stays driven by the observed labels.
expect(w.dayOfCycle).toBe(2);
expect(w.phase).toBe("MENSTRUAL");
// FOUR sensible arcs, not one dominant sliver. The idealized cycle length
// (5 + follicular + 2 + 14 = 28) is represented, and no single phase
// swallows the ring.
expect(w.spans).toHaveLength(4);
expect(w.spans.map((s) => s.phase)).toEqual([
"MENSTRUAL",
"FOLLICULAR",
"OVULATORY",
"LUTEAL",
]);
const total = w.spans.reduce((s, x) => s + x.fraction, 0);
expect(total).toBeCloseTo(1, 5);
for (const span of w.spans) {
expect(span.fraction).toBeGreaterThan(0);
expect(span.fraction).toBeLessThan(0.95);
}
expect(w.cycleLength).toBe(28);
});
it("uses textbook defaults for the low-data ring when no profile is given", () => {
const days = [day("2026-06-01", "MENSTRUAL")];
const w = deriveWheelState(days, "2026-06-01");
expect(w.spans).toHaveLength(4);
// Defaults: 28-day cycle.
expect(w.cycleLength).toBe(28);
expect(w.phase).toBe("MENSTRUAL");
expect(w.dayOfCycle).toBe(1);
expect(w.periodOverdue).toBe(false);
});
// v1.27.5 — a months-old open cycle whose predicted next start moved into
// the future labels every gap day LUTEAL; the wheel must not read that back
// as "day 90 of your cycle".
describe("overdue ceiling", () => {
/** A run of 5 MENSTRUAL days + (n−5) LUTEAL days ending at `today`. */
function longRun(n: number): { days: CalendarDay[]; today: string } {
const start = Date.UTC(2026, 0, 1);
const days: CalendarDay[] = [];
for (let i = 0; i < n; i++) {
const date = new Date(start + i * 86_400_000)
.toISOString()
.slice(0, 10);
days.push(day(date, i < 5 ? "MENSTRUAL" : "LUTEAL"));
}
return { days, today: days[n - 1].date };
}
it("stops asserting a day count beyond typical length + grace", () => {
const { days, today } = longRun(90);
const w = deriveWheelState(days, today, { typicalCycleLength: 28 });
expect(w.periodOverdue).toBe(true);
expect(w.dayOfCycle).toBeNull();
expect(w.phase).toBeNull();
// The ring still draws the canonical four-phase dial.
expect(w.spans).toHaveLength(4);
expect(w.cycleLength).toBe(28);
});
it("keeps counting inside the grace window", () => {
// Typical 28 + 14 grace = 42; day 42 is still an honest count.
const { days, today } = longRun(42);
const w = deriveWheelState(days, today, { typicalCycleLength: 28 });
expect(w.periodOverdue).toBe(false);
expect(w.dayOfCycle).toBe(42);
});
it("respects a long typical cycle length from the profile", () => {
// A 60-day typical cycle keeps day 49 honest.
const { days, today } = longRun(49);
const w = deriveWheelState(days, today, { typicalCycleLength: 60 });
expect(w.periodOverdue).toBe(false);
expect(w.dayOfCycle).toBe(49);
});
});
});
describe("currentCycleStartDate", () => {
it("returns the most recent menstrual run-start at/before today", () => {
const days = [
day("2026-05-30", "LUTEAL"),
day("2026-06-01", "MENSTRUAL"),
day("2026-06-02", "MENSTRUAL"),
day("2026-06-03", "FOLLICULAR"),
day("2026-06-04", "FOLLICULAR"),
];
expect(currentCycleStartDate(days, "2026-06-04")).toBe("2026-06-01");
});
it("returns null when today carries no phase", () => {
const days = [day("2026-06-01", null), day("2026-06-02", null)];
expect(currentCycleStartDate(days, "2026-06-02")).toBeNull();
});
it("returns null when today is absent from the calendar", () => {
const days = [day("2026-06-01", "MENSTRUAL")];
expect(currentCycleStartDate(days, "2026-06-09")).toBeNull();
});
});