mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
refactor(lint): enforce the lib → components and client → server boundaries
Add the in-repo rule `healthlog/import-boundaries`: - a file under src/lib may not import src/components or src/app (alias, relative, re-export and dynamic forms, type-only included); - a "use client" file may not make a value import of the database client, the crypto module, the Prisma client entry, the job queue, pg, pg-boss or next/headers. Type-only imports and the Prisma enums entry stay legal. The four lib files that still import upward are listed in the rule's allow map with a reason each; a listed file that stops importing upward is reported, so the map can only shrink. Five of the nine upward imports are gone by moving pure modules to their layer, without behaviour change: - supply-runway estimate → src/lib/medications/supply-runway.ts (read by the low-stock job and the medication list read); - weekday BYDAY tokens → src/lib/medications/scheduling/weekday-tokens.ts (read by the medication extraction prompt); - settings section slugs → src/lib/settings/section-slugs.ts (read by the record-settings classification); - the command palette index → src/components/command-palette/ (it is a client index built from component registries). Proof the rule can fail: an import of @/components/ui/card appended to src/lib/medications/supply-runway.ts reported libUpward, and a planted "use client" file importing @/lib/db reported clientServerOnly; both were removed again.
This commit is contained in:
1 parent
fdd0f50130
commit
c86c7d1a79
40 files changed
+429
-49
No files matched your search
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Server-safe constants for the v1.5 admin split. Mirrors the pattern in
|
||||
* `src/components/settings/section-slugs.ts` so server-rendered code paths
|
||||
* `src/lib/settings/section-slugs.ts` so server-rendered code paths
|
||||
* (`generateStaticParams()`, the page guard, route-existence tests) can
|
||||
* import the slug list without dragging the `<AdminShell>` client bundle
|
||||
* into the server graph.
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildPaletteIndex,
|
||||
type PaletteIndexInput,
|
||||
} from "@/components/command-palette/build-index";
|
||||
|
||||
const t = (key: string) => key;
|
||||
|
||||
function index(over: Partial<PaletteIndexInput> = {}) {
|
||||
return buildPaletteIndex({
|
||||
t,
|
||||
modules: {},
|
||||
navModules: {},
|
||||
inSharedRecord: false,
|
||||
sections: null,
|
||||
isAdmin: false,
|
||||
settingsListed: () => true,
|
||||
canCapture: true,
|
||||
moduleToggles: [
|
||||
{ key: "mood", enabled: true },
|
||||
{ key: "timeline", enabled: false },
|
||||
],
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
const ids = (entries: ReturnType<typeof index>) => entries.map((e) => e.id);
|
||||
|
||||
describe("buildPaletteIndex — modules", () => {
|
||||
it("a switched-off module takes its page, its Insights page and its cards along", () => {
|
||||
const off = { mood: false, timeline: false, environment: false };
|
||||
const entries = ids(index({ modules: off, navModules: off }));
|
||||
expect(entries).not.toContain("nav:/mood");
|
||||
expect(entries).not.toContain("nav:/timeline");
|
||||
expect(entries).not.toContain("insights:mood");
|
||||
expect(entries).not.toContain("settings:notifications#mood-reminder");
|
||||
expect(entries).not.toContain("settings:environment");
|
||||
expect(entries).not.toContain("settings:environment#home-location");
|
||||
});
|
||||
|
||||
it("and they come back while it is on", () => {
|
||||
const on = { mood: true, timeline: true, environment: true };
|
||||
const entries = ids(index({ modules: on, navModules: on }));
|
||||
expect(entries).toContain("nav:/mood");
|
||||
expect(entries).toContain("nav:/timeline");
|
||||
expect(entries).toContain("insights:mood");
|
||||
expect(entries).toContain("insights:sleep");
|
||||
expect(entries).toContain("settings:notifications#mood-reminder");
|
||||
expect(entries).toContain("settings:environment#home-location");
|
||||
});
|
||||
|
||||
it("a layout sub-page follows its module", () => {
|
||||
expect(ids(index({ modules: { labs: false } }))).not.toContain(
|
||||
"settings:layout/labs",
|
||||
);
|
||||
expect(ids(index({ modules: { labs: true } }))).toContain(
|
||||
"settings:layout/labs",
|
||||
);
|
||||
});
|
||||
|
||||
it("the Coach page and action follow the capability folded into the nav map", () => {
|
||||
const without = ids(index({ navModules: { coach: false } }));
|
||||
expect(without).not.toContain("nav:/coach");
|
||||
expect(without).not.toContain("action:coach");
|
||||
const withIt = ids(index({ navModules: { coach: true } }));
|
||||
expect(withIt).toContain("nav:/coach");
|
||||
expect(withIt).toContain("action:coach");
|
||||
});
|
||||
|
||||
it("offers the switches it is given, with their state", () => {
|
||||
const toggles = index().filter((e) => e.group === "modules");
|
||||
expect(toggles.map((e) => e.run)).toEqual([
|
||||
{ kind: "module", module: "mood", enabled: true },
|
||||
{ kind: "module", module: "timeline", enabled: false },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPaletteIndex — admin", () => {
|
||||
it("lists the admin pages for an admin only", () => {
|
||||
expect(ids(index()).some((id) => id.startsWith("admin:"))).toBe(false);
|
||||
const admin = index({ isAdmin: true }).filter((e) =>
|
||||
e.id.startsWith("admin:"),
|
||||
);
|
||||
expect(admin.length).toBeGreaterThan(5);
|
||||
expect(admin[0]?.run).toEqual({
|
||||
kind: "href",
|
||||
href: `/admin/${admin[0]?.id.slice("admin:".length)}`,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPaletteIndex — a shared record", () => {
|
||||
const shared = (over: Partial<PaletteIndexInput> = {}) =>
|
||||
index({
|
||||
inSharedRecord: true,
|
||||
isAdmin: true,
|
||||
moduleToggles: [],
|
||||
settingsListed: (slug) => slug === "anamnesis",
|
||||
...over,
|
||||
});
|
||||
|
||||
it("offers only the doors sharing opens", () => {
|
||||
const entries = ids(shared());
|
||||
expect(entries).toContain("nav:/");
|
||||
expect(entries).not.toContain("nav:/insights");
|
||||
expect(entries).not.toContain("nav:/coach");
|
||||
expect(entries).not.toContain("nav:/notifications");
|
||||
expect(entries.some((id) => id.startsWith("insights:"))).toBe(false);
|
||||
});
|
||||
|
||||
it("never the account around it: no admin, no cards, no switches, no backup", () => {
|
||||
const entries = ids(shared());
|
||||
expect(entries.some((id) => id.startsWith("admin:"))).toBe(false);
|
||||
expect(entries.some((id) => id.includes("#"))).toBe(false);
|
||||
expect(entries.some((id) => id.startsWith("module:"))).toBe(false);
|
||||
expect(entries).not.toContain("action:backup");
|
||||
expect(entries).not.toContain("action:coach");
|
||||
});
|
||||
|
||||
it("lists the Settings pages the record lists, and those only", () => {
|
||||
const settings = shared().filter((e) => e.group === "settings");
|
||||
expect(settings.map((e) => e.id)).toEqual(["settings:anamnesis"]);
|
||||
});
|
||||
|
||||
it("drops the add action when the grant cannot write", () => {
|
||||
expect(ids(shared({ canCapture: false }))).not.toContain("action:capture");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPaletteIndex — links", () => {
|
||||
it("a card links to its section with its anchor", () => {
|
||||
const passkeys = index().find((e) => e.id === "settings:security#passkeys");
|
||||
expect(passkeys?.run).toEqual({
|
||||
kind: "href",
|
||||
href: "/settings/security#passkeys",
|
||||
});
|
||||
expect(passkeys?.hint).toBe("settings.sections.security.title");
|
||||
});
|
||||
|
||||
it("every id is unique", () => {
|
||||
const all = ids(index({ isAdmin: true }));
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { Activity, Moon, Plus, Smile } from "lucide-react";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import type { PaletteEntry } from "@/lib/command-palette/build-index";
|
||||
import type { PaletteEntry } from "@/components/command-palette/build-index";
|
||||
import type { SearchResponse } from "@/lib/search/contract";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
import {
|
||||
Bell,
|
||||
CalendarDays,
|
||||
ChartLine,
|
||||
DatabaseBackup,
|
||||
Keyboard,
|
||||
MessagesSquare,
|
||||
Palette,
|
||||
Plus,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { ADMIN_SECTIONS } from "@/components/admin/admin-shell";
|
||||
import { SUB_PAGE_TABS } from "@/components/insights/insights-tab-strip";
|
||||
import { visibleNavDestinations } from "@/components/layout/nav-model";
|
||||
import { MODULE_ICONS } from "@/components/settings/module-icons";
|
||||
import { SETTINGS_SECTIONS } from "@/components/settings/settings-shell";
|
||||
import { SUB_PAGE_SLUGS } from "@/lib/insights/sub-page-metric";
|
||||
import { MODULE_REGISTRY, type ModuleKey } from "@/lib/modules/registry";
|
||||
import { isSurfaceVisible, type SurfaceModuleMap } from "@/lib/modules/surface";
|
||||
import type { ShareDomain } from "@/lib/sharing/scope";
|
||||
|
||||
import {
|
||||
SETTINGS_CARDS,
|
||||
SETTINGS_LAYOUT_PAGES,
|
||||
SETTINGS_MODULE_PAGES,
|
||||
} from "@/lib/command-palette/settings-cards";
|
||||
import { PALETTE_SYNONYMS } from "@/lib/command-palette/synonyms";
|
||||
|
||||
/**
|
||||
* The command palette's index: every place and action this session may
|
||||
* reach, built on the client from the same lists the navigation renders.
|
||||
*
|
||||
* Nothing here is a second opinion about access. A page comes from
|
||||
* `visibleNavDestinations` (modules, the Coach's AI capability folded into
|
||||
* the map by `useNavModules`, what a shared record covers); an Insights page,
|
||||
* a Settings section and a card from the surface map; an admin page only for
|
||||
* an admin in their own record. Inside somebody else's record the palette
|
||||
* offers the doors sharing opens and the Settings pages the record lists,
|
||||
* and nothing that configures the account around it: no cards, no module
|
||||
* switches, no backup.
|
||||
*/
|
||||
|
||||
export type PaletteGroup =
|
||||
"recent" | "pages" | "insights" | "settings" | "modules" | "actions";
|
||||
|
||||
export type PaletteActionId =
|
||||
"capture" | "coach" | "backup" | "today" | "shortcuts";
|
||||
|
||||
export type PaletteRun =
|
||||
| { kind: "href"; href: string }
|
||||
| { kind: "action"; action: PaletteActionId }
|
||||
| { kind: "module"; module: ModuleKey; enabled: boolean };
|
||||
|
||||
export interface PaletteEntry {
|
||||
id: string;
|
||||
group: Exclude<PaletteGroup, "recent">;
|
||||
title: string;
|
||||
/** Where it sits, shown beside the title (a card's section). */
|
||||
hint?: string;
|
||||
keywords: ReadonlyArray<string>;
|
||||
icon: LucideIcon;
|
||||
run: PaletteRun;
|
||||
}
|
||||
|
||||
type Translate = (
|
||||
key: string,
|
||||
vars?: Record<string, string | number>,
|
||||
) => string;
|
||||
|
||||
export interface PaletteIndexInput {
|
||||
t: Translate;
|
||||
/** The record's resolved module map (`GET /api/auth/me` → `modules`). */
|
||||
modules: SurfaceModuleMap | undefined;
|
||||
/** The same map with `coach` following the AI capability (`useNavModules`). */
|
||||
navModules: SurfaceModuleMap | undefined;
|
||||
inSharedRecord: boolean;
|
||||
/** The shared record's covered sections, when there is one. */
|
||||
sections: ReadonlyArray<ShareDomain> | null;
|
||||
isAdmin: boolean;
|
||||
/**
|
||||
* Whether the Settings shell lists a section for the record on screen.
|
||||
* One's own record: every section. A shared record: the record's own list.
|
||||
*/
|
||||
settingsListed: (slug: string) => boolean;
|
||||
/** Whether the add menu has anything to offer. */
|
||||
canCapture: boolean;
|
||||
/**
|
||||
* The module switches to offer with their state. Empty inside a shared
|
||||
* record (a delegate does not configure the account) and for a module the
|
||||
* operator switched off or code disabled.
|
||||
*/
|
||||
moduleToggles: ReadonlyArray<{ key: ModuleKey; enabled: boolean }>;
|
||||
}
|
||||
|
||||
const INSIGHTS_EXTRA: ReadonlyArray<{
|
||||
slug: string;
|
||||
labelKey: string;
|
||||
surface?: string;
|
||||
}> = [
|
||||
{ slug: "catalog", labelKey: "insights.navCatalog" },
|
||||
{
|
||||
slug: "recovery",
|
||||
labelKey: "insights.navRecovery",
|
||||
surface: "insights-page:recovery",
|
||||
},
|
||||
{ slug: "ecg", labelKey: "insights.navEcg" },
|
||||
];
|
||||
|
||||
function keywordsFor(id: string, extra: ReadonlyArray<string> = []) {
|
||||
return [...extra, ...(PALETTE_SYNONYMS[id] ?? [])];
|
||||
}
|
||||
|
||||
export function buildPaletteIndex(input: PaletteIndexInput): PaletteEntry[] {
|
||||
const { t, modules } = input;
|
||||
const entries: PaletteEntry[] = [];
|
||||
|
||||
// ── Pages: the navigation's own list. ──
|
||||
const nav = visibleNavDestinations(
|
||||
input.navModules,
|
||||
true,
|
||||
input.inSharedRecord,
|
||||
input.sections,
|
||||
);
|
||||
const navHrefs = new Set(nav.map((d) => d.href));
|
||||
for (const d of nav) {
|
||||
const id = `nav:${d.href}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "pages",
|
||||
title: t(d.tKey),
|
||||
keywords: keywordsFor(id),
|
||||
icon: d.icon,
|
||||
run: { kind: "href", href: d.href },
|
||||
});
|
||||
}
|
||||
if (!input.inSharedRecord) {
|
||||
entries.push({
|
||||
id: "nav:/notifications",
|
||||
group: "pages",
|
||||
title: t("nav.notifications"),
|
||||
keywords: keywordsFor("nav:/notifications"),
|
||||
icon: Bell,
|
||||
run: { kind: "href", href: "/notifications" },
|
||||
});
|
||||
}
|
||||
if (input.isAdmin && !input.inSharedRecord) {
|
||||
const admin = t("nav.admin");
|
||||
for (const section of ADMIN_SECTIONS) {
|
||||
const id = `admin:${section.slug}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "pages",
|
||||
title: t(section.titleKey),
|
||||
hint: admin,
|
||||
keywords: keywordsFor(id, [admin]),
|
||||
icon: section.icon,
|
||||
run: { kind: "href", href: `/admin/${section.slug}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Insights pages, while the area is offered at all. ──
|
||||
if (navHrefs.has("/insights")) {
|
||||
const area = t("nav.insights");
|
||||
const pages = [
|
||||
...SUB_PAGE_SLUGS.map((slug) => ({
|
||||
slug: slug as string,
|
||||
labelKey: SUB_PAGE_TABS[slug].labelKey,
|
||||
surface: `insights-page:${slug}`,
|
||||
})),
|
||||
...INSIGHTS_EXTRA,
|
||||
];
|
||||
for (const page of pages) {
|
||||
if (page.surface && !isSurfaceVisible(page.surface, modules)) continue;
|
||||
const id = `insights:${page.slug}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "insights",
|
||||
title: t(page.labelKey),
|
||||
hint: area,
|
||||
keywords: keywordsFor(id),
|
||||
icon: ChartLine,
|
||||
run: { kind: "href", href: `/insights/${page.slug}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Settings: sections, then each card, then the Appearance pages. ──
|
||||
const sectionTitle = new Map<string, string>();
|
||||
const sectionVisible = new Set<string>();
|
||||
for (const section of SETTINGS_SECTIONS) {
|
||||
if (!isSurfaceVisible(`settings:${section.slug}`, modules)) continue;
|
||||
if (!input.settingsListed(section.slug)) continue;
|
||||
const title = t(section.titleKey);
|
||||
sectionTitle.set(section.slug, title);
|
||||
sectionVisible.add(section.slug);
|
||||
const id = `settings:${section.slug}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "settings",
|
||||
title,
|
||||
hint: t("nav.settings"),
|
||||
keywords: keywordsFor(id),
|
||||
icon: section.icon,
|
||||
run: { kind: "href", href: `/settings/${section.slug}` },
|
||||
});
|
||||
}
|
||||
if (!input.inSharedRecord) {
|
||||
for (const card of SETTINGS_CARDS) {
|
||||
if (!sectionVisible.has(card.section)) continue;
|
||||
if (
|
||||
card.modules &&
|
||||
!card.modules.some((key) => modules?.[key] !== false)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const section = sectionTitle.get(card.section) ?? "";
|
||||
const id = `settings:${card.section}#${card.anchor}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "settings",
|
||||
title: t(card.titleKey),
|
||||
hint: section,
|
||||
keywords: keywordsFor(id, [section]),
|
||||
icon:
|
||||
SETTINGS_SECTIONS.find((s) => s.slug === card.section)?.icon ??
|
||||
Palette,
|
||||
run: {
|
||||
kind: "href",
|
||||
href: `/settings/${card.section}#${card.anchor}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (sectionVisible.has("layout")) {
|
||||
const layout = sectionTitle.get("layout") ?? "";
|
||||
for (const page of SETTINGS_LAYOUT_PAGES) {
|
||||
if (page.module && modules?.[page.module] === false) continue;
|
||||
const id = `settings:layout/${page.slug}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "settings",
|
||||
title: t(page.titleKey),
|
||||
hint: layout,
|
||||
keywords: keywordsFor(id, [layout]),
|
||||
icon: Palette,
|
||||
run: { kind: "href", href: `/settings/layout/${page.slug}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
if (sectionVisible.has("modules")) {
|
||||
const modulesTitle = sectionTitle.get("modules") ?? "";
|
||||
for (const page of SETTINGS_MODULE_PAGES) {
|
||||
if (modules?.[page.module] === false) continue;
|
||||
const id = `settings:modules/${page.slug}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "settings",
|
||||
title: t(page.titleKey),
|
||||
hint: modulesTitle,
|
||||
keywords: keywordsFor(id, [modulesTitle]),
|
||||
icon: MODULE_ICONS[page.module],
|
||||
run: { kind: "href", href: `/settings/modules/${page.slug}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Module switches. ──
|
||||
for (const toggle of input.moduleToggles) {
|
||||
const def = MODULE_REGISTRY[toggle.key];
|
||||
const id = `module:${toggle.key}`;
|
||||
entries.push({
|
||||
id,
|
||||
group: "modules",
|
||||
title: t(def.labelKey),
|
||||
keywords: keywordsFor(id, [t("settings.sections.modules.title")]),
|
||||
icon: MODULE_ICONS[toggle.key],
|
||||
run: { kind: "module", module: toggle.key, enabled: toggle.enabled },
|
||||
});
|
||||
}
|
||||
|
||||
// ── Actions. ──
|
||||
const action = (
|
||||
id: PaletteActionId,
|
||||
titleKey: string,
|
||||
icon: LucideIcon,
|
||||
): PaletteEntry => ({
|
||||
id: `action:${id}`,
|
||||
group: "actions",
|
||||
title: t(titleKey),
|
||||
keywords: keywordsFor(`action:${id}`),
|
||||
icon,
|
||||
run: { kind: "action", action: id },
|
||||
});
|
||||
if (input.canCapture) {
|
||||
entries.push(action("capture", "palette.actions.capture", Plus));
|
||||
}
|
||||
if (navHrefs.has("/coach") && !input.inSharedRecord) {
|
||||
entries.push(action("coach", "palette.actions.coach", MessagesSquare));
|
||||
}
|
||||
if (!input.inSharedRecord && sectionVisible.has("export")) {
|
||||
entries.push(action("backup", "palette.actions.backup", DatabaseBackup));
|
||||
}
|
||||
entries.push(action("today", "palette.actions.today", CalendarDays));
|
||||
entries.push(action("shortcuts", "palette.actions.shortcuts", Keyboard));
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** The actions the empty palette offers below the recent places. */
|
||||
export const EMPTY_STATE_ACTIONS: ReadonlyArray<string> = [
|
||||
"action:capture",
|
||||
"action:today",
|
||||
"action:coach",
|
||||
"action:shortcuts",
|
||||
];
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
EMPTY_STATE_ACTIONS,
|
||||
type PaletteEntry,
|
||||
type PaletteGroup,
|
||||
} from "@/lib/command-palette/build-index";
|
||||
} from "@/components/command-palette/build-index";
|
||||
import { rankEntries } from "@/lib/command-palette/rank";
|
||||
import { pushRecent, readRecent } from "@/lib/command-palette/recent";
|
||||
import { scrollToAnchorWhenReady } from "@/lib/dom/scroll-to-anchor";
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
|
||||
import {
|
||||
buildPaletteIndex,
|
||||
type PaletteEntry,
|
||||
} from "@/lib/command-palette/build-index";
|
||||
} from "@/components/command-palette/build-index";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import {
|
||||
MODULE_REGISTRY,
|
||||
|
||||
@@ -11,7 +11,7 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isSettingsSectionSlug } from "@/components/settings/section-slugs";
|
||||
import { isSettingsSectionSlug } from "@/lib/settings/section-slugs";
|
||||
|
||||
describe("sleep-overview empty-state CTA href", () => {
|
||||
it("links to /settings/integrations (a real settings slug)", () => {
|
||||
|
||||
@@ -24,10 +24,8 @@ import {
|
||||
weekdayIndexesToTokens,
|
||||
weekdayIndexToToken,
|
||||
} from "@/components/medications/scheduling/legacy-bridge";
|
||||
import {
|
||||
DEFAULT_SUB_CONTROLS,
|
||||
type WeekdayToken,
|
||||
} from "@/components/medications/scheduling/types";
|
||||
import { DEFAULT_SUB_CONTROLS } from "@/components/medications/scheduling/types";
|
||||
import { type WeekdayToken } from "@/lib/medications/scheduling/weekday-tokens";
|
||||
|
||||
describe("weekdayIndexToToken", () => {
|
||||
it("maps Sunday-anchored 0..6 to SU/MO/TU/WE/TH/FR/SA", () => {
|
||||
|
||||
@@ -1,468 +0,0 @@
|
||||
/**
|
||||
* v1.15.20 — supply-runway estimate behind the detail Übersicht's
|
||||
* "lasts about N more days" line. Pure helpers, no render needed.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import {
|
||||
cadenceIntervalDays,
|
||||
classifyLowStockState,
|
||||
effectiveUnitsPerDose,
|
||||
estimateDailyDoseCount,
|
||||
estimateDailyUnitsCount,
|
||||
estimateRunwayDays,
|
||||
estimateUnitsRunwayDays,
|
||||
lowStockTriggerDays,
|
||||
supplyRunwayDates,
|
||||
type RunwaySchedule,
|
||||
} from "@/components/medications/detail/supply-runway";
|
||||
|
||||
function schedule(partial: Partial<RunwaySchedule>): RunwaySchedule {
|
||||
return {
|
||||
windowStart: "08:00",
|
||||
daysOfWeek: null,
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
describe("estimateDailyDoseCount", () => {
|
||||
it("counts a plain daily schedule as its times-of-day per day", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([schedule({ timesOfDay: ["08:00", "20:00"] })]),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("falls back to one dose per day when timesOfDay is absent", () => {
|
||||
expect(estimateDailyDoseCount([schedule({})])).toBe(1);
|
||||
});
|
||||
|
||||
it("scales a rolling interval down (one dose every N days)", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["09:00"], rollingIntervalDays: 7 }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 7);
|
||||
});
|
||||
|
||||
it("scales weekday picks against the 7-day week", () => {
|
||||
// Mon/Wed/Fri → 3 doses per 7 days.
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], daysOfWeek: "1,3,5" }),
|
||||
]),
|
||||
).toBeCloseTo(3 / 7);
|
||||
});
|
||||
|
||||
it("honours the encoded interval-weeks cadence", () => {
|
||||
// Every 2nd week on one weekday → 1 dose per 14 days.
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], daysOfWeek: "i2;1" }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 14);
|
||||
});
|
||||
|
||||
it("approximates a monthly RRULE at one dose per 30 days", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], rrule: "FREQ=MONTHLY;BYMONTHDAY=1" }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 30);
|
||||
});
|
||||
|
||||
it("treats a once-weekly RRULE as one dose per 7 days", () => {
|
||||
// FREQ=WEEKLY;BYDAY=MO is the modern once-weekly injection encoding;
|
||||
// it must NOT fall through to the daysPerWeek=7 legacy branch.
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], rrule: "FREQ=WEEKLY;BYDAY=MO" }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 7);
|
||||
});
|
||||
|
||||
it("halves a bi-weekly RRULE via INTERVAL=2 (one dose per 14 days)", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({
|
||||
timesOfDay: ["08:00"],
|
||||
rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO",
|
||||
}),
|
||||
]),
|
||||
).toBeCloseTo(1 / 14);
|
||||
});
|
||||
|
||||
it("counts each BYDAY pick on a weekly RRULE (Mon+Thu → 2 per 7 days)", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], rrule: "FREQ=WEEKLY;BYDAY=MO,TH" }),
|
||||
]),
|
||||
).toBeCloseTo(2 / 7);
|
||||
});
|
||||
|
||||
it("defaults a weekly RRULE with no BYDAY to one pick per week", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"], rrule: "FREQ=WEEKLY" }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 7);
|
||||
});
|
||||
|
||||
it("sums across multiple schedules", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ timesOfDay: ["08:00"] }),
|
||||
schedule({ timesOfDay: ["20:00"] }),
|
||||
]),
|
||||
).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("estimateRunwayDays", () => {
|
||||
it("divides the remaining doses by the daily consumption", () => {
|
||||
expect(
|
||||
estimateRunwayDays(14, [schedule({ timesOfDay: ["08:00", "20:00"] })]),
|
||||
).toBe(7);
|
||||
});
|
||||
|
||||
it("floors to whole days", () => {
|
||||
expect(
|
||||
estimateRunwayDays(5, [schedule({ timesOfDay: ["08:00", "20:00"] })]),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("returns null when no supply remains", () => {
|
||||
expect(estimateRunwayDays(0, [schedule({})])).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when no schedule consumes doses", () => {
|
||||
expect(estimateRunwayDays(10, [])).toBeNull();
|
||||
});
|
||||
|
||||
it("covers the weekly injection case (rolling 7-day pen)", () => {
|
||||
// 4 doses left on a once-a-week injection → ~28 days.
|
||||
expect(
|
||||
estimateRunwayDays(4, [
|
||||
schedule({ timesOfDay: ["09:00"], rollingIntervalDays: 7 }),
|
||||
]),
|
||||
).toBe(28);
|
||||
});
|
||||
});
|
||||
|
||||
describe("estimateRunwayDays — v1.16.10 multi-unit doses", () => {
|
||||
it("runs off the dose-derived count: floor(units / unitsPerDose) before dividing by daily consumption", () => {
|
||||
// 9 units at 2 units per dose → floor(9 / 2) = 4 doses; a daily
|
||||
// single-dose schedule then reads 4 days of runway. The call sites
|
||||
// (Übersicht supply row, Bestand summary) derive the dose count this
|
||||
// way before handing it to the estimator.
|
||||
const unitsRemaining = 9;
|
||||
const unitsPerDose = 2;
|
||||
const dosesRemaining = Math.floor(unitsRemaining / unitsPerDose);
|
||||
expect(
|
||||
estimateRunwayDays(dosesRemaining, [schedule({ timesOfDay: ["08:00"] })]),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
it("a partial dose's worth of units never counts as a day", () => {
|
||||
// 1 unit at 2 units per dose is not a dose → no runway.
|
||||
expect(
|
||||
estimateRunwayDays(Math.floor(1 / 2), [
|
||||
schedule({ timesOfDay: ["08:00"] }),
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cadenceIntervalDays — v1.17.0", () => {
|
||||
it("is ≈1 for a daily med", () => {
|
||||
expect(cadenceIntervalDays([schedule({ timesOfDay: ["08:00"] })])).toBe(1);
|
||||
});
|
||||
|
||||
it("is ≈7 for a weekly injection", () => {
|
||||
expect(
|
||||
cadenceIntervalDays([
|
||||
schedule({ timesOfDay: ["09:00"], rollingIntervalDays: 7 }),
|
||||
]),
|
||||
).toBe(7);
|
||||
});
|
||||
|
||||
it("is null for a schedule-less (as-needed) medication", () => {
|
||||
expect(cadenceIntervalDays([])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("lowStockTriggerDays — v1.17.0", () => {
|
||||
const daily = [schedule({ timesOfDay: ["08:00"] })];
|
||||
const weekly = [schedule({ timesOfDay: ["09:00"], rollingIntervalDays: 7 })];
|
||||
|
||||
it("keeps a daily med with no lead at the bare floor (never shrinks)", () => {
|
||||
expect(
|
||||
lowStockTriggerDays({
|
||||
lowStockRunwayDays: 7,
|
||||
leadDays: 0,
|
||||
schedules: daily,
|
||||
}),
|
||||
).toBe(7);
|
||||
});
|
||||
|
||||
it("widens a weekly med to cover the reorder lead PLUS one dose-interval", () => {
|
||||
// max(7, 10 lead + 7 interval) = 17 → fires ~10 days before the last dose.
|
||||
expect(
|
||||
lowStockTriggerDays({
|
||||
lowStockRunwayDays: 7,
|
||||
leadDays: 10,
|
||||
schedules: weekly,
|
||||
}),
|
||||
).toBe(17);
|
||||
});
|
||||
|
||||
it("never drops below the user floor even when lead + cadence are small", () => {
|
||||
expect(
|
||||
lowStockTriggerDays({
|
||||
lowStockRunwayDays: 14,
|
||||
leadDays: 2,
|
||||
schedules: daily,
|
||||
}),
|
||||
).toBe(14);
|
||||
});
|
||||
|
||||
it("falls back to the bare floor for a schedule-less medication", () => {
|
||||
expect(
|
||||
lowStockTriggerDays({
|
||||
lowStockRunwayDays: 7,
|
||||
leadDays: 10,
|
||||
schedules: [],
|
||||
}),
|
||||
).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyLowStockState — v1.17.0", () => {
|
||||
const weekly = [schedule({ timesOfDay: ["09:00"], rollingIntervalDays: 7 })];
|
||||
|
||||
it("returns null when comfortably above the trigger", () => {
|
||||
expect(
|
||||
classifyLowStockState({
|
||||
runwayDays: 20,
|
||||
triggerDays: 17,
|
||||
schedules: weekly,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("flags running_low within the trigger but above one cadence interval", () => {
|
||||
expect(
|
||||
classifyLowStockState({
|
||||
runwayDays: 14,
|
||||
triggerDays: 17,
|
||||
schedules: weekly,
|
||||
}),
|
||||
).toBe("running_low");
|
||||
});
|
||||
|
||||
it("flags last_dose at one cadence interval", () => {
|
||||
expect(
|
||||
classifyLowStockState({
|
||||
runwayDays: 7,
|
||||
triggerDays: 17,
|
||||
schedules: weekly,
|
||||
}),
|
||||
).toBe("last_dose");
|
||||
});
|
||||
});
|
||||
|
||||
describe("supplyRunwayDates — v1.17.0", () => {
|
||||
const today = new Date(Date.UTC(2026, 5, 1)); // 1 Jun 2026
|
||||
|
||||
it("computes runsOutOn = today + runway and reorderBy = runsOutOn − lead", () => {
|
||||
const { runsOutOn, reorderBy } = supplyRunwayDates({
|
||||
today,
|
||||
runwayDays: 14,
|
||||
leadDays: 10,
|
||||
});
|
||||
expect(runsOutOn.toISOString().slice(0, 10)).toBe("2026-06-15");
|
||||
expect(reorderBy.toISOString().slice(0, 10)).toBe("2026-06-05");
|
||||
});
|
||||
|
||||
it("clamps reorderBy to today when the lead pushes it into the past", () => {
|
||||
const { reorderBy } = supplyRunwayDates({
|
||||
today,
|
||||
runwayDays: 3,
|
||||
leadDays: 10,
|
||||
});
|
||||
expect(reorderBy.toISOString().slice(0, 10)).toBe("2026-06-01");
|
||||
});
|
||||
});
|
||||
|
||||
// v1.37.19 (iOS #25 parity) — slot-aware burn rate.
|
||||
//
|
||||
// Watched red: with `estimateDailyUnitsCount` ignoring per-slot
|
||||
// `unitsPerDose` (the pre-fix behaviour — dose rate × medication-level
|
||||
// units only), the mixed-dose case below computes 2 units/day instead of
|
||||
// 1.5 and both the effective-units and the runway assertions fail.
|
||||
describe("slot-aware units math (#219 parity)", () => {
|
||||
const wholeMorning = schedule({ timesOfDay: ["08:00"], unitsPerDose: 1 });
|
||||
const halfNoon = schedule({ timesOfDay: ["12:00"], unitsPerDose: 0.5 });
|
||||
|
||||
it("weights each slot's own unitsPerDose by its cadence share", () => {
|
||||
// 1 unit + 0.5 unit per day = 1.5 units/day.
|
||||
expect(estimateDailyUnitsCount([wholeMorning, halfNoon], 1)).toBeCloseTo(
|
||||
1.5,
|
||||
);
|
||||
});
|
||||
|
||||
it("inherits the medication level for a NULL per-slot value", () => {
|
||||
expect(
|
||||
estimateDailyUnitsCount(
|
||||
[schedule({ timesOfDay: ["08:00"], unitsPerDose: null }), halfNoon],
|
||||
2,
|
||||
),
|
||||
).toBeCloseTo(2.5);
|
||||
});
|
||||
|
||||
it("derives the schedule-weighted average units per dose", () => {
|
||||
// 1.5 units over 2 doses per day → 0.75 units per dose.
|
||||
expect(effectiveUnitsPerDose([wholeMorning, halfNoon], 1)).toBeCloseTo(
|
||||
0.75,
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the medication level with no consuming schedule", () => {
|
||||
expect(effectiveUnitsPerDose([], 2)).toBe(2);
|
||||
expect(effectiveUnitsPerDose([], 0)).toBe(1);
|
||||
});
|
||||
|
||||
it("projects the units runway under the slot-aware rate", () => {
|
||||
// 15 units at 1.5 units/day → 10 days.
|
||||
expect(estimateUnitsRunwayDays(15, [wholeMorning, halfNoon], 1)).toBe(10);
|
||||
});
|
||||
|
||||
it("is honest about an exhausted supply (0 days, not null)", () => {
|
||||
expect(estimateUnitsRunwayDays(0, [wholeMorning], 1)).toBe(0);
|
||||
});
|
||||
|
||||
it("returns null with no consuming cadence", () => {
|
||||
expect(estimateUnitsRunwayDays(10, [], 1)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// #1034 — a whole number plus a fraction (1½) and a free decimal (1.2)
|
||||
// run through the same arithmetic as a whole tablet.
|
||||
describe("units runway with a mixed units-per-dose value (#1034)", () => {
|
||||
const morning = schedule({ timesOfDay: ["08:00"] });
|
||||
const evening = schedule({ timesOfDay: ["20:00"] });
|
||||
|
||||
it("burns 1½ units per dose at the medication level", () => {
|
||||
// Two doses a day at 1.5 units = 3 units/day; 30 units last 10 days.
|
||||
expect(estimateDailyUnitsCount([morning, evening], 1.5)).toBeCloseTo(3);
|
||||
expect(estimateUnitsRunwayDays(30, [morning, evening], 1.5)).toBe(10);
|
||||
expect(effectiveUnitsPerDose([morning, evening], 1.5)).toBeCloseTo(1.5);
|
||||
});
|
||||
|
||||
it("honours a 2¼ per-slot override beside the inherited value", () => {
|
||||
const heavy = schedule({ timesOfDay: ["20:00"], unitsPerDose: 2.25 });
|
||||
// 1 + 2.25 = 3.25 units/day; 13 units last 4 days.
|
||||
expect(estimateDailyUnitsCount([morning, heavy], 1)).toBeCloseTo(3.25);
|
||||
expect(estimateUnitsRunwayDays(13, [morning, heavy], 1)).toBe(4);
|
||||
});
|
||||
|
||||
it("floors a partial day under a free decimal dose", () => {
|
||||
// 1.2 units/day; 10 units cover 8 whole days (8.33…).
|
||||
expect(estimateUnitsRunwayDays(10, [morning], 1.2)).toBe(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe("estimateDailyDoseCount — cadence parts the rate used to drop", () => {
|
||||
it("stretches a monthly RRULE by its INTERVAL (every third month)", () => {
|
||||
const perDay = estimateDailyDoseCount([
|
||||
schedule({ rrule: "FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=10" }),
|
||||
]);
|
||||
expect(perDay).toBeCloseTo(1 / 90, 10);
|
||||
// Two doses left last about half a year, not two months.
|
||||
expect(
|
||||
estimateRunwayDays(2, [
|
||||
schedule({ rrule: "FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=10" }),
|
||||
]),
|
||||
).toBe(180);
|
||||
});
|
||||
|
||||
it("counts each BYMONTHDAY of a monthly RRULE", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ rrule: "FREQ=MONTHLY;BYMONTHDAY=1,15" }),
|
||||
]),
|
||||
).toBeCloseTo(2 / 30, 10);
|
||||
});
|
||||
|
||||
it.each([
|
||||
// Every Monday of the month is a weekly dose, not one a month.
|
||||
["FREQ=MONTHLY;BYDAY=MO", 1 / 7],
|
||||
["FREQ=MONTHLY;BYDAY=MO,TH", 2 / 7],
|
||||
// With an ordinal it is one day of the month.
|
||||
["FREQ=MONTHLY;BYDAY=1MO", 1 / 30],
|
||||
["FREQ=MONTHLY;BYDAY=1MO,-1FR", 2 / 30],
|
||||
// The last weekday of the month: BYSETPOS picks one of the five.
|
||||
["FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1", 1 / 30],
|
||||
["FREQ=MONTHLY;INTERVAL=2;BYDAY=MO", 1 / 14],
|
||||
// Every Monday in January, and the first Monday of March and September.
|
||||
["FREQ=YEARLY;BYMONTH=1;BYDAY=MO", 30 / 7 / 365],
|
||||
["FREQ=YEARLY;BYMONTH=3,9;BYDAY=1MO", 2 / 365],
|
||||
])("counts the occurrences of %s", (rrule, perDay) => {
|
||||
expect(estimateDailyDoseCount([schedule({ rrule })])).toBeCloseTo(
|
||||
perDay,
|
||||
10,
|
||||
);
|
||||
});
|
||||
|
||||
it("stretches a daily RRULE by its INTERVAL (every other day)", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([schedule({ rrule: "FREQ=DAILY;INTERVAL=2" })]),
|
||||
).toBeCloseTo(1 / 2, 10);
|
||||
});
|
||||
|
||||
it("stretches a yearly RRULE by its INTERVAL and counts BYMONTH", () => {
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ rrule: "FREQ=YEARLY;INTERVAL=2;BYMONTH=1;BYMONTHDAY=1" }),
|
||||
]),
|
||||
).toBeCloseTo(1 / 730, 10);
|
||||
expect(
|
||||
estimateDailyDoseCount([
|
||||
schedule({ rrule: "FREQ=YEARLY;BYMONTH=3,9;BYMONTHDAY=1" }),
|
||||
]),
|
||||
).toBeCloseTo(2 / 365, 10);
|
||||
});
|
||||
|
||||
it("scales a CYCLIC schedule by its on share (3 weeks on, 1 off)", () => {
|
||||
const cyclic = schedule({
|
||||
rrule: "FREQ=DAILY",
|
||||
scheduleType: "CYCLIC",
|
||||
cyclicOnWeeks: 3,
|
||||
cyclicOffWeeks: 1,
|
||||
});
|
||||
expect(estimateDailyDoseCount([cyclic])).toBeCloseTo(3 / 4, 10);
|
||||
expect(estimateRunwayDays(21, [cyclic])).toBe(28);
|
||||
});
|
||||
|
||||
it("counts nothing for an as-needed (PRN) schedule", () => {
|
||||
expect(estimateDailyDoseCount([schedule({ scheduleType: "PRN" })])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("whole counts survive binary floating point", () => {
|
||||
it("2.4 units at 0.8 per dose is three doses", () => {
|
||||
// 2.4 / 0.8 === 2.9999999999999996 in IEEE 754.
|
||||
expect(effectiveUnitsPerDose([schedule({})], 0.8)).toBe(0.8);
|
||||
expect(estimateUnitsRunwayDays(2.4, [schedule({})], 0.8)).toBe(3);
|
||||
});
|
||||
|
||||
it("a dose-count runway that divides exactly is not a day short", () => {
|
||||
// Three doses on Mon/Wed/Fri: 9/7 a day, and 9 / (9/7) is
|
||||
// 6.999999999999999 in IEEE 754 — a week of supply, not six days.
|
||||
const s = schedule({
|
||||
daysOfWeek: "1,3,5",
|
||||
timesOfDay: ["08:00", "12:00", "20:00"],
|
||||
});
|
||||
expect(estimateRunwayDays(9, [s])).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -88,7 +88,7 @@ import { PhaseConfigSheet } from "@/components/medications/sections/phase-config
|
||||
import { SideEffectsSection } from "@/components/medications/side-effects-section";
|
||||
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
|
||||
import { TitrationTimeline } from "@/components/medications/titration-timeline";
|
||||
import { estimateRunwayDays } from "@/components/medications/detail/supply-runway";
|
||||
import { estimateRunwayDays } from "@/lib/medications/supply-runway";
|
||||
import type { SupplySummary } from "@/lib/medications/inventory/summary";
|
||||
import { MedicationWizardDialog } from "@/components/medications/wizard/medication-wizard-dialog";
|
||||
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
/**
|
||||
* v1.15.20 — supply-runway estimate for the medication detail Übersicht.
|
||||
*
|
||||
* Pure helpers that turn the schedule snapshot the detail GET already
|
||||
* carries into an approximate doses-per-day figure, so the Übersicht tab
|
||||
* can render "lasts about N more days" from the inventory remaining-doses
|
||||
* count without a new endpoint. The estimate is deliberately coarse
|
||||
* (calendar months ≈ 30 days) — the copy says "about" and the Bestand tab
|
||||
* stays the authoritative per-item readout.
|
||||
*/
|
||||
|
||||
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
|
||||
import { floorWhole } from "@/lib/medications/units-per-dose";
|
||||
|
||||
/** The schedule fields the runway estimate reads. */
|
||||
export interface RunwaySchedule {
|
||||
windowStart: string;
|
||||
daysOfWeek: string | null;
|
||||
timesOfDay?: string[];
|
||||
rrule?: string | null;
|
||||
rollingIntervalDays?: number | null;
|
||||
/**
|
||||
* v1.37.19 (#219 parity) — per-slot units override as a plain number
|
||||
* (the wire shape). `null`/`undefined` inherits the medication-level
|
||||
* `unitsPerDose`, exactly like the consumption path's resolver.
|
||||
*/
|
||||
unitsPerDose?: number | null;
|
||||
/**
|
||||
* Schedule type. PRN consumes nothing on a cadence; CYCLIC consumes only
|
||||
* in its "on" weeks, so its rate is scaled by on / (on + off).
|
||||
*/
|
||||
scheduleType?: "SCHEDULED" | "PRN" | "CYCLIC" | string | null;
|
||||
cyclicOnWeeks?: number | null;
|
||||
cyclicOffWeeks?: number | null;
|
||||
}
|
||||
|
||||
/** A positive integer RRULE part (`INTERVAL=3`), or `fallback`. */
|
||||
function rrulePositiveInt(
|
||||
rrule: string,
|
||||
key: string,
|
||||
fallback: number,
|
||||
): number {
|
||||
const m = new RegExp(`(?:^|;)${key}=(\\d+)(?:;|$)`, "i").exec(rrule);
|
||||
const n = m ? Number(m[1]) : NaN;
|
||||
return Number.isInteger(n) && n >= 1 ? n : fallback;
|
||||
}
|
||||
|
||||
/** How many comma-separated values an RRULE list part carries, or 0. */
|
||||
function rruleListCount(rrule: string, key: string): number {
|
||||
const m = new RegExp(`(?:^|;)${key}=([^;]+)`, "i").exec(rrule);
|
||||
return m ? m[1].split(",").filter((v) => v.trim() !== "").length : 0;
|
||||
}
|
||||
|
||||
/** The raw values of an RRULE list part (`BYDAY=1MO,FR` → `1MO`, `FR`). */
|
||||
function rruleList(rrule: string, key: string): string[] {
|
||||
const m = new RegExp(`(?:^|;)${key}=([^;]+)`, "i").exec(rrule);
|
||||
return m ? m[1].split(",").filter((v) => v.trim() !== "") : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Occurrences one period of a monthly or yearly rule holds, with the period
|
||||
* `periodDays` long. `BYSETPOS` picks that many of the candidates. A
|
||||
* `BYDAY` entry with an ordinal (`1MO`, `-1FR`) is one day of the period;
|
||||
* one without (`MO`) is every such weekday in it, about `periodDays / 7`.
|
||||
* Counting `FREQ=MONTHLY;BYDAY=MO` as one dose a month made a Monday
|
||||
* medication's supply read four times longer than it lasts.
|
||||
*/
|
||||
function occurrencesPerPeriod(
|
||||
rrule: string,
|
||||
periodDays: number,
|
||||
fallback: number,
|
||||
): number {
|
||||
const setPos = rruleListCount(rrule, "BYSETPOS");
|
||||
if (setPos > 0) return setPos;
|
||||
const monthDays = rruleListCount(rrule, "BYMONTHDAY");
|
||||
if (monthDays > 0) return monthDays;
|
||||
const byDay = rruleList(rrule, "BYDAY");
|
||||
if (byDay.length === 0) return fallback;
|
||||
let count = 0;
|
||||
for (const entry of byDay) {
|
||||
count += /^[+-]?\d/.test(entry.trim()) ? 1 : periodDays / 7;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximate doses per day for ONE schedule: times-of-day count, scaled
|
||||
* down by the cadence (rolling interval, weekly day picks + interval
|
||||
* weeks, monthly/yearly RRULEs).
|
||||
*/
|
||||
function scheduleDailyDoseCount(s: RunwaySchedule): number {
|
||||
if (s.scheduleType === "PRN") return 0;
|
||||
const rate = cadenceDailyDoseCount(s);
|
||||
if (s.scheduleType === "CYCLIC") {
|
||||
// Doses fall only in the "on" weeks of the cycle.
|
||||
const on = s.cyclicOnWeeks ?? 0;
|
||||
const off = s.cyclicOffWeeks ?? 0;
|
||||
if (on > 0 && off > 0) return (rate * on) / (on + off);
|
||||
}
|
||||
return rate;
|
||||
}
|
||||
|
||||
function cadenceDailyDoseCount(s: RunwaySchedule): number {
|
||||
const times =
|
||||
s.timesOfDay && s.timesOfDay.length > 0 ? s.timesOfDay.length : 1;
|
||||
if (typeof s.rollingIntervalDays === "number" && s.rollingIntervalDays >= 1) {
|
||||
return times / s.rollingIntervalDays;
|
||||
}
|
||||
const rrule = s.rrule ?? "";
|
||||
// INTERVAL stretches every calendar frequency: FREQ=MONTHLY;INTERVAL=3 is
|
||||
// one dose a quarter, not one a month.
|
||||
const interval = rrulePositiveInt(rrule, "INTERVAL", 1);
|
||||
if (/FREQ=DAILY/i.test(rrule)) {
|
||||
return times / interval;
|
||||
}
|
||||
if (/FREQ=MONTHLY/i.test(rrule)) {
|
||||
const perMonth = occurrencesPerPeriod(rrule, 30, 1);
|
||||
return (times * perMonth) / (30 * interval);
|
||||
}
|
||||
if (/FREQ=YEARLY/i.test(rrule)) {
|
||||
// Within each BYMONTH month (or the year, without one), the day parts
|
||||
// count as they would for a monthly rule.
|
||||
const months = rruleListCount(rrule, "BYMONTH");
|
||||
const perYear =
|
||||
months > 0
|
||||
? months * occurrencesPerPeriod(rrule, 30, 1)
|
||||
: occurrencesPerPeriod(rrule, 365, 1);
|
||||
return (times * perYear) / (365 * interval);
|
||||
}
|
||||
// FREQ=WEEKLY;BYDAY=…;INTERVAL=… is the modern weekly encoding (the
|
||||
// create path stores the cadence on the rrule and leaves daysOfWeek
|
||||
// empty). Honour the BYDAY pick count and the week INTERVAL: a
|
||||
// once-weekly injection is one dose per 7 days, a bi-weekly one per
|
||||
// 14. Without this branch a weekly rrule fell through to the legacy
|
||||
// daysOfWeek fallback below with daysPerWeek=7, over-estimating the
|
||||
// rate ~7× (≈14× bi-weekly) and firing low-stock alerts far too early.
|
||||
if (/FREQ=WEEKLY/.test(rrule)) {
|
||||
const bydayCount = Math.max(1, rruleListCount(rrule, "BYDAY"));
|
||||
return (times * bydayCount) / (7 * interval);
|
||||
}
|
||||
const { daysOfWeek, intervalWeeks } = parseScheduleRecurrence(s.daysOfWeek);
|
||||
const daysPerWeek = daysOfWeek.length > 0 ? daysOfWeek.length : 7;
|
||||
const weeks = intervalWeeks >= 1 ? intervalWeeks : 1;
|
||||
return (times * daysPerWeek) / (7 * weeks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximate doses per day across every schedule.
|
||||
*/
|
||||
export function estimateDailyDoseCount(schedules: RunwaySchedule[]): number {
|
||||
let perDay = 0;
|
||||
for (const s of schedules) {
|
||||
perDay += scheduleDailyDoseCount(s);
|
||||
}
|
||||
return perDay;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.37.19 (#219 parity) — approximate inventory UNITS consumed per day,
|
||||
* honouring each slot's own `unitsPerDose` where set. The pre-fix figure
|
||||
* multiplied the dose rate by the medication-level units alone, which
|
||||
* over- or under-stated the burn rate for any medication whose slots
|
||||
* carry different doses (a whole tablet in the morning, a half at noon).
|
||||
*/
|
||||
export function estimateDailyUnitsCount(
|
||||
schedules: RunwaySchedule[],
|
||||
medicationUnitsPerDose: number,
|
||||
): number {
|
||||
const fallback = medicationUnitsPerDose > 0 ? medicationUnitsPerDose : 1;
|
||||
let perDayUnits = 0;
|
||||
for (const s of schedules) {
|
||||
const perSlot =
|
||||
typeof s.unitsPerDose === "number" && s.unitsPerDose > 0
|
||||
? s.unitsPerDose
|
||||
: fallback;
|
||||
perDayUnits += scheduleDailyDoseCount(s) * perSlot;
|
||||
}
|
||||
return perDayUnits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The schedule-weighted average units one dose consumes — the divisor that
|
||||
* turns a units pool into an honest doses-remaining figure for a
|
||||
* medication with per-slot doses. Falls back to the medication level when
|
||||
* no schedule derives a consumption rate.
|
||||
*/
|
||||
export function effectiveUnitsPerDose(
|
||||
schedules: RunwaySchedule[],
|
||||
medicationUnitsPerDose: number,
|
||||
): number {
|
||||
const fallback = medicationUnitsPerDose > 0 ? medicationUnitsPerDose : 1;
|
||||
const perDay = estimateDailyDoseCount(schedules);
|
||||
if (perDay <= 0) return fallback;
|
||||
const perDayUnits = estimateDailyUnitsCount(
|
||||
schedules,
|
||||
medicationUnitsPerDose,
|
||||
);
|
||||
return perDayUnits > 0 ? perDayUnits / perDay : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.37.19 (#219 parity) — whole days a UNITS pool covers under the
|
||||
* slot-aware burn rate, or `null` when no consuming schedule exists.
|
||||
* Zero units with a consuming schedule is honestly 0 days.
|
||||
*/
|
||||
export function estimateUnitsRunwayDays(
|
||||
unitsRemaining: number,
|
||||
schedules: RunwaySchedule[],
|
||||
medicationUnitsPerDose: number,
|
||||
): number | null {
|
||||
const perDayUnits = estimateDailyUnitsCount(
|
||||
schedules,
|
||||
medicationUnitsPerDose,
|
||||
);
|
||||
if (perDayUnits <= 0) return null;
|
||||
return floorWhole(Math.max(0, unitsRemaining) / perDayUnits);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole days the remaining supply covers, or `null` when no estimate is
|
||||
* possible (no supply, no consuming schedule).
|
||||
*/
|
||||
export function estimateRunwayDays(
|
||||
dosesRemaining: number,
|
||||
schedules: RunwaySchedule[],
|
||||
): number | null {
|
||||
if (dosesRemaining <= 0) return null;
|
||||
const perDay = estimateDailyDoseCount(schedules);
|
||||
if (perDay <= 0) return null;
|
||||
return floorWhole(dosesRemaining / perDay);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.17.0 — one dose-interval in whole days for a cadence: the inverse
|
||||
* of the daily-dose rate, rounded up. ≈1 for a daily med, ≈7 for a
|
||||
* weekly injection, ≈30 for a monthly RRULE. Returns `null` for a
|
||||
* schedule with no derivable consumption (as-needed / empty).
|
||||
*/
|
||||
export function cadenceIntervalDays(
|
||||
schedules: RunwaySchedule[],
|
||||
): number | null {
|
||||
const perDay = estimateDailyDoseCount(schedules);
|
||||
if (perDay <= 0) return null;
|
||||
return Math.ceil(1 / perDay);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.17.0 — reorder-lead-aware low-stock trigger threshold in days.
|
||||
*
|
||||
* The bare `lowStockRunwayDays` floor fired the alert only when the
|
||||
* runway dropped below it; for a sparse cadence (a weekly injection's
|
||||
* 7-day floor ≈ one dose-interval) that warning landed with ~1 dose
|
||||
* left — too late to reorder. The effective trigger widens the floor to
|
||||
* cover the reorder lead PLUS one dose-interval:
|
||||
*
|
||||
* trigger = max(lowStockRunwayDays, leadDays + cadenceIntervalDays)
|
||||
*
|
||||
* so the alert lands before the LAST dose for any cadence. Because the
|
||||
* result is `max(...)` over the user's own floor, it NEVER shrinks
|
||||
* anyone's current threshold — only widens it when the lead + cadence
|
||||
* demand more headroom. A schedule with no derivable cadence falls back
|
||||
* to the bare floor (it has no runway anyway, so it never fires).
|
||||
*/
|
||||
export function lowStockTriggerDays(input: {
|
||||
lowStockRunwayDays: number;
|
||||
leadDays: number;
|
||||
schedules: RunwaySchedule[];
|
||||
}): number {
|
||||
const interval = cadenceIntervalDays(input.schedules);
|
||||
if (interval === null) return input.lowStockRunwayDays;
|
||||
return Math.max(input.lowStockRunwayDays, input.leadDays + interval);
|
||||
}
|
||||
|
||||
/** v1.17.0 — informational vs actionable low-stock presentation state. */
|
||||
export type LowStockState = "running_low" | "last_dose";
|
||||
|
||||
/**
|
||||
* v1.17.0 — classify a runway against its cadence + trigger for the
|
||||
* card / push copy. Returns `null` when the supply is comfortably above
|
||||
* the trigger (no notice). `"last_dose"` when the runway is down to one
|
||||
* dose-interval (informational — about to take the final dose);
|
||||
* `"running_low"` otherwise within the trigger (actionable — reorder
|
||||
* now). `last_dose` wins when both apply so the final-dose case reads
|
||||
* as the calmer, more specific line.
|
||||
*/
|
||||
export function classifyLowStockState(input: {
|
||||
runwayDays: number;
|
||||
triggerDays: number;
|
||||
schedules: RunwaySchedule[];
|
||||
}): LowStockState | null {
|
||||
if (input.runwayDays > input.triggerDays) return null;
|
||||
const interval = cadenceIntervalDays(input.schedules);
|
||||
if (interval !== null && input.runwayDays <= interval) return "last_dose";
|
||||
return "running_low";
|
||||
}
|
||||
|
||||
/** A calendar date as a UTC-midnight `Date` — the copy renders day-only. */
|
||||
function addDaysUtc(base: Date, days: number): Date {
|
||||
const d = new Date(base);
|
||||
d.setUTCDate(d.getUTCDate() + days);
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.17.0 — the two concrete dates the low-stock copy surfaces:
|
||||
* runsOutOn = today + runwayDays (supply depletes)
|
||||
* reorderBy = runsOutOn − leadDays (order by this date to avoid a gap)
|
||||
* Both are clamped to never precede `today` (a deep low-stock state can
|
||||
* push `reorderBy` into the past — surface today instead of a past date).
|
||||
*/
|
||||
export function supplyRunwayDates(input: {
|
||||
today: Date;
|
||||
runwayDays: number;
|
||||
leadDays: number;
|
||||
}): { runsOutOn: Date; reorderBy: Date } {
|
||||
const runsOutOn = addDaysUtc(input.today, Math.max(0, input.runwayDays));
|
||||
const reorderRaw = addDaysUtc(runsOutOn, -input.leadDays);
|
||||
const reorderBy =
|
||||
reorderRaw < input.today ? new Date(input.today) : reorderRaw;
|
||||
return { runsOutOn, reorderBy };
|
||||
}
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
estimateDailyDoseCount,
|
||||
estimateRunwayDays,
|
||||
lowStockTriggerDays,
|
||||
} from "@/components/medications/detail/supply-runway";
|
||||
} from "@/lib/medications/supply-runway";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useMedicationComplianceSummary } from "@/lib/queries/use-medication-compliance-summary";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
estimateDailyDoseCount,
|
||||
estimateRunwayDays,
|
||||
lowStockTriggerDays,
|
||||
} from "@/components/medications/detail/supply-runway";
|
||||
} from "@/lib/medications/supply-runway";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import {
|
||||
invalidateKeys,
|
||||
|
||||
@@ -28,7 +28,7 @@ import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { MedicationStatusPill } from "@/components/medications/card-parts/medication-status-pill";
|
||||
import { useWeekdayLabel } from "@/components/medications/card-parts/medication-next-last-slot";
|
||||
import { resolveDisplayedSlotInstant } from "@/components/medications/card-parts/displayed-slot-instant";
|
||||
import { estimateRunwayDays } from "@/components/medications/detail/supply-runway";
|
||||
import { estimateRunwayDays } from "@/lib/medications/supply-runway";
|
||||
import { useMedicationIntake } from "@/components/medications/use-medication-intake";
|
||||
import { reduceCurrentWindowStatus } from "@/lib/medications/window-status";
|
||||
import { resolveNextDueDayLabel } from "@/lib/medications/next-due-day-label";
|
||||
|
||||
@@ -59,9 +59,11 @@ import {
|
||||
type CadenceSubControls,
|
||||
type CadenceValue,
|
||||
DEFAULT_SUB_CONTROLS,
|
||||
} from "./types";
|
||||
import {
|
||||
type WeekdayToken,
|
||||
WEEKDAY_TOKENS,
|
||||
} from "./types";
|
||||
} from "@/lib/medications/scheduling/weekday-tokens";
|
||||
|
||||
export interface CadencePickerProps {
|
||||
value: CadenceValue;
|
||||
|
||||
@@ -17,9 +17,11 @@ import {
|
||||
type CadenceSubControls,
|
||||
type CadenceValue,
|
||||
DEFAULT_SUB_CONTROLS,
|
||||
} from "./types";
|
||||
import {
|
||||
type WeekdayToken,
|
||||
WEEKDAY_TOKENS,
|
||||
} from "./types";
|
||||
} from "@/lib/medications/scheduling/weekday-tokens";
|
||||
|
||||
/**
|
||||
* Legacy schedule shape the page passes to the form. Sunday-anchored
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
* structured values; the wizard / form maps them to the wire format.
|
||||
*/
|
||||
|
||||
import type { WeekdayToken } from "@/lib/medications/scheduling/weekday-tokens";
|
||||
|
||||
/**
|
||||
* The eight cadence kinds the wizard exposes. Maps to the engine's
|
||||
* dispatch tiers in `src/lib/medications/scheduling/recurrence.ts`:
|
||||
@@ -71,18 +73,6 @@ export interface CadenceSubControls {
|
||||
rollingDays: number;
|
||||
}
|
||||
|
||||
/** RFC 5545 BYDAY tokens — the order the chip row renders. */
|
||||
export const WEEKDAY_TOKENS = [
|
||||
"MO",
|
||||
"TU",
|
||||
"WE",
|
||||
"TH",
|
||||
"FR",
|
||||
"SA",
|
||||
"SU",
|
||||
] as const;
|
||||
export type WeekdayToken = (typeof WEEKDAY_TOKENS)[number];
|
||||
|
||||
/** Sensible defaults so a brand-new picker has valid sub-controls. */
|
||||
export const DEFAULT_SUB_CONTROLS: CadenceSubControls = {
|
||||
weekdays: ["MO"],
|
||||
|
||||
@@ -16,8 +16,8 @@ import { isoStringToDate } from "@/components/medications/scheduling/course-wind
|
||||
import {
|
||||
DEFAULT_SUB_CONTROLS,
|
||||
type CadenceSubControls,
|
||||
type WeekdayToken,
|
||||
} from "@/components/medications/scheduling/types";
|
||||
import { type WeekdayToken } from "@/lib/medications/scheduling/weekday-tokens";
|
||||
import type { WizardPayload as ExtractorPayload } from "@/components/medications/scheduling/natural-language-extractor";
|
||||
|
||||
import type { WizardPayload } from "./wizard-payload";
|
||||
|
||||
@@ -5,11 +5,11 @@ import { useMemo } from "react";
|
||||
import { encodeCadence } from "@/components/medications/scheduling/cadence-picker";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { type CadenceSubControls } from "@/components/medications/scheduling/types";
|
||||
import {
|
||||
type CadenceSubControls,
|
||||
type WeekdayToken,
|
||||
WEEKDAY_TOKENS,
|
||||
} from "@/components/medications/scheduling/types";
|
||||
} from "@/lib/medications/scheduling/weekday-tokens";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import type { StepProps } from "./step1-name";
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import en from "../../../../messages/en.json" with { type: "json" };
|
||||
import de from "../../../../messages/de.json" with { type: "json" };
|
||||
import { SETTINGS_SECTION_SLUGS } from "../section-slugs";
|
||||
import { SETTINGS_SECTION_SLUGS } from "@/lib/settings/section-slugs";
|
||||
|
||||
type Bag = Record<string, unknown>;
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ vi.mock("@/components/settings/thresholds-editor-section", () => ({
|
||||
}));
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { SettingsSectionFrame } from "./section-frame-harness";
|
||||
import type { SettingsSectionSlug } from "../section-slugs";
|
||||
import type { SettingsSectionSlug } from "@/lib/settings/section-slugs";
|
||||
import { AboutSection } from "../about-section";
|
||||
import { AccountSection } from "../account-section";
|
||||
import { AdvancedSection } from "../advanced-section";
|
||||
|
||||
@@ -11,7 +11,7 @@ import { classifySettingsDestination } from "@/lib/record-settings/classificatio
|
||||
import { SettingsCardHeader } from "@/components/settings/_card-header";
|
||||
import { ManagedIntegrationStatus } from "@/components/settings/managed-integration-status";
|
||||
import { SettingsCard } from "@/components/settings/settings-card";
|
||||
import type { SettingsSectionSlug } from "@/components/settings/section-slugs";
|
||||
import type { SettingsSectionSlug } from "@/lib/settings/section-slugs";
|
||||
|
||||
// The two record-scoped surfaces load on demand. Both are forms that validate
|
||||
// with Zod (the managed settings patch, the allergy and family-history
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
/**
|
||||
* Server-safe constants for the v1.4 settings split. Kept in a separate
|
||||
* module from `<SettingsShell>` (a client component) so server-rendered code
|
||||
* paths — `generateStaticParams()`, the page guard, future tests — can import
|
||||
* the slug list without dragging the whole client bundle into the server
|
||||
* graph.
|
||||
*/
|
||||
|
||||
// v1.18.0 — `sources` was folded into Settings → Integrations as the
|
||||
// "Sources" sub-tab.
|
||||
// v1.18.1 — the Integrations sub-tabs (Connections / Channels / Sources)
|
||||
// were split back into three separate left-side entries: `integrations` (the
|
||||
// Connections content, shown directly), `channels` (delivery channels), and
|
||||
// `sources` (source weighting). The `/settings/sources` redirect is gone
|
||||
// (it is a real route again); `channels` is a brand-new entry.
|
||||
// `thresholds` (Targets) keeps its own left-nav entry + route, served by the
|
||||
// dynamic `[section]` route below.
|
||||
// v1.16.10 — `medications` sits after `insights`: the customise surface
|
||||
// for the /medications list (view preference + manual order), following
|
||||
// the dashboard / insights pattern of a dedicated settings section
|
||||
// reached from the page header's Settings2 glyph.
|
||||
// v1.17 — `mood` sits after `medications`: the mood-tag management
|
||||
// surface (groups, custom tags, hide/archive, picker order), reached
|
||||
// from the /mood page header's wrench glyph.
|
||||
// v1.18.7 — `labs`, `illness`, and `vorsorge` move INTO the Settings
|
||||
// shell as first-class sections, right after `mood`, so the three
|
||||
// tracking-domain customise surfaces sit together. They were standalone
|
||||
// `ModuleSettingsFrame` pages (their own back-button + title, outside the
|
||||
// shell); now the dynamic `[section]` route renders them in shell chrome
|
||||
// 1:1 with the other sections. The wrench deep-links (`/settings/labs`,
|
||||
// `/settings/illness`, `/settings/vorsorge`) are unchanged — they now
|
||||
// resolve through the shell. `labs` + `illness` are module-gated (they are
|
||||
// toggleable modules); `vorsorge` (preventive-care reminders) is not a
|
||||
// module, so its entry is always shown.
|
||||
// v1.17.1 — `layout` is the one "Layout & Personalization" home.
|
||||
// The dashboard / insights / medications / mood personalization editors
|
||||
// each keep their own route (deep links, page-header cogs, and the hub's
|
||||
// own links all resolve), but the settings NAV now surfaces a single
|
||||
// `layout` entry instead of four scattered "arrange" entries, so the
|
||||
// concept reads as one place. The four editor slugs stay in this list so
|
||||
// their routes still resolve; they are simply not listed in the shell nav.
|
||||
// v1.18.0 — the standalone `reminders` hub is gone. It was a
|
||||
// link-only page ("doppelt gemoppelt") that merely deep-linked into the
|
||||
// canonical editors; reminder TYPES now live centrally in `notifications`,
|
||||
// each row gated on its module. `/settings/reminders` 301-redirects to
|
||||
// `/settings/notifications` (next.config.ts).
|
||||
// v1.18.0 — per-submodule settings split. `gesundheitsakte` (the full
|
||||
// health-record export, always available) lifts out of Export & Import into
|
||||
// its own top-level entry.
|
||||
export const SETTINGS_SECTION_SLUGS = [
|
||||
"account",
|
||||
// v1.23 — `security` is the dedicated account-security home: second-factor
|
||||
// setup (TOTP + security keys), recovery codes, and passkey management. Sits
|
||||
// right after `account` so the two identity surfaces read as neighbours.
|
||||
"security",
|
||||
// v1.36.0 — `access` ("Shared access"): which other accounts on this
|
||||
// instance may open this health record, which records this one may open, and
|
||||
// when they were opened. Sits beside `security` because it answers the same
|
||||
// question those surfaces do — who can get at my account, and what have they
|
||||
// been doing. Distinct from the `sharing` slug below, which is the clinician
|
||||
// share LINK (a time-boxed read-only report handed to somebody outside the
|
||||
// instance); this one is a standing relationship between two accounts on it.
|
||||
"access",
|
||||
// v1.18.0 — `modules` ("Was du trackst") sits right after account: the
|
||||
// single front door for enabling/disabling secondary tracking domains.
|
||||
"modules",
|
||||
"integrations",
|
||||
// v1.18.1 — Quellen (source weighting) split out of the Integrations
|
||||
// tabs into its own left-side entry. v1.25.3 — Kanäle (delivery channels)
|
||||
// folded back into Notifications as an in-page group; `/settings/channels`
|
||||
// 301-redirects to `/settings/notifications#channels` (next.config.ts).
|
||||
"sources",
|
||||
"notifications",
|
||||
// v1.37.19 — the per-module personalization slugs (`dashboard`,
|
||||
// `insights`, `medications`, `mood`, `labs`, `illness`, `vorsorge`) and
|
||||
// `sharing` left this list. Their URLs are owned by permanent redirects
|
||||
// in `next.config.ts` (`/settings/<module>` → `/settings/layout/<module>`,
|
||||
// `/settings/sharing` → `/settings/gesundheitsakte#sharing`), so the
|
||||
// dynamic route could never serve them — prerendering eight unreachable
|
||||
// pages and keeping eight dead component wirings. The redirects, the
|
||||
// section components, and the layout-hub subpages are unchanged.
|
||||
"layout",
|
||||
// v1.25 — "Umwelt" (environmental context): home location, travel
|
||||
// overrides, and the weather/daylight backfill. Module-gated on the opt-in
|
||||
// `environment` module (the nav entry only shows when it is on).
|
||||
"environment",
|
||||
// v1.25 — "Anamnese" (medical history): the structured-record
|
||||
// home for allergies + family history. Always shown (not module-gated, like
|
||||
// `vorsorge`); the records are foundational health-profile data.
|
||||
"anamnesis",
|
||||
// v1.35.0 — "Health Score": which pillars count toward the composite.
|
||||
// Its own surface rather than a corner of the modules hub, because the
|
||||
// module switches answer a different question (what is recorded and
|
||||
// shown) and folding the two together is what kept the score's
|
||||
// composition invisible.
|
||||
"score",
|
||||
"thresholds",
|
||||
"ai",
|
||||
// v1.18.0 — `coach` gathers the Coach preference cards (disable
|
||||
// toggle, preferences, memory) out of the AI section, module-gated on
|
||||
// the coach module. The `ai` entry keeps provider / model / BYOK only.
|
||||
"coach",
|
||||
"api",
|
||||
// v1.22.0 — the remote MCP connector card: enable the opt-in `mcp` module and
|
||||
// mint / revoke the dedicated `health:read` token used to connect an external
|
||||
// assistant (Claude.ai / ChatGPT). Sits next to `api` (both are programmatic
|
||||
// access surfaces). Not nav-gated — the card carries its own enable toggle.
|
||||
"mcp",
|
||||
"gesundheitsakte",
|
||||
"export",
|
||||
"advanced",
|
||||
// v1.23 — "Data & Privacy": a single surface that assembles the already-
|
||||
// shipped export / deletion / retention / encryption / session / activity
|
||||
// pieces into one coherent privacy pane. Sits next to `advanced` (the
|
||||
// destructive-action home) and before `about`.
|
||||
"privacy",
|
||||
// v1.44 — "Preview features" (per-user opt-ins, Settings > System) is not
|
||||
// listed until the first preview it switches, the topic pages, ships: a
|
||||
// switch that changes nothing is a promise the page cannot keep. The stored
|
||||
// flag, `/api/settings/preview-features` and its backup round-trip stay.
|
||||
"about",
|
||||
] as const;
|
||||
|
||||
export type SettingsSectionSlug = (typeof SETTINGS_SECTION_SLUGS)[number];
|
||||
|
||||
export function isSettingsSectionSlug(
|
||||
value: string,
|
||||
): value is SettingsSectionSlug {
|
||||
return (SETTINGS_SECTION_SLUGS as readonly string[]).includes(value);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { useEffect, type ComponentType } from "react";
|
||||
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { SettingsCard } from "@/components/settings/settings-card";
|
||||
import type { SettingsSectionSlug } from "@/components/settings/section-slugs";
|
||||
import type { SettingsSectionSlug } from "@/lib/settings/section-slugs";
|
||||
import type { IntegrationCallbackUrls } from "@/lib/integrations/callback-urls";
|
||||
|
||||
/**
|
||||
|
||||
@@ -55,7 +55,7 @@ import {
|
||||
SETTINGS_SECTION_SLUGS,
|
||||
isSettingsSectionSlug,
|
||||
type SettingsSectionSlug,
|
||||
} from "./section-slugs";
|
||||
} from "@/lib/settings/section-slugs";
|
||||
import { SettingsHubBackLink } from "./settings-hub-back-link";
|
||||
import { SettingsMobileNav } from "./settings-mobile-nav";
|
||||
import { SettingsAnchorForward } from "./settings-anchor-forward";
|
||||
|
||||
Reference in new issue
Block a user