Merge pull request #723 from MBombeck/fix/cycle-correctness

Cycle correctness: overdue verdicts, backfills, deletes that leave no torso
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-08-07 19:58:39 +02:00
commit 8a1585a391
37 files changed
+2385 -180

No files matched your search

@@ -19,6 +19,7 @@ function day(date: string, overrides: Partial<CalendarDay> = {}): CalendarDay {
isFertileWindow: false,
isPredictedOvulation: false,
isPeriodLogged: false,
isCycleStart: false,
flow: null,
hasSymptoms: false,
confidence: 1,
@@ -0,0 +1,93 @@
/**
* The window arithmetic behind the month grid's own read.
*
* The bug it exists for is a save that appeared not to happen: the page read a
* fixed ninety-days-back window, an April cell in August fell outside it, and
* the write landed with nothing on screen to show for it. The month bounds and
* the "is this month already covered" question are the whole of the decision,
* so they are pinned here rather than left inside a component no test can drive.
*/
import { describe, it, expect } from "vitest";
import { monthBounds, monthOf, monthWindowOutside } from "../calendar-window";
describe("monthBounds", () => {
it("spans a 30-day month", () => {
expect(monthBounds("2026-04")).toEqual({
from: "2026-04-01",
to: "2026-04-30",
});
});
it("spans a 31-day month", () => {
expect(monthBounds("2026-08")).toEqual({
from: "2026-08-01",
to: "2026-08-31",
});
});
it("spans February in a common year and in a leap year", () => {
expect(monthBounds("2026-02").to).toBe("2026-02-28");
expect(monthBounds("2028-02").to).toBe("2028-02-29");
});
it("zero-pads so a day key compares as a date", () => {
expect(monthBounds("2026-01")).toEqual({
from: "2026-01-01",
to: "2026-01-31",
});
expect(monthBounds("2026-09").from < monthBounds("2026-10").from).toBe(
true,
);
});
});
describe("monthWindowOutside", () => {
// The page's anchored read on 2026-08-07: 90 days back, 180 forward.
const anchor = { from: "2026-05-09", to: "2027-02-03" };
it("reads nothing more for the month the anchor already carries", () => {
expect(monthWindowOutside("2026-08", anchor)).toBeNull();
expect(monthWindowOutside("2026-06", anchor)).toBeNull();
});
it("asks for the month the maintainer could not back-fill into", () => {
expect(monthWindowOutside("2026-04", anchor)).toEqual({
from: "2026-04-01",
to: "2026-04-30",
});
});
it("asks for a month that only overlaps the anchor's edge", () => {
// May 2026 starts before 2026-05-09, so half of it is missing.
expect(monthWindowOutside("2026-05", anchor)).toEqual({
from: "2026-05-01",
to: "2026-05-31",
});
});
it("asks for a month past the forward edge too", () => {
expect(monthWindowOutside("2027-03", anchor)).toEqual({
from: "2027-03-01",
to: "2027-03-31",
});
});
it("stays a bounded read however far back the grid navigates", () => {
// The anchor cannot simply be widened: the calendar route caps a span at
// 400 days, and a union with a month two years back blows through it.
const far = monthWindowOutside("2024-01", anchor);
expect(far).toEqual({ from: "2024-01-01", to: "2024-01-31" });
const span =
(Date.parse(`${far!.to}T12:00:00Z`) -
Date.parse(`${far!.from}T12:00:00Z`)) /
86_400_000;
expect(span).toBeLessThan(31);
});
});
describe("monthOf", () => {
it("takes the month a day key belongs to", () => {
expect(monthOf("2026-04-18")).toBe("2026-04");
});
});
@@ -19,6 +19,7 @@ function dayBase(date: string): CalendarDay {
isFertileWindow: false,
isPredictedOvulation: false,
isPeriodLogged: false,
isCycleStart: false,
flow: null,
hasSymptoms: false,
confidence: 1,
+58
View File
@@ -0,0 +1,58 @@
/**
* The date range the /cycle page reads, and what a month outside it needs.
*
* The page reads one anchored window — ninety days back, half a year forward —
* and that window drives the ring, the forecast panel and the temperature
* chart, all of which are about today. The month grid is not: it navigates
* freely, and a month the anchored read does not cover came back with no days
* at all. The cells still rendered (they come from the month, not the read) and
* still opened the log sheet, and the write behind it still landed — the period
* route is built for back-dating and re-anchors the neighbouring cycles for it.
* What did not happen is anything visible. Save an April flow in August and the
* sheet closes onto a month the read never carried, so the entry appears not to
* have been made, and entering it again does not help.
*
* So the month grid gets its own read when it steps outside the anchor. A month
* is a bounded thing to fetch, the anchored window stays exactly as it was for
* every surface that means "today", and the two grids merge by date.
*
* Pure and dateless — the caller supplies both the month and the window.
*/
/** An inclusive `YYYY-MM-DD` range, the shape the calendar read takes. */
export interface CalendarWindow {
from: string;
to: string;
}
/** Zero-padded `YYYY-MM-DD`. */
function ymd(year: number, month: number, day: number): string {
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
/** First and last day of a `YYYY-MM` month. */
export function monthBounds(month: string): CalendarWindow {
const [year, monthIndex] = month.split("-").map(Number);
// Day 0 of the following month is the last day of this one, leap years and all.
const lastDay = new Date(year, monthIndex, 0).getDate();
return { from: ymd(year, monthIndex, 1), to: ymd(year, monthIndex, lastDay) };
}
/**
* The extra window a visible month needs, or null when `anchor` already covers
* it and the page should read nothing more. Day keys are zero-padded, so a
* plain string compare is a date compare.
*/
export function monthWindowOutside(
month: string,
anchor: CalendarWindow,
): CalendarWindow | null {
const bounds = monthBounds(month);
if (bounds.from >= anchor.from && bounds.to <= anchor.to) return null;
return bounds;
}
/** The `YYYY-MM` a `YYYY-MM-DD` day key belongs to. */
export function monthOf(date: string): string {
return date.slice(0, 7);
}
+19 -1
View File
@@ -76,6 +76,13 @@ export interface CycleCalendarProps {
* rather than opening a sheet whose every button the server would refuse.
*/
onSelectDay?: (date: string) => void;
/**
* The month the grid moved to (`YYYY-MM`). The page's anchored read covers
* a fixed span around today, so a month outside it arrives with no days —
* the caller uses this to fetch that month rather than render empty cells
* over entries that exist.
*/
onVisibleMonthChange?: (month: string) => void;
className?: string;
}
@@ -84,6 +91,7 @@ export function CycleCalendar({
today,
confirmedOvulation,
onSelectDay,
onVisibleMonthChange,
className,
}: CycleCalendarProps) {
const { t, locale } = useTranslations();
@@ -125,7 +133,17 @@ export function CycleCalendar({
});
function shiftMonth(delta: number) {
setMonthAnchor((a) => new Date(a.getFullYear(), a.getMonth() + delta, 1));
const next = new Date(
monthAnchor.getFullYear(),
monthAnchor.getMonth() + delta,
1,
);
setMonthAnchor(next);
// The page reads a window anchored on today, so a month outside it has no
// days until somebody asks for them.
onVisibleMonthChange?.(
`${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, "0")}`,
);
}
return (
+44 -35
View File
@@ -3,13 +3,7 @@
import { useMemo, useState } from "react";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import {
Loader2,
Plus,
RefreshCw,
SlidersHorizontal,
Sparkles,
} from "lucide-react";
import { Loader2, Plus, RefreshCw, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
@@ -29,6 +23,7 @@ import { CyclePhaseHeadline, CyclePhaseCrosstab } from "./cycle-phase-crosstab";
import { CycleSymptomPatterns } from "./cycle-symptom-patterns";
import { CycleSettings } from "./cycle-settings";
import { PHASE_HUE } from "./phase-tokens";
import { monthOf, monthWindowOutside } from "./calendar-window";
import {
localYmd,
useCycleCalendar,
@@ -110,9 +105,7 @@ export function CycleView() {
: "calendar";
}, [searchParams]);
// Controlled so the header "cycle settings" wrench (parity with the
// labs/medications/illness modules, which expose a customize glyph) can jump
// to the settings tab. Initialised from the `?tab=` deep-link, matching the
// Controlled tabs, initialised from the `?tab=` deep-link and matching the
// prior uncontrolled `defaultValue` behaviour (the initial param is honoured;
// a later param change does not force-switch a tab the user is reading).
const [tab, setTab] = useState<CycleTab>(initialTab);
@@ -126,6 +119,29 @@ export function CycleView() {
const profileQuery = useCycleProfile();
const insights = useCycleInsights();
// The month grid navigates freely; the anchored read above does not follow
// it, because every other surface on this page (the ring, the forecast panel,
// the temperature chart) is about today and the route caps a span at 400
// days. A month outside the anchor therefore gets its own bounded read, and
// the two grids merge by date. Without it a back-dated entry landed on the
// server and had nothing on screen to land in.
const [visibleMonth, setVisibleMonth] = useState(() => monthOf(today));
const monthWindow = useMemo(
() => monthWindowOutside(visibleMonth, { from, to }),
[visibleMonth, from, to],
);
const monthCalendar = useCycleCalendar(
monthWindow?.from ?? from,
monthWindow?.to ?? to,
monthWindow !== null,
);
// Month days last: on the edge months the two reads overlap and the grid
// keys by date, so the later entry wins and both carry the same answer.
const calendarDays = useMemo(
() => [...(calendar.data?.days ?? []), ...(monthCalendar.data?.days ?? [])],
[calendar.data?.days, monthCalendar.data?.days],
);
const [sheetOpen, setSheetOpen] = useState(false);
const [selectedDate, setSelectedDate] = useState(today);
@@ -167,30 +183,18 @@ export function CycleView() {
title={<span data-tour-id="cycle-hero">{t("cycle.title")}</span>}
description={t("cycle.subtitle")}
actions={
<>
{canManage && (
<>
<Button
variant="outline"
size="icon"
className="min-h-11 min-w-11 sm:min-h-9 sm:min-w-9"
aria-label={t("cycle.tabs.settings")}
title={t("cycle.tabs.settings")}
data-slot="cycle-settings-wrench"
onClick={() => setTab("settings")}
>
<SlidersHorizontal className="h-4 w-4" aria-hidden="true" />
</Button>
<Button
onClick={() => openSheet(today)}
className="min-h-11 sm:min-h-9"
>
<Plus className="h-4 w-4" />
{t("cycle.logToday")}
</Button>
</>
)}
</>
// One action. The settings glyph that used to sit beside it was a
// second door to the tab directly below, and no other page in the
// app carries a gear in that corner.
canManage ? (
<Button
onClick={() => openSheet(today)}
className="min-h-11 sm:min-h-9"
>
<Plus className="h-4 w-4" />
{t("cycle.logToday")}
</Button>
) : null
}
/>
@@ -365,7 +369,7 @@ export function CycleView() {
</div>
) : null}
<CycleCalendar
days={calendar.data?.days ?? []}
days={calendarDays}
today={today}
confirmedOvulation={
calendar.data?.prediction?.ovulationConfirmed
@@ -374,6 +378,7 @@ export function CycleView() {
: null
}
onSelectDay={canManage ? openSheet : undefined}
onVisibleMonthChange={setVisibleMonth}
/>
</>
)}
@@ -458,6 +463,10 @@ export function CycleView() {
onOpenChange={setSheetOpen}
date={selectedDate}
today={today}
startsCycle={
calendarDays.find((d) => d.date === selectedDate)?.isCycleStart ??
false
}
activePeriod={verdict?.phase === "MENSTRUAL"}
phase={verdict?.phase ?? null}
dayOfCycle={verdict?.dayOfCycle ?? null}
+63 -7
View File
@@ -45,6 +45,8 @@ import {
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
import { SheetSection, SheetSectionCount } from "@/components/ui/sheet-section";
import { useTranslations } from "@/lib/i18n/context";
import { resolveIntlLocale } from "@/lib/format-locale";
import type { Locale } from "@/lib/i18n/config";
import { CUSTOM_SYMPTOM_ICON_ALLOWLIST } from "@/lib/cycle/custom-symptoms-shared";
import { FieldInfo } from "./field-info";
import { CYCLE_SYMPTOM_CATALOG } from "./symptom-catalog";
@@ -321,6 +323,11 @@ export interface LogDaySheetProps {
date: string;
/** Today (YYYY-MM-DD). */
today: string;
/**
* Whether a logged cycle opens on `date`. Deleting the day-log of a cycle
* start removes that start too, so the confirm dialog has to say so.
*/
startsCycle?: boolean;
/**
* Whether a period is currently open (today is in the MENSTRUAL phase) — gates
* the one-tap "end period" affordance so it never shows when no period is in
@@ -463,10 +470,37 @@ function CervixRow<T extends string>({
);
}
/**
* The day the sheet is writing to, spelled out in the reader's language.
*
* The sheet used to be titled "Log your day" whichever cell opened it, so a
* back-dated entry gave no clue which date it would land on and "Log today"
* gave no clue that any other date was possible. The weekday is included
* deliberately: it is how people recognise a date they are recalling.
*/
export function formatSheetDate(date: string, locale: Locale): string {
// A cycle day key is a calendar day, not an instant, so it is anchored at
// noon UTC and rendered in UTC — the same anchor the domain's day arithmetic
// uses. Formatting it in the browser's zone would let a reader east or west
// of it see the sheet name a different day than the one it writes to.
return new Date(`${date}T12:00:00Z`).toLocaleDateString(
resolveIntlLocale(locale),
{
weekday: "long",
day: "numeric",
month: "long",
year: "numeric",
timeZone: "UTC",
},
);
}
export function LogDaySheet({
open,
onOpenChange,
date,
today,
startsCycle = false,
activePeriod = false,
phase = null,
dayOfCycle = null,
@@ -475,7 +509,7 @@ export function LogDaySheet({
rawChartMode = false,
cyclesObserved = 0,
}: LogDaySheetProps) {
const { t } = useTranslations();
const { t, locale } = useTranslations();
const logDay = useLogDay();
const patchDay = usePatchDayLog();
const startPeriod = useStartPeriod();
@@ -682,8 +716,20 @@ export function LogDaySheet({
<ResponsiveSheet
open={open}
onOpenChange={onOpenChange}
title={t("cycle.sheet.title")}
description={t("cycle.sheet.description")}
// The target date IS the title. Every button below writes to it and
// nothing else on the surface says which day it is.
title={
<span data-slot="cycle-log-sheet-date">
{t("cycle.sheet.titleForDate", {
date: formatSheetDate(date, locale),
})}
</span>
}
description={
date === today
? t("cycle.sheet.descriptionToday")
: t("cycle.sheet.description")
}
contentWidth="lg"
footer={
<>
@@ -696,7 +742,11 @@ export function LogDaySheet({
label={t("cycle.sheet.delete")}
ariaLabel={t("cycle.sheet.delete")}
title={t("cycle.sheet.deleteTitle")}
body={t("cycle.sheet.deleteBody")}
body={
startsCycle
? t("cycle.sheet.deleteBodyCycleStart")
: t("cycle.sheet.deleteBody")
}
confirmLabel={t("cycle.sheet.deleteConfirm")}
disabled={busy && !deleteDay.isPending}
pending={deleteDay.isPending}
@@ -732,7 +782,9 @@ export function LogDaySheet({
{/* One-tap period boundaries — available on any selected date so a
forgotten day-1 can be corrected retroactively (M3). "End period"
shows only while a period is actually open (M2). */}
shows only while a period is actually open (M2). The labels drop the
word "today" on a back-dated day: they always wrote to the selected
date, and saying otherwise is how a correction reads as a mistake. */}
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
@@ -746,7 +798,9 @@ export function LogDaySheet({
) : (
<Droplets className="h-4 w-4" style={{ color: FLOW_HUE }} />
)}
{t("cycle.startedPeriod")}
{date === today
? t("cycle.startedPeriod")
: t("cycle.startedPeriodOnDate")}
</Button>
{activePeriod ? (
<Button
@@ -758,7 +812,9 @@ export function LogDaySheet({
{endPeriod.isPending ? (
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
) : null}
{t("cycle.endedPeriod")}
{date === today
? t("cycle.endedPeriod")
: t("cycle.endedPeriodOnDate")}
</Button>
) : null}
</div>
+2
View File
@@ -29,6 +29,8 @@ export interface CalendarDay {
isFertileWindow: boolean;
isPredictedOvulation: boolean;
isPeriodLogged: boolean;
/** Whether a logged cycle opens on this day. */
isCycleStart: boolean;
flow: string | null;
hasSymptoms: boolean;
confidence: number;
+40 -6
View File
@@ -20,6 +20,7 @@ import {
apiPost,
} from "@/lib/api/api-fetch";
import { useTranslations } from "@/lib/i18n/context";
import { toastWrittenOutcome } from "@/components/outcome/outcome-toast";
import {
cycleDependentKeys,
@@ -93,9 +94,16 @@ export function useCycleDayLog(date: string | null) {
});
}
export function useCycleCalendar(from: string, to: string) {
/**
* The calendar read for one window. `enabled` exists for the month grid's own
* read: the page's anchored window covers today, and a month the grid
* navigates outside it needs a second, bounded read rather than a widened
* anchor the route's span cap would refuse.
*/
export function useCycleCalendar(from: string, to: string, enabled = true) {
return useQuery({
queryKey: queryKeys.cycleCalendar(from, to),
enabled,
queryFn: () =>
apiGet<CalendarResponse>(`/api/cycle/calendar?from=${from}&to=${to}`),
staleTime: 60_000,
@@ -220,15 +228,28 @@ function idempotencyKey(): string {
return crypto.randomUUID();
}
/**
* Capture one day.
*
* The success toast is not decoration. A day-log write is silent by nature —
* the sheet closes and the grid repaints — and for a back-dated entry the grid
* had nothing to repaint, so a save that worked and a save that never happened
* looked identical. A write says so now, either way: this names the success and
* the sheet's inline strip names the failure.
*/
export function useLogDay() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async (input: CycleDayLogInput) => {
return apiPost<unknown>("/api/cycle/day-logs", input, {
headers: { "Idempotency-Key": idempotencyKey() },
});
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
toastWrittenOutcome("success", t("cycle.saveSuccess"));
},
});
}
@@ -260,6 +281,7 @@ export interface CycleDayLogPatch {
/** Edit an existing day-log by id (PATCH — accepts explicit null to clear). */
export function usePatchDayLog() {
const qc = useQueryClient();
const { t } = useTranslations();
return useMutation({
mutationFn: async ({
id,
@@ -270,7 +292,10 @@ export function usePatchDayLog() {
}) => {
return apiPatch<CycleDayLogDTO>(`/api/cycle/day-logs/${id}`, patch);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
toastWrittenOutcome("success", t("cycle.saveSuccess"));
},
});
}
@@ -285,7 +310,10 @@ export function useStartPeriod() {
loggedAt: new Date().toISOString(),
});
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
toastWrittenOutcome("success", t("cycle.periodStartSaved"));
},
// v1.16.4 — period boundaries had no failure signal at all (the sheet
// simply stayed open); a toast names the rejection.
onError: () => toast.error(t("cycle.saveError")),
@@ -304,7 +332,10 @@ export function useEndPeriod() {
loggedAt: new Date().toISOString(),
});
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
toastWrittenOutcome("success", t("cycle.periodEndSaved"));
},
onError: () => toast.error(t("cycle.saveError")),
});
}
@@ -317,7 +348,10 @@ export function useDeleteDayLog() {
mutationFn: async (id: string) => {
await apiDelete(`/api/cycle/day-logs/${id}`);
},
onSuccess: () => invalidateKeys(qc, cycleDependentKeys),
onSuccess: () => {
void invalidateKeys(qc, cycleDependentKeys);
toastWrittenOutcome("success", t("cycle.deleteSuccess"));
},
onError: () => toast.error(t("cycle.deleteError")),
});
}