mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Merge pull request #1376 from ferges123/fix/illness-episode-dates-publish
fix(illness): allow adding episodes before noon
This commit is contained in:
11 files changed
+653
-90
No files matched your search
@@ -42,6 +42,11 @@
|
||||
links the help page. Brave keeps push messaging off by default, so in
|
||||
Brave the message names the setting to turn on: "Use Google services
|
||||
for push messaging" under brave://settings/privacy. (Discussion #1378)
|
||||
- **Illness episode onset dates keep the intended calendar day.**
|
||||
Creating a new illness episode in the morning was refused because its noon
|
||||
default was rejected as in the future, and onset dates could display as the
|
||||
wrong calendar day in non-UTC time zones. Saving now anchors to the current
|
||||
time when before local noon and preserves stored timestamps on edit.
|
||||
|
||||
### Security
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Illness episode date serialization, timezone handling & window tests.
|
||||
*
|
||||
* Covers:
|
||||
* - Before/after noon serialization (morning clamp to now vs noon anchor).
|
||||
* - UTC+14 and UTC-12 boundary timezones.
|
||||
* - Daylight Saving Time (DST) transitions.
|
||||
* - Preserving stored instant on edit when calendar date is unchanged.
|
||||
* - Same-day clamp (resolvedAt clamped up to onsetAt when resolved === onset).
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { illnessEpisodeCreateSchema } from "@/lib/validations/illness";
|
||||
import {
|
||||
resolveEpisodeInstant,
|
||||
resolveEpisodeWindow,
|
||||
serializeEpisodeDate,
|
||||
toLocalDateKey,
|
||||
} from "../dates";
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("episode date serialization — before and after noon", () => {
|
||||
it("serializes today before local noon to now", () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const tz = "Europe/Berlin";
|
||||
// 08:30 local time on 2026-11-10 (07:30 UTC in CET)
|
||||
const now = new Date("2026-11-10T07:30:00.000Z");
|
||||
vi.setSystemTime(now);
|
||||
|
||||
const onsetAt = serializeEpisodeDate("2026-11-10", tz);
|
||||
|
||||
expect(onsetAt).toBe("2026-11-10T07:30:00.000Z");
|
||||
expect(toLocalDateKey(onsetAt, tz)).toBe("2026-11-10");
|
||||
|
||||
const parsed = illnessEpisodeCreateSchema.safeParse({
|
||||
label: "Headache",
|
||||
type: "INFECTION",
|
||||
onsetAt,
|
||||
});
|
||||
expect(parsed.success).toBe(true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("serializes today after local noon and historical dates to local noon", () => {
|
||||
const tz = "Europe/Berlin";
|
||||
// 15:30 local time on 2026-11-10 (14:30 UTC in CET)
|
||||
const now = new Date("2026-11-10T14:30:00.000Z");
|
||||
|
||||
// Today after noon anchors to local noon (12:00 CET = 11:00 UTC)
|
||||
const todayOnset = serializeEpisodeDate("2026-11-10", tz, now);
|
||||
expect(todayOnset).toBe("2026-11-10T11:00:00.000Z");
|
||||
expect(toLocalDateKey(todayOnset, tz)).toBe("2026-11-10");
|
||||
|
||||
// Historical date also anchors to local noon
|
||||
const histOnset = serializeEpisodeDate("2026-11-05", tz, now);
|
||||
expect(histOnset).toBe("2026-11-05T11:00:00.000Z");
|
||||
expect(toLocalDateKey(histOnset, tz)).toBe("2026-11-05");
|
||||
});
|
||||
});
|
||||
|
||||
describe("episode date serialization — extreme timezones (UTC+14 & UTC-12)", () => {
|
||||
it("preserves calendar date in UTC+14 (Pacific/Kiritimati)", () => {
|
||||
const tz = "Pacific/Kiritimati";
|
||||
// Local noon on 2026-11-10 in UTC+14 is 2026-11-09T22:00:00.000Z
|
||||
const now = new Date("2026-11-10T04:00:00.000Z"); // local 18:00
|
||||
const onsetAt = serializeEpisodeDate("2026-11-10", tz, now);
|
||||
|
||||
expect(onsetAt).toBe("2026-11-09T22:00:00.000Z");
|
||||
expect(toLocalDateKey(onsetAt, tz)).toBe("2026-11-10");
|
||||
});
|
||||
|
||||
it("preserves calendar date in UTC-12 (Etc/GMT+12)", () => {
|
||||
const tz = "Etc/GMT+12";
|
||||
// Local noon on 2026-11-10 in UTC-12 is 2026-11-11T00:00:00.000Z
|
||||
const now = new Date("2026-11-11T04:00:00.000Z"); // local 16:00
|
||||
const onsetAt = serializeEpisodeDate("2026-11-10", tz, now);
|
||||
|
||||
expect(onsetAt).toBe("2026-11-11T00:00:00.000Z");
|
||||
expect(toLocalDateKey(onsetAt, tz)).toBe("2026-11-10");
|
||||
});
|
||||
});
|
||||
|
||||
describe("episode date serialization — daylight saving time (DST)", () => {
|
||||
it("handles summer EDT (UTC-4) and winter EST (UTC-5) correctly", () => {
|
||||
const tz = "America/New_York";
|
||||
const now = new Date("2026-12-01T20:00:00.000Z");
|
||||
|
||||
// Summer EDT (UTC-4): noon = 16:00 UTC
|
||||
const summerOnset = serializeEpisodeDate("2026-07-01", tz, now);
|
||||
expect(summerOnset).toBe("2026-07-01T16:00:00.000Z");
|
||||
expect(toLocalDateKey(summerOnset, tz)).toBe("2026-07-01");
|
||||
|
||||
// Winter EST (UTC-5): noon = 17:00 UTC
|
||||
const winterOnset = serializeEpisodeDate("2026-01-15", tz, now);
|
||||
expect(winterOnset).toBe("2026-01-15T17:00:00.000Z");
|
||||
expect(toLocalDateKey(winterOnset, tz)).toBe("2026-01-15");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEpisodeInstant & resolveEpisodeWindow", () => {
|
||||
it("preserves exact stored instant when calendar date is unchanged", () => {
|
||||
const tz = "America/New_York";
|
||||
const now = new Date("2026-11-10T15:00:00.000Z");
|
||||
const storedInstant = "2026-11-05T09:42:15.123Z";
|
||||
const calendarDate = toLocalDateKey(storedInstant, tz); // "2026-11-05"
|
||||
|
||||
const resolved = resolveEpisodeInstant({
|
||||
date: calendarDate,
|
||||
storedInstant,
|
||||
now,
|
||||
timeZone: tz,
|
||||
});
|
||||
expect(resolved).toBe(storedInstant);
|
||||
|
||||
// When the user changes the calendar date, it freshly serializes
|
||||
const changed = resolveEpisodeInstant({
|
||||
date: "2026-11-06",
|
||||
storedInstant,
|
||||
now,
|
||||
timeZone: tz,
|
||||
});
|
||||
expect(changed).toBe("2026-11-06T17:00:00.000Z");
|
||||
});
|
||||
|
||||
it("clamps same-day resolvedAt up to onsetAt when resolved instant is earlier", () => {
|
||||
const tz = "UTC";
|
||||
const now = new Date("2026-11-10T10:00:00.000Z");
|
||||
// Both on 2026-11-10; storedResolved is 08:00 UTC, freshly serialized onsetAt is 10:00 UTC
|
||||
const window = resolveEpisodeWindow({
|
||||
onset: "2026-11-10",
|
||||
resolved: "2026-11-10",
|
||||
storedOnset: null,
|
||||
storedResolved: "2026-11-10T08:00:00.000Z",
|
||||
now,
|
||||
timeZone: tz,
|
||||
});
|
||||
|
||||
expect(window.onsetAt).toBe("2026-11-10T10:00:00.000Z");
|
||||
// resolvedAt clamped up to onsetAt
|
||||
expect(window.resolvedAt).toBe(window.onsetAt);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* Real-browser integration tests for the illness episode save lifecycle.
|
||||
*
|
||||
* Exercises `<NewEpisodeSheet>` in a real Chromium browser with TanStack Query
|
||||
* and the application providers, stubbing network traffic at the fetch boundary:
|
||||
* 1. Edit hydration across timezones (Asia/Tokyo onset dates).
|
||||
* 2. Disabling save button while POST is in-flight.
|
||||
* 3. Updating an episode via PATCH with preserved stored timestamps.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
|
||||
import { storeDateFormat } from "@/lib/date-format";
|
||||
import { storeTimezone } from "@/lib/timezone-mirror";
|
||||
import { pinDate } from "../../../../tests/browser/clock";
|
||||
import {
|
||||
stubFetch,
|
||||
type FetchStub,
|
||||
} from "../../../../tests/browser/fetch-stub";
|
||||
import { renderWithApp } from "../../../../tests/browser/render";
|
||||
import { NewEpisodeSheet } from "../new-episode-sheet";
|
||||
import type { IllnessEpisodeDTO } from "../types";
|
||||
|
||||
let api: FetchStub;
|
||||
|
||||
beforeEach(() => {
|
||||
storeTimezone("");
|
||||
storeDateFormat("AUTO");
|
||||
api = stubFetch()
|
||||
.on("GET", "/api/illness/episodes", { data: [] })
|
||||
.on("GET", "/api/body-sites", { data: { sites: [] } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
storeTimezone("");
|
||||
storeDateFormat("AUTO");
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function assertAllowedRequests(allowed: string[]) {
|
||||
const actual = api.requests.map((r) => `${r.method} ${r.path.split("?")[0]}`);
|
||||
for (const entry of actual) {
|
||||
expect(allowed).toContain(entry);
|
||||
}
|
||||
}
|
||||
|
||||
describe("<NewEpisodeSheet> save lifecycle in browser", () => {
|
||||
it("hydrates edit onset into the mirror's timezone and renders according to date format", async () => {
|
||||
const timezone = "Asia/Tokyo";
|
||||
const dateFormat = "MDY" as const;
|
||||
const onsetAt = "2026-11-09T20:00:00.000Z";
|
||||
const expectedMirrorDate = "2026-11-10";
|
||||
const expectedVisibleDate = "11/10/2026";
|
||||
|
||||
storeTimezone(timezone);
|
||||
storeDateFormat(dateFormat);
|
||||
|
||||
const editEpisode: IllnessEpisodeDTO = {
|
||||
id: "ep-tz-1",
|
||||
label: "Seasonal Allergy",
|
||||
type: "ALLERGY",
|
||||
lifecycle: "ACUTE",
|
||||
onsetAt,
|
||||
resolvedAt: null,
|
||||
parentConditionId: null,
|
||||
note: null,
|
||||
bodySite: null,
|
||||
laterality: null,
|
||||
createdAt: onsetAt,
|
||||
updatedAt: onsetAt,
|
||||
};
|
||||
|
||||
const { screen } = await renderWithApp(
|
||||
<NewEpisodeSheet
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
today="2026-11-10"
|
||||
editEpisode={editEpisode}
|
||||
/>,
|
||||
{ user: { timezone, dateFormat } },
|
||||
);
|
||||
|
||||
const dialog = screen.getByRole("dialog");
|
||||
await expect.element(dialog).toBeVisible();
|
||||
|
||||
const selector =
|
||||
'div:has(> label[for="illness-onset"]) [data-slot="date-field"] input[type="text"]';
|
||||
await expect
|
||||
.poll(() => document.querySelector<HTMLInputElement>(selector))
|
||||
.not.toBeNull();
|
||||
const dateInputElement = document.querySelector<HTMLInputElement>(selector);
|
||||
if (!dateInputElement) {
|
||||
throw new Error("Visible onset DateField input not found");
|
||||
}
|
||||
const visibleOnsetInput = page.elementLocator(dateInputElement);
|
||||
await expect.element(visibleOnsetInput).toBeVisible();
|
||||
await expect.element(visibleOnsetInput).toHaveValue(expectedVisibleDate);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
document.querySelector<HTMLInputElement>("input#illness-onset")
|
||||
?.value,
|
||||
)
|
||||
.toBe(expectedMirrorDate);
|
||||
|
||||
assertAllowedRequests(["GET /api/illness/episodes", "GET /api/body-sites"]);
|
||||
});
|
||||
|
||||
it("saves today's episode before noon and disables save button while POST is in-flight", async () => {
|
||||
const timezone = "Europe/Berlin";
|
||||
const pinnedNow = "2026-11-10T08:30:00.000Z";
|
||||
const localNoon = "2026-11-10T11:00:00.000Z";
|
||||
|
||||
storeTimezone(timezone);
|
||||
pinDate(pinnedNow);
|
||||
|
||||
const post = api.deferred("POST", "/api/illness/episodes");
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
const { screen } = await renderWithApp(
|
||||
<NewEpisodeSheet
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
today="2026-11-10"
|
||||
/>,
|
||||
{ user: { timezone } },
|
||||
);
|
||||
|
||||
const nameInput = screen.getByLabelText("Name");
|
||||
await nameInput.fill("Migraine");
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: "Save" });
|
||||
await expect.element(saveButton).toBeEnabled();
|
||||
|
||||
// Clearing onset disables the save button; restoring onset re-enables save
|
||||
const onsetSelector =
|
||||
'div:has(> label[for="illness-onset"]) [data-slot="date-field"] input[type="text"]';
|
||||
await expect
|
||||
.poll(() => document.querySelector<HTMLInputElement>(onsetSelector))
|
||||
.not.toBeNull();
|
||||
const onsetInputElement =
|
||||
document.querySelector<HTMLInputElement>(onsetSelector);
|
||||
if (!onsetInputElement) {
|
||||
throw new Error("Visible onset DateField input not found");
|
||||
}
|
||||
const visibleOnsetInput = page.elementLocator(onsetInputElement);
|
||||
await visibleOnsetInput.fill("");
|
||||
onsetInputElement.blur();
|
||||
await expect.element(saveButton).toBeDisabled();
|
||||
|
||||
await visibleOnsetInput.fill("2026-11-10");
|
||||
onsetInputElement.blur();
|
||||
await expect.element(saveButton).toBeEnabled();
|
||||
|
||||
await saveButton.click();
|
||||
|
||||
// While deferred, save button enters pending/disabled state
|
||||
await expect.element(saveButton).toBeDisabled();
|
||||
|
||||
// Verify exactly one POST was dispatched
|
||||
await expect
|
||||
.poll(() => api.calls("POST", "/api/illness/episodes").length)
|
||||
.toBe(1);
|
||||
|
||||
// Release the deferred POST
|
||||
post.release({
|
||||
status: 201,
|
||||
data: {
|
||||
id: "ep-created-1",
|
||||
label: "Migraine",
|
||||
type: "INFECTION",
|
||||
lifecycle: "ACUTE",
|
||||
onsetAt: pinnedNow,
|
||||
resolvedAt: null,
|
||||
parentConditionId: null,
|
||||
note: null,
|
||||
bodySite: null,
|
||||
laterality: null,
|
||||
createdAt: pinnedNow,
|
||||
updatedAt: pinnedNow,
|
||||
},
|
||||
});
|
||||
|
||||
// Sheet requests closure after successful save
|
||||
await expect.poll(() => onOpenChange.mock.calls.length).toBe(1);
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
|
||||
// Request count remains strictly 1 and matches the payload
|
||||
expect(api.calls("POST", "/api/illness/episodes")).toHaveLength(1);
|
||||
const [createCall] = api.calls("POST", "/api/illness/episodes");
|
||||
expect(createCall.body).toMatchObject({
|
||||
label: "Migraine",
|
||||
type: "INFECTION",
|
||||
lifecycle: "ACUTE",
|
||||
parentConditionId: null,
|
||||
note: null,
|
||||
bodySite: null,
|
||||
laterality: null,
|
||||
});
|
||||
expect(createCall.body).toMatchObject({ onsetAt: pinnedNow });
|
||||
expect(createCall.body).not.toMatchObject({ onsetAt: localNoon });
|
||||
|
||||
assertAllowedRequests([
|
||||
"GET /api/illness/episodes",
|
||||
"GET /api/body-sites",
|
||||
"POST /api/illness/episodes",
|
||||
]);
|
||||
});
|
||||
|
||||
it("submits updated episode via PATCH and preserves stored timestamp when onset date is unchanged", async () => {
|
||||
const episode: IllnessEpisodeDTO = {
|
||||
id: "ep-edit-1",
|
||||
label: "Original label",
|
||||
type: "OTHER",
|
||||
lifecycle: "ACUTE",
|
||||
onsetAt: "2026-11-05T12:00:00.000Z",
|
||||
resolvedAt: null,
|
||||
parentConditionId: null,
|
||||
note: null,
|
||||
bodySite: null,
|
||||
laterality: null,
|
||||
createdAt: "2026-11-05T12:00:00.000Z",
|
||||
updatedAt: "2026-11-05T12:00:00.000Z",
|
||||
};
|
||||
const patch = api.deferred("PATCH", `/api/illness/episodes/${episode.id}`);
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
const { screen } = await renderWithApp(
|
||||
<NewEpisodeSheet
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
today="2026-11-10"
|
||||
editEpisode={episode}
|
||||
/>,
|
||||
);
|
||||
|
||||
const nameInput = screen.getByLabelText("Name");
|
||||
await nameInput.fill("Updated label");
|
||||
|
||||
const saveButton = screen.getByRole("button", { name: "Save" });
|
||||
await saveButton.click();
|
||||
|
||||
await expect.element(saveButton).toBeDisabled();
|
||||
|
||||
patch.release({
|
||||
status: 200,
|
||||
data: {
|
||||
...episode,
|
||||
label: "Updated label",
|
||||
},
|
||||
});
|
||||
|
||||
await expect.poll(() => onOpenChange.mock.calls.length).toBe(1);
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
|
||||
expect(
|
||||
api.calls("PATCH", `/api/illness/episodes/${episode.id}`),
|
||||
).toHaveLength(1);
|
||||
const [patchCall] = api.calls(
|
||||
"PATCH",
|
||||
`/api/illness/episodes/${episode.id}`,
|
||||
);
|
||||
expect(patchCall.body).toMatchObject({
|
||||
label: "Updated label",
|
||||
onsetAt: episode.onsetAt,
|
||||
});
|
||||
|
||||
assertAllowedRequests([
|
||||
"GET /api/illness/episodes",
|
||||
"GET /api/body-sites",
|
||||
`PATCH /api/illness/episodes/${episode.id}`,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
describe("episode saves", () => {
|
||||
it.each([
|
||||
["create", () => useCreateEpisode()],
|
||||
["update", () => useUpdateEpisode()],
|
||||
["update", () => useUpdateEpisode("e1")],
|
||||
["resolve", () => useResolveEpisode()],
|
||||
["delete", () => useDeleteEpisode()],
|
||||
["restore", () => useRestoreEpisode()],
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Date serialization and parsing helpers for illness episodes.
|
||||
*
|
||||
* Date-only fields (`YYYY-MM-DD`) from `<DateField>` are serialized to ISO 8601
|
||||
* instants for the `/api/illness/episodes` wire contract.
|
||||
*/
|
||||
import { userDayKey } from "@/lib/tz/format";
|
||||
import { zonedWallClockToUtc } from "@/lib/tz/wall-clock";
|
||||
|
||||
/**
|
||||
* Format a stored ISO instant to a `YYYY-MM-DD` calendar date string in the
|
||||
* target timezone.
|
||||
*/
|
||||
export function toLocalDateKey(iso: string, timeZone: string): string {
|
||||
return userDayKey(new Date(iso), timeZone);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a date-only input (`YYYY-MM-DD`) to an ISO 8601 instant.
|
||||
* Anchors to local noon in the user's timezone, or now if noon is still in the future.
|
||||
*/
|
||||
export function serializeEpisodeDate(
|
||||
date: string,
|
||||
timeZone: string,
|
||||
now: Date = new Date(),
|
||||
): string {
|
||||
const [year, month, day] = date.split("-").map(Number);
|
||||
const localNoon = zonedWallClockToUtc(
|
||||
{ year, month, day, hour: 12, minute: 0, second: 0 },
|
||||
timeZone,
|
||||
);
|
||||
const ms = Math.min(localNoon.getTime(), now.getTime());
|
||||
return new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve an episode instant from a calendar date input, preserving the exact
|
||||
* stored timestamp when the calendar date is unchanged in the active display timezone.
|
||||
*/
|
||||
export function resolveEpisodeInstant({
|
||||
date,
|
||||
storedInstant,
|
||||
now,
|
||||
timeZone,
|
||||
}: {
|
||||
date: string;
|
||||
storedInstant?: string | null;
|
||||
now: Date;
|
||||
timeZone: string;
|
||||
}): string {
|
||||
if (
|
||||
storedInstant != null &&
|
||||
date === toLocalDateKey(storedInstant, timeZone)
|
||||
) {
|
||||
return storedInstant;
|
||||
}
|
||||
return serializeEpisodeDate(date, timeZone, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve both instants of an episode save from its two calendar-date fields.
|
||||
*
|
||||
* Each field keeps its stored instant when the selected calendar date is
|
||||
* unchanged (see {@link resolveEpisodeInstant}); the rest are serialized. An
|
||||
* end date equal to the onset is clamped up to the onset's instant, because a
|
||||
* preserved end can otherwise sit before a freshly serialized same-day onset
|
||||
* (e.g. onset changed to today before local noon).
|
||||
*/
|
||||
export function resolveEpisodeWindow({
|
||||
onset,
|
||||
resolved,
|
||||
storedOnset,
|
||||
storedResolved,
|
||||
now,
|
||||
timeZone,
|
||||
}: {
|
||||
onset: string;
|
||||
resolved: string;
|
||||
storedOnset?: string | null;
|
||||
storedResolved?: string | null;
|
||||
now: Date;
|
||||
timeZone: string;
|
||||
}): { onsetAt: string; resolvedAt: string | null } {
|
||||
const onsetAt = resolveEpisodeInstant({
|
||||
date: onset,
|
||||
storedInstant: storedOnset,
|
||||
now,
|
||||
timeZone,
|
||||
});
|
||||
let resolvedAt =
|
||||
resolved === ""
|
||||
? null
|
||||
: resolveEpisodeInstant({
|
||||
date: resolved,
|
||||
storedInstant: storedResolved,
|
||||
now,
|
||||
timeZone,
|
||||
});
|
||||
if (
|
||||
resolvedAt !== null &&
|
||||
onset === resolved &&
|
||||
new Date(resolvedAt).getTime() < new Date(onsetAt).getTime()
|
||||
) {
|
||||
resolvedAt = onsetAt;
|
||||
}
|
||||
return { onsetAt, resolvedAt };
|
||||
}
|
||||
@@ -24,7 +24,12 @@ import { QueryErrorCard } from "@/components/ui/query-error-card";
|
||||
import { PageHeader } from "@/components/ui/page-header";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { RevealWhenSettled } from "@/components/ui/reveal-when-settled";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import {
|
||||
useDisplayTimezone,
|
||||
useTranslations,
|
||||
useFormatters,
|
||||
} from "@/lib/i18n/context";
|
||||
import { useTodayKey } from "@/components/day/use-today-key";
|
||||
import { bodySiteText } from "@/components/encounters/encounter-labels";
|
||||
import { canReadBodySites } from "@/hooks/use-body-sites";
|
||||
|
||||
@@ -34,15 +39,7 @@ import { LogDaySheet, useLastLoggableDay } from "./log-day-sheet";
|
||||
import { NewEpisodeSheet } from "./new-episode-sheet";
|
||||
import { EpisodeMenu } from "./episode-menu";
|
||||
import { useIllnessEpisode, useResolveEpisode } from "./use-illness";
|
||||
|
||||
/** Today as YYYY-MM-DD in the viewer's local calendar. */
|
||||
function todayLocal(): string {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(now.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
import { toLocalDateKey } from "./dates";
|
||||
|
||||
export function IllnessEpisodeDetail({ episodeId }: { episodeId: string }) {
|
||||
const { t } = useTranslations();
|
||||
@@ -65,7 +62,8 @@ export function IllnessEpisodeDetail({ episodeId }: { episodeId: string }) {
|
||||
|
||||
const [logOpen, setLogOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const today = todayLocal();
|
||||
const today = useTodayKey();
|
||||
const timeZone = useDisplayTimezone();
|
||||
const logLastDay = useLastLoggableDay(today, episode?.resolvedAt);
|
||||
|
||||
if (isError) {
|
||||
@@ -228,7 +226,7 @@ export function IllnessEpisodeDetail({ episodeId }: { episodeId: string }) {
|
||||
onOpenChange={setLogOpen}
|
||||
episodeId={episode.id}
|
||||
date={logLastDay}
|
||||
onsetDate={episode.onsetAt.slice(0, 10)}
|
||||
onsetDate={toLocalDateKey(episode.onsetAt, timeZone)}
|
||||
/>
|
||||
<NewEpisodeSheet
|
||||
open={editOpen}
|
||||
|
||||
@@ -39,7 +39,12 @@ import { PageHeader } from "@/components/ui/page-header";
|
||||
import { QueryErrorCard } from "@/components/ui/query-error-card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import {
|
||||
useDisplayTimezone,
|
||||
useTranslations,
|
||||
useFormatters,
|
||||
} from "@/lib/i18n/context";
|
||||
import { useTodayKey } from "@/components/day/use-today-key";
|
||||
import { applyOrder, useModuleListPrefs } from "@/lib/module-list-prefs";
|
||||
|
||||
import { LogDaySheet, useLastLoggableDay } from "./log-day-sheet";
|
||||
@@ -49,17 +54,9 @@ import { IllnessInsightsCard } from "./illness-insights-card";
|
||||
import { SymptomsSection } from "@/components/symptoms/symptoms-section";
|
||||
import { groupEpisodes } from "./group-episodes";
|
||||
import { useIllnessEpisodes, useResolveEpisode } from "./use-illness";
|
||||
import { toLocalDateKey } from "./dates";
|
||||
import type { IllnessEpisodeDTO } from "./types";
|
||||
|
||||
/** Today as a YYYY-MM-DD string in the viewer's local calendar. */
|
||||
function todayLocal(): string {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(now.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The flares and recurring bouts filed under a condition, inside its card or
|
||||
* list row. Each one names its course, since a recurring bout is not a flare,
|
||||
@@ -376,7 +373,8 @@ export function IllnessView() {
|
||||
const resolve = useResolveEpisode();
|
||||
const { prefs } = useModuleListPrefs("illness");
|
||||
|
||||
const today = todayLocal();
|
||||
const today = useTodayKey();
|
||||
const timeZone = useDisplayTimezone();
|
||||
const [newOpen, setNewOpen] = useState(false);
|
||||
const [editEpisode, setEditEpisode] = useState<IllnessEpisodeDTO | null>(
|
||||
null,
|
||||
@@ -534,7 +532,11 @@ export function IllnessView() {
|
||||
}}
|
||||
episodeId={logEpisodeId}
|
||||
date={logLastDay}
|
||||
onsetDate={logEpisode?.onsetAt.slice(0, 10)}
|
||||
onsetDate={
|
||||
logEpisode
|
||||
? toLocalDateKey(logEpisode.onsetAt, timeZone)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useDisplayTimezone, useTranslations } from "@/lib/i18n/context";
|
||||
import {
|
||||
BodySiteFields,
|
||||
type BodySiteSideValue,
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
useIllnessEpisodes,
|
||||
useUpdateEpisode,
|
||||
} from "./use-illness";
|
||||
import { resolveEpisodeWindow, toLocalDateKey } from "./dates";
|
||||
import type { IllnessEpisodeDTO, IllnessLifecycle, IllnessType } from "./types";
|
||||
|
||||
const TYPES: IllnessType[] = [
|
||||
@@ -57,14 +58,20 @@ const PARENTABLE: IllnessLifecycle[] = ["FLARE", "RECURRING"];
|
||||
const NONE = "__none__";
|
||||
|
||||
/** What the form opens with: the edited episode, or a new one from today. */
|
||||
function episodeForm(episode: IllnessEpisodeDTO | undefined, today: string) {
|
||||
function episodeForm(
|
||||
episode: IllnessEpisodeDTO | undefined,
|
||||
today: string,
|
||||
timeZone: string,
|
||||
) {
|
||||
return {
|
||||
label: episode?.label ?? "",
|
||||
type: episode?.type ?? ("INFECTION" as IllnessType),
|
||||
lifecycle: episode?.lifecycle ?? ("ACUTE" as IllnessLifecycle),
|
||||
onset: episode ? episode.onsetAt.slice(0, 10) : today,
|
||||
resolved: episode?.resolvedAt ? episode.resolvedAt.slice(0, 10) : "",
|
||||
parentId: episode?.parentConditionId ?? NONE,
|
||||
onset: episode ? toLocalDateKey(episode.onsetAt, timeZone) : today,
|
||||
resolved: episode?.resolvedAt
|
||||
? toLocalDateKey(episode.resolvedAt, timeZone)
|
||||
: "",
|
||||
parentId: episode?.parentConditionId ?? null,
|
||||
note: episode?.note ?? "",
|
||||
bodySite: episode?.bodySite ?? "",
|
||||
laterality: (episode?.laterality ?? null) as BodySiteSideValue,
|
||||
@@ -86,27 +93,26 @@ export function NewEpisodeSheet({
|
||||
editEpisode,
|
||||
}: NewEpisodeSheetProps) {
|
||||
const { t } = useTranslations();
|
||||
const timeZone = useDisplayTimezone();
|
||||
const create = useCreateEpisode();
|
||||
const update = useUpdateEpisode();
|
||||
const update = useUpdateEpisode(editEpisode?.id);
|
||||
const isEdit = editEpisode !== undefined;
|
||||
const pending = create.isPending || update.isPending;
|
||||
const isError = create.isError || update.isError;
|
||||
const [saveError, setSaveError] = useState(false);
|
||||
|
||||
// Candidate parents: live episodes other than the one being edited.
|
||||
const { data: allEpisodes } = useIllnessEpisodes(true);
|
||||
const parentCandidates = (allEpisodes ?? []).filter(
|
||||
(e) => e.id !== editEpisode?.id,
|
||||
);
|
||||
const parentCandidates =
|
||||
allEpisodes?.filter((e) => e.id !== editEpisode?.id) ?? [];
|
||||
|
||||
const [label, setLabel] = useState("");
|
||||
const [type, setType] = useState<IllnessType>("INFECTION");
|
||||
const [lifecycle, setLifecycle] = useState<IllnessLifecycle>("ACUTE");
|
||||
const [onset, setOnset] = useState(today);
|
||||
// Resolved/end date — "" means the episode is still ongoing (open-ended).
|
||||
// Backdating both onset and this end date lets a whole past episode be
|
||||
// recorded after the fact.
|
||||
// Resolved/end date — "" means ongoing (open-ended). Backdating both onset
|
||||
// and this end date lets a whole past episode be recorded after the fact.
|
||||
const [resolved, setResolved] = useState("");
|
||||
const [parentId, setParentId] = useState<string>(NONE);
|
||||
const [parentId, setParentId] = useState<string | null>(null);
|
||||
const [note, setNote] = useState("");
|
||||
// v1.39.2 — where on the body. Offered on every type: an injury or a joint
|
||||
// condition is the usual case, but nothing about a type rules a site out.
|
||||
@@ -117,9 +123,11 @@ export function NewEpisodeSheet({
|
||||
// render keyed on the open transition (React's recommended alternative to a
|
||||
// setState-in-effect).
|
||||
const [wasOpen, setWasOpen] = useState(false);
|
||||
const [seed, setSeed] = useState(() => episodeForm(editEpisode, today));
|
||||
const [seed, setSeed] = useState(() =>
|
||||
episodeForm(editEpisode, today, timeZone),
|
||||
);
|
||||
if (open && !wasOpen) {
|
||||
const next = episodeForm(editEpisode, today);
|
||||
const next = episodeForm(editEpisode, today, timeZone);
|
||||
setWasOpen(true);
|
||||
setSeed(next);
|
||||
setLabel(next.label);
|
||||
@@ -131,8 +139,10 @@ export function NewEpisodeSheet({
|
||||
setNote(next.note);
|
||||
setBodySite(next.bodySite);
|
||||
setLaterality(next.laterality);
|
||||
setSaveError(false);
|
||||
} else if (!open && wasOpen) {
|
||||
setWasOpen(false);
|
||||
setSaveError(false);
|
||||
}
|
||||
const form = {
|
||||
label,
|
||||
@@ -154,45 +164,37 @@ export function NewEpisodeSheet({
|
||||
const endBeforeStart = resolved !== "" && resolved < onset;
|
||||
|
||||
async function handleSave() {
|
||||
if (label.trim() === "" || endBeforeStart) return;
|
||||
const onsetAt = new Date(`${onset}T12:00:00`).toISOString();
|
||||
// "" ⇒ ongoing (null clears any stored end). Anchor to local noon so the
|
||||
// UTC instant lands on the intended calendar day regardless of offset.
|
||||
const resolvedAt =
|
||||
resolved === "" ? null : new Date(`${resolved}T12:00:00`).toISOString();
|
||||
const parentConditionId = showParent && parentId !== NONE ? parentId : null;
|
||||
if (pending || label.trim() === "" || onset === "" || endBeforeStart)
|
||||
return;
|
||||
setSaveError(false);
|
||||
const now = new Date();
|
||||
const { onsetAt, resolvedAt } = resolveEpisodeWindow({
|
||||
onset,
|
||||
resolved,
|
||||
storedOnset: editEpisode?.onsetAt,
|
||||
storedResolved: editEpisode?.resolvedAt,
|
||||
now,
|
||||
timeZone,
|
||||
});
|
||||
const payload = {
|
||||
label: label.trim(),
|
||||
type,
|
||||
lifecycle,
|
||||
onsetAt,
|
||||
resolvedAt,
|
||||
parentConditionId: showParent ? parentId : null,
|
||||
note: note.trim() === "" ? null : note,
|
||||
bodySite: bodySite.trim() || null,
|
||||
laterality,
|
||||
};
|
||||
try {
|
||||
if (isEdit && editEpisode) {
|
||||
await update.mutateAsync({
|
||||
id: editEpisode.id,
|
||||
input: {
|
||||
label: label.trim(),
|
||||
type,
|
||||
lifecycle,
|
||||
onsetAt,
|
||||
resolvedAt,
|
||||
parentConditionId,
|
||||
note: note.trim() === "" ? null : note,
|
||||
bodySite: bodySite.trim() || null,
|
||||
laterality,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await create.mutateAsync({
|
||||
label: label.trim(),
|
||||
type,
|
||||
lifecycle,
|
||||
onsetAt,
|
||||
resolvedAt,
|
||||
parentConditionId,
|
||||
note: note.trim() === "" ? null : note,
|
||||
bodySite: bodySite.trim() || null,
|
||||
laterality,
|
||||
});
|
||||
}
|
||||
await (isEdit && editEpisode
|
||||
? update.mutateAsync(payload)
|
||||
: create.mutateAsync(payload));
|
||||
onOpenChange(false);
|
||||
} catch {
|
||||
// Keep the sheet open; the error strip reports it.
|
||||
setSaveError(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +214,9 @@ export function NewEpisodeSheet({
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={pending || label.trim() === "" || endBeforeStart}
|
||||
disabled={
|
||||
pending || label.trim() === "" || onset === "" || endBeforeStart
|
||||
}
|
||||
>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
@@ -280,7 +284,10 @@ export function NewEpisodeSheet({
|
||||
{showParent ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="illness-parent">{t("illness.new.parent")}</Label>
|
||||
<Select value={parentId} onValueChange={setParentId}>
|
||||
<Select
|
||||
value={parentId ?? NONE}
|
||||
onValueChange={(v) => setParentId(v === NONE ? null : v)}
|
||||
>
|
||||
<SelectTrigger id="illness-parent" className="w-full">
|
||||
<SelectValue placeholder={t("illness.new.parentNone")} />
|
||||
</SelectTrigger>
|
||||
@@ -348,7 +355,7 @@ export function NewEpisodeSheet({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isError ? (
|
||||
{saveError ? (
|
||||
<p className="text-destructive text-sm" role="alert">
|
||||
{t("illness.new.saveError")}
|
||||
</p>
|
||||
|
||||
@@ -176,16 +176,11 @@ export function useCreateEpisode() {
|
||||
}
|
||||
|
||||
/** Edit an episode (partial). */
|
||||
export function useUpdateEpisode() {
|
||||
export function useUpdateEpisode(id?: string) {
|
||||
const invalidate = useInvalidateIllness();
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
id,
|
||||
input,
|
||||
}: {
|
||||
id: string;
|
||||
input: IllnessEpisodeUpdateInput;
|
||||
}) => apiPatch<IllnessEpisodeDTO>(`/api/illness/episodes/${id}`, input),
|
||||
mutationFn: (input: IllnessEpisodeUpdateInput) =>
|
||||
apiPatch<IllnessEpisodeDTO>(`/api/illness/episodes/${id}`, input),
|
||||
onSuccess: invalidate,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* episode schemas. An episode can never resolve before it began; the schema
|
||||
* `superRefine` rejects an inverted window when both instants are supplied
|
||||
* (a partial edit touching only one is checked against the stored row in the
|
||||
* route).
|
||||
* route). Instants are compared at millisecond precision via Date.parse.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
@@ -49,6 +49,24 @@ describe("illnessEpisodeCreateSchema — window invariant", () => {
|
||||
});
|
||||
expect(out.success).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["after", "2026-01-10T11:00:00Z", true],
|
||||
["before", "2026-01-10T09:00:00Z", false],
|
||||
["equal", "2026-01-10T10:00:00Z", true],
|
||||
])(
|
||||
"compares mixed Z/offset instants correctly (%s)",
|
||||
(_, resolvedAt, expected) => {
|
||||
// 19:00:00+09:00 is 10:00:00Z
|
||||
const out = illnessEpisodeCreateSchema.safeParse({
|
||||
label: "Cold",
|
||||
type: "INFECTION",
|
||||
onsetAt: "2026-01-10T19:00:00+09:00",
|
||||
resolvedAt,
|
||||
});
|
||||
expect(out.success).toBe(expected);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("illnessEpisodeUpdateSchema — window invariant", () => {
|
||||
|
||||
@@ -84,7 +84,11 @@ export const illnessEpisodeCreateSchema = z
|
||||
// server-side when omitted, so the invariant only bites when BOTH instants
|
||||
// are supplied (the inverted-window case).
|
||||
.superRefine((v, ctx) => {
|
||||
if (v.resolvedAt && v.onsetAt && v.resolvedAt < v.onsetAt) {
|
||||
if (
|
||||
v.resolvedAt &&
|
||||
v.onsetAt &&
|
||||
Date.parse(v.resolvedAt) < Date.parse(v.onsetAt)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["resolvedAt"],
|
||||
@@ -116,7 +120,11 @@ export const illnessEpisodeUpdateSchema = z
|
||||
// parse time. A partial edit touching only one is validated against the
|
||||
// stored value in the route (it must load the row anyway).
|
||||
.superRefine((v, ctx) => {
|
||||
if (v.resolvedAt && v.onsetAt && v.resolvedAt < v.onsetAt) {
|
||||
if (
|
||||
v.resolvedAt &&
|
||||
v.onsetAt &&
|
||||
Date.parse(v.resolvedAt) < Date.parse(v.onsetAt)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["resolvedAt"],
|
||||
|
||||
Reference in new issue
Block a user