"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/`, 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. */ 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 { useAuth } from "@/hooks/use-auth"; import { formatDate, formatDateTime } from "@/lib/format"; import { useTranslations } from "@/lib/i18n/context"; import { queryKeys } from "@/lib/query-keys"; /** 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() { const { t } = useTranslations(); return (

{t("settings.sections.sharing.title")}

{t("settings.sections.sharing.description")}

); } 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([ "Patient", "Observation", ]); const [newToken, setNewToken] = useState(null); const [copied, setCopied] = useState(false); const [formError, setFormError] = useState(null); const [showRevoked, setShowRevoked] = useState(false); const { data: links } = useQuery({ queryKey: queryKeys.shareLinks(), queryFn: async () => { const res = await fetch("/api/share-links"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data.shareLinks as ShareLinkSummary[]; }, enabled: isAuthenticated, }); const createMutation = useMutation({ mutationFn: async () => { 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) { throw new Error("EXPIRY_RANGE"); } const res = await fetch("/api/share-links", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: trimmed, rangeStart: isoDaysFromNow(-rangeDays), rangeEnd: null, resourceTypes, allowFhirApi, expiresAt: isoDaysFromNow(expiryDays), }), }); const json = await res.json(); if (!res.ok) { throw new Error(json.error || "FAILED"); } return json.data as ShareLinkSummary & { token: string }; }, 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 }) : err.message === "FAILED" || err.message === "" ? t("common.error") : err.message, ); }, }); const revokeMutation = useMutation({ mutationFn: async (id: string) => { const res = await fetch(`/api/share-links/${id}`, { method: "DELETE" }); if (!res.ok) throw new Error("Failed"); }, 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 (

{t("settings.sharing.createTitle")}

{t("settings.sharing.createDescription")}

{ e.preventDefault(); createMutation.mutate(); }} >
setLabel(e.target.value)} placeholder={t("settings.sharing.labelPlaceholder")} maxLength={120} />
setRangeDays(Math.max(1, Number(e.target.value) || 1)) } />

{t("settings.sharing.rangeHint")}

setExpiryDays(Math.max(1, Number(e.target.value) || 1)) } aria-invalid={expiryDays < 1 || expiryDays > MAX_DAYS} />

{t("settings.sharing.expiryHint", { max: MAX_DAYS })}

{t("settings.sharing.fhirApiHint")}

{allowFhirApi && (
{t("settings.sharing.resourceTypes")}
{RESOURCE_TYPES.map((type) => ( ))}
)} {formError && (

{formError}

)}
{newToken && (

{t("settings.sharing.tokenCreated")}

{t("settings.sharing.tokenOnce")}

{`${typeof window !== "undefined" ? window.location.origin : ""}/c/${newToken}`}
{copied && (

{t("settings.sharing.copied")}

)}
)}

{t("settings.sharing.activeTitle")}

{activeLinks.length === 0 ? (

{t("settings.sharing.noActive")}

) : (
    {activeLinks.map((link) => (
  • {link.label}

    {t("settings.sharing.statusActive")} {link.allowFhirApi && ( FHIR )}

    {t("settings.sharing.created")}: {" "} {formatDate(link.createdAt)}

    {t("settings.sharing.expires")}: {" "} {formatDateTime(link.expiresAt)}

    {t("settings.sharing.accessCount")}: {" "} {link.accessCount} {link.lastAccessAt ? ` · ${formatDateTime(link.lastAccessAt)}` : ""}

    {t("settings.sharing.revoke")} {t("settings.sharing.revokeDescription")} {t("common.cancel")} revokeMutation.mutate(link.id)} > {t("settings.sharing.revoke")}
  • ))}
)}
{inactiveLinks.length > 0 && (
{showRevoked && (
    {inactiveLinks.map((link) => (
  • {link.label}

    {link.revokedAt ? t("settings.sharing.statusRevoked") : t("settings.sharing.statusExpired")}

    {t("settings.sharing.accessCount")}: {" "} {link.accessCount}

  • ))}
)}
)}
); }