taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit f0081559d9e7a0c5005bc65db467640fd0a66741
parent cdf370a57faa47660a42844a4f24aeb537177f77
Author: Florian Dold <dold@taler.net>
Date:   Mon, 23 Nov 2026 18:31:40 +0100

wallet web UI: show fountain grants, receipts and recovery actions

Show localized names, per-grant limits and the amount available in the
wallet. Let users retry a pending withdrawal or confirm discarding that
specific batch.

Diffstat:
Apackages/wallet-webui/src/routes/fountain-model.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apackages/wallet-webui/src/screens/FountainsScreen.tsx | 354+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/screens/StorybookScreen.tsx | 44++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/stories/catalog.ts | 1+
Apackages/wallet-webui/src/testing/fountain-fixture.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/ui/WalletIcon.tsx | 12++++++++++++
Mpackages/wallet-webui/test/screens.test.tsx | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
7 files changed, 791 insertions(+), 0 deletions(-)

diff --git a/packages/wallet-webui/src/routes/fountain-model.ts b/packages/wallet-webui/src/routes/fountain-model.ts @@ -0,0 +1,90 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import { + TalerErrorCode, + type FountainDetails, + type TalerProtocolTimestamp, +} from "@gnu-taler/taler-util"; +import { i18n } from "../i18n/runtime.js"; + +export type FountainView = FountainDetails; + +export function fountainDate( + value: TalerProtocolTimestamp | undefined, + language: string, +): string { + if (!value || value.t_s === 0) return i18n.str`Not yet`; + if (value.t_s === "never") return i18n.str`Never`; + return new Intl.DateTimeFormat(language, { + dateStyle: "medium", + timeStyle: "short", + }).format(value.t_s * 1000); +} + +export function fountainCollectionFailed(f: FountainView): boolean { + return ( + !!f.lastError && + f.lastError.code !== + TalerErrorCode.MERCHANT_POST_FOUNTAIN_WITHDRAW_LIMIT_EXCEEDED + ); +} + +export function grantLimitReached( + f: FountainView, + slug: string, + now = Date.now() / 1000, +): boolean { + const current = f.quotas?.filter( + (q) => + q.tokenFamilySlug === slug && + typeof q.validityStart.t_s === "number" && + q.validityStart.t_s <= now && + (q.validityEnd.t_s === "never" || q.validityEnd.t_s > now), + ); + return !!current?.length && current.every((q) => q.limitReached); +} + +export function fountainStatus( + f: FountainView, + now = Date.now() / 1000, +): string { + if (f.status === "revoked") return i18n.str`Access revoked`; + if (fountainCollectionFailed(f)) return i18n.str`Collection failed`; + if (!f.lastPoll) return i18n.str`Waiting to collect`; + if (!f.grants.length) return i18n.str`No grants`; + if (f.grants.every((g) => grantLimitReached(f, g.token_family_slug, now))) + return i18n.str`Period limit reached`; + if (f.collectionPending) return i18n.str`Collection pending`; + return i18n.str`Active`; +} + +export function localizedFountainText( + fallback: string, + translations: Record<string, string> | undefined, + language: string, +): string { + if (!translations) return fallback; + const tags = language.toLowerCase().split("-"); + const entries = Object.entries(translations); + while (tags.length) { + const tag = tags.join("-"); + const match = entries.find(([key]) => key.toLowerCase() === tag); + if (match) return match[1]; + tags.pop(); + } + return fallback; +} diff --git a/packages/wallet-webui/src/screens/FountainsScreen.tsx b/packages/wallet-webui/src/screens/FountainsScreen.tsx @@ -0,0 +1,354 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import { useEffect, useRef, useState } from "preact/hooks"; +import type { RemoveFountainResponse } from "@gnu-taler/taler-util"; +import type { FountainView } from "../routes/fountain-model.js"; +import { + fountainCollectionFailed, + grantLimitReached, + fountainDate, + localizedFountainText, + fountainStatus, +} from "../routes/fountain-model.js"; +import { i18n } from "../i18n/runtime.js"; +import { Button } from "../ui/Button.js"; +import { Card } from "../ui/Card.js"; +import { ConfirmationDialog } from "../ui/ConfirmationDialog.js"; +import { ErrorCard } from "../ui/ErrorCard.js"; +import type { ErrorPresentation } from "../ui/error.js"; + +interface FountainActions { + onRefresh: (id: string) => Promise<ErrorPresentation | undefined>; + onRemove: ( + id: string, + discardPendingWithdrawalId?: string, + ) => Promise<RemoveFountainResponse | ErrorPresentation>; +} + +export function FountainsScreen( + props: FountainActions & { + enabled: boolean; + fountains?: FountainView[]; + loading: boolean; + language: string; + focusId?: string; + error?: ErrorPresentation; + onSettings: () => void; + onImport: () => void; + }, +) { + return ( + <div class="mx-auto max-w-3xl space-y-5"> + <header class="flex flex-wrap items-center justify-between gap-3"> + <h1 class="text-2xl font-normal">{i18n.str`Fountains`}</h1> + {props.enabled && ( + <Button onClick={props.onImport}>{i18n.str`Import fountain`}</Button> + )} + </header> + {!props.enabled ? ( + <Card> + <p class="mb-4">{i18n.str`Enable fountains in Developer settings to manage them. Existing fountains continue collecting while this setting is off.`}</p> + <Button onClick={props.onSettings}>{i18n.str`Settings`}</Button> + </Card> + ) : ( + <> + <p class="text-secondary">{i18n.str`Fountains automatically provide discounts and passes while the wallet is running. Available counts include tokens from all sources at the same merchant.`}</p> + {props.loading && ( + <Card> + <p role="status">{i18n.str`Loading fountains…`}</p> + </Card> + )} + {props.error && <ErrorCard error={props.error} />} + {!props.loading && !props.error && props.fountains?.length === 0 && ( + <Card> + <p>{i18n.str`You have no fountains. Scan a merchant's QR code or enter its Taler link to import one.`}</p> + </Card> + )} + {props.fountains?.map((f) => ( + <FountainCard + key={f.fountainId} + fountain={f} + language={props.language} + focused={f.fountainId === props.focusId} + onRefresh={props.onRefresh} + onRemove={props.onRemove} + /> + ))} + </> + )} + </div> + ); +} + +function FountainCard( + props: FountainActions & { + fountain: FountainView; + language: string; + focused: boolean; + }, +) { + const f = props.fountain; + const name = localizedFountainText(f.name, f.nameI18n, props.language); + const [busy, setBusy] = useState(false); + const working = useRef(false); + const [confirm, setConfirm] = useState< + "remove" | { pendingWithdrawalId: string } + >(); + const pendingId = + typeof confirm === "object" ? confirm.pendingWithdrawalId : undefined; + const [error, setError] = useState<ErrorPresentation>(); + const card = useRef<HTMLElement>(null); + useEffect(() => { + if (props.focused) card.current?.focus(); + }, [props.focused]); + const run = async (remove: boolean) => { + if (working.current) return; + working.current = true; + setBusy(true); + setError(undefined); + try { + if (remove) { + const result = await props.onRemove(f.fountainId, pendingId); + if ("message" in result) setError(result); + else if (result.status === "withdrawalPending") setConfirm(result); + else setConfirm(undefined); + } else { + const failure = await props.onRefresh(f.fountainId); + setError(failure); + if (!failure) setConfirm(undefined); + } + } finally { + working.current = false; + setBusy(false); + } + }; + const stats = f.statistics; + const receivedLabel = + stats && !stats.historyComplete + ? i18n.str`Received since ${fountainDate(stats.trackingSince, props.language)}` + : i18n.str`Received from this fountain`; + const current = stats?.families.filter((s) => + f.grants.some( + (g) => + g.token_family_slug === s.tokenFamilySlug && + g.token_family.details.class === s.kind, + ), + ); + const previous = stats?.families.filter( + (s) => + !f.grants.some( + (g) => + g.token_family_slug === s.tokenFamilySlug && + g.token_family.details.class === s.kind, + ), + ); + const counts = (family: NonNullable<typeof current>[number]) => ( + <dl class="mt-3 grid grid-cols-2 gap-3 text-sm"> + <div> + <dt class="text-secondary">{receivedLabel}</dt> + <dd class="text-lg font-medium">{family.receivedFromFountain}</dd> + </div> + <div> + <dt class="text-secondary">{i18n.str`Available in wallet`}</dt> + <dd class="text-lg font-medium">{family.availableInWallet}</dd> + </div> + {family.futureInWallet > 0 && ( + <div> + <dt class="text-secondary">{i18n.str`Valid in the future`}</dt> + <dd>{family.futureInWallet}</dd> + </div> + )} + </dl> + ); + return ( + <article + ref={card} + tabIndex={-1} + aria-label={i18n.str`Fountain ${name}`} + class="rounded-xl border border-outlineVariant bg-surface p-5 focus:outline-primary" + > + <div class="flex flex-wrap justify-between gap-3"> + <h2 class="min-w-0 break-words text-lg font-medium">{name}</h2> + <span role="status" class="text-sm text-secondary"> + {fountainStatus(f)} + </span> + </div> + <p class="mt-2 break-all text-sm text-secondary">{f.merchantBaseUrl}</p> + {f.grants.map((grant) => { + const family = current?.find( + (s) => s.tokenFamilySlug === grant.token_family_slug, + ); + return ( + <section + key={grant.token_family_slug} + class="mt-4 border-t border-outlineVariant pt-3" + > + <h3 class="font-medium"> + {grant.token_family.name} ·{" "} + {grant.token_family.details.class === "discount" + ? i18n.str`Discounts` + : i18n.str`Passes`} + </h3> + {grantLimitReached(f, grant.token_family_slug) && ( + <p class="text-sm font-medium">{i18n.str`Period limit reached`}</p> + )} + {family && counts(family)} + </section> + ); + })} + {!stats && ( + <p class="mt-3 text-secondary">{i18n.str`Receipt statistics are unavailable.`}</p> + )} + {f.status === "revoked" && ( + <p class="mt-3">{i18n.str`The merchant revoked access. Tokens already received remain in your wallet.`}</p> + )} + {fountainCollectionFailed(f) && f.status !== "revoked" && ( + <p + role="alert" + class="mt-3 text-error" + >{i18n.str`Collection failed. Check your connection and refresh to retry.`}</p> + )} + <details class="mt-4 border-t border-outlineVariant pt-3"> + <summary class="cursor-pointer py-2 font-medium">{i18n.str`Details`}</summary> + <dl class="space-y-3 break-words text-sm"> + <div> + <dt class="text-secondary">{i18n.str`Fountain ID`}</dt> + <dd class="break-all">{f.merchantFountainId}</dd> + </div> + <div> + <dt class="text-secondary">{i18n.str`Last checked`}</dt> + <dd>{fountainDate(f.lastPoll, props.language)}</dd> + </div> + <div> + <dt class="text-secondary">{i18n.str`Next check`}</dt> + <dd>{fountainDate(f.nextPoll, props.language)}</dd> + </div> + {f.pollFrequency && ( + <div> + <dt class="text-secondary">{i18n.str`Polling interval`}</dt> + <dd> + {f.pollFrequency.d_us === "forever" + ? i18n.str`Never` + : i18n.str`${f.pollFrequency.d_us / 1000000} seconds`} + </dd> + </div> + )} + </dl> + {f.grants.map((g) => ( + <section + key={g.token_family_slug} + class="mt-4 space-y-2 border-t border-outlineVariant pt-3 text-sm" + > + <h3 class="font-medium"> + {g.token_family.name} ({g.token_family_slug}) + </h3> + <p> + {localizedFountainText( + g.token_family.description, + g.token_family.description_i18n, + props.language, + )} + </p> + <p>{i18n.str`Target stash per period: ${g.tokens_per_period_stash}`}</p> + <p>{i18n.str`Issuance limit per period: ${g.tokens_per_period_limit}`}</p> + <p>{i18n.str`Future periods to collect: ${g.key_window_size}`}</p> + {f.quotas + ?.filter((q) => q.tokenFamilySlug === g.token_family_slug) + .map((q) => ( + <p key={String(q.validityStart.t_s)}> + {fountainDate(q.validityStart, props.language)} –{" "} + {fountainDate(q.validityEnd, props.language)}:{" "} + {i18n.str`${q.issued} received in this wallet`} + {q.limitReached ? ` · ${i18n.str`Period limit reached`}` : ""} + </p> + ))} + </section> + ))} + <p class="mt-3 text-sm text-secondary">{i18n.str`Limits are shared by wallets using the same fountain link. Tokens collected elsewhere may use part of the limit.`}</p> + {!!previous?.length && ( + <section class="mt-4 border-t border-outlineVariant pt-3"> + <h3 class="font-medium">{i18n.str`Previous grants`}</h3> + {previous.map((s) => ( + <div key={s.tokenFamilySlug} class="mt-3"> + <h4>{s.name}</h4> + {counts(s)} + </div> + ))} + </section> + )} + </details> + {error && !confirm && ( + <div class="mt-3"> + <ErrorCard error={error} /> + </div> + )} + <div class="mt-5 flex flex-wrap gap-3"> + <Button + disabled={busy || f.status === "revoked"} + onClick={() => void run(false)} + > + {busy ? i18n.str`Working…` : i18n.str`Refresh`} + </Button> + <Button + tone="danger" + disabled={busy} + onClick={() => { + setError(undefined); + setConfirm("remove"); + }} + >{i18n.str`Remove`}</Button> + </div> + {confirm && ( + <ConfirmationDialog + key={pendingId ?? "remove"} + title={ + pendingId + ? i18n.str`Withdrawal pending` + : i18n.str`Remove fountain?` + } + description={ + pendingId + ? i18n.str`The merchant may already have issued tokens for this withdrawal. Retry collection to recover them. Removing the fountain now gives up those tokens.` + : i18n.str`This deletes the fountain credential and receipt counts from this wallet. Tokens already received stay in your wallet. Importing the fountain again starts new receipt counts.` + } + cancelLabel={i18n.str`Cancel`} + confirmLabel={ + pendingId ? i18n.str`Remove anyway` : i18n.str`Remove fountain` + } + working={busy} + tone="danger" + onCancel={() => setConfirm(undefined)} + onConfirm={() => void run(true)} + > + {pendingId && ( + <div class="mt-3"> + <Button + disabled={busy} + onClick={() => void run(false)} + >{i18n.str`Retry collection`}</Button> + </div> + )} + {error && ( + <div class="mt-3"> + <ErrorCard error={error} /> + </div> + )} + </ConfirmationDialog> + )} + </article> + ); +} diff --git a/packages/wallet-webui/src/screens/StorybookScreen.tsx b/packages/wallet-webui/src/screens/StorybookScreen.tsx @@ -1,3 +1,5 @@ +import { FountainsScreen } from "./FountainsScreen.js"; +import { fountainFixture } from "../testing/fountain-fixture.js"; import { Button } from "../ui/Button.js"; import { Card } from "../ui/Card.js"; import { BankConfirmationScreen } from "./BankConfirmationScreen.js"; @@ -787,6 +789,48 @@ export function StorybookScreen(props: { onBack={() => {}} /> </section> + <section aria-labelledby="fountains-story"> + <h2 + id="fountains-story" + class="mb-3 text-xl font-semibold" + >{i18n.str`Fountains`}</h2> + <FountainsScreen + enabled + loading={false} + language="en" + fountains={[ + fountainFixture, + { + ...fountainFixture, + fountainId: "revoked", + merchantFountainId: "revoked", + name: "Previous membership", + nameI18n: undefined, + status: "revoked", + statistics: { + ...fountainFixture.statistics!, + historyComplete: false, + }, + }, + { + ...fountainFixture, + fountainId: "empty", + merchantFountainId: "empty", + name: "New membership", + nameI18n: undefined, + grants: [], + statistics: { + ...fountainFixture.statistics!, + families: [], + }, + }, + ]} + onSettings={() => {}} + onImport={() => {}} + onRefresh={async () => undefined} + onRemove={async () => ({ status: "removed" })} + /> + </section> <section aria-labelledby="shopping-story"> <h2 id="shopping-story" class="mb-3 text-xl font-semibold"> {/* Translators: DD 81 is a design-document identifier and must not be translated. */} diff --git a/packages/wallet-webui/src/stories/catalog.ts b/packages/wallet-webui/src/stories/catalog.ts @@ -144,6 +144,7 @@ function makeStoryGroups(): readonly StoryGroup[] { ], ["discounts", i18n.str`Discounts`], ["passes", i18n.str`Passes`], + ["fountains", i18n.str`Fountains`], ["shopping", i18n.str`Shop discovery`], [ "donau-settings", diff --git a/packages/wallet-webui/src/testing/fountain-fixture.ts b/packages/wallet-webui/src/testing/fountain-fixture.ts @@ -0,0 +1,74 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import { + MerchantContractTokenKind, + type FountainDetails, +} from "@gnu-taler/taler-util"; + +export const fountainFixture: FountainDetails = { + fountainId: "local-fountain", + merchantFountainId: "merchant-fountain", + name: "Member benefits", + nameI18n: { de: "Mitgliedervorteile", "de-CH": "Vereinsvorteile" }, + merchantBaseUrl: "https://merchant.example/instances/museum/", + status: "active", + collectionPending: false, + lastPoll: { t_s: 1790000000 }, + nextPoll: { t_s: 1790003600 }, + pollFrequency: { d_us: 3600000000 }, + grants: [ + { + token_family_slug: "member", + tokens_per_period_limit: 10, + tokens_per_period_stash: 2, + key_window_size: 1, + token_family: { + name: "Member discount", + description: "Reduced admission", + details: { + class: MerchantContractTokenKind.Discount, + expected_domains: [], + }, + critical: false, + keys: [], + }, + }, + ], + statistics: { + trackingSince: { t_s: 1790000000 }, + historyComplete: true, + families: [ + { + tokenFamilySlug: "member", + kind: "discount", + name: "Member discount", + receivedFromFountain: 17, + availableInWallet: 2, + futureInWallet: 2, + }, + { + tokenFamilySlug: "retired", + kind: "subscription", + name: "Summer pass", + receivedFromFountain: 3, + availableInWallet: 0, + futureInWallet: 0, + }, + ], + }, + quotas: [], +}; diff --git a/packages/wallet-webui/src/ui/WalletIcon.tsx b/packages/wallet-webui/src/ui/WalletIcon.tsx @@ -1,4 +1,5 @@ export type WalletIconName = + | "fountain" | "balances" | "bank" | "bell" @@ -33,6 +34,17 @@ export function WalletIcon(props: { }; let drawing; switch (props.name) { + case "fountain": + drawing = ( + <> + <path + {...common} + d="M4 15h16l-2 5H6ZM12 15V4M12 9C8 3 4 5 4 9M12 9c4-6 8-4 8 0" + /> + <path {...common} d="M8 23h8" /> + </> + ); + break; // The six "My wallet" glyphs (balances, history, discount, // subscriptions, donation, and bank) are dedicated to the public domain // under CC0-1.0. See WalletIcon.CC0.md for generation details. diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -1,3 +1,9 @@ +import { + fountainStatus, + grantLimitReached, +} from "../src/routes/fountain-model.js"; +import { FountainsScreen } from "../src/screens/FountainsScreen.js"; +import { fountainFixture } from "../src/testing/fountain-fixture.js"; import assert from "node:assert/strict"; import test from "node:test"; import { Window } from "happy-dom"; @@ -5119,3 +5125,213 @@ test("withdrawal review keeps unknown limits informational and blocks known hard cleanup(); await window.happyDOM.abort(); }); + +test("fountain cards retain past grants and require removal confirmation", async () => { + const window = installDom(); + const { render, cleanup, act } = await import("@testing-library/preact"); + let removes = 0; + let refreshes = 0; + const props = { + enabled: true, + loading: false, + language: "en", + fountains: [fountainFixture], + onSettings() {}, + onImport() {}, + onRefresh: async () => { + refreshes++; + return { message: "Refresh failed" }; + }, + onRemove: async () => { + removes++; + return { message: "Removal failed" }; + }, + }; + const view = render(<FountainsScreen {...props} />); + try { + for (const [language, name] of [ + ["de-ch", "Vereinsvorteile"], + ["de-AT", "Mitgliedervorteile"], + ["en", "Member benefits"], + ]) { + view.rerender(<FountainsScreen {...props} language={language} />); + assert(view.getByRole("heading", { name, level: 2 })); + assert(view.getByRole("article", { name: `Fountain ${name}` })); + } + assert(view.getByText("17")); + assert(view.getByText("Summer pass")); + await act(async () => { + ( + view.getByRole("button", { name: "Refresh" }) as HTMLButtonElement + ).click(); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + assert.equal(refreshes, 1); + assert(view.getByText("Refresh failed")); + await act(() => + ( + view.getByRole("button", { + name: "Remove", + exact: true, + }) as HTMLButtonElement + ).click(), + ); + assert(view.getByRole("dialog")); + assert.equal(removes, 0); + await act(() => + ( + view.getByRole("button", { + name: "Cancel", + exact: true, + }) as HTMLButtonElement + ).click(), + ); + assert.equal(removes, 0); + await act(() => + ( + view.getByRole("button", { + name: "Remove", + exact: true, + }) as HTMLButtonElement + ).click(), + ); + await act(async () => { + ( + view.getByRole("button", { + name: "Remove fountain", + exact: true, + }) as HTMLButtonElement + ).click(); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + assert.equal(removes, 1); + assert(view.getByRole("dialog")); + assert(view.getByText("Removal failed")); + await act(() => + ( + view.getByRole("button", { + name: "Cancel", + exact: true, + }) as HTMLButtonElement + ).click(), + ); + view.rerender( + <FountainsScreen + {...props} + fountains={[ + { + ...fountainFixture, + status: "revoked", + statistics: { + ...fountainFixture.statistics!, + historyComplete: false, + }, + }, + ]} + />, + ); + assert( + (view.getByRole("button", { name: "Refresh" }) as HTMLButtonElement) + .disabled, + ); + assert(view.getAllByText(/^Received since /).length); + view.rerender(<FountainsScreen {...props} enabled={false} />); + assert.equal(view.queryByRole("button", { name: "Refresh" }), null); + assert.equal(view.queryByText("17"), null); + } finally { + cleanup(); + await window.happyDOM.abort(); + } +}); + +test("removing a fountain with a pending withdrawal offers recovery and scopes abandonment to that withdrawal", async () => { + const window = installDom(); + const { render, cleanup, act } = await import("@testing-library/preact"); + const discarded: (string | undefined)[] = []; + let retries = 0; + let pendingId = "first"; + const view = render( + <FountainsScreen + enabled + loading={false} + language="en" + fountains={[{ ...fountainFixture, collectionPending: true }]} + onSettings={() => {}} + onImport={() => {}} + onRefresh={async () => { + retries++; + return retries === 1 ? { message: "Offline" } : undefined; + }} + onRemove={async (_, id) => { + discarded.push(id); + return id === pendingId + ? { status: "removed" } + : { status: "withdrawalPending", pendingWithdrawalId: pendingId }; + }} + />, + ); + const click = async (name: string) => + act(async () => view.getByRole("button", { name, exact: true }).click()); + try { + assert.ok(view.getByText("Collection pending")); + await click("Remove"); + await click("Remove fountain"); + assert.ok(view.getByRole("dialog", { name: "Withdrawal pending" })); + await click("Retry collection"); + assert.ok(view.getByText("Offline")); + await click("Retry collection"); + assert.equal(view.queryByRole("dialog"), null); + assert.deepEqual(discarded, [undefined]); + await click("Remove"); + await click("Remove fountain"); + await click("Cancel"); + await click("Remove"); + await click("Remove fountain"); + pendingId = "second"; + await click("Remove anyway"); + assert.ok(view.getByRole("dialog")); + await click("Remove anyway"); + assert.equal(view.queryByRole("dialog"), null); + assert.deepEqual(discarded, [ + undefined, + undefined, + undefined, + "first", + "second", + ]); + } finally { + cleanup(); + await window.happyDOM.abort(); + } +}); + +test("the fountain card reports a period limit only when every current grant is exhausted", () => { + const grant = fountainFixture.grants[0]!; + const f = { + ...fountainFixture, + grants: [grant, { ...grant, token_family_slug: "second" }], + }; + const slot = { + tokenFamilySlug: grant.token_family_slug, + validityStart: { t_s: 10 }, + validityEnd: { t_s: 20 }, + limitReached: true, + issued: 3, + }; + f.quotas = [ + slot, + { ...slot, tokenFamilySlug: "second", validityStart: { t_s: 20 } }, + { ...slot, tokenFamilySlug: "second", validityEnd: { t_s: 10 } }, + ]; + assert.equal(grantLimitReached(f, grant.token_family_slug, 10), true); + assert.equal(grantLimitReached(f, "second", 10), false); + assert.equal(fountainStatus(f, 10), "Active"); + f.quotas.push({ ...slot, tokenFamilySlug: "second", limitReached: false }); + assert.equal(fountainStatus(f, 10), "Active"); + f.quotas[f.quotas.length - 1]!.limitReached = true; + assert.equal(fountainStatus(f, 10), "Period limit reached"); + assert.equal( + fountainStatus({ ...f, status: "revoked" }, 10), + "Access revoked", + ); +});