taler-typescript-core

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

commit dee640c6aec6ec4f6d7c9a1dd746802953def602
parent cb9ddaa830dfe7cadaeb198c6d5a8f22ca751652
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 21:25:40 +0100

wallet web UI: show shopping websites for the selected balance

Keep wallet route parameters inside the hash so opening a balance action
preserves its scope. Show the shopping action in both balance layouts
and use the selected scope to find its websites.

Issue: https://bugs.taler.net/n/10676

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-demo.ts | 36+++++++++++++++++++++++++++++++++++-
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-donau.ts | 2+-
Mpackages/wallet-webui/src/routes/App.tsx | 58+++++++++++++++++++++++++++++++++++++++-------------------
Mpackages/wallet-webui/src/routes/balance-model.ts | 28+++++++++++++++++++++++++++-
Mpackages/wallet-webui/src/screens/BalanceScreen.tsx | 36++++++++++++++++++++----------------
Mpackages/wallet-webui/src/screens/ShoppingScreen.tsx | 28++++++++++------------------
Mpackages/wallet-webui/test/balance-model.test.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/screens.test.tsx | 44++++++++++++++++++++++++++++++++------------
8 files changed, 216 insertions(+), 68 deletions(-)

diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-demo.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-demo.ts @@ -105,6 +105,38 @@ export async function runWalletWebUiDemoTest(t: GlobalTestState) { await page.getByText("Demo · fictional", { exact: true }).waitFor(); }); + await stage.step( + "shop with the selected balance on both layouts", + async (page) => { + await page.goto(`${demoUrl}?embed=demo`); + for (const width of [767, 768]) { + await page.setViewportSize({ width, height: 844 }); + await page + .getByRole("button", { name: "Where to pay with CHF" }) + .click(); + await page + .getByRole("heading", { name: "Where to pay with CHF" }) + .waitFor(); + const url = new URL(page.url()); + t.assertDeepEqual(url.search, "?embed=demo"); + const params = new URLSearchParams(url.hash.split("?")[1]); + t.assertDeepEqual(params.get("currency"), "CHF"); + t.assertDeepEqual( + params.get("scope"), + "CHF/" + encodeURIComponent("https://exchange.demo.invalid/"), + ); + await page + .getByRole("button", { + name: "Visit website https://shops.demo.invalid/", + }) + .waitFor(); + await page.goBack(); + await page.getByRole("heading", { name: "Balances" }).waitFor(); + } + await page.setViewportSize({ width: 390, height: 844 }); + }, + ); + await stage.step("seeded transaction edge states", async (page) => { await page.goto(`${demoUrl}#/transactions`); await page.getByRole("heading", { name: "History" }).waitFor(); @@ -158,7 +190,9 @@ export async function runWalletWebUiDemoTest(t: GlobalTestState) { }); await stage.step("simulated deposit", async (page) => { - await page.goto(`${demoUrl}#/deposit?currency=CHF`); + await page.getByRole("link", { name: "Balances", exact: true }).click(); + await page.getByRole("button", { name: "Deposit", exact: true }).click(); + t.assertDeepEqual(new URL(page.url()).hash, "#/deposit?currency=CHF"); await page .getByRole("heading", { name: "Deposit to a bank account" }) .waitFor(); diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-donau.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-donau.ts @@ -278,7 +278,7 @@ export async function runWalletWebUiPwaDonauTest(t: GlobalTestState) { .waitFor(); await page .getByText( - "No shopping directories are available for this currency.", + "No websites are available for this currency.", ) .waitFor(); }, diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -177,6 +177,7 @@ import { tokenListView } from "./token-model.js"; import { balancesToView, balanceTrendView, + shoppingWebsites, selectedBalanceView, } from "./balance-model.js"; import { @@ -237,9 +238,33 @@ export function walletRoutePath(location: string): string { return location.split("?", 1)[0] || "/"; } +function walletRouteHref(path: string): string { + return `#/${path.replace(/^#?\/?/, "")}`; +} + +function navigateWalletRoute( + path: string, + { + replace = false, + state = null, + }: { replace?: boolean; state?: unknown } = {}, +): void { + const oldURL = window.location.href; + const href = walletRouteHref(path); + if (replace) window.history.replaceState(state, "", href); + else window.history.pushState(state, "", href); + // The History API does not fire the event used by useHashLocation. + window.dispatchEvent( + new window.HashChangeEvent("hashchange", { + oldURL, + newURL: window.location.href, + }), + ); +} + function useWalletHashLocation(): ReturnType<typeof useHashLocation> { - const [location, navigate] = useHashLocation(); - return [walletRoutePath(location), navigate]; + const [location] = useHashLocation(); + return [walletRoutePath(location), navigateWalletRoute]; } export function App(props: AppServices) { @@ -257,7 +282,7 @@ function AppContent(props: AppServices) { useLanguage(); return ( <ServicesContext.Provider value={props}> - <Router hook={useWalletHashLocation}> + <Router hook={useWalletHashLocation} hrefs={walletRouteHref}> <DurabilityProvider platform={props.platform} connection={props.connection} @@ -918,7 +943,7 @@ function BalanceRoute() { `/exchange/${exchangeRouteId(exchangeBaseUrl)}?returnTo=${encodeURIComponent("/")}`, ) } - onShop={(currency) => withCurrency("/shopping", currency)} + onShop={(scope) => withScope("/shopping", scope)} onOpenTransaction={(transactionId) => navigate(`/transaction/${transactionId}`) } @@ -937,16 +962,9 @@ function ShoppingRoute() { const { connection, platform } = useServices(); const [, navigate] = useLocation(); const query = useWalletQuery(connection, WalletApiOperation.GetBalances, {}); - const currency = hashQueryValue("currency"); - const urls = Array.from( - new Set( - query.data?.balances - .filter( - (balance) => !currency || balance.scopeInfo.currency === currency, - ) - .flatMap((balance) => balance.shoppingUrls ?? []) - .filter(safeWebUrl) ?? [], - ), + const { currency, urls } = shoppingWebsites( + query.data?.balances ?? [], + hashRouteParameters(window.location.hash), ); return ( <ShoppingScreen @@ -957,7 +975,7 @@ function ShoppingRoute() { query.error ? errorFromException( query.error, - i18n.str`Shopping directories could not be loaded.`, + i18n.str`Websites could not be loaded.`, ) : undefined } @@ -1214,11 +1232,13 @@ export function hashQueryValue( name: string, hash = window.location.hash, ): string { + return hashRouteParameters(hash).get(name) ?? ""; +} + +function hashRouteParameters(hash: string): URLSearchParams { const queryStart = hash.indexOf("?"); - return ( - new URLSearchParams( - queryStart === -1 ? "" : hash.slice(queryStart + 1), - ).get(name) ?? "" + return new URLSearchParams( + queryStart === -1 ? "" : hash.slice(queryStart + 1), ); } diff --git a/packages/wallet-webui/src/routes/balance-model.ts b/packages/wallet-webui/src/routes/balance-model.ts @@ -9,6 +9,7 @@ import type { import { Amounts, BalanceFlag, + isSafeExternalUrl, ScopeType, TransactionType, } from "@gnu-taler/taler-util"; @@ -84,6 +85,31 @@ function refreshDate(stamp: { t_s: number | "never" }): string { }).format(new Date(stamp.t_s * 1000)); } +function usableShoppingUrls(balance: WalletBalance): string[] { + return (balance.shoppingUrls ?? []).filter(isSafeExternalUrl); +} + +export function shoppingWebsites( + balances: WalletBalance[], + params: URLSearchParams, +) { + const currency = params.get("currency") ?? ""; + const scope = params.get("scope"); + const matching = balances.filter((balance) => + scope === null + ? !currency || balance.scopeInfo.currency === currency + : scopeIdentity(balance.scopeInfo) === scope && + balance.scopeInfo.type !== ScopeType.ExchangeLegacyKeys, + ); + return { + currency: + scope !== null && matching.length + ? matching[0].scopeInfo.currency + : currency, + urls: [...new Set(matching.flatMap(usableShoppingUrls))], + }; +} + function balanceView( balance: WalletBalance, refresh?: WalletRefreshInfo, @@ -168,7 +194,7 @@ function balanceView( 2, ), warnings, - shoppingUrls: balance.shoppingUrls ?? [], + shoppingUrls: usableShoppingUrls(balance), peerPaymentsDisabled: balance.disablePeerPayments === true, depositsDisabled: balance.disableDirectDeposits === true, ...(balance.scopeInfo.type === ScopeType.ExchangeLegacyKeys diff --git a/packages/wallet-webui/src/screens/BalanceScreen.tsx b/packages/wallet-webui/src/screens/BalanceScreen.tsx @@ -710,7 +710,7 @@ export function BalanceScreen(props: { onSend: (scope: ScopeInfo) => void; onRequest: (scope: ScopeInfo) => void; onManageLegacyBalance?: (exchangeBaseUrl: string) => void; - onShop?: (currency: string) => void; + onShop?: (scope: ScopeInfo) => void; onOpenTransaction?: (transactionId: string) => void; onShowTransactions?: (scope: ScopeInfo) => void; onShowDiscounts?: () => void; @@ -781,6 +781,23 @@ export function BalanceScreen(props: { ); if (!selected) return null; + const onShop = props.onShop; + const shopButton = !selected.legacy && + selected.shoppingUrls.length > 0 && + onShop && ( + <button + type="button" + onClick={() => onShop(selected.scopeInfo)} + class="flex min-h-14 w-full md:w-auto items-center justify-center gap-5 rounded-xl bg-secondaryContainer px-5 font-semibold text-onSecondaryContainer hover:brightness-95" + > + <WalletIcon name="map" class="h-8 w-8" /> + { + // Translators: Opens merchant locations; the placeholder is a currency code. + i18n.str`Where to pay with ${selected.currency}` + } + </button> + ); + return ( <div class="mx-auto max-w-6xl text-onBackground"> <h1 class="sr-only">{i18n.str`Balances`}</h1> @@ -851,6 +868,7 @@ export function BalanceScreen(props: { balance={selected} onDismiss={props.onDismissRenewal} /> + {shopButton && <div class="mt-4">{shopButton}</div>} {selected.legacy && props.onManageLegacyBalance && ( <div class="mt-4"> <Button @@ -954,21 +972,7 @@ export function BalanceScreen(props: { <PendingAmounts balance={selected} /> </div> </section> - {!selected.legacy && - selected.shoppingUrls.length > 0 && - props.onShop && ( - <button - type="button" - onClick={() => props.onShop!(selected.currency)} - class="flex min-h-14 w-full items-center justify-center gap-5 rounded-xl bg-secondaryContainer px-5 font-semibold text-onSecondaryContainer hover:brightness-95" - > - <WalletIcon name="map" class="h-8 w-8" /> - { - // Translators: Opens merchant locations; the placeholder is a currency code. - i18n.str`Where to pay with ${selected.currency}` - } - </button> - )} + {shopButton} <div class="flex items-center justify-center gap-3" aria-label={ diff --git a/packages/wallet-webui/src/screens/ShoppingScreen.tsx b/packages/wallet-webui/src/screens/ShoppingScreen.tsx @@ -12,42 +12,34 @@ export function ShoppingScreen(props: { onOpen: (url: string) => void; onBack: () => void; }) { + const currency = props.currency || "Taler"; return ( <div class="space-y-5"> <div> - <p class="text-sm font-semibold uppercase tracking-wide text-secondary">{ - /* Translators: Find merchants accepting the selected currency through exchange-recommended directories. */ i18n.str`Shop discovery` - }</p> {/* Translators: %1$s is a currency code; “Taler” is used only when no currency is selected. */} - <h1 class="text-2xl font-bold">{i18n.str`Where to pay with ${props.currency || "Taler"}`}</h1> - <p class="text-secondary">{ - /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`These independent directories are suggested by exchanges used by this wallet.` - }</p> + <h1 class="text-2xl font-bold">{i18n.str`Where to pay with ${currency}`}</h1> + <p class="text-secondary">{i18n.str`These websites list shops that accept ${currency}.`}</p> </div> {props.loading ? ( <Card> - <p role="status">{i18n.str`Loading shopping directories…`}</p> + <p role="status">{i18n.str`Loading websites…`}</p> </Card> ) : props.error ? ( <ErrorCard error={props.error} /> ) : props.urls.length === 0 ? ( <Card> - <p>{i18n.str`No shopping directories are available for this currency.`}</p> + <p>{i18n.str`No websites are available for this currency.`}</p> </Card> ) : ( <ul class="space-y-3"> {props.urls.map((url) => ( <li key={url}> <Card class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"> - <div class="min-w-0"> - <p class="font-semibold">{ - /* Translators: An external directory of merchants that accept Taler payments. */ i18n.str`Shopping directory` - }</p> - <p class="mt-1 break-all text-sm text-secondary">{url}</p> - </div> - <Button onClick={() => props.onOpen(url)}>{ - /* Translators: Open an external merchant directory website, not a filesystem folder. */ i18n.str`Open directory` - }</Button> + <p class="min-w-0 break-all text-sm">{url}</p> + <Button onClick={() => props.onOpen(url)}> + {i18n.str`Visit website`} + <span class="sr-only"> {url}</span> + </Button> </Card> </li> ))} diff --git a/packages/wallet-webui/test/balance-model.test.ts b/packages/wallet-webui/test/balance-model.test.ts @@ -6,11 +6,13 @@ import { TransactionType, type BalancesResponse, type Transaction, + type WalletBalance, } from "@gnu-taler/taler-util"; import { balancesToView, balanceTrendView, selectedBalanceView, + shoppingWebsites, } from "../src/routes/balance-model.js"; import { BALANCE_SELECTION_PREFERENCE_KEY, @@ -19,6 +21,8 @@ import { type BalanceSelectionPreferenceStorage, } from "../src/platform/balance-preference.js"; +import { scopeIdentity, scopeRouteQuery } from "../src/routes/scope-model.js"; + class MemoryStorage implements BalanceSelectionPreferenceStorage { readonly values = new Map<string, string>(); @@ -89,6 +93,54 @@ test("balance model exposes shopping, capability flags, and sorted Donau summari assert.equal(view.donauSummaries[0].legalDomain, "Bern"); }); +test("shop discovery matches the selected exchange even when currencies coincide", () => { + function exchange( + currency: string, + name: string, + shoppingUrls: string[], + ): WalletBalance { + return { + scopeInfo: { + type: ScopeType.Exchange, + currency, + url: `https://${name}.example/`, + }, + available: `${currency}:5`, + pendingIncoming: `${currency}:0`, + pendingOutgoing: `${currency}:0`, + flags: [], + shoppingUrls, + }; + } + const first = "https://shop.example/one"; + const second = "https://shop.example/two"; + const balances = [ + exchange("CHF", "one", [first, first, second, "javascript:void(0)"]), + exchange("CHF", "two", ["https://chf.example/"]), + exchange("EUR", "three", ["https://eur.example/"]), + exchange("CHF", "empty", ["data:text/plain,invalid"]), + ]; + const scope = new URLSearchParams(scopeRouteQuery(balances[0].scopeInfo)); + assert.deepEqual(shoppingWebsites(balances, scope), { + currency: "CHF", + urls: [first, second], + }); + for (const id of ["unknown", "", "CHF/%zz"]) { + scope.set("scope", id); + assert.deepEqual(shoppingWebsites(balances, scope).urls, []); + } + assert.deepEqual( + shoppingWebsites(balances, new URLSearchParams("currency=CHF")).urls, + [first, second, "https://chf.example/"], + ); + assert.deepEqual( + balancesToView({ balances, haveProdBalance: true }).balances?.find( + (balance) => balance.scopeId === scopeIdentity(balances[3].scopeInfo), + )?.shoppingUrls, + [], + ); +}); + test("balance selection restores the exact scope after a reload", () => { const balances = balancesToView({ balances: [ diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -1,7 +1,11 @@ import assert from "node:assert/strict"; import test from "node:test"; import { Window } from "happy-dom"; -import { ScopeType, TalerErrorCode } from "@gnu-taler/taler-util"; +import { + ScopeType, + TalerErrorCode, + type ScopeInfo, +} from "@gnu-taler/taler-util"; import { BalanceScreen } from "../src/screens/BalanceScreen.js"; import { ActionScreen } from "../src/screens/ActionScreen.js"; import { BankConfirmationScreen } from "../src/screens/BankConfirmationScreen.js"; @@ -999,7 +1003,7 @@ test("balance capability flags block unavailable money flows and expose shopping click(element: Element): Promise<void>; }; }; - let shopped = ""; + const shopped: ScopeInfo[] = []; const view = render( <main> <BalanceScreen @@ -1027,9 +1031,7 @@ test("balance capability flags block unavailable money flows and expose shopping onDeposit={() => {}} onSend={() => {}} onRequest={() => {}} - onShop={(currency) => { - shopped = currency; - }} + onShop={(scope) => shopped.push(scope)} /> </main>, ); @@ -1047,10 +1049,18 @@ test("balance capability flags block unavailable money flows and expose shopping .disabled, true, ); - await userEvent - .setup({ document: window.document as unknown as Document }) - .click(view.getByRole("button", { name: "Where to pay with CHF" })); - assert.equal(shopped, "CHF"); + const user = userEvent.setup({ + document: window.document as unknown as Document, + }); + const shopButtons = view.getAllByRole("button", { + name: "Where to pay with CHF", + }); + assert.equal(shopButtons.length, 2); + for (const button of shopButtons) await user.click(button); + assert.deepEqual( + shopped, + Array(2).fill({ type: ScopeType.Global, currency: "CHF" }), + ); assert.equal( view.queryByRole("combobox", { name: "Balance history period" }), null, @@ -1091,7 +1101,7 @@ test("legacy balances are struck through and only expose management", async () = pendingOutgoing: "CHF:0", pendingOutgoingValue: "0.00", warnings: ["Issued under superseded exchange keys"], - shoppingUrls: [], + shoppingUrls: ["https://shops.example/"], peerPaymentsDisabled: false, depositsDisabled: false, legacy: true, @@ -1103,6 +1113,7 @@ test("legacy balances are struck through and only expose management", async () = onDeposit={() => {}} onSend={() => {}} onRequest={() => {}} + onShop={() => {}} onManageLegacyBalance={(url) => { managed = url; }} @@ -1123,6 +1134,10 @@ test("legacy balances are struck through and only expose management", async () = .setup({ document: window.document as unknown as Document }) .click(view.getAllByRole("button", { name: "Manage legacy balance" })[0]); assert.equal(managed, "https://exchange.example/"); + assert.equal( + view.queryByRole("button", { name: "Where to pay with CHF" }), + null, + ); cleanup(); await window.happyDOM.abort(); }); @@ -1562,7 +1577,7 @@ test("shop discovery requires an explicit external-navigation action", async () <main> <ShoppingScreen currency="CHF" - urls={["https://shops.example/"]} + urls={["https://first.example/", "https://shops.example/"]} loading={false} onOpen={(url) => { opened = url; @@ -1571,9 +1586,14 @@ test("shop discovery requires an explicit external-navigation action", async () /> </main>, ); + assert.equal(opened, ""); await userEvent .setup({ document: window.document as unknown as Document }) - .click(view.getByRole("button", { name: "Open directory" })); + .click( + view.getByRole("button", { + name: "Visit website https://shops.example/", + }), + ); assert.equal(opened, "https://shops.example/"); cleanup(); await window.happyDOM.abort();