feat: embed medication overview into shared links

Closes #424
This commit is contained in:
Daniel Volz
2026-03-14 20:26:17 +01:00
committed by GitHub
parent fd3134be24
commit e0fb77d494
35 changed files with 2607 additions and 1297 deletions
@@ -1,4 +1,4 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ShareDialog } from "../../components/ShareDialog";
@@ -45,6 +45,12 @@ describe("ShareDialog", () => {
expect(screen.getByRole("option", { name: "Bob" })).toBeInTheDocument();
});
it("renders the translated all-people option label", () => {
render(<ShareDialog {...defaultProps} sharePeople={["all", "Alice"]} shareSelectedPerson="all" />);
expect(screen.getByRole("option", { name: "share.allPeople" })).toBeInTheDocument();
expect(screen.getByRole("option", { name: "Alice" })).toBeInTheDocument();
});
it("renders period selection dropdown", () => {
render(<ShareDialog {...defaultProps} />);
// The dropdown renders with 3 options for time periods
@@ -70,7 +76,7 @@ describe("ShareDialog", () => {
render(<ShareDialog {...defaultProps} shareLink="http://example.com/share/abc123" />);
const inputs = screen.getAllByRole("textbox") as HTMLInputElement[];
expect(inputs[0]).toHaveValue("http://example.com/share/abc123");
expect(inputs[1]).toHaveValue("http://example.com/share/abc123/overview");
expect(inputs).toHaveLength(1);
});
it("calls onCopyShareLink when copy button is clicked", () => {
@@ -93,16 +99,6 @@ describe("ShareDialog", () => {
expect(selectMock).toHaveBeenCalled();
});
it("copies overview link when overview copy button is clicked", async () => {
render(<ShareDialog {...defaultProps} shareLink="http://example.com/share/abc123" />);
fireEvent.click(screen.getByRole("button", { name: /share\.copyOverviewLink/i }));
await waitFor(() => {
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("http://example.com/share/abc123/overview");
});
});
it("calls person and period change callbacks", () => {
render(<ShareDialog {...defaultProps} />);
@@ -23,6 +23,74 @@ function createSharedData() {
};
}
function createSharedDataWithEmbeddedOverview() {
return {
...createSharedData(),
takenBy: "all",
shareMedicationOverview: true,
medicationOverview: [
{
name: "Aspirin",
genericName: "Acetylsalicylic Acid",
imageUrl: null,
packageType: "blister",
packCount: 1,
blistersPerPack: 2,
pillsPerBlister: 10,
totalPills: null,
looseTablets: 0,
currentStock: 8,
capacity: 20,
daysLeft: 8,
nextIntakeDate: null,
depletionDate: "2026-01-20",
priority: "high",
expiryDate: null,
medicationStartDate: null,
prescriptionEnabled: false,
prescriptionRemainingRefills: null,
},
],
};
}
function createSharedDataWithTodayDose() {
const now = new Date();
now.setHours(10, 0, 0, 0);
const dateOnlyMs = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
return {
sharedBy: "Owner",
takenBy: "Max",
scheduleDays: 30,
automaticDoseId: `1-0-${dateOnlyMs}`,
shareStockStatus: true,
medications: [
{
id: 1,
name: "Ibuprofen",
genericName: null,
takenBy: [],
packageType: "blister",
packCount: 2,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
pillWeightMg: null,
doseUnit: "mg",
expiryDate: null,
notes: null,
intakeRemindersEnabled: false,
blisters: [{ usage: 1, every: 1, start: now.toISOString() }],
intakes: [{ usage: 1, every: 1, start: now.toISOString(), takenBy: null, intakeRemindersEnabled: false }],
updatedAt: null,
dismissedUntil: null,
lastStockCorrectionAt: null,
},
],
};
}
describe("SharedSchedule", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -117,4 +185,54 @@ describe("SharedSchedule", () => {
expect(screen.getByText("share.error")).toBeInTheDocument();
});
});
it("shows the robot marker for automatically taken shared doses", async () => {
const sharedData = createSharedDataWithTodayDose();
(globalThis.fetch as ReturnType<typeof vi.fn>).mockImplementation((url: string, init?: RequestInit) => {
if (url === "/api/share/token-123/doses" && (!init || !init.method || init.method === "GET")) {
return Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
doses: [{ doseId: sharedData.automaticDoseId, dismissed: false, takenSource: "automatic" }],
}),
});
}
if (url === "/api/share/token-123") {
return Promise.resolve({ ok: true, json: () => Promise.resolve(sharedData) });
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
renderSharedSchedule("/share/token-123");
await waitFor(() => {
expect(screen.getByText("🤖")).toBeInTheDocument();
});
});
it("renders the embedded medication overview on the shared page when enabled", async () => {
const sharedData = createSharedDataWithEmbeddedOverview();
(globalThis.fetch as ReturnType<typeof vi.fn>).mockImplementation((url: string, init?: RequestInit) => {
if (url === "/api/share/token-123/doses" && (!init || !init.method || init.method === "GET")) {
return Promise.resolve({ ok: true, json: () => Promise.resolve({ doses: [] }) });
}
if (url === "/api/share/token-123") {
return Promise.resolve({ ok: true, json: () => Promise.resolve(sharedData) });
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
renderSharedSchedule("/share/token-123");
await waitFor(() => {
expect(screen.getAllByText("Aspirin").length).toBeGreaterThan(0);
expect(screen.getAllByText("Acetylsalicylic Acid").length).toBeGreaterThan(0);
});
expect(screen.getByText("sharedOverview.columns.priority")).toBeInTheDocument();
expect(screen.getByText("share.noSchedule")).toBeInTheDocument();
});
});
@@ -23,6 +23,7 @@ function createSharedData(overrides: Record<string, unknown> = {}) {
takenBy: "Max",
scheduleDays: 30,
shareStockStatus: true,
upcomingTodayOnly: false,
shareScheduleTodayOnly: true,
stockCalculationMode: "automatic",
stockThresholds: {
@@ -73,7 +74,7 @@ describe("SharedSchedule today-only", () => {
vi.restoreAllMocks();
});
it("hides past and future sections when shareScheduleTodayOnly is enabled", async () => {
it("hides past and future sections when shareScheduleTodayOnly is enabled even if dashboard today-only is off", async () => {
const sharedData = createSharedData();
(globalThis.fetch as ReturnType<typeof vi.fn>).mockImplementation((url: string, init?: RequestInit) => {
+49 -1
View File
@@ -17,13 +17,17 @@ describe("useSettings", () => {
vi.restoreAllMocks();
});
it("initializes with default settings", () => {
it("initializes with default settings", async () => {
const { result } = renderHook(() => useSettings());
expect(result.current.settings.emailEnabled).toBe(false);
expect(result.current.settings.lowStockDays).toBe(30);
expect(result.current.settings.reminderDaysBefore).toBe(7);
expect(result.current.settingsLoading).toBe(true);
await waitFor(() => {
expect(result.current.settingsLoading).toBe(false);
});
});
it("loads settings from API on mount", async () => {
@@ -137,6 +141,50 @@ describe("useSettings", () => {
expect(result.current.settingsSaved).toBe(true);
});
it("flushes unsaved settings on pagehide with keepalive including shareMedicationOverview", async () => {
const fetchMock = global.fetch as ReturnType<typeof vi.fn>;
fetchMock.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ shareMedicationOverview: false }),
});
const { result } = renderHook(() => useSettings());
await waitFor(() => {
expect(result.current.settingsLoading).toBe(false);
});
vi.useFakeTimers();
act(() => {
result.current.setSettings((settings) => ({
...settings,
shareMedicationOverview: true,
}));
});
act(() => {
window.dispatchEvent(new Event("pagehide"));
});
const keepaliveCall = fetchMock.mock.calls.find(
([url, init]) => url === "/api/settings" && (init as RequestInit | undefined)?.keepalive === true
);
expect(keepaliveCall).toBeDefined();
expect(keepaliveCall?.[1]).toEqual(
expect.objectContaining({
method: "PUT",
keepalive: true,
})
);
const payload = JSON.parse(((keepaliveCall?.[1] as RequestInit).body as string) ?? "{}");
expect(payload.shareMedicationOverview).toBe(true);
vi.useRealTimers();
});
it("keeps email channel enabled when recipient is non-empty", async () => {
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
+1 -1
View File
@@ -86,7 +86,7 @@ describe("useShare", () => {
});
expect(result.current.showShareDialog).toBe(true);
expect(result.current.sharePeople).toEqual(["Alice", "Bob", "Charlie"]);
expect(result.current.sharePeople).toEqual(["all", "Alice", "Bob", "Charlie"]);
expect(result.current.shareSelectedPerson).toBe("Alice");
expect(window.history.pushState).toHaveBeenCalled();
});
+5 -21
View File
@@ -200,46 +200,30 @@ describe("SettingsPage", () => {
const swapRow = screen.getByText("settings.timeline.swapDashboardSections").closest(".setting-row");
const upcomingRow = screen.getByText("settings.timeline.upcomingTodayOnly").closest(".setting-row");
const overviewRow = screen.getByText("settings.timeline.shareMedicationOverview").closest(".setting-row");
const sharedRow = screen.getByText("settings.timeline.shareScheduleTodayOnly").closest(".setting-row");
const swapToggle = swapRow?.querySelector('input[type="checkbox"]') as HTMLInputElement;
const upcomingToggle = upcomingRow?.querySelector('input[type="checkbox"]') as HTMLInputElement;
const overviewToggle = overviewRow?.querySelector('input[type="checkbox"]') as HTMLInputElement;
const sharedToggle = sharedRow?.querySelector('input[type="checkbox"]') as HTMLInputElement;
expect(swapToggle).toBeInTheDocument();
expect(upcomingToggle).toBeInTheDocument();
expect(overviewToggle).toBeInTheDocument();
expect(sharedToggle).toBeInTheDocument();
fireEvent.click(swapToggle);
fireEvent.click(upcomingToggle);
fireEvent.click(overviewToggle);
fireEvent.click(sharedToggle);
expect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ swapDashboardMainSections: true }));
expect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ upcomingTodayOnly: true }));
expect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ shareMedicationOverview: true }));
expect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ shareScheduleTodayOnly: true }));
});
it("updates share stock status toggle through setSettings", () => {
const setSettings = vi.fn();
mockContextValue = createMockContext({
setSettings,
settings: {
...createMockContext().settings,
shareStockStatus: false,
},
});
renderPage();
const shareStockRow = screen.getByText("settings.stock.shareStockStatus").closest(".setting-row");
const shareStockToggle = shareStockRow?.querySelector('input[type="checkbox"]') as HTMLInputElement;
expect(shareStockToggle).toBeInTheDocument();
fireEvent.click(shareStockToggle);
expect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ shareStockStatus: true }));
});
it("opens export modal when export action is clicked", () => {
const setShowExportModal = vi.fn();
mockContextValue = createMockContext({ setShowExportModal });
@@ -10,6 +10,7 @@ function renderSharedOverview(path: string) {
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/share/:token/overview" element={<SharedOverviewPage />} />
<Route path="/share/:token" element={<div>shared schedule target</div>} />
</Routes>
</MemoryRouter>
);
@@ -21,66 +22,13 @@ describe("SharedOverviewPage", () => {
window.localStorage.clear();
});
it("renders medication overview for valid token", async () => {
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
status: 200,
json: () =>
Promise.resolve({
takenBy: "Max",
sharedBy: "Owner",
generatedAt: "2026-03-06T10:00:00.000Z",
medications: [
{
name: "Aspirin",
genericName: "Acetylsalicylic Acid",
imageUrl: null,
packageType: "blister",
packCount: 1,
blistersPerPack: 2,
pillsPerBlister: 10,
totalPills: null,
looseTablets: 0,
currentStock: 18,
capacity: 20,
daysLeft: 18,
nextIntakeDate: "2026-03-07",
depletionDate: "2026-03-24",
priority: "normal",
expiryDate: null,
medicationStartDate: null,
prescriptionEnabled: false,
prescriptionRemainingRefills: null,
},
],
}),
});
it("redirects the legacy overview route to the normal shared schedule route", async () => {
renderSharedOverview("/share/abcdef0123456789/overview");
await waitFor(() => {
expect(screen.getByText("sharedOverview.title")).toBeInTheDocument();
expect(screen.getAllByText("Aspirin").length).toBeGreaterThan(0);
expect(screen.getAllByText("Acetylsalicylic Acid").length).toBeGreaterThan(0);
expect(screen.getByText("shared schedule target")).toBeInTheDocument();
});
const headerPair = document.querySelector(".shared-overview-table .date-pair-stack-header");
expect(headerPair).toBeInTheDocument();
expect(headerPair).toHaveTextContent("sharedOverview.columns.nextIntake");
expect(headerPair).toHaveTextContent("sharedOverview.columns.depletion");
const rowPair = document.querySelector(".shared-overview-table .date-pair-stack");
expect(rowPair).toBeInTheDocument();
const rowEntries = Array.from(rowPair?.querySelectorAll(".date-pair-entry") ?? []);
expect(rowEntries).toHaveLength(2);
expect(rowEntries[0]).toHaveTextContent("sharedOverview.columns.nextIntake");
expect(rowEntries[1]).toHaveTextContent("sharedOverview.columns.depletion");
expect(screen.getAllByText("sharedOverview.columns.daysLeft")).toHaveLength(2);
expect(screen.getByText("sharedOverview.columns.priority")).toBeInTheDocument();
expect(screen.getAllByText("sharedOverview.priority.normal")).toHaveLength(2);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/share/abcdef0123456789/overview");
expect(globalThis.fetch).not.toHaveBeenCalled();
});
it("keeps the updated shared overview stock wording in English and German", () => {
@@ -95,46 +43,12 @@ describe("SharedOverviewPage", () => {
expect(de.sharedOverview.priority.high).toBe("Niedriger Bestand");
});
it("renders not found state for missing token", async () => {
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: false,
status: 404,
json: () => Promise.resolve({ error: "not_found" }),
});
it("redirects even when the token would previously have been loaded from the overview route", async () => {
renderSharedOverview("/share/abcdef0123456789/overview");
await waitFor(() => {
expect(screen.getByText("sharedOverview.error.notFound")).toBeInTheDocument();
});
});
it("renders expired state for expired token", async () => {
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: false,
status: 410,
json: () => Promise.resolve({ error: "expired", expiredAt: "2026-03-01T10:00:00.000Z" }),
});
renderSharedOverview("/share/abcdef0123456789/overview");
await waitFor(() => {
expect(screen.getByText("sharedOverview.error.expired")).toBeInTheDocument();
expect(screen.getByText("sharedOverview.expiredOn")).toBeInTheDocument();
});
});
it("renders rate-limit error state", async () => {
(globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: false,
status: 429,
json: () => Promise.resolve({ error: "rate_limited" }),
});
renderSharedOverview("/share/abcdef0123456789/overview");
await waitFor(() => {
expect(screen.getByText("sharedOverview.error.rateLimit")).toBeInTheDocument();
expect(screen.getByText("shared schedule target")).toBeInTheDocument();
});
expect(globalThis.fetch).not.toHaveBeenCalled();
});
});