All files / src/components ConnectAppCard.tsx

68.57% Statements 48/70
61.81% Branches 34/55
64.7% Functions 11/17
70.76% Lines 46/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 3732x                                                                                                     22x 22x 22x                 2x     2x     32x 32x 32x 32x 32x   32x 8x 8x 8x       32x     32x 8x         32x 12x 1x 1x 1x     1x                             1x 1x 1x         2x 2x 2x 2x 2x 1x 1x   1x 1x     1x                             32x   32x                                                                             12x                                                                                                                                               16x 16x     14x                                         1x 1x                                                                                                                                                         1x                    
"use client";
 
import { useCallback, useEffect, useState } from "react";
import { Smartphone, QrCode, ShieldCheck, Unplug } from "lucide-react";
import { fetchApi } from "@/lib/api";
import { IS_STATIC } from "@/lib/static-export";
import { T, useT } from "@/lib/i18n/translate";
import { useLanguage } from "@/lib/use-language";
import type { CatalogLanguage } from "@/lib/metadata-language";
 
/**
 * "Connect the Klarbefund app": the patient screen's half of #473 (ADR-049).
 *
 * The patient asks for a QR code, scans it with Klarbefund, and approves on
 * Keycloak's own consent page in this browser. The phone fetches its token
 * from Keycloak directly; this card only learns that it worked when the phone
 * registers, and then lists it with Disconnect.
 *
 * On a phone the QR code is useless, so the same link is offered as "Open in
 * Klarbefund". In the static GitHub Pages build there is no Keycloak to ask,
 * so the card says where connecting works instead.
 *
 * `#connect-app` is where a new wallet account lands when its owner chose to
 * connect the app next (`CONNECT_APP_PATH`, ADR-067).
 */
 
interface Device {
  deviceId: string;
  deviceName: string;
  connectedAt: string;
  lastSeenAt: string | null;
}
 
interface PairingStart {
  pairingId: string;
  appLink: string;
  qrDataUri: string;
  userCode: string;
  verificationUri: string;
  expiresAt: string;
}
 
type Phase =
  | { kind: "idle" }
  | { kind: "starting" }
  | { kind: "showing"; pairing: PairingStart }
  | { kind: "connected"; deviceName: string }
  | { kind: "expired" }
  | { kind: "error"; message: string };
 
function formatDate(iso: string | null, lang: CatalogLanguage): string {
  Iif (!iso) return "";
  const d = new Date(iso);
  return Number.isNaN(d.getTime())
    ? iso
    : d.toLocaleString(lang === "en" ? "en-GB" : lang, {
        dateStyle: "medium",
        timeStyle: "short",
      });
}
 
/** The app's own menu path, as Klarbefund labels it. */
const APP_MENU = "More, Connect to EHDS";
 
/** The card's anchor, `CONNECT_APP_PATH` in `lib/use-wallet-sign-in.ts`. */
const CARD_ID = "connect-app";
 
export default function ConnectAppCard() {
  const t = useT("patient");
  const lang = useLanguage();
  const [phase, setPhase] = useState<Phase>({ kind: "idle" });
  const [devices, setDevices] = useState<Device[]>([]);
  const [secondsLeft, setSecondsLeft] = useState(0);
 
  const loadDevices = useCallback(() => {
    fetchApi("/api/patient/app-devices")
      .then((r) => (r.ok ? r.json() : { devices: [] }))
      .then((d) => setDevices(d.devices ?? []))
      .catch(() => setDevices([]));
  }, []);
 
  useEffect(loadDevices, [loadDevices]);
 
  // Arriving at #connect-app, from the register dialog: show the card.
  useEffect(() => {
    Eif (window.location.hash !== `#${CARD_ID}`) return;
    document.getElementById(CARD_ID)?.scrollIntoView({ block: "start" });
  }, []);
 
  // While the QR code shows: count down, and ask whether the phone arrived.
  useEffect(() => {
    if (phase.kind !== "showing") return;
    const { pairing } = phase;
    const expires = new Date(pairing.expiresAt).getTime();
    const tick = setInterval(() => {
      setSecondsLeft(Math.max(0, Math.round((expires - Date.now()) / 1000)));
    }, 1000);
    const poll = setInterval(async () => {
      try {
        const r = await fetch(`/api/patient/app-pairing/${pairing.pairingId}`);
        if (!r.ok) return;
        const s = (await r.json()) as { status: string; deviceName?: string };
        if (s.status === "connected") {
          setPhase({ kind: "connected", deviceName: s.deviceName ?? "iPhone" });
          loadDevices();
        } else if (s.status === "expired") {
          setPhase({ kind: "expired" });
        }
      } catch {
        // a missed poll is retried on the next tick
      }
    }, 3000);
    return () => {
      clearInterval(tick);
      clearInterval(poll);
    };
  }, [phase, loadDevices]);
 
  async function start() {
    setPhase({ kind: "starting" });
    try {
      const r = await fetch("/api/patient/app-pairing", { method: "POST" });
      const body = await r.json();
      if (!r.ok) {
        setPhase({ kind: "error", message: body.error ?? `HTTP ${r.status}` });
        return;
      }
      const pairing = body as PairingStart;
      setSecondsLeft(
        Math.round((new Date(pairing.expiresAt).getTime() - Date.now()) / 1000),
      );
      setPhase({ kind: "showing", pairing });
    } catch {
      setPhase({ kind: "error", message: t("The hub could not be reached") });
    }
  }
 
  async function disconnect(deviceId: string) {
    const r = await fetch(`/api/patient/app-devices/${deviceId}`, {
      method: "DELETE",
    });
    if (r.ok || r.status === 404) loadDevices();
  }
 
  // A connected patient sees their phones first, and the QR code only on
  // request: it pairs a further phone, not the one already connected.
  const connected = devices.length > 0;
 
  return (
    <section
      id={CARD_ID}
      className="mb-6 rounded-lg border border-(--border) bg-(--surface) p-4 scroll-mt-24"
      data-testid="connect-app-card"
      aria-labelledby="connect-app-heading"
    >
      <h2
        id="connect-app-heading"
        className="text-lg font-semibold flex items-center gap-2 mb-1"
      >
        <Smartphone size={18} className="text-(--accent)" aria-hidden />
        {connected
          ? t("Klarbefund is connected")
          : t("Connect the Klarbefund app")}
      </h2>
      {connected ? (
        <p className="text-sm text-(--text-secondary) mb-3">
          {t(
            "Your iPhone reads your record here and sends the values you allowed in the app. Nothing to scan: a QR code is needed only to connect another phone.",
          )}
        </p>
      ) : (
        <p className="text-sm text-(--text-secondary) mb-3">
          <T area="patient" vars={{ menu: APP_MENU }} tags={{ b: <strong /> }}>
            {
              "Klarbefund turns your paper lab reports into structured values on your iPhone. Connected, it can read your record here. In the app, choose <b>{menu}</b> and scan the code."
            }
          </T>
        </p>
      )}
 
      {devices.length > 0 && (
        <div className="mb-3" data-testid="connected-devices">
          <h3 className="text-sm font-semibold mb-2">
            {t("Connected phones")}
          </h3>
          <ul className="space-y-2">
            {devices.map((d) => (
              <li
                key={d.deviceId}
                className="flex items-center justify-between gap-3 rounded border border-(--border) px-3 py-2 text-sm"
              >
                <span>
                  <strong>{d.deviceName}</strong>
                  <span className="block text-xs text-(--text-secondary)">
                    {d.lastSeenAt
                      ? t("Connected {date}, last seen {seen}", {
                          date: formatDate(d.connectedAt, lang),
                          seen: formatDate(d.lastSeenAt, lang),
                        })
                      : t("Connected {date}", {
                          date: formatDate(d.connectedAt, lang),
                        })}
                  </span>
                </span>
                {!IS_STATIC && (
                  <button
                    type="button"
                    onClick={() => disconnect(d.deviceId)}
                    className="inline-flex items-center gap-1 rounded border border-(--border) px-2 py-1 text-xs hover:bg-(--surface-2)"
                    aria-label={t("Disconnect {device}", {
                      device: d.deviceName,
                    })}
                  >
                    <Unplug size={14} aria-hidden /> {t("Disconnect")}
                  </button>
                )}
              </li>
            ))}
          </ul>
        </div>
      )}
      {IS_STATIC ? (
        <p className="text-sm" data-testid="connect-app-static">
          {t("Connecting needs the live demo, where you sign in as a patient:")}{" "}
          <a
            className="underline text-(--accent)"
            href="https://ehds.mabu.red/patient/profile"
          >
            ehds.mabu.red/patient/profile
          </a>
          .
        </p>
      ) : (
        <PairingPanel
          phase={phase}
          secondsLeft={secondsLeft}
          onStart={start}
          onReset={() => setPhase({ kind: "idle" })}
          another={connected}
        />
      )}
    </section>
  );
}
 
function PairingPanel({
  phase,
  secondsLeft,
  onStart,
  onReset,
  another = false,
}: {
  phase: Phase;
  secondsLeft: number;
  onStart: () => void;
  onReset: () => void;
  /** A phone is connected already: offer the code for another one, quietly. */
  another?: boolean;
}) {
  const t = useT("patient");
  switch (phase.kind) {
    case "idle":
    case "starting":
      return (
        <button
          type="button"
          onClick={onStart}
          disabled={phase.kind === "starting"}
          className={
            another
              ? "inline-flex items-center gap-2 rounded border border-(--border) px-3 py-1.5 text-sm hover:bg-(--surface-2) disabled:opacity-60"
              : "inline-flex items-center gap-2 rounded bg-(--accent) px-3 py-2 text-sm font-medium text-white dark:text-gray-900 disabled:opacity-60"
          }
          data-testid="connect-app-start"
        >
          <QrCode size={16} aria-hidden />
          {phase.kind === "starting"
            ? t("Preparing...")
            : another
              ? t("Connect another phone")
              : t("Show QR code")}
        </button>
      );
    case "showing": {
      const { pairing } = phase;
      return (
        <div className="grid gap-4 sm:grid-cols-[auto_1fr] items-start">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={pairing.qrDataUri}
            alt={t("QR code that connects the Klarbefund app to your record")}
            width={220}
            height={220}
            className="rounded bg-white p-2"
            data-testid="connect-app-qr"
          />
          <div className="text-sm space-y-2">
            <ol className="list-decimal pl-5 space-y-1">
              <li>{t("Scan the code with Klarbefund.")}</li>
              <li>
                <T
                  area="patient"
                  vars={{ code: pairing.userCode }}
                  tags={{
                    a: (
                      <a
                        href={pairing.verificationUri}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="underline text-(--accent)"
                        data-testid="connect-app-approve"
                      />
                    ),
                    b: <strong />,
                  }}
                >
                  {
                    "<a>Approve on this computer</a>, and check the code reads <b>{code}</b>."
                  }
                </T>
              </li>
            </ol>
            <p>
              {t("On this phone instead?")}{" "}
              <a
                href={pairing.appLink}
                className="underline text-(--accent)"
                data-testid="connect-app-open"
              >
                {t("Open in Klarbefund")}
              </a>
            </p>
            <p className="text-xs text-(--text-secondary)" aria-live="polite">
              {t(
                "The code works for {n} more seconds, once. Scan it only with your own phone: whoever holds it when you approve gets read access to your record.",
                { n: secondsLeft },
              )}
            </p>
          </div>
        </div>
      );
    }
    case "connected":
      return (
        <p
          className="text-sm flex items-center gap-2"
          data-testid="connect-app-connected"
        >
          <ShieldCheck size={16} className="text-(--accent)" aria-hidden />
          {t("{device} is connected.", { device: phase.deviceName })}
        </p>
      );
    case "expired":
      return (
        <p className="text-sm">
          {t("The code expired before a phone connected.")}{" "}
          <button type="button" className="underline" onClick={onReset}>
            {t("Show a new one")}
          </button>
        </p>
      );
    case "error":
      return (
        <p className="text-sm" role="alert">
          {t("Connecting failed: {message}.", { message: phase.message })}{" "}
          <button type="button" className="underline" onClick={onReset}>
            {t("Try again")}
          </button>
        </p>
      );
  }
}