All files / src/app/patient/wallet page.tsx

89.47% Statements 34/38
78.57% Branches 44/56
81.81% Functions 9/11
91.42% Lines 32/35

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 2491x                                                     1x 1x                 22x 22x 22x 22x 22x 22x   22x 5x 5x 5x   5x 5x         22x   22x     1x         1x     22x   22x 1x 1x 1x 1x     1x 1x 1x 1x                   1x       22x                                                                                                                                                                                                       2x                                                                                                            
"use client";
 
import { useCallback, useEffect, useState } from "react";
import {
  AlertTriangle,
  CheckCircle2,
  RefreshCw,
  Unplug,
  Wallet,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import { EudiQrPanel } from "@/components/wallet/EudiQrPanel";
import { fetchApi } from "@/lib/api";
import { IS_STATIC } from "@/lib/static-export";
import { useEudiPresentation } from "@/lib/use-eudi-presentation";
import { CITIZEN_WALLET } from "@/lib/wallet-config";
import { useT } from "@/lib/i18n/translate";
 
/** What `GET /api/patient/wallet-link` answers. Never the hash itself. */
interface LinkState {
  /** a sandbox account (`kb-`), the only kind a PID links to */
  eligible: boolean;
  /** the hub has the hash key and the account service */
  available: boolean;
  linked: boolean;
}
 
const WALLET = CITIZEN_WALLET;
const LINK_BODY = { purpose: "link" } as const;
 
/**
 * "Connect your EUDI wallet" (ADR-067): a signed-in sandbox patient presents
 * their PID once, and from then on signs in to this account with the wallet,
 * at assurance level high. The hub keeps a secure hash of the PID's name and
 * birth date on the account, nothing else; "Disconnect wallet" removes it.
 */
export default function PatientWalletPage() {
  const t = useT("patient");
  const tc = useT("common");
  const [state, setState] = useState<LinkState | null>(null);
  const [loadError, setLoadError] = useState(false);
  const [busy, setBusy] = useState(false);
  const [notice, setNotice] = useState<string | null>(null);
 
  const load = useCallback(() => {
    Iif (IS_STATIC) return;
    fetchApi("/api/patient/wallet-link")
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error("load"))))
      .then((d: LinkState) => {
        setState(d);
        setLoadError(false);
      })
      .catch(() => setLoadError(true));
  }, []);
 
  useEffect(load, [load]);
 
  const presentation = useEudiPresentation({
    startBody: LINK_BODY,
    onDone: () => {
      setNotice(
        t("{wallet} is now connected to this account.", {
          wallet: WALLET.name,
        }),
      );
      setState((s) => (s ? { ...s, linked: true } : s));
    },
  });
  const { phase, setPhase, start, refusal } = presentation;
 
  const disconnect = useCallback(async () => {
    setBusy(true);
    setNotice(null);
    try {
      const res = await fetch("/api/patient/wallet-link", {
        method: "DELETE",
      });
      if (res.ok) {
        setState((s) => (s ? { ...s, linked: false } : s));
        setPhase("idle");
        setNotice(
          t(
            "{wallet} is disconnected. The hub no longer keeps anything of your PID.",
            { wallet: WALLET.name },
          ),
        );
      } else E{
        setNotice(t("The hub could not disconnect the wallet. Try again."));
      }
    } finally {
      setBusy(false);
    }
  }, [setPhase, t]);
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="max-w-3xl mx-auto px-6 py-10">
        <PageIntro
          title={t("Connect your EUDI wallet")}
          icon={Wallet}
          description={t(
            "EHDS Art. 16 / eIDAS: sign in to this account with your EUDI Wallet's PID, at assurance level high.",
          )}
          prevStep={{ href: "/patient/profile", label: t("Health Profile") }}
          infoText={t(
            "Connecting asks your wallet for your name and birth date once. The hub computes a secure hash of them, keeps that hash on your account and forgets the name and the date. At the next sign-in the wallet's PID is hashed again and opens this account.",
          )}
          docLink={{ href: "/hub/privacy.html", label: t("Privacy notice") }}
        />
 
        <section
          className="rounded-lg border border-(--border) bg-(--surface) p-6 text-center"
          aria-labelledby="wallet-link-heading"
          data-testid="wallet-link-card"
        >
          <h2
            id="wallet-link-heading"
            className="text-lg font-semibold flex items-center justify-center gap-2 mb-2"
          >
            <Wallet size={18} className="text-(--accent)" aria-hidden />
            {state?.linked
              ? t("{wallet} is connected", { wallet: WALLET.name })
              : t("Connect {wallet}", { wallet: WALLET.name })}
          </h2>
 
          {IS_STATIC && (
            <p className="text-sm text-(--text-secondary)">
              {t(
                "Connecting a wallet works on the live deployment only, not in the static demo.",
              )}
            </p>
          )}
 
          {!IS_STATIC && !state && !loadError && (
            <p className="text-sm text-(--text-secondary)">{tc("Loading…")}</p>
          )}
 
          {!IS_STATIC && loadError && (
            <p role="alert" className="text-sm text-amber-600">
              {t("The hub could not say whether a wallet is connected.")}
            </p>
          )}
 
          {state && !state.eligible && (
            <p className="text-sm text-(--text-secondary)">
              {t(
                "Only an account the Klarbefund app or a wallet created can be connected to a wallet. The demo patients sign in with a wallet by the name on their PID.",
              )}
            </p>
          )}
 
          {state?.eligible && !state.available && (
            <p className="text-sm text-(--text-secondary)">
              {t("This hub does not connect wallets to accounts.")}
            </p>
          )}
 
          {notice && (
            <p
              role="status"
              className="text-sm text-green-700 dark:text-green-400 mb-3"
            >
              {notice}
            </p>
          )}
 
          {state?.eligible && state.available && state.linked && (
            <div className="flex flex-col items-center gap-3">
              <p className="text-sm text-(--text-secondary)">
                {t(
                  "Sign in with {wallet} and your PID opens this account. The hub keeps one secure hash on it, never your name or birth date.",
                  { wallet: WALLET.name },
                )}
              </p>
              <button
                onClick={disconnect}
                disabled={busy}
                className="inline-flex items-center gap-2 px-4 py-2 border border-(--border) rounded-lg text-sm hover:bg-(--surface-2) disabled:opacity-60"
              >
                <Unplug size={16} /> {t("Disconnect wallet")}
              </button>
            </div>
          )}
 
          {state?.eligible && state.available && !state.linked && (
            <div className="flex flex-col items-center gap-3">
              {phase === "idle" && (
                <>
                  <p className="text-sm text-(--text-secondary) max-w-md">
                    {t(
                      "Your wallet will show what it is asked for: your name and birth date. By connecting you consent to the hub keeping a secure hash of them on this account until you disconnect or delete the account (GDPR Art. 6(1)(a)).",
                    )}
                  </p>
                  <button
                    onClick={() => void start()}
                    className="inline-flex items-center gap-2 px-4 py-2 bg-(--accent) hover:bg-(--accent-hover) text-white dark:text-gray-900 rounded-lg font-medium"
                  >
                    <Wallet size={16} /> {t("Connect your EUDI wallet")}
                  </button>
                </>
              )}
              {phase === "loading" && (
                <p className="text-sm text-(--text-secondary)">
                  {t("Preparing a secure request…")}
                </p>
              )}
              {phase === "scanning" && presentation.qr && (
                <EudiQrPanel
                  qr={presentation.qr}
                  walletLink={presentation.walletLink}
                  walletOpened={presentation.walletOpened}
                  walletSilent={presentation.walletSilent}
                />
              )}
              {phase === "done" && (
                <CheckCircle2
                  size={36}
                  className="text-green-600 dark:text-green-400"
                />
              )}
              {(phase === "error" ||
                phase === "expired" ||
                phase === "refused") && (
                <>
                  <AlertTriangle size={32} className="text-amber-500" />
                  <p role="alert" className="text-sm text-(--text-secondary)">
                    {phase === "expired"
                      ? t("This request expired.")
                      : phase === "refused"
                        ? refusal?.error
                        : presentation.startError ??
                          t("Could not reach the EUDI verifier.")}
                  </p>
                  <button
                    onClick={() => void start()}
                    className="inline-flex items-center gap-2 px-4 py-2 bg-(--accent) hover:bg-(--accent-hover) text-white dark:text-gray-900 rounded-lg font-medium"
                  >
                    <RefreshCw size={16} /> {t("Try again")}
                  </button>
                </>
              )}
            </div>
          )}
        </section>
      </div>
    </div>
  );
}