Merge wave-sharing-restore: bring back the Freigabe settings section

Restore the clinician share-link section as its own Settings entry next to
the health-record export, rendering through the shared SettingsCard and the
envelope-aware api helpers. The backing routes and the public view were
untouched by the earlier trim, so the owner UI reconnects to them as before.
This commit is contained in:
Marc-André Bombeck committed 2026-06-19 21:39:46 +02:00
commit f4812f9af2
7 files changed
+635

No files matched your search

+2
View File
@@ -24,6 +24,7 @@ import { VorsorgeSection } from "@/components/settings/vorsorge-section";
// v1.18.1 (D4) — `channels` and `sources` are standalone left-side entries
// again (split out of the Integrations sub-tabs).
import { ChannelsSection } from "@/components/settings/channels-section";
import { SharingSection } from "@/components/settings/sharing-section";
import { SourcesSection } from "@/components/settings/sources-section";
import { ThresholdsSection } from "@/components/settings/thresholds-section";
import {
@@ -73,6 +74,7 @@ const SECTION_COMPONENTS: Record<
thresholds: ThresholdsSection,
api: ApiSection,
gesundheitsakte: GesundheitsakteSection,
sharing: SharingSection,
export: ExportSection,
advanced: AdvancedSection,
};
@@ -94,6 +94,9 @@ describe("SETTINGS_SECTION_SLUGS", () => {
// v1.18.7 — `labs`, `illness`, `vorsorge` move into the shell as
// first-class sections, right after `mood` (the three were standalone
// `ModuleSettingsFrame` pages).
// v1.18.7 — `sharing` (clinician share links) sits directly after
// `gesundheitsakte`, before `export`: minting a read-only link to the
// health record belongs next to the health-record export.
expect([...SETTINGS_SECTION_SLUGS]).toEqual([
"account",
"modules",
@@ -114,6 +117,7 @@ describe("SETTINGS_SECTION_SLUGS", () => {
"coach",
"api",
"gesundheitsakte",
"sharing",
"export",
"advanced",
"about",
@@ -0,0 +1,125 @@
/**
* v1.11.0 — Settings → Sharing (Epic C, C7).
*
* The owner share-link surface. The security-load-bearing guarantees the
* test pins:
* 1. The list never carries a raw `hls_` token — the server stores only the
* hash, so the list response shape has no token field and the rendered
* markup must not surface one.
* 2. The one-time token reveal card (`share-token-reveal`) is absent until a
* create succeeds — on first paint (no token in state) it must not render.
* 3. Active links render with a revoke control; revoked/expired links fold
* into the inactive list.
* 4. The expiry input is bounded at the server cap (90 days).
*
* SSR-static render only (no jsdom), matching the sibling settings-section
* tests. The TanStack hooks are mocked so the query returns a fixed link list.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", role: "USER" },
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
}),
}));
const FIXTURE_LINKS = [
{
id: "link-active",
label: "Cardiology referral",
rangeStart: "2026-01-01T00:00:00.000Z",
rangeEnd: null,
resourceTypes: ["Patient", "Observation"],
allowFhirApi: true,
expiresAt: "2099-01-01T00:00:00.000Z",
createdAt: "2026-06-01T00:00:00.000Z",
revokedAt: null,
lastAccessAt: "2026-06-02T10:00:00.000Z",
accessCount: 3,
active: true,
},
{
id: "link-revoked",
label: "Old GP link",
rangeStart: "2026-01-01T00:00:00.000Z",
rangeEnd: null,
resourceTypes: [],
allowFhirApi: false,
expiresAt: "2099-01-01T00:00:00.000Z",
createdAt: "2026-05-01T00:00:00.000Z",
revokedAt: "2026-05-15T00:00:00.000Z",
lastAccessAt: null,
accessCount: 0,
active: false,
},
];
vi.mock("@tanstack/react-query", () => ({
useQuery: () => ({ data: FIXTURE_LINKS, isLoading: false }),
useMutation: () => ({ mutate: vi.fn(), isPending: false }),
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
import { I18nProvider } from "@/lib/i18n/context";
import { SharingSection } from "../sharing-section";
function render(locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<SharingSection />
</I18nProvider>,
);
}
describe("<SharingSection> — owner share-link surface (C7)", () => {
it("renders the create form with a 90-day-capped expiry input", () => {
const html = render();
expect(html).toContain("New share link");
// The expiry field carries the server's max-days cap.
expect(html).toContain('max="90"');
expect(html).toContain("Create link");
});
it("does not reveal a token before a create succeeds", () => {
const html = render();
// The one-time reveal card only mounts once `newToken` state is set.
expect(html).not.toContain('data-testid="share-token-reveal"');
});
it("lists the active link with a revoke control and never a raw token", () => {
const html = render();
expect(html).toContain('data-testid="share-active-list"');
expect(html).toContain("Cardiology referral");
expect(html).toContain("Revoke");
// The list response shape carries no token; the markup must not surface
// an `hls_` string anywhere.
expect(html).not.toContain("hls_");
// The FHIR badge surfaces for the FHIR-enabled link.
expect(html).toContain("FHIR");
});
it("folds revoked links into the inactive list (not the active list)", () => {
const html = render();
// The active list must NOT contain the revoked link's label.
const activeListStart = html.indexOf('data-testid="share-active-list"');
const activeListEnd = html.indexOf('data-testid="share-inactive-list"');
// Inactive list is collapsed by default, so the label only appears once
// the disclosure is open — but the active list must never carry it.
const activeSlice =
activeListEnd > activeListStart
? html.slice(activeListStart, activeListEnd)
: html.slice(activeListStart);
expect(activeSlice).not.toContain("Old GP link");
// The inactive-count disclosure surfaces.
expect(html).toContain("Revoked and expired");
});
it("renders localized section copy", () => {
const html = render("de");
expect(html).toContain("Neuer Freigabe-Link");
});
});
@@ -27,6 +27,7 @@ import {
Pill,
Radio,
Settings2,
Share2,
SlidersHorizontal,
Smile,
Sparkles,
@@ -60,6 +61,7 @@ const SLUG_ICON: Record<SettingsSectionSlug, LucideIcon> = {
coach: Bot,
api: KeyRound,
gesundheitsakte: FileHeart,
sharing: Share2,
export: Download,
advanced: Settings2,
about: Info,
+7
View File
@@ -74,6 +74,13 @@ export const SETTINGS_SECTION_SLUGS = [
"coach",
"api",
"gesundheitsakte",
// v1.18.7 — `sharing` (clinician share links) sits directly after
// `gesundheitsakte`, before `export`: minting a time-boxed read-only link
// to the health record belongs next to the health-record export. Always
// available (no module gate), like account / export. The backing model,
// the `/api/share-links` routes, and the public `/c/[token]` view are
// unchanged — this restores only the owner Settings surface.
"sharing",
"export",
"advanced",
"about",
@@ -33,6 +33,7 @@ import {
Pill,
Radio,
Settings2,
Share2,
SlidersHorizontal,
Smile,
Sparkles,
@@ -224,6 +225,15 @@ export const SETTINGS_SECTIONS: readonly SettingsSection[] = [
titleKey: "settings.sections.gesundheitsakte.title",
icon: FileHeart,
},
// v1.18.7 — clinician share links sit next to the health record: minting a
// time-boxed read-only link is a sharing face of the same data. Not
// module-gated; the link surface is always available (the public
// `/c/[token]` view and the `/api/share-links` lifecycle are unchanged).
{
slug: "sharing",
titleKey: "settings.sections.sharing.title",
icon: Share2,
},
{
slug: "export",
titleKey: "settings.sections.export.title",
+485
View File
@@ -0,0 +1,485 @@
"use client";
/**
* v1.11.0 — Settings → Sharing (Epic C, C7).
*
* The OWNER surface for clinician share links. A share link is a time-boxed,
* scope-frozen, read-only view of the owner's own health record at
* `/c/<token>`, optionally exposing a scoped read-only FHIR face. The raw
* `hls_` token is shown EXACTLY ONCE on create — the list never carries it
* (the server only stores its hash), so the copy-on-create card is the single
* chance to capture it.
*
* Client island: the create form, the active/revoked lists, and the revoke
* action all need state and mutate via the C4 lifecycle API
* (`/api/share-links`). Reads unwrap `(await res.json()).data`; the query key
* comes from the centralised factory. No markdown anywhere — every value
* renders as escaped React text.
*
* v1.18.7 — restored as a first-class Settings section. The visible heading +
* subtitle now come from the shared shell chrome in the route; this body is
* the share-links card. Cards paint through `<SettingsCard>` so the surface
* matches every sibling section 1:1.
*/
import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Copy, Loader2, Share2, Trash2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { SettingsCard } from "@/components/settings/settings-card";
import { SettingsCardHeader } from "@/components/settings/_card-header";
import { useAuth } from "@/hooks/use-auth";
import { formatDate, formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiDelete, apiGet, apiPost } from "@/lib/api/api-fetch";
/** The FHIR resource types a share link may serve — mirrors C4's enum. */
const RESOURCE_TYPES = [
"Patient",
"Observation",
"MedicationStatement",
"MedicationAdministration",
] as const;
type ResourceType = (typeof RESOURCE_TYPES)[number];
/** Maximum lifetime, in days — mirrors `SHARE_LINK_MAX_DAYS` on the server. */
const MAX_DAYS = 90;
const DEFAULT_DAYS = 30;
/** Owner-facing shape returned by `GET /api/share-links` (never the token). */
interface ShareLinkSummary {
id: string;
label: string;
rangeStart: string;
rangeEnd: string | null;
resourceTypes: string[];
allowFhirApi: boolean;
expiresAt: string;
createdAt: string;
revokedAt: string | null;
lastAccessAt: string | null;
accessCount: number;
active: boolean;
}
export function SharingSection() {
// v1.18.7 — the visible heading + subtitle come from the shared settings
// shell chrome in the route; this body is the share-links card only.
return (
<div className="space-y-6">
<ShareLinksCard />
</div>
);
}
function isoDaysFromNow(days: number): string {
return new Date(Date.now() + days * 86_400_000).toISOString();
}
function ShareLinksCard() {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
const queryClient = useQueryClient();
const [label, setLabel] = useState("");
const [rangeDays, setRangeDays] = useState(DEFAULT_DAYS);
const [expiryDays, setExpiryDays] = useState(DEFAULT_DAYS);
const [allowFhirApi, setAllowFhirApi] = useState(false);
const [resourceTypes, setResourceTypes] = useState<ResourceType[]>([
"Patient",
"Observation",
]);
const [newToken, setNewToken] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [showRevoked, setShowRevoked] = useState(false);
const { data: links } = useQuery({
queryKey: queryKeys.shareLinks(),
queryFn: () =>
apiGet<{ shareLinks: ShareLinkSummary[] }>("/api/share-links").then(
(data) => data.shareLinks,
),
enabled: isAuthenticated,
});
const createMutation = useMutation({
mutationFn: () => {
const trimmed = label.trim();
// Surface the same expiry-bound the server enforces before the round
// trip, so the validation feedback is immediate.
if (expiryDays < 1 || expiryDays > MAX_DAYS) {
return Promise.reject(new Error("EXPIRY_RANGE"));
}
return apiPost<ShareLinkSummary & { token: string }>(
"/api/share-links",
{
label: trimmed,
rangeStart: isoDaysFromNow(-rangeDays),
rangeEnd: null,
resourceTypes,
allowFhirApi,
expiresAt: isoDaysFromNow(expiryDays),
},
);
},
onSuccess: (created) => {
setNewToken(created.token);
setCopied(false);
setLabel("");
setFormError(null);
queryClient.invalidateQueries({ queryKey: queryKeys.shareLinks() });
},
onError: (err: Error) => {
setNewToken(null);
setFormError(
err.message === "EXPIRY_RANGE"
? t("settings.sharing.expiryInvalid", { max: MAX_DAYS })
: t("common.error"),
);
},
});
const revokeMutation = useMutation({
mutationFn: (id: string) => apiDelete(`/api/share-links/${id}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.shareLinks() });
},
});
function toggleResourceType(type: ResourceType) {
setResourceTypes((prev) =>
prev.includes(type) ? prev.filter((r) => r !== type) : [...prev, type],
);
}
async function copyToken() {
if (!newToken) return;
try {
const origin = window.location.origin;
await navigator.clipboard.writeText(`${origin}/c/${newToken}`);
setCopied(true);
} catch {
// Clipboard can be unavailable (insecure context); the token stays
// visible in the card so the owner can copy it by hand.
}
}
const activeLinks = useMemo(
() => (links ?? []).filter((l) => l.active),
[links],
);
const inactiveLinks = useMemo(
() => (links ?? []).filter((l) => !l.active),
[links],
);
return (
<SettingsCard className="space-y-6">
<SettingsCardHeader
icon={Share2}
title={t("settings.sharing.createTitle")}
description={t("settings.sharing.createDescription")}
/>
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
createMutation.mutate();
}}
>
<div className="space-y-1.5">
<Label htmlFor="share-label">{t("settings.sharing.label")}</Label>
<Input
id="share-label"
value={label}
onChange={(e) => setLabel(e.target.value)}
placeholder={t("settings.sharing.labelPlaceholder")}
maxLength={120}
/>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="share-range">{t("settings.sharing.range")}</Label>
<Input
id="share-range"
type="number"
min={1}
max={3650}
value={rangeDays}
onChange={(e) =>
setRangeDays(Math.max(1, Number(e.target.value) || 1))
}
/>
<p className="text-muted-foreground text-[11px]">
{t("settings.sharing.rangeHint")}
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="share-expiry">
{t("settings.sharing.expiry")}
</Label>
<Input
id="share-expiry"
type="number"
min={1}
max={MAX_DAYS}
value={expiryDays}
onChange={(e) =>
setExpiryDays(Math.max(1, Number(e.target.value) || 1))
}
aria-invalid={expiryDays < 1 || expiryDays > MAX_DAYS}
/>
<p className="text-muted-foreground text-[11px]">
{t("settings.sharing.expiryHint", { max: MAX_DAYS })}
</p>
</div>
</div>
<div className="border-border flex items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5 pr-3">
<Label htmlFor="share-fhir" className="text-sm font-medium">
{t("settings.sharing.fhirApi")}
</Label>
<p className="text-muted-foreground text-[11px]">
{t("settings.sharing.fhirApiHint")}
</p>
</div>
<Switch
id="share-fhir"
checked={allowFhirApi}
onCheckedChange={setAllowFhirApi}
/>
</div>
{allowFhirApi && (
<fieldset className="space-y-2">
<legend className="text-sm font-medium">
{t("settings.sharing.resourceTypes")}
</legend>
<div className="grid gap-2 sm:grid-cols-2">
{RESOURCE_TYPES.map((type) => (
<label
key={type}
className="flex items-center gap-2 text-sm"
htmlFor={`share-rt-${type}`}
>
<Checkbox
id={`share-rt-${type}`}
checked={resourceTypes.includes(type)}
onCheckedChange={() => toggleResourceType(type)}
/>
<span className="font-mono text-xs">{type}</span>
</label>
))}
</div>
</fieldset>
)}
{formError && (
<p role="alert" className="text-destructive text-sm">
{formError}
</p>
)}
<Button
type="submit"
disabled={createMutation.isPending || !label.trim()}
className="min-h-11 sm:min-h-9"
>
{createMutation.isPending && (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
)}
{t("settings.sharing.create")}
</Button>
</form>
{newToken && (
<div
className="bg-success/10 space-y-2 rounded-lg p-3 text-sm"
data-testid="share-token-reveal"
>
<p className="text-success font-medium">
{t("settings.sharing.tokenCreated")}
</p>
<p className="text-muted-foreground text-[11px]">
{t("settings.sharing.tokenOnce")}
</p>
<div className="flex items-center gap-2">
<code className="bg-muted block flex-1 rounded p-2 font-mono text-xs break-all">
{`${typeof window !== "undefined" ? window.location.origin : ""}/c/${newToken}`}
</code>
<Button
type="button"
variant="outline"
size="icon"
className="min-h-11 min-w-11 shrink-0 sm:h-9 sm:w-9"
onClick={copyToken}
aria-label={t("settings.sharing.copy")}
>
<Copy className="h-3.5 w-3.5" />
</Button>
</div>
{copied && (
<p className="text-success text-[11px]">
{t("settings.sharing.copied")}
</p>
)}
</div>
)}
<div className="space-y-2">
<h3 className="text-sm font-medium">
{t("settings.sharing.activeTitle")}
</h3>
{activeLinks.length === 0 ? (
<p
className="text-muted-foreground rounded-lg border border-dashed px-3 py-4 text-center text-sm"
data-testid="share-active-empty"
>
{t("settings.sharing.noActive")}
</p>
) : (
<ul className="space-y-2" data-testid="share-active-list">
{activeLinks.map((link) => (
<li
key={link.id}
className="bg-muted/30 border-border space-y-2 rounded-lg border p-3"
>
<div className="flex flex-wrap items-start justify-between gap-2">
<p className="min-w-0 flex-1 text-sm font-medium break-words">
{link.label}
</p>
<div className="flex flex-wrap items-center gap-1.5">
<Badge className="bg-success/15 text-success text-[10px]">
{t("settings.sharing.statusActive")}
</Badge>
{link.allowFhirApi && (
<Badge variant="outline" className="text-[10px]">
FHIR
</Badge>
)}
</div>
</div>
<p className="text-muted-foreground text-[11px]">
<span className="font-medium">
{t("settings.sharing.created")}:
</span>{" "}
{formatDate(link.createdAt)}
</p>
<p className="text-muted-foreground text-[11px]">
<span className="font-medium">
{t("settings.sharing.expires")}:
</span>{" "}
{formatDateTime(link.expiresAt)}
</p>
<p className="text-muted-foreground text-[11px]">
<span className="font-medium">
{t("settings.sharing.accessCount")}:
</span>{" "}
{link.accessCount}
{link.lastAccessAt
? ` · ${formatDateTime(link.lastAccessAt)}`
: ""}
</p>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="outline"
size="sm"
className="text-destructive border-destructive/30 min-h-11 w-full sm:min-h-9"
>
<Trash2 className="mr-2 h-3.5 w-3.5" />
{t("settings.sharing.revoke")}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{t("settings.sharing.revoke")}
</AlertDialogTitle>
<AlertDialogDescription>
{t("settings.sharing.revokeDescription")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>
{t("common.cancel")}
</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => revokeMutation.mutate(link.id)}
>
{t("settings.sharing.revoke")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</li>
))}
</ul>
)}
</div>
{inactiveLinks.length > 0 && (
<div className="space-y-2">
<button
type="button"
onClick={() => setShowRevoked((prev) => !prev)}
className="text-foreground hover:text-primary text-sm font-medium transition-colors"
>
{t("settings.sharing.inactiveTitle", {
count: inactiveLinks.length,
})}
</button>
{showRevoked && (
<ul className="space-y-2" data-testid="share-inactive-list">
{inactiveLinks.map((link) => (
<li
key={link.id}
className="bg-muted/20 border-border space-y-1.5 rounded-lg border p-3"
>
<div className="flex flex-wrap items-start justify-between gap-2">
<p className="min-w-0 flex-1 text-sm font-medium break-words">
{link.label}
</p>
<Badge variant="secondary" className="text-[10px]">
{link.revokedAt
? t("settings.sharing.statusRevoked")
: t("settings.sharing.statusExpired")}
</Badge>
</div>
<p className="text-muted-foreground text-[11px]">
<span className="font-medium">
{t("settings.sharing.accessCount")}:
</span>{" "}
{link.accessCount}
</p>
</li>
))}
</ul>
)}
</div>
)}
</SettingsCard>
);
}