mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
Merge pull request #723 from MBombeck/fix/cycle-correctness
Cycle correctness: overdue verdicts, backfills, deletes that leave no torso
This commit is contained in:
37 files changed
+2385
-180
No files matched your search
@@ -103,6 +103,16 @@ const LONG_CYCLE_STARTS = [
|
||||
"2026-04-30",
|
||||
];
|
||||
|
||||
/**
|
||||
* Four period starts exactly 28 days apart — the textbook regular record. The
|
||||
* last start is open, so where "today" sits relative to `lastStart + 28`
|
||||
* decides what the verdict may claim. Built from a supplied last start so a
|
||||
* test can place today a chosen number of days past the predicted one.
|
||||
*/
|
||||
function regularStarts(lastStart: string): string[] {
|
||||
return [-84, -56, -28, 0].map((offset) => addDays(lastStart, offset));
|
||||
}
|
||||
|
||||
function cycleRows(starts: readonly string[]) {
|
||||
return starts.map((startDate, i) => ({
|
||||
id: `cyc-${i}`,
|
||||
@@ -249,6 +259,7 @@ describe("GET /api/cycle/calendar carries the resolved verdict", () => {
|
||||
cycleRows(LONG_CYCLE_STARTS) as never,
|
||||
prediction?.nextPeriodStart ?? null,
|
||||
resolveLuteal(profile() as never),
|
||||
"2026-05-20",
|
||||
);
|
||||
expect(verdict.dayOfCycle).toBe(fromEngine.dayOfCycle);
|
||||
expect(verdict.phase).toBe(fromEngine.phase);
|
||||
@@ -276,6 +287,259 @@ describe("GET /api/cycle/calendar carries the resolved verdict", () => {
|
||||
expect(prediction!.nextPeriodStart).toBe(addDays("2026-05-20", expected));
|
||||
});
|
||||
|
||||
/**
|
||||
* D-list edge 1 — the verdict at and after the predicted start day, driven
|
||||
* through the real route.
|
||||
*
|
||||
* A regular 28-day record whose period has not arrived is the ORDINARY way
|
||||
* to be late, and it is the case the ring was silent about: the engine ends
|
||||
* the open cycle's phase window at the predicted start, so the day after it
|
||||
* carried no phase, and the verdict resolver read "no phase today" as "no
|
||||
* data at all". The person saw an empty ring and the words insufficient data
|
||||
* on the third day of a late period. `OVERDUE` was only ever reachable when
|
||||
* the engine itself forecast a cycle longer than the grace window.
|
||||
*/
|
||||
describe("a period that has not arrived", () => {
|
||||
/** Place today N days past `lastStart + 28`, the predicted next start. */
|
||||
function overdueBy(days: number): { today: string; lastStart: string } {
|
||||
const today = "2026-06-11";
|
||||
return { today, lastStart: addDays(today, -(28 + days)) };
|
||||
}
|
||||
|
||||
function seedRegular(lastStart: string): void {
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows(regularStarts(lastStart)) as never,
|
||||
);
|
||||
}
|
||||
|
||||
it("keeps counting the open cycle past the predicted start", async () => {
|
||||
const { today, lastStart } = overdueBy(3);
|
||||
seedRegular(lastStart);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const data = body.data as Record<string, unknown>;
|
||||
const verdict = data.verdict as Record<string, unknown>;
|
||||
const prediction = data.prediction as { nextPeriodStart: string } | null;
|
||||
|
||||
// The predicted start really is behind us — otherwise this asserts nothing.
|
||||
expect(prediction?.nextPeriodStart).toBe(addDays(today, -3));
|
||||
|
||||
expect(verdict.state).toBe("IN_CYCLE");
|
||||
expect(verdict.dayOfCycle).toBe(32);
|
||||
expect(verdict.phase).toBe("LUTEAL");
|
||||
expect(verdict.cycleStartDate).toBe(lastStart);
|
||||
// There is no "until" once the predicted start is behind us.
|
||||
expect(verdict.daysUntilNext).toBeNull();
|
||||
});
|
||||
|
||||
it("says OVERDUE, with the day count, once the grace window is spent", async () => {
|
||||
// Typical 28 + 14 days of grace = 42. Day 44 is past it.
|
||||
const { today, lastStart } = overdueBy(15);
|
||||
seedRegular(lastStart);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const verdict = (body.data as Record<string, unknown>).verdict as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
expect(verdict.state).toBe("OVERDUE");
|
||||
expect(verdict.dayOfCycle).toBeNull();
|
||||
expect(verdict.phase).toBeNull();
|
||||
expect(verdict.overdueDays).toBe(16);
|
||||
expect(verdict.cycleStartDate).toBe(lastStart);
|
||||
expect(verdict.spans).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("holds the count on the predicted start day itself", async () => {
|
||||
const { today, lastStart } = overdueBy(0);
|
||||
seedRegular(lastStart);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const verdict = (body.data as Record<string, unknown>).verdict as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
// Day 29 of a 28-day cycle: the period is due today and has not been
|
||||
// logged, which is a cycle day, not an absence of data.
|
||||
expect(verdict.state).toBe("IN_CYCLE");
|
||||
expect(verdict.dayOfCycle).toBe(29);
|
||||
expect(verdict.daysUntilNext).toBe(0);
|
||||
});
|
||||
|
||||
it("stops extending the open window once the next period is logged", async () => {
|
||||
// The same record with one more start logged four days ago: the earlier
|
||||
// cycle closes at that start and today is day 5 of the new one.
|
||||
const { today, lastStart } = overdueBy(3);
|
||||
const withNewStart = [...regularStarts(lastStart), addDays(today, -4)];
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows(withNewStart) as never,
|
||||
);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const verdict = (body.data as Record<string, unknown>).verdict as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
expect(verdict.state).toBe("IN_CYCLE");
|
||||
expect(verdict.dayOfCycle).toBe(5);
|
||||
expect(verdict.cycleStartDate).toBe(addDays(today, -4));
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The cold-start gate suppresses the PHASE band while the engine is still
|
||||
* learning — a population-framed phase word off one or two cycles is not
|
||||
* earned. The day count is not a guess: it is the number of days since a
|
||||
* start the person logged themselves. Reading it off the phase labels meant
|
||||
* the gate took both, so a record with three logged periods rendered an
|
||||
* empty ring and offered to log a first period.
|
||||
*/
|
||||
describe("while the engine is still learning", () => {
|
||||
it("still counts the cycle day off the logged start", async () => {
|
||||
const today = "2026-06-11";
|
||||
const lastStart = addDays(today, -10);
|
||||
// Three starts → two observed lengths → under the three-cycle gate.
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows([
|
||||
addDays(lastStart, -56),
|
||||
addDays(lastStart, -28),
|
||||
lastStart,
|
||||
]) as never,
|
||||
);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const data = body.data as Record<string, unknown>;
|
||||
// The gate really is on, so the phase below is suppressed rather than absent.
|
||||
expect(data.stillLearning).toBe(true);
|
||||
|
||||
const verdict = data.verdict as Record<string, unknown>;
|
||||
expect(verdict.state).toBe("IN_CYCLE");
|
||||
expect(verdict.dayOfCycle).toBe(11);
|
||||
expect(verdict.cycleStartDate).toBe(lastStart);
|
||||
// No phase claim — that part of the gate stands.
|
||||
expect(verdict.phase).toBeNull();
|
||||
// The ring still draws a full wheel rather than an empty circle.
|
||||
expect(verdict.spans).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("still says how late a period is", async () => {
|
||||
const today = "2026-06-11";
|
||||
const lastStart = addDays(today, -50);
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows([
|
||||
addDays(lastStart, -56),
|
||||
addDays(lastStart, -28),
|
||||
lastStart,
|
||||
]) as never,
|
||||
);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const { body } = await callCalendar();
|
||||
const verdict = (body.data as Record<string, unknown>).verdict as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
|
||||
// Day 51 against a stated 28-day typical plus 14 days of grace.
|
||||
expect(verdict.state).toBe("OVERDUE");
|
||||
expect(verdict.overdueDays).toBe(23);
|
||||
expect(verdict.cycleStartDate).toBe(lastStart);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* D-list edge 15 — the day count under a narrowed `from` window.
|
||||
*
|
||||
* The count used to be the length of the labelled run inside the grid, so a
|
||||
* caller that asked for a shorter span got a smaller number for the same day:
|
||||
* the run was cut off at the window's edge, not at the cycle's start. That was
|
||||
* a latent contract question while every caller asked for the same ninety
|
||||
* days. It stopped being latent when the month grid started reading its own
|
||||
* month, which is a thirty-day window by construction.
|
||||
*/
|
||||
describe("under a narrowed window", () => {
|
||||
async function callWindow(
|
||||
from: string,
|
||||
to: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
`http://localhost/api/cycle/calendar?from=${from}&to=${to}`,
|
||||
),
|
||||
);
|
||||
const body = JSON.parse(await res.text());
|
||||
return (body.data as Record<string, unknown>).verdict as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
}
|
||||
|
||||
it("counts from the logged start, not from the window's edge", async () => {
|
||||
const today = "2026-06-11";
|
||||
const lastStart = "2026-05-20"; // day 23 of the open cycle
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows([
|
||||
addDays(lastStart, -84),
|
||||
addDays(lastStart, -56),
|
||||
addDays(lastStart, -28),
|
||||
lastStart,
|
||||
]) as never,
|
||||
);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
const wide = await callWindow(addDays(today, -90), addDays(today, 180));
|
||||
expect(wide.dayOfCycle).toBe(23);
|
||||
|
||||
// The month the grid would be showing: the cycle start is inside it, but
|
||||
// the window begins after several earlier cycles.
|
||||
const narrow = await callWindow("2026-06-01", "2026-06-30");
|
||||
expect(narrow.dayOfCycle).toBe(23);
|
||||
expect(narrow.cycleStartDate).toBe(lastStart);
|
||||
});
|
||||
|
||||
it("counts correctly when the window excludes the start entirely", async () => {
|
||||
const today = "2026-06-25";
|
||||
const lastStart = "2026-05-20";
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
cycleRows([
|
||||
addDays(lastStart, -56),
|
||||
addDays(lastStart, -28),
|
||||
lastStart,
|
||||
]) as never,
|
||||
);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(`${today}T12:00:00Z`));
|
||||
|
||||
// June only: the cycle opened in May, outside the window entirely.
|
||||
const narrow = await callWindow("2026-06-01", "2026-06-30");
|
||||
expect(narrow.cycleStartDate).toBe(lastStart);
|
||||
expect(narrow.dayOfCycle).toBe(37);
|
||||
});
|
||||
});
|
||||
|
||||
it("says INSUFFICIENT_DATA when nothing has been logged", async () => {
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(getSession).mockResolvedValue(session("UTC") as never);
|
||||
|
||||
@@ -195,6 +195,12 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
nextPeriodStart: predictionDto?.nextPeriodStart ?? null,
|
||||
fertileWindowStart: predictionDto?.fertileWindowStart ?? null,
|
||||
fertileWindowEnd: predictionDto?.fertileWindowEnd ?? null,
|
||||
// The latest start the person logged, read off the cycle rows rather than
|
||||
// the grid. The grid's phase band is withheld while the engine is still
|
||||
// learning, and the day count must not go with it — `cycles` is ordered by
|
||||
// startDate ascending, so the last one at or before today is the anchor.
|
||||
lastPeriodStart:
|
||||
cycles.filter((c) => c.startDate <= today).at(-1)?.startDate ?? null,
|
||||
});
|
||||
|
||||
annotate({
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
* `DELETE /api/cycle/cycles/{id}` — soft-delete a cycle
|
||||
* (ios-contract §2.F): set `deletedAt` + bump `syncVersion`, emit a
|
||||
* tombstone on the next sync page. 204. Idempotent. Owner-scoped + gated.
|
||||
*
|
||||
* The delete also hands the span back to the preceding cycle. Opening a cycle
|
||||
* closes the one before it, so removing it without re-deriving that boundary
|
||||
* left the previous cycle standing as a closed torso with an end date taken
|
||||
* from a cycle that no longer exists — and a record whose last cycle is closed
|
||||
* has no open cycle to forecast from.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
@@ -9,8 +15,10 @@ import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { overwriteDetails } from "@/lib/sharing/audit-details";
|
||||
import { apiError, getClientIp } from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import { reanchorAfterRemovedStart } from "@/lib/cycle/cycle-boundaries";
|
||||
|
||||
type RouteParams = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -28,21 +36,46 @@ export const DELETE = apiHandler(
|
||||
|
||||
const existing = await prisma.menstrualCycle.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, userId: true },
|
||||
select: { id: true, userId: true, startDate: true },
|
||||
});
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Cycle not found", 404);
|
||||
}
|
||||
|
||||
await prisma.menstrualCycle.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
// Tombstone + re-anchor as one unit: a neighbour re-derived against a
|
||||
// half-applied delete would read the row being removed as still live.
|
||||
const reanchored = await prisma.$transaction(async (db) => {
|
||||
await db.menstrualCycle.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
return reanchorAfterRemovedStart(db, user.id, existing.startDate);
|
||||
});
|
||||
|
||||
await auditLog("cycle.cycle.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { cycleId: id },
|
||||
// The tombstone carries the deleted cycle's own columns, so the only
|
||||
// unrecoverable part of this write is what it moved on the NEIGHBOUR.
|
||||
details: {
|
||||
cycleId: id,
|
||||
startDate: existing.startDate,
|
||||
...(reanchored
|
||||
? {
|
||||
reanchoredCycleId: reanchored.cycleId,
|
||||
...overwriteDetails({
|
||||
before: {
|
||||
endDate: reanchored.endDateBefore,
|
||||
lengthDays: reanchored.lengthDaysBefore,
|
||||
},
|
||||
after: {
|
||||
endDate: reanchored.endDateAfter,
|
||||
lengthDays: reanchored.lengthDaysAfter,
|
||||
},
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
@@ -51,6 +84,7 @@ export const DELETE = apiHandler(
|
||||
entity_type: "menstrual_cycle",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: { reanchored_prior: reanchored !== null },
|
||||
});
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
|
||||
@@ -23,6 +23,11 @@ import {
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { requireCycleEnabled } from "@/lib/cycle/gate";
|
||||
import {
|
||||
ensureCycleForBleedingDay,
|
||||
removeCycleStartedOn,
|
||||
} from "@/lib/cycle/cycle-boundaries";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { encrypt, decrypt } from "@/lib/crypto";
|
||||
import { getOrCreateCycleProfile } from "@/lib/cycle/profile";
|
||||
import { replaceSymptomLinks } from "@/lib/cycle/day-log-write";
|
||||
@@ -157,6 +162,26 @@ export const PATCH = apiHandler(
|
||||
include: dayLogSymptomInclude,
|
||||
});
|
||||
|
||||
// An edit that turns a day into a first bleeding day opens the cycle it
|
||||
// starts, and an edit that takes the bleeding back off it removes the
|
||||
// cycle that day opened. Both directions go through the same shared
|
||||
// boundary work the capture route and the one-tap start use — a cycle that
|
||||
// could be created here but not undone here is how the record ends up
|
||||
// holding a period nothing on the day says happened.
|
||||
const openedCycleId = await ensureCycleForBleedingDay(
|
||||
user.id,
|
||||
existing.date,
|
||||
user.timezone ?? DEFAULT_TIMEZONE,
|
||||
row,
|
||||
);
|
||||
let removedCycleId: string | null = null;
|
||||
if (!openedCycleId && !stillBleeds(row)) {
|
||||
const removed = await prisma.$transaction((db) =>
|
||||
removeCycleStartedOn(db, user.id, existing.date),
|
||||
);
|
||||
removedCycleId = removed?.cycleId ?? null;
|
||||
}
|
||||
|
||||
await auditLog("cycle.day-log.update", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
@@ -166,6 +191,8 @@ export const PATCH = apiHandler(
|
||||
details: {
|
||||
dayLogId: id,
|
||||
date: existing.date,
|
||||
...(openedCycleId ? { openedCycleId } : {}),
|
||||
...(removedCycleId ? { removedCycleId } : {}),
|
||||
...overwriteDetails({
|
||||
before: {},
|
||||
after: {},
|
||||
@@ -183,6 +210,10 @@ export const PATCH = apiHandler(
|
||||
entity_type: "cycle_day_log",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: {
|
||||
opened_cycle: openedCycleId !== null,
|
||||
removed_cycle: removedCycleId !== null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(toCycleDayLogDTO(row));
|
||||
@@ -202,7 +233,7 @@ export const DELETE = apiHandler(
|
||||
|
||||
const existing = await prisma.cycleDayLog.findUnique({
|
||||
where: { id },
|
||||
select: { id: true, userId: true },
|
||||
select: { id: true, userId: true, date: true },
|
||||
});
|
||||
if (!existing || existing.userId !== user.id) {
|
||||
return apiError("Day-log not found", 404);
|
||||
@@ -211,15 +242,44 @@ export const DELETE = apiHandler(
|
||||
// Soft-delete: leave the row in place so the `/api/sync/changes`
|
||||
// delta feed surfaces it as a tombstone. A re-delete re-bumps
|
||||
// `syncVersion` harmlessly (idempotent).
|
||||
await prisma.cycleDayLog.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
//
|
||||
// A day that OPENS a cycle takes that cycle with it. The one-tap "started
|
||||
// my period" writes both rows, and this delete is the only way the web
|
||||
// offers to take it back — leaving the cycle behind meant the previous one
|
||||
// stayed closed against a start whose last trace had just been removed, and
|
||||
// the forecast never came back. The cycle boundary is then re-derived for
|
||||
// the preceding cycle, the same repair the cycle delete does.
|
||||
const removed = await prisma.$transaction(async (db) => {
|
||||
await db.cycleDayLog.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
return removeCycleStartedOn(db, user.id, existing.date);
|
||||
});
|
||||
|
||||
await auditLog("cycle.day-log.delete", {
|
||||
userId: user.id,
|
||||
ipAddress: getClientIp(request),
|
||||
details: { dayLogId: id },
|
||||
details: {
|
||||
dayLogId: id,
|
||||
date: existing.date,
|
||||
...(removed ? { removedCycleId: removed.cycleId } : {}),
|
||||
...(removed?.reanchored
|
||||
? {
|
||||
reanchoredCycleId: removed.reanchored.cycleId,
|
||||
...overwriteDetails({
|
||||
before: {
|
||||
endDate: removed.reanchored.endDateBefore,
|
||||
lengthDays: removed.reanchored.lengthDaysBefore,
|
||||
},
|
||||
after: {
|
||||
endDate: removed.reanchored.endDateAfter,
|
||||
lengthDays: removed.reanchored.lengthDaysAfter,
|
||||
},
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
annotate({
|
||||
@@ -228,6 +288,10 @@ export const DELETE = apiHandler(
|
||||
entity_type: "cycle_day_log",
|
||||
entity_id: id,
|
||||
},
|
||||
meta: {
|
||||
removed_cycle: removed !== null,
|
||||
reanchored_prior: removed?.reanchored != null,
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
@@ -281,3 +345,15 @@ function readStoredSensitive(row: {
|
||||
contraceptive: row.contraceptive,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the edited day still records a period. A cleared or downgraded flow,
|
||||
* or one re-flagged as bleeding between periods, no longer anchors a cycle.
|
||||
*/
|
||||
function stillBleeds(row: {
|
||||
flow: string | null;
|
||||
intermenstrualBleeding: boolean;
|
||||
}): boolean {
|
||||
if (row.intermenstrualBleeding) return false;
|
||||
return row.flow !== null && row.flow !== "NONE" && row.flow !== "SPOTTING";
|
||||
}
|
||||
@@ -176,6 +176,7 @@ export const GET = apiHandler(async () => {
|
||||
profile.lutealPhaseLength ?? LUTEAL_DEFAULT,
|
||||
from,
|
||||
today,
|
||||
today,
|
||||
);
|
||||
|
||||
const measurements: CrossMetricMeasurement[] = measurementRows.map((m) => ({
|
||||
|
||||
@@ -37,26 +37,20 @@ import {
|
||||
dayLogSymptomInclude,
|
||||
} from "@/lib/cycle/dto";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
|
||||
import { addDays, dayDiff } from "@/lib/cycle/day-math";
|
||||
import { openCycleAt, type MovedAnchors } from "@/lib/cycle/cycle-boundaries";
|
||||
|
||||
export const POST = apiHandler(withIdempotency<[NextRequest]>(postPeriod));
|
||||
|
||||
/**
|
||||
* v1.37.0 — the anchors a boundary write moves, carried out of the
|
||||
* transaction so the audit row can name them (C4).
|
||||
* transaction so the audit row can name them (C4). The `start` arm's own
|
||||
* anchors live with the shared boundary helper; the `end` arm adds the one
|
||||
* column it overwrites.
|
||||
*/
|
||||
interface MovedAnchors {
|
||||
priorCycleId?: string;
|
||||
/** Day keys, the shape this domain stores its dates in. */
|
||||
priorEndDateBefore?: string | null;
|
||||
priorEndDateAfter?: string | null;
|
||||
priorLengthBefore?: number | null;
|
||||
priorLengthAfter?: number | null;
|
||||
openedEndDateBefore?: string | null;
|
||||
openedEndDateAfter?: string | null;
|
||||
type PeriodMovedAnchors = MovedAnchors & {
|
||||
periodEndDateBefore?: string | null;
|
||||
periodEndDateAfter?: string | null;
|
||||
}
|
||||
};
|
||||
|
||||
async function postPeriod(request: NextRequest): Promise<Response> {
|
||||
// v1.37.0 — MANAGE. Setting a boundary re-anchors the neighbouring cycles,
|
||||
@@ -97,73 +91,15 @@ async function postPeriod(request: NextRequest): Promise<Response> {
|
||||
// exact-key replay; the transaction guards the interleaving case.
|
||||
const txResult = await prisma.$transaction(async (db) => {
|
||||
if (action === "start") {
|
||||
// Close the prior open cycle (its end is the day before this start)
|
||||
// and record its observed length.
|
||||
const prior = await db.menstrualCycle.findFirst({
|
||||
where: { userId: user.id, deletedAt: null, startDate: { lt: date } },
|
||||
orderBy: { startDate: "desc" },
|
||||
// v1.37.0 — `endDate` and `lengthDays` are read for the audit row:
|
||||
// this write overwrites both on the prior cycle and they are the
|
||||
// dates C4 exists to name.
|
||||
select: {
|
||||
id: true,
|
||||
startDate: true,
|
||||
endDate: true,
|
||||
lengthDays: true,
|
||||
},
|
||||
});
|
||||
const moved: MovedAnchors = {};
|
||||
if (prior) {
|
||||
moved.priorCycleId = prior.id;
|
||||
moved.priorEndDateBefore = prior.endDate;
|
||||
moved.priorEndDateAfter = addDays(date, -1);
|
||||
moved.priorLengthBefore = prior.lengthDays;
|
||||
moved.priorLengthAfter = dayDiff(date, prior.startDate);
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: prior.id },
|
||||
data: {
|
||||
endDate: addDays(date, -1),
|
||||
lengthDays: dayDiff(date, prior.startDate),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Upsert the new cycle on the `(userId, startDate)` unique so a
|
||||
// re-tap on the same day is idempotent.
|
||||
const cycle = await db.menstrualCycle.upsert({
|
||||
where: { userId_startDate: { userId: user.id, startDate: date } },
|
||||
create: { userId: user.id, startDate: date, tz, isPredicted: false },
|
||||
update: {
|
||||
deletedAt: null,
|
||||
isPredicted: false,
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
// Re-anchor the FOLLOWING neighbour: when this start is back-filled
|
||||
// between two existing cycles, the new cycle's end + length are already
|
||||
// known from its successor's start. Without this the inserted cycle keeps
|
||||
// endDate/lengthDays = null even though the next start exists, and the
|
||||
// iOS mirror + history surfaces read a stale open cycle (QA M-1).
|
||||
const next = await db.menstrualCycle.findFirst({
|
||||
where: { userId: user.id, deletedAt: null, startDate: { gt: date } },
|
||||
orderBy: { startDate: "asc" },
|
||||
select: { startDate: true },
|
||||
});
|
||||
if (next) {
|
||||
moved.openedEndDateBefore = cycle.endDate;
|
||||
moved.openedEndDateAfter = addDays(next.startDate, -1);
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: cycle.id },
|
||||
data: {
|
||||
endDate: addDays(next.startDate, -1),
|
||||
lengthDays: dayDiff(next.startDate, date),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
return { cycleId: cycle.id as string | null, moved };
|
||||
// Close the prior open cycle, open this one, and re-anchor the following
|
||||
// neighbour when the start is back-filled between two existing cycles.
|
||||
// The same helper runs when a first bleeding day is captured as flow, so
|
||||
// a period start means one thing however it was entered.
|
||||
const { cycleId, moved } = await openCycleAt(db, user.id, date, tz);
|
||||
return {
|
||||
cycleId: cycleId as string | null,
|
||||
moved: moved as PeriodMovedAnchors,
|
||||
};
|
||||
}
|
||||
|
||||
// `end`: stamp the current cycle's periodEndDate.
|
||||
@@ -174,7 +110,7 @@ async function postPeriod(request: NextRequest): Promise<Response> {
|
||||
select: { id: true, periodEndDate: true },
|
||||
});
|
||||
if (!current) {
|
||||
return { cycleId: null, moved: {} satisfies MovedAnchors };
|
||||
return { cycleId: null, moved: {} satisfies PeriodMovedAnchors };
|
||||
}
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: current.id },
|
||||
@@ -185,7 +121,7 @@ async function postPeriod(request: NextRequest): Promise<Response> {
|
||||
moved: {
|
||||
periodEndDateBefore: current.periodEndDate,
|
||||
periodEndDateAfter: date,
|
||||
} satisfies MovedAnchors,
|
||||
} satisfies PeriodMovedAnchors,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 (
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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")),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -242,6 +242,7 @@ export async function buildCycleSnapshotBlock(
|
||||
cycles,
|
||||
prediction?.nextPeriodStart ?? null,
|
||||
lutealLength,
|
||||
today,
|
||||
);
|
||||
|
||||
// Next predicted event — period range + confidence + method, fertile window
|
||||
@@ -280,6 +281,7 @@ export async function buildCycleSnapshotBlock(
|
||||
lutealLength,
|
||||
from,
|
||||
today,
|
||||
today,
|
||||
);
|
||||
const measurements: CrossMetricMeasurement[] = measurementRows.map((m) => ({
|
||||
type: m.type,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The rule that decides whether a logged bleeding day starts a cycle.
|
||||
*
|
||||
* It is the one piece of the flow-to-cycle inference that is a judgement
|
||||
* rather than bookkeeping, and a wrong yes is worse than a wrong no: a false
|
||||
* cycle start corrupts every length the engine derives after it, while a
|
||||
* missed one leaves the person exactly where they were before, with the
|
||||
* one-tap start still available on any date.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { bleedOpensCycle } from "../cycle-boundaries";
|
||||
import { HARD_CYCLE_MIN } from "../types";
|
||||
import { addDays } from "../day-math";
|
||||
|
||||
const DAY = "2026-06-01";
|
||||
|
||||
describe("bleedOpensCycle", () => {
|
||||
it("opens the first cycle a record ever has", () => {
|
||||
expect(bleedOpensCycle("MEDIUM", false, null, DAY)).toBe(true);
|
||||
expect(bleedOpensCycle("HEAVY", false, null, DAY)).toBe(true);
|
||||
expect(bleedOpensCycle("LIGHT", false, null, DAY)).toBe(true);
|
||||
});
|
||||
|
||||
it("declines a day that records no bleeding", () => {
|
||||
expect(bleedOpensCycle(null, false, null, DAY)).toBe(false);
|
||||
expect(bleedOpensCycle("NONE", false, null, DAY)).toBe(false);
|
||||
});
|
||||
|
||||
it("declines spotting", () => {
|
||||
// As often the tail or the herald of a period as its first day, and the
|
||||
// person has a chip for a real flow when it is one.
|
||||
expect(bleedOpensCycle("SPOTTING", false, null, DAY)).toBe(false);
|
||||
});
|
||||
|
||||
it("declines bleeding the person flagged as between periods", () => {
|
||||
expect(bleedOpensCycle("HEAVY", true, null, DAY)).toBe(false);
|
||||
});
|
||||
|
||||
it("declines a bleeding day inside the current cycle's plausible span", () => {
|
||||
// Day two, day three, and a day somebody forgot and entered late: all of
|
||||
// them are this period, not a new one.
|
||||
for (const offset of [1, 2, 4, HARD_CYCLE_MIN - 1]) {
|
||||
expect(bleedOpensCycle("HEAVY", false, addDays(DAY, -offset), DAY)).toBe(
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("declines a bleeding day on a date a cycle already starts", () => {
|
||||
// What the one-tap boundary's own day-log write hits.
|
||||
expect(bleedOpensCycle("MEDIUM", false, DAY, DAY)).toBe(false);
|
||||
});
|
||||
|
||||
it("opens the next cycle at the hard physiological minimum and beyond", () => {
|
||||
expect(
|
||||
bleedOpensCycle("MEDIUM", false, addDays(DAY, -HARD_CYCLE_MIN), DAY),
|
||||
).toBe(true);
|
||||
expect(bleedOpensCycle("MEDIUM", false, addDays(DAY, -28), DAY)).toBe(true);
|
||||
});
|
||||
|
||||
it("declines when the nearest cycle start is AFTER the day", () => {
|
||||
// Never happens through the resolver (it queries `startDate <= date`), but
|
||||
// a negative gap must not read as a large one.
|
||||
expect(bleedOpensCycle("HEAVY", false, addDays(DAY, 10), DAY)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -11,15 +11,44 @@
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const db = vi.hoisted(() => ({
|
||||
cycleDayLog: {
|
||||
findUnique: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
cycleSymptom: { findMany: vi.fn() },
|
||||
cycleSymptomLink: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
}));
|
||||
const db = vi.hoisted(() => {
|
||||
const client: Record<string, unknown> = {
|
||||
cycleDayLog: {
|
||||
findUnique: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
// The write path asks whether the logged day opens a cycle. These cases
|
||||
// are about the encryption columns, so the fake answers "no cycles on
|
||||
// record" and lets the boundary work run for real against itself — the
|
||||
// inference itself is pinned by its own unit + integration cases.
|
||||
menstrualCycle: {
|
||||
findFirst: vi.fn(async () => null),
|
||||
upsert: vi.fn(async () => ({ id: "cyc-1", endDate: null })),
|
||||
update: vi.fn(),
|
||||
},
|
||||
cycleSymptom: { findMany: vi.fn() },
|
||||
cycleSymptomLink: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
};
|
||||
client.$transaction = async (fn: (tx: unknown) => unknown) => fn(client);
|
||||
return client as {
|
||||
cycleDayLog: {
|
||||
findUnique: ReturnType<typeof vi.fn>;
|
||||
upsert: ReturnType<typeof vi.fn>;
|
||||
update: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
menstrualCycle: {
|
||||
findFirst: ReturnType<typeof vi.fn>;
|
||||
upsert: ReturnType<typeof vi.fn>;
|
||||
update: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
cycleSymptom: { findMany: ReturnType<typeof vi.fn> };
|
||||
cycleSymptomLink: {
|
||||
deleteMany: ReturnType<typeof vi.fn>;
|
||||
createMany: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/lib/db", () => ({ prisma: db }));
|
||||
vi.mock("@/lib/cycle/profile", () => ({
|
||||
@@ -70,6 +99,8 @@ function existingRow(overrides: Record<string, unknown> = {}) {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
db.cycleDayLog.upsert.mockResolvedValue({ id: "cdl-1" });
|
||||
db.menstrualCycle.findFirst.mockResolvedValue(null);
|
||||
db.menstrualCycle.upsert.mockResolvedValue({ id: "cyc-1", endDate: null });
|
||||
});
|
||||
|
||||
describe("upsertCycleDayLog — C-1 undecryptable note preservation", () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { addDays } from "../day-math";
|
||||
import { FERTILE_POST, FERTILE_PRE } from "../types";
|
||||
import {
|
||||
clampLuteal,
|
||||
confirmSymptothermal,
|
||||
@@ -1091,3 +1092,33 @@ describe("cycle/dto — toCyclePredictionDTO still-learning honesty gate (M-1)",
|
||||
expect(goalGated.predictedOvulation).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cycle/prediction — the fertile window's width (A10)", () => {
|
||||
it("spans seven days, ending the day after the ovulation estimate", () => {
|
||||
// The comment on the constants used to say six days and the constants made
|
||||
// seven. The width is now a decision with a reason written at the constant,
|
||||
// so it is pinned here rather than left to be re-read off the same numbers
|
||||
// the code uses: five days before the estimate, the estimate, and one after.
|
||||
const cycles = cyclesFromGaps("2026-01-01", [28, 28, 28]);
|
||||
const p = predictCycle(cycles, [], BASE_PROFILE, "2026-03-20", []);
|
||||
|
||||
expect(p.predictedOvulation).not.toBeNull();
|
||||
expect(p.fertileWindowStart).toBe(addDays(p.predictedOvulation!, -5));
|
||||
expect(p.fertileWindowEnd).toBe(addDays(p.predictedOvulation!, 1));
|
||||
|
||||
const span =
|
||||
(Date.parse(`${p.fertileWindowEnd}T12:00:00Z`) -
|
||||
Date.parse(`${p.fertileWindowStart}T12:00:00Z`)) /
|
||||
86_400_000;
|
||||
// Inclusive of both ends.
|
||||
expect(span + 1).toBe(7);
|
||||
});
|
||||
|
||||
it("keeps the extra day on the side that costs least to be wrong about", () => {
|
||||
// The trailing day is estimator slack plus ovum viability. Dropping it
|
||||
// would shorten the window for somebody avoiding pregnancy, which is the
|
||||
// direction that misses.
|
||||
expect(FERTILE_PRE).toBe(5);
|
||||
expect(FERTILE_POST).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -163,6 +163,60 @@ describe("resolveCycleVerdict — what the record supports", () => {
|
||||
expect(v.cycleLength).toBe(8);
|
||||
});
|
||||
|
||||
it("counts off the logged start when the grid withholds its phase labels", () => {
|
||||
// What the calendar hands over while the engine is still learning: a grid
|
||||
// with every phase suppressed. The count is not the suppressed claim.
|
||||
const days = [day("2026-06-01", null), day("2026-06-11", null)];
|
||||
const v = resolveCycleVerdict({
|
||||
days,
|
||||
today: "2026-06-11",
|
||||
profile: { typicalCycleLength: 28 },
|
||||
lastPeriodStart: "2026-06-01",
|
||||
});
|
||||
expect(v.state).toBe("IN_CYCLE");
|
||||
expect(v.dayOfCycle).toBe(11);
|
||||
expect(v.cycleStartDate).toBe("2026-06-01");
|
||||
expect(v.phase).toBeNull();
|
||||
expect(v.spans).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("says how late a period is with no phase labels to read", () => {
|
||||
const days = [day("2026-06-11", null)];
|
||||
const v = resolveCycleVerdict({
|
||||
days,
|
||||
today: "2026-06-11",
|
||||
profile: { typicalCycleLength: 28 },
|
||||
lastPeriodStart: "2026-04-22",
|
||||
});
|
||||
expect(v.state).toBe("OVERDUE");
|
||||
expect(v.dayOfCycle).toBeNull();
|
||||
expect(v.overdueDays).toBe(23);
|
||||
expect(v.cycleStartDate).toBe("2026-04-22");
|
||||
});
|
||||
|
||||
it("counts off the logged start when today is absent from the grid", () => {
|
||||
const days = [day("2026-06-01", "MENSTRUAL")];
|
||||
const v = resolveCycleVerdict({
|
||||
days,
|
||||
today: "2026-06-09",
|
||||
lastPeriodStart: "2026-06-01",
|
||||
});
|
||||
expect(v.state).toBe("IN_CYCLE");
|
||||
expect(v.dayOfCycle).toBe(9);
|
||||
});
|
||||
|
||||
it("keeps INSUFFICIENT_DATA when the anchor is ahead of today", () => {
|
||||
// A start dated in the future is not a cycle the person is in.
|
||||
const days = [day("2026-06-02", null)];
|
||||
const v = resolveCycleVerdict({
|
||||
days,
|
||||
today: "2026-06-02",
|
||||
lastPeriodStart: "2026-06-20",
|
||||
});
|
||||
expect(v.state).toBe("INSUFFICIENT_DATA");
|
||||
expect(v.cycleStartDate).toBeNull();
|
||||
});
|
||||
|
||||
it("draws the canonical four arcs for a low-data tracker", () => {
|
||||
// A two-day first-ever run: the observed-share math would let MENSTRUAL
|
||||
// fill nearly the whole circle, so the ring falls back to the profile's
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Cycle boundary re-derivation — the inverse of what a period-start write does
|
||||
* to its neighbours.
|
||||
*
|
||||
* `POST /api/cycle/period` with `action:"start"` is not an insert. It closes
|
||||
* the previous open cycle (stamps `endDate` and `lengthDays` from the new
|
||||
* start) and, when the start is back-filled between two existing cycles, takes
|
||||
* the inserted cycle's own end from its successor. Removing that start left
|
||||
* every one of those overwrites standing: the previous cycle kept the end date
|
||||
* a cycle that no longer exists gave it, and a record whose last cycle is
|
||||
* closed has no open cycle for the engine to forecast from. The prediction
|
||||
* disappeared and there was no way to bring it back from the app.
|
||||
*
|
||||
* The repair is a re-derivation rather than an undo log, which is why it is
|
||||
* safe to run on a record whose history came from an import or a restore
|
||||
* instead of from the one-tap boundary: a cycle ends the day before the next
|
||||
* one begins, and when there is no next one it is open. That statement is true
|
||||
* of every cycle in the table regardless of how the row got there, so applying
|
||||
* it to the surviving neighbour restores exactly the state the start write
|
||||
* moved — and applying it twice changes nothing the second time.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { addDays, dayDiff } from "./day-math";
|
||||
import { HARD_CYCLE_MIN } from "./types";
|
||||
import type {
|
||||
FlowLevel,
|
||||
Prisma,
|
||||
PrismaClient,
|
||||
} from "@/generated/prisma/client";
|
||||
|
||||
/** The Prisma client or an interactive-transaction handle. */
|
||||
type CycleDb = PrismaClient | Prisma.TransactionClient;
|
||||
|
||||
/**
|
||||
* The boundary columns an opening write moved on the cycles around it, so the
|
||||
* audit row can name them. They are the only unrecoverable part of the write:
|
||||
* the opened cycle is a row, the re-anchoring is an overwrite of two columns
|
||||
* on somebody else's cycle history.
|
||||
*/
|
||||
export interface MovedAnchors {
|
||||
priorCycleId?: string;
|
||||
/** Day keys, the shape this domain stores its dates in. */
|
||||
priorEndDateBefore?: string | null;
|
||||
priorEndDateAfter?: string | null;
|
||||
priorLengthBefore?: number | null;
|
||||
priorLengthAfter?: number | null;
|
||||
openedEndDateBefore?: string | null;
|
||||
openedEndDateAfter?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a cycle at `date`, closing the one before it and taking the opened
|
||||
* cycle's own end from the one after it when the start is back-filled between
|
||||
* two existing cycles. Without that second half an inserted cycle keeps a null
|
||||
* endDate even though its successor's start is right there, and every history
|
||||
* surface reads a stale open cycle.
|
||||
*
|
||||
* Idempotent on `(userId, startDate)`: a re-tap on the same day, or a flow
|
||||
* entry on a day the one-tap boundary already anchored, updates the existing
|
||||
* row rather than adding a second one.
|
||||
*
|
||||
* Callers run this inside a transaction — the close-prior and open-new pair
|
||||
* must not interleave with a concurrent write, or two taps double-close a
|
||||
* prior cycle or compute a length against a stale read.
|
||||
*/
|
||||
export async function openCycleAt(
|
||||
db: CycleDb,
|
||||
userId: string,
|
||||
date: string,
|
||||
tz: string | null,
|
||||
): Promise<{ cycleId: string; moved: MovedAnchors }> {
|
||||
const moved: MovedAnchors = {};
|
||||
|
||||
// Close the prior open cycle: its end is the day before this start.
|
||||
const prior = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: { lt: date } },
|
||||
orderBy: { startDate: "desc" },
|
||||
select: { id: true, startDate: true, endDate: true, lengthDays: true },
|
||||
});
|
||||
if (prior) {
|
||||
moved.priorCycleId = prior.id;
|
||||
moved.priorEndDateBefore = prior.endDate;
|
||||
moved.priorEndDateAfter = addDays(date, -1);
|
||||
moved.priorLengthBefore = prior.lengthDays;
|
||||
moved.priorLengthAfter = dayDiff(date, prior.startDate);
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: prior.id },
|
||||
data: {
|
||||
endDate: addDays(date, -1),
|
||||
lengthDays: dayDiff(date, prior.startDate),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const cycle = await db.menstrualCycle.upsert({
|
||||
where: { userId_startDate: { userId, startDate: date } },
|
||||
create: { userId, startDate: date, tz, isPredicted: false },
|
||||
update: {
|
||||
deletedAt: null,
|
||||
isPredicted: false,
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
// Re-anchor the FOLLOWING neighbour's side of the boundary.
|
||||
const next = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: { gt: date } },
|
||||
orderBy: { startDate: "asc" },
|
||||
select: { startDate: true },
|
||||
});
|
||||
if (next) {
|
||||
moved.openedEndDateBefore = cycle.endDate;
|
||||
moved.openedEndDateAfter = addDays(next.startDate, -1);
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: cycle.id },
|
||||
data: {
|
||||
endDate: addDays(next.startDate, -1),
|
||||
lengthDays: dayDiff(next.startDate, date),
|
||||
syncVersion: { increment: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { cycleId: cycle.id, moved };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a logged day's bleeding is the first day of a period, and therefore
|
||||
* opens a cycle.
|
||||
*
|
||||
* Cycle rows used to come only from the one-tap period boundary. Every other
|
||||
* way of recording bleeding — the log sheet's flow chips, the bulk drain, an
|
||||
* Apple Health export of menstrual-flow samples — wrote a day-log and stopped
|
||||
* there, and the engine reads cycle rows. A person could log every period they
|
||||
* had and the module would still hold that none had happened.
|
||||
*
|
||||
* The rule is deliberately conservative, because a false cycle start corrupts
|
||||
* every length the engine derives afterwards:
|
||||
*
|
||||
* - SPOTTING does not open a cycle. It is as often the tail of a period or
|
||||
* its herald as its first day, and the user has an explicit chip for a
|
||||
* real flow when it is one.
|
||||
* - Bleeding flagged as between periods does not open a cycle. That flag
|
||||
* exists to say exactly this.
|
||||
* - A bleeding day within the hard physiological minimum cycle length of an
|
||||
* existing cycle's start is part of that cycle, not a new one. This is
|
||||
* what keeps day three of a period — or a day two somebody forgot and
|
||||
* entered later — from starting a cycle of its own, and it needs no
|
||||
* contiguity check to do it.
|
||||
*
|
||||
* The cost is that a genuinely short cycle (under the hard minimum) is not
|
||||
* inferred from flow alone. The one-tap start still opens one on any date, so
|
||||
* the case has an answer; guessing it from flow does not.
|
||||
*/
|
||||
export function bleedOpensCycle(
|
||||
flow: FlowLevel | null,
|
||||
intermenstrualBleeding: boolean,
|
||||
priorCycleStart: string | null,
|
||||
date: string,
|
||||
): boolean {
|
||||
if (flow === null || flow === "NONE" || flow === "SPOTTING") return false;
|
||||
if (intermenstrualBleeding) return false;
|
||||
if (priorCycleStart === null) return true;
|
||||
return dayDiff(date, priorCycleStart) >= HARD_CYCLE_MIN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a cycle for a bleeding day when `bleedOpensCycle` says it starts one.
|
||||
* Returns the opened cycle's id, or null when the day changes nothing.
|
||||
*
|
||||
* Runs its own transaction so the boundary work is atomic even when the caller
|
||||
* is a plain day-log write with no transaction of its own.
|
||||
*/
|
||||
export async function ensureCycleForBleedingDay(
|
||||
userId: string,
|
||||
date: string,
|
||||
tz: string | null,
|
||||
day: { flow: FlowLevel | null; intermenstrualBleeding: boolean },
|
||||
): Promise<string | null> {
|
||||
// Cheap pre-check before a transaction: most logged days are not a first
|
||||
// bleeding day, and the flow grade alone rules most of them out.
|
||||
if (
|
||||
day.flow === null ||
|
||||
day.flow === "NONE" ||
|
||||
day.flow === "SPOTTING" ||
|
||||
day.intermenstrualBleeding
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return prisma.$transaction(async (db) => {
|
||||
const prior = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: { lte: date } },
|
||||
orderBy: { startDate: "desc" },
|
||||
select: { startDate: true },
|
||||
});
|
||||
if (
|
||||
!bleedOpensCycle(
|
||||
day.flow,
|
||||
day.intermenstrualBleeding,
|
||||
prior?.startDate ?? null,
|
||||
date,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const { cycleId } = await openCycleAt(db, userId, date, tz);
|
||||
return cycleId;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the cycle that opens on `date`, if there is one, and hand its span
|
||||
* back to the cycle before it. The inverse of `openCycleAt`, and the shared
|
||||
* body behind every way of taking a period start back: deleting the day-log
|
||||
* that opened it, clearing that day's flow, and deleting the cycle itself.
|
||||
*
|
||||
* Returns null when no live cycle starts on that date.
|
||||
*/
|
||||
export async function removeCycleStartedOn(
|
||||
db: CycleDb,
|
||||
userId: string,
|
||||
date: string,
|
||||
): Promise<{ cycleId: string; reanchored: ReanchoredCycle | null } | null> {
|
||||
const opened = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: date },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!opened) return null;
|
||||
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: opened.id },
|
||||
data: { deletedAt: new Date(), syncVersion: { increment: 1 } },
|
||||
});
|
||||
return {
|
||||
cycleId: opened.id,
|
||||
reanchored: await reanchorAfterRemovedStart(db, userId, date),
|
||||
};
|
||||
}
|
||||
|
||||
/** The boundary columns the re-derivation moved, for the audit row. */
|
||||
export interface ReanchoredCycle {
|
||||
cycleId: string;
|
||||
endDateBefore: string | null;
|
||||
endDateAfter: string | null;
|
||||
lengthDaysBefore: number | null;
|
||||
lengthDaysAfter: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-derive the boundary of the cycle that precedes `removedStartDate` from
|
||||
* the cycles that remain. Call it AFTER the cycle at that date is soft-deleted
|
||||
* (the queries below read live rows only, so a still-live row at the removed
|
||||
* start would re-derive against itself and change nothing).
|
||||
*
|
||||
* Returns the columns it moved, or null when there is no preceding cycle or
|
||||
* the preceding cycle already holds the derived boundary — an idempotent
|
||||
* re-run must not bump `syncVersion` and make every device re-pull a row that
|
||||
* did not change.
|
||||
*/
|
||||
export async function reanchorAfterRemovedStart(
|
||||
db: CycleDb,
|
||||
userId: string,
|
||||
removedStartDate: string,
|
||||
): Promise<ReanchoredCycle | null> {
|
||||
const prior = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: { lt: removedStartDate } },
|
||||
orderBy: { startDate: "desc" },
|
||||
select: { id: true, startDate: true, endDate: true, lengthDays: true },
|
||||
});
|
||||
if (!prior) return null;
|
||||
|
||||
const next = await db.menstrualCycle.findFirst({
|
||||
where: { userId, deletedAt: null, startDate: { gt: removedStartDate } },
|
||||
orderBy: { startDate: "asc" },
|
||||
select: { startDate: true },
|
||||
});
|
||||
|
||||
// A cycle ends the day before the next one starts; with no next one it is
|
||||
// open again, which is the state the removed start took away from it.
|
||||
const endDate = next ? addDays(next.startDate, -1) : null;
|
||||
const lengthDays = next ? dayDiff(next.startDate, prior.startDate) : null;
|
||||
|
||||
if (prior.endDate === endDate && prior.lengthDays === lengthDays) return null;
|
||||
|
||||
await db.menstrualCycle.update({
|
||||
where: { id: prior.id },
|
||||
data: { endDate, lengthDays, syncVersion: { increment: 1 } },
|
||||
});
|
||||
|
||||
return {
|
||||
cycleId: prior.id,
|
||||
endDateBefore: prior.endDate,
|
||||
endDateAfter: endDate,
|
||||
lengthDaysBefore: prior.lengthDays,
|
||||
lengthDaysAfter: lengthDays,
|
||||
};
|
||||
}
|
||||
@@ -31,6 +31,7 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { encrypt, decrypt } from "@/lib/crypto";
|
||||
import { getOrCreateCycleProfile } from "@/lib/cycle/profile";
|
||||
import { ensureCycleForBleedingDay } from "@/lib/cycle/cycle-boundaries";
|
||||
import type { CycleDayLogInput } from "@/lib/validations/cycle";
|
||||
import type {
|
||||
CervicalMucus,
|
||||
@@ -387,6 +388,25 @@ async function writeDayLog(args: WriteArgs): Promise<DayLogWriteResult> {
|
||||
? (entry.cervixOpening ?? null)
|
||||
: (existing?.cervixOpening ?? null);
|
||||
|
||||
// A first bleeding day opens the cycle it belongs to. Cycle rows used to
|
||||
// come only from the one-tap period boundary, so a person who logged every
|
||||
// period as flow had a module that held none had ever happened — no lengths,
|
||||
// no forecast, an empty chart. This is the one shared seam behind the single
|
||||
// capture, the bulk drain, the Apple Health fold and the boundary itself, so
|
||||
// all four infer a start the same way (the boundary's own write lands on a
|
||||
// date that already has a cycle, which the detector declines). The day is
|
||||
// then attributed to the cycle it just opened rather than the one before it.
|
||||
const openedCycleId = await ensureCycleForBleedingDay(
|
||||
userId,
|
||||
entry.date,
|
||||
tz,
|
||||
{
|
||||
flow,
|
||||
intermenstrualBleeding,
|
||||
},
|
||||
);
|
||||
const attributedCycleId = openedCycleId ?? cycleId;
|
||||
|
||||
// Was any of the five sensitive fields actually supplied in THIS update?
|
||||
// Used to decide whether an undecryptable existing envelope may be preserved
|
||||
// verbatim (an unrelated-field edit) or must be rewritten (the user is
|
||||
@@ -479,7 +499,7 @@ async function writeDayLog(args: WriteArgs): Promise<DayLogWriteResult> {
|
||||
const updateData: Prisma.CycleDayLogUncheckedUpdateInput = {
|
||||
...baseData,
|
||||
...(entry.externalId ? { date: entry.date } : {}),
|
||||
...(cycleId !== null ? { cycleId } : {}),
|
||||
...(attributedCycleId !== null ? { cycleId: attributedCycleId } : {}),
|
||||
deletedAt: null,
|
||||
// Only bump syncVersion when a field actually changed — an unchanged
|
||||
// re-post must be a true no-op on the /api/sync/changes feed so other
|
||||
@@ -498,7 +518,7 @@ async function writeDayLog(args: WriteArgs): Promise<DayLogWriteResult> {
|
||||
tz,
|
||||
source,
|
||||
externalId: entry.externalId ?? null,
|
||||
cycleId,
|
||||
cycleId: attributedCycleId,
|
||||
flow,
|
||||
intermenstrualBleeding,
|
||||
basalBodyTempC,
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
type CyclePhase,
|
||||
type PhaseCycle,
|
||||
resolveLuteal,
|
||||
clampLuteal,
|
||||
POPULATION_DEFAULT_CYCLE,
|
||||
} from "@/lib/cycle";
|
||||
import type {
|
||||
CycleProfile,
|
||||
@@ -32,6 +34,13 @@ export interface CalendarDayDTO {
|
||||
isFertileWindow: boolean;
|
||||
isPredictedOvulation: boolean;
|
||||
isPeriodLogged: boolean;
|
||||
/**
|
||||
* Whether a logged cycle opens on this day. The client uses it to say what a
|
||||
* delete would take: removing the day-log of a cycle start removes the start
|
||||
* too, and a confirm dialog that does not name that is asking about the
|
||||
* wrong thing.
|
||||
*/
|
||||
isCycleStart: boolean;
|
||||
flow: string | null;
|
||||
hasSymptoms: boolean;
|
||||
confidence: number;
|
||||
@@ -129,9 +138,30 @@ function periodLengthOf(
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a contiguous `PhaseCycle[]` from the observed cycles (each cycle's
|
||||
* span ends where the next begins; the latest open cycle runs to the
|
||||
* predicted next-period start). Used to label every calendar day's phase.
|
||||
* Build a contiguous `PhaseCycle[]` from the observed cycles: each closed
|
||||
* cycle's span ends where the next begins, and the latest open cycle runs to
|
||||
* the predicted next-period start — or, when that day has come and gone with
|
||||
* no period logged, on through `today`.
|
||||
*
|
||||
* That trailing extension is the difference between a late period and no
|
||||
* record at all. A cycle stays open until the next one starts, and a forecast
|
||||
* is a forecast: the day after a missed prediction is still a day of the cycle
|
||||
* the person is in. Ending the span at the predicted start instead made every
|
||||
* day past it carry no phase, which the verdict resolver could only read as
|
||||
* "today falls outside every known cycle window" — so an ordinary three-days-
|
||||
* late period reported INSUFFICIENT_DATA, and the honest OVERDUE state was
|
||||
* unreachable unless the engine itself forecast a cycle longer than the grace
|
||||
* window. The count is bounded on the other side: `resolveCycleVerdict` stops
|
||||
* claiming a cycle day once the run passes the profile's typical length plus
|
||||
* its grace window.
|
||||
*
|
||||
* The extension deliberately does NOT move the ovulation estimate. Left to
|
||||
* `phaseForDay`, an ovulation with no confirmed date is back-calculated from
|
||||
* the span's own length, so a window that grows a day per day of delay would
|
||||
* walk the estimate — and every FOLLICULAR/OVULATORY/LUTEAL boundary already
|
||||
* drawn for that cycle — forward with it. The open cycle therefore carries an
|
||||
* explicit anchor derived from the PREDICTED length, which is the same date
|
||||
* `phaseForDay` computes when the span ends where the forecast said it would.
|
||||
*/
|
||||
export function buildPhaseCycles(
|
||||
cycles: readonly Pick<
|
||||
@@ -140,18 +170,37 @@ export function buildPhaseCycles(
|
||||
>[],
|
||||
predictedNextStart: string | null,
|
||||
lutealLength: number,
|
||||
/** Today in the USER's timezone. The open cycle runs at least this far. */
|
||||
today: string,
|
||||
): PhaseCycle[] {
|
||||
const sorted = [...cycles].sort((a, b) => dayDiff(a.startDate, b.startDate));
|
||||
const out: PhaseCycle[] = [];
|
||||
for (let i = 0; i < sorted.length; i++) {
|
||||
const c = sorted[i];
|
||||
const next = sorted[i + 1];
|
||||
if (next) {
|
||||
out.push({
|
||||
startDate: c.startDate,
|
||||
nextStart: next.startDate,
|
||||
ovulationDate: c.ovulationDate,
|
||||
periodLength: periodLengthOf(c),
|
||||
lutealLength,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// The open cycle. `phaseForDay` treats `nextStart` as exclusive, so the
|
||||
// window has to reach the day AFTER today for today to carry a phase.
|
||||
const forecastEnd =
|
||||
predictedNextStart ?? addDays(c.startDate, POPULATION_DEFAULT_CYCLE);
|
||||
const throughToday = addDays(today, 1);
|
||||
const nextStart =
|
||||
next?.startDate ?? predictedNextStart ?? addDays(c.startDate, 28);
|
||||
dayDiff(throughToday, forecastEnd) > 0 ? throughToday : forecastEnd;
|
||||
out.push({
|
||||
startDate: c.startDate,
|
||||
nextStart,
|
||||
ovulationDate: c.ovulationDate,
|
||||
ovulationDate:
|
||||
c.ovulationDate ?? addDays(forecastEnd, -clampLuteal(lutealLength)),
|
||||
periodLength: periodLengthOf(c),
|
||||
lutealLength,
|
||||
});
|
||||
@@ -186,11 +235,14 @@ export function phaseForDate(
|
||||
>[],
|
||||
predictedNextStart: string | null,
|
||||
lutealLength: number,
|
||||
/** Today in the USER's timezone — how far a still-open cycle runs. */
|
||||
today: string,
|
||||
): { phase: CyclePhase | null; dayOfCycle: number | null } {
|
||||
const phaseCycles = buildPhaseCycles(
|
||||
cycles,
|
||||
predictedNextStart,
|
||||
lutealLength,
|
||||
today,
|
||||
);
|
||||
for (const pc of phaseCycles) {
|
||||
const r = phaseForDay(date, pc);
|
||||
@@ -219,11 +271,14 @@ export function buildPhaseDayMap(
|
||||
lutealLength: number,
|
||||
from: string,
|
||||
to: string,
|
||||
/** Today in the USER's timezone — how far a still-open cycle runs. */
|
||||
today: string,
|
||||
): Map<string, CyclePhase> {
|
||||
const phaseCycles = buildPhaseCycles(
|
||||
cycles,
|
||||
predictedNextStart,
|
||||
lutealLength,
|
||||
today,
|
||||
);
|
||||
const out = new Map<string, CyclePhase>();
|
||||
const span = dayDiff(to, from);
|
||||
@@ -304,6 +359,7 @@ export function buildCalendar(
|
||||
cycles,
|
||||
prediction?.nextPeriodStart ?? null,
|
||||
lutealLength,
|
||||
today,
|
||||
);
|
||||
|
||||
// Forward predicted period bar: [nextPeriodStart, +predictedPeriodLength).
|
||||
@@ -319,6 +375,8 @@ export function buildCalendar(
|
||||
const logByDate = new Map<string, CalendarDayLogRow>();
|
||||
for (const l of dayLogs) logByDate.set(l.date, l);
|
||||
|
||||
const cycleStartDates = new Set(cycles.map((c) => c.startDate));
|
||||
|
||||
const days: CalendarDayDTO[] = [];
|
||||
const span = dayDiff(to, from);
|
||||
for (let i = 0; i <= span; i++) {
|
||||
@@ -356,6 +414,7 @@ export function buildCalendar(
|
||||
isFertileWindow,
|
||||
isPredictedOvulation,
|
||||
isPeriodLogged: log?.flow != null && log.flow !== "NONE",
|
||||
isCycleStart: cycleStartDates.has(date),
|
||||
flow: log?.flow ?? null,
|
||||
hasSymptoms: log?.hasSymptoms ?? false,
|
||||
confidence: prediction?.confidence ?? 0,
|
||||
|
||||
+20
-1
@@ -103,7 +103,26 @@ export const LUTEAL_DEFAULT = 14;
|
||||
export const LUTEAL_MIN = 10;
|
||||
export const LUTEAL_MAX = 16;
|
||||
|
||||
/** §4 — six-day fertile window: ovulation − 5 … ovulation + 1. */
|
||||
/**
|
||||
* §4 — the fertile window: ovulation − 5 … ovulation + 1, seven days.
|
||||
*
|
||||
* Wilcox's six-day window is the five days BEFORE ovulation plus the day
|
||||
* itself, and the trailing day here is a deliberate departure from it. The
|
||||
* six-day figure is measured against a KNOWN ovulation day; ours is estimated,
|
||||
* usually by back-calculating a luteal length from a median cycle, and an
|
||||
* estimate that lands a day early would put the last fertile day outside a
|
||||
* window drawn tight to it. The ovum also stays viable for the better part of a
|
||||
* day after release, so the extra day is not only estimator slack.
|
||||
*
|
||||
* The asymmetry of the cost decides the direction. This window is surfaced to
|
||||
* people trying to conceive and to people avoiding it, and for the second group
|
||||
* a window one day too short is a window that misses. The constants are the
|
||||
* conservative reading; the comment used to claim six days and describe seven,
|
||||
* which is the only part of this that was wrong.
|
||||
*
|
||||
* Changing either constant changes what the iOS client reimplements from the
|
||||
* same spec, so it needs a coordination note, not just an edit here.
|
||||
*/
|
||||
export const FERTILE_PRE = 5;
|
||||
export const FERTILE_POST = 1;
|
||||
|
||||
|
||||
@@ -116,6 +116,21 @@ export interface ResolveCycleVerdictInput {
|
||||
/** Already goal- and cold-start-gated fertile window bounds. */
|
||||
fertileWindowStart?: string | null;
|
||||
fertileWindowEnd?: string | null;
|
||||
/**
|
||||
* The latest LOGGED period start at or before today, or null when the record
|
||||
* holds none. Read straight off the cycle rows, never off the grid.
|
||||
*
|
||||
* The grid's phase labels are gated: the calendar suppresses the whole phase
|
||||
* band while the engine is still learning (fewer than three observed cycles),
|
||||
* because a population-framed phase word off one or two cycles is not earned.
|
||||
* The day count is not that kind of claim — it is the number of days since a
|
||||
* start the person entered themselves — but deriving it from the labelled run
|
||||
* meant the gate took both, and a record with three logged periods rendered an
|
||||
* empty ring under an offer to log a first period. This anchor keeps the count
|
||||
* and the honest overdue judgement available when the labels are withheld;
|
||||
* the phase stays null, which is the part the gate is actually about.
|
||||
*/
|
||||
lastPeriodStart?: string | null;
|
||||
}
|
||||
|
||||
/** Below this many labelled days in the current cycle run, the ring would
|
||||
@@ -234,6 +249,41 @@ function resolveFertileWindow(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The verdict for a record whose grid carries no phase for today but whose
|
||||
* cycle rows carry a logged period start: count from that start, and apply the
|
||||
* same overdue ceiling. No phase is claimed — that is exactly the claim the
|
||||
* missing labels were withholding. Null when no start precedes today, which is
|
||||
* the one case that really is INSUFFICIENT_DATA.
|
||||
*/
|
||||
function verdictFromLoggedStart(
|
||||
input: ResolveCycleVerdictInput,
|
||||
fertileWindow: CycleVerdict["fertileWindow"],
|
||||
daysUntilNext: number | null,
|
||||
): CycleVerdict | null {
|
||||
const { today, profile, lastPeriodStart } = input;
|
||||
if (!lastPeriodStart) return null;
|
||||
const elapsed = dayDiff(today, lastPeriodStart);
|
||||
if (elapsed < 0) return null;
|
||||
|
||||
const dayOfCycle = elapsed + 1;
|
||||
const typicalLength = typicalCycleLength(profile);
|
||||
const ideal = idealizedSpans(profile);
|
||||
const overdue = dayOfCycle > typicalLength + OVERDUE_GRACE_DAYS;
|
||||
|
||||
return {
|
||||
state: overdue ? "OVERDUE" : "IN_CYCLE",
|
||||
dayOfCycle: overdue ? null : dayOfCycle,
|
||||
cycleLength: ideal.cycleLength,
|
||||
phase: null,
|
||||
spans: ideal.spans,
|
||||
cycleStartDate: lastPeriodStart,
|
||||
overdueDays: overdue ? dayOfCycle - typicalLength : null,
|
||||
daysUntilNext,
|
||||
fertileWindow,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve everything a client needs to render the cycle ring and its caption.
|
||||
* The only place in the product that decides any of it.
|
||||
@@ -259,17 +309,39 @@ export function resolveCycleVerdict(
|
||||
fertileWindow,
|
||||
};
|
||||
|
||||
if (!todayDay || todayDay.phase == null) return nothingToSay;
|
||||
if (!todayDay || todayDay.phase == null) {
|
||||
return (
|
||||
verdictFromLoggedStart(input, fertileWindow, daysUntilNext) ??
|
||||
nothingToSay
|
||||
);
|
||||
}
|
||||
|
||||
// Sort dates ascending and find today's index.
|
||||
const sorted = [...days].sort((a, b) => a.date.localeCompare(b.date));
|
||||
const todayIdx = sorted.findIndex((d) => d.date === today);
|
||||
if (todayIdx < 0) return nothingToSay;
|
||||
if (todayIdx < 0) {
|
||||
return (
|
||||
verdictFromLoggedStart(input, fertileWindow, daysUntilNext) ??
|
||||
nothingToSay
|
||||
);
|
||||
}
|
||||
|
||||
const startIdx = findCycleStartIndex(sorted, todayIdx);
|
||||
const cycleStartDate = sorted[startIdx].date;
|
||||
const run = sorted.slice(startIdx, todayIdx + 1);
|
||||
const dayOfCycle = run.length;
|
||||
|
||||
// The day count comes from the logged start when the caller supplied one,
|
||||
// and only falls back to the length of the labelled run when it did not.
|
||||
// The run is bounded by the grid, so counting rows made the answer depend on
|
||||
// how much calendar the caller happened to ask for: the same day reads as
|
||||
// day 11 over a month and day 23 over three. That was latent while every
|
||||
// caller asked for the same ninety days, and stopped being latent when the
|
||||
// month grid started reading its own month. The arcs below stay grid-derived
|
||||
// — they are about what the ring can draw, not about what day it is.
|
||||
const anchoredStart =
|
||||
input.lastPeriodStart && dayDiff(today, input.lastPeriodStart) >= 0
|
||||
? input.lastPeriodStart
|
||||
: sorted[startIdx].date;
|
||||
const cycleStartDate = anchoredStart;
|
||||
const dayOfCycle = dayDiff(today, anchoredStart) + 1;
|
||||
|
||||
// Honest ceiling: once the run overshoots the typical length + grace, the
|
||||
// count reflects the engine's open-ended cycle window, not an observed
|
||||
|
||||
@@ -181,6 +181,10 @@ const cycleCalendarDayDto = z.object({
|
||||
isFertileWindow: z.boolean(),
|
||||
isPredictedOvulation: z.boolean(),
|
||||
isPeriodLogged: z.boolean(),
|
||||
isCycleStart: z.boolean().meta({
|
||||
description:
|
||||
"Whether a logged cycle opens on this day. Deleting this day's log removes that cycle start with it.",
|
||||
}),
|
||||
flow: flowLevelEnum.nullable(),
|
||||
hasSymptoms: z.boolean(),
|
||||
confidence: z.number(),
|
||||
|
||||
Reference in new issue
Block a user