taler-typescript-core

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

commit 507ea73ebef11c2b901abcb738fb2e501b4f6a64
parent c8c5a21abbd6596687c66dfe65db173bc48d9165
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 04:23:47 +0100

wallet-webui: show the funding balance and payto details for a deposit

Starting a deposit kept only the currency, so another exchange's balance
could be selected. Carry the chosen balance into the form and show it
alongside the link's requested amount and reference. Ask for
acknowledgment if the bank will receive less, the currency differs, or
the link's instructions cannot be honored.

Diffstat:
Mpackages/taler-harness/src/integrationtests/test-wallet-web-ui-demo.ts | 9++++++++-
Mpackages/wallet-webui/src/routes/App.tsx | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mpackages/wallet-webui/src/routes/deposit-model.ts | 75++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/wallet-webui/src/routes/scope-model.ts | 10++--------
Mpackages/wallet-webui/src/screens/BalanceScreen.tsx | 4++--
Mpackages/wallet-webui/src/screens/DepositScreen.tsx | 213++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mpackages/wallet-webui/src/ui/exchange-label.ts | 11++++++-----
Mpackages/wallet-webui/test/deposit-model.test.ts | 30+++++++++++++++++++++++++++++-
Mpackages/wallet-webui/test/scope-model.test.ts | 18++++++++++++++++++
Mpackages/wallet-webui/test/screens.test.tsx | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
10 files changed, 452 insertions(+), 63 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 @@ -236,7 +236,14 @@ export async function runWalletWebUiDemoTest(t: GlobalTestState) { await stage.step("simulated deposit", async (page) => { 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"); + const [route, search] = new URL(page.url()).hash.split("?"); + t.assertDeepEqual(route, "#/deposit"); + const params = new URLSearchParams(search); + t.assertDeepEqual(params.get("currency"), "CHF"); + t.assertDeepEqual( + params.get("scope"), + "CHF/" + encodeURIComponent("https://exchange.demo.invalid/"), + ); await page .getByRole("heading", { name: "Deposit to a bank account" }) .waitFor(); diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -161,7 +161,11 @@ import { publicTestBalanceRequest, validatedPaytoUri, } from "./money-flow-model.js"; -import { depositDestinationView } from "./deposit-model.js"; +import { + depositAccountDraftFromHistory, + depositDestinationView, + depositLinkInstructions, +} from "./deposit-model.js"; import { BankAccountsRoute, ExchangeDetailRoute, @@ -594,7 +598,7 @@ function WalletShell() { path="/deposit-action/:actionId" component={KeyedDepositRoute} /> - <Route path="/deposit" component={DepositRoute} /> + <Route path="/deposit" component={KeyedDepositRoute} /> <Route path="/peer/send"> <PeerCreateRoute key="send" mode="send" /> </Route> @@ -693,8 +697,8 @@ function KeyedIntegratedWithdrawalRoute() { } function KeyedDepositRoute() { - const [, params] = useRoute("/deposit-action/:actionId"); - return <DepositRoute key={params?.actionId ?? ""} />; + const [location] = useHashLocation(); + return <DepositRoute key={location} />; } function KeyedPeerReceiveRoute() { @@ -853,8 +857,6 @@ function BalanceRoute() { { ...activityRequest, filterByState: "nonfinal" }, { enabled: Boolean(selectedBalance) && activitySupported }, ); - const withCurrency = (route: string, currency: string) => - navigate(`${route}?currency=${encodeURIComponent(currency)}`); const withScope = (route: string, scope: ScopeInfo) => navigate(`${route}?${scopeRouteQuery(scope)}`); const withdraw = (scope?: ScopeInfo) => { @@ -984,7 +986,7 @@ function BalanceRoute() { onGetDemoCash={() => void getDemoCash()} gettingDemoCash={gettingDemoCash} demoCashError={demoCashError} - onDeposit={(currency) => withCurrency("/deposit", currency)} + onDeposit={(scope) => withScope("/deposit", scope)} onSend={(scope) => withScope("/peer/send", scope)} onRequest={(scope) => withScope("/peer/request", scope)} onManageLegacyBalance={(exchangeBaseUrl) => @@ -1401,7 +1403,16 @@ function DepositRoute() { balance.scopeInfo.type !== ScopeType.ExchangeLegacyKeys, ) ?? []; const requestedScope = scopeFromIdentity(hashQueryValue("scope")); - const requestedCurrency = hashQueryValue("currency"); + const [initialPaytoUri, setInitialPaytoUri] = useState<string>(); + const link = useMemo( + () => + initialPaytoUri ? depositLinkInstructions(initialPaytoUri) : undefined, + [initialPaytoUri], + ); + const [accountDraft] = useState(depositAccountDraftFromHistory); + const requestedCurrency = link?.suggestedAmount + ? Amounts.currencyOf(link.suggestedAmount) + : hashQueryValue("currency"); const initialBalance = eligibleBalances.find( (balance) => @@ -1416,7 +1427,6 @@ function DepositRoute() { const actionId = actionParams?.actionId ?? hashQueryValue("actionId"); const returnTo = actionId ? `/deposit-action/${actionId}` : "/deposit"; const [gateDraft] = useState(() => loadDepositGateDraft(returnTo)); - const [initialPaytoUri, setInitialPaytoUri] = useState<string>(); const [actionLoading, setActionLoading] = useState(actionId.length > 0); const [prepared, setPrepared] = useState<{ amount: AmountString; @@ -1573,16 +1583,25 @@ function DepositRoute() { } }; const response = prepared?.response; + const loading = accounts.isLoading || balances.isLoading || actionLoading; + const initialScopeId = gateDraft?.scope + ? scopeIdentity(gateDraft.scope) + : requestedScope + ? scopeIdentity(requestedScope) + : requestedCurrency + ? initialBalance?.scopeInfo.currency === requestedCurrency + ? scopeIdentity(initialBalance.scopeInfo) + : "unavailable" + : undefined; + const suggested = gateDraft?.amount ?? link?.suggestedAmount; return ( <DepositScreen + key={loading ? "loading" : "ready"} currency={currency} - initialScopeId={ - gateDraft?.scope - ? scopeIdentity(gateDraft.scope) - : initialBalance - ? scopeIdentity(initialBalance.scopeInfo) - : undefined - } + initialScopeId={initialScopeId} + accountDraft={actionId ? undefined : accountDraft} + link={link} + onCopy={(value) => navigator.clipboard.writeText(value)} scopes={eligibleBalances.map((balance) => ({ id: scopeIdentity(balance.scopeInfo), currency: balance.scopeInfo.currency, @@ -1592,8 +1611,8 @@ function DepositRoute() { }))} initialPaytoUri={gateDraft?.paytoUri ?? initialPaytoUri} initialAmount={ - gateDraft - ? Amounts.stringifyValue(Amounts.parseOrThrow(gateDraft.amount)) + suggested + ? Amounts.stringifyValue(Amounts.parseOrThrow(suggested)) : undefined } initialDestination={ @@ -1608,7 +1627,7 @@ function DepositRoute() { ...(account.currencies ? { currencies: account.currencies } : {}), destination: depositDestinationView(account.paytoUri, account.label), }))} - loading={accounts.isLoading || balances.isLoading || actionLoading} + loading={loading} working={working} error={ error ?? @@ -1637,6 +1656,22 @@ function DepositRoute() { prepared && response ? { amount: prepared.amount, + scopeLabel: prepared.scope + ? scopeLabel(prepared.scope) + : undefined, + quoteKey: JSON.stringify([ + response.kycSoftLimit, + response.kycHardLimit, + response.kycExchanges, + ]), + creditDiffers: + !!link?.suggestedAmount && + (Amounts.currencyOf(response.effectiveDepositAmount) !== + Amounts.currencyOf(link.suggestedAmount) || + Amounts.cmp( + response.effectiveDepositAmount, + link.suggestedAmount, + ) < 0), totalCost: response.totalDepositCost, effectiveAmount: response.effectiveDepositAmount, coinFee: response.fees.coin, diff --git a/packages/wallet-webui/src/routes/deposit-model.ts b/packages/wallet-webui/src/routes/deposit-model.ts @@ -1,4 +1,10 @@ -import { encodeCrock, Paytos, PaytoType, Result } from "@gnu-taler/taler-util"; +import { + Amounts, + encodeCrock, + Paytos, + PaytoType, + Result, +} from "@gnu-taler/taler-util"; import { i18n } from "../i18n/runtime.js"; import type { DepositDestinationFieldView, @@ -101,3 +107,70 @@ export function depositDestinationView( fields, }; } + +export interface DepositLinkInstructions { + uri: string; + suggestedAmount?: string; + invalidAmount: boolean; + references: string[]; +} + +/** Read transfer options separately from the precise destination URI handed to wallet-core. */ +export function depositLinkInstructions(uri: string): DepositLinkInstructions { + const options = new URLSearchParams(uri.split("?").slice(1).join("?")); + const amounts: string[] = []; + const references: string[] = []; + for (const [key, value] of options) { + switch (key.toLowerCase()) { + case "amount": + amounts.push(value); + break; + case "message": + case "instruction": + case "ch-qrr": + if (value) references.push(value); + break; + } + } + // RFC 8905 uses "." as the decimal separator; commas in amounts are ignored. + const amount = + amounts.length === 1 && /^[a-z]+:[\d,]+(?:\.[\d,]+)?$/i.test(amounts[0]) + ? Amounts.parse(amounts[0].replaceAll(",", "")) + : undefined; + const suggestedAmount = + amount && !Amounts.isZero(amount) ? Amounts.stringify(amount) : undefined; + return { + uri, + references, + suggestedAmount, + invalidAmount: amounts.length > 0 && !suggestedAmount, + }; +} + +export interface DepositAccountDraft { + input: string; + scopeId: string; + currency: string; + language: string; + savedAt: number; + accountId?: string; +} + +export function depositAccountDraftFromHistory(): + | DepositAccountDraft + | undefined { + const value = window.history.state?.depositAccountDraft; + if ( + !value || + typeof value.input !== "string" || + typeof value.scopeId !== "string" || + (value.accountId !== undefined && typeof value.accountId !== "string") || + typeof value.currency !== "string" || + typeof value.language !== "string" || + typeof value.savedAt !== "number" || + value.savedAt > Date.now() || + Date.now() - value.savedAt > 30 * 60_000 + ) + return undefined; + return value; +} diff --git a/packages/wallet-webui/src/routes/scope-model.ts b/packages/wallet-webui/src/routes/scope-model.ts @@ -5,6 +5,8 @@ import { type ScopeInfo, } from "@gnu-taler/taler-util"; import { i18n } from "../i18n/runtime.js"; +import { scopeProviderLabel } from "../ui/exchange-label.js"; +export { scopeProviderLabel }; export function scopeIdentity(scope: ScopeInfo): string { return stringifyScopeInfoShort(scope); @@ -51,14 +53,6 @@ export function scopeFromIdentity(identity: string): ScopeInfo | undefined { return undefined; } -export function scopeProviderLabel(url: string): string { - try { - return new URL(url).host; - } catch { - return url; - } -} - export function scopeLabel(scope: ScopeInfo): string { switch (scope.type) { case ScopeType.Global: diff --git a/packages/wallet-webui/src/screens/BalanceScreen.tsx b/packages/wallet-webui/src/screens/BalanceScreen.tsx @@ -728,7 +728,7 @@ export function BalanceScreen(props: { onGetDemoCash: () => void; gettingDemoCash?: boolean; demoCashError?: ErrorPresentation; - onDeposit: (currency: string) => void; + onDeposit: (scope: ScopeInfo) => void; onSend: (scope: ScopeInfo) => void; onRequest: (scope: ScopeInfo) => void; onManageLegacyBalance?: (exchangeBaseUrl: string) => void; @@ -1067,7 +1067,7 @@ export function BalanceScreen(props: { icon="deposit" label={depositActionLabel} disabled={selected.depositsDisabled} - onClick={() => props.onDeposit(selected.currency)} + onClick={() => props.onDeposit(selected.scopeInfo)} /> <details class="relative"> <summary class="list-none"> diff --git a/packages/wallet-webui/src/screens/DepositScreen.tsx b/packages/wallet-webui/src/screens/DepositScreen.tsx @@ -1,5 +1,11 @@ +import { useLanguage } from "../i18n/LanguageProvider.js"; +import type { + DepositAccountDraft, + DepositLinkInstructions, +} from "../routes/deposit-model.js"; +import { CopyButton } from "../ui/ClipboardFeedback.js"; import { useFocusScope } from "@gnu-taler/web-util/browser"; -import { useEffect, useMemo, useRef, useState } from "preact/hooks"; +import { useEffect, useId, useMemo, useRef, useState } from "preact/hooks"; import { Button } from "../ui/Button.js"; import { Card } from "../ui/Card.js"; import { ErrorCard } from "../ui/ErrorCard.js"; @@ -8,7 +14,11 @@ import { i18n } from "../i18n/runtime.js"; import type { ScopeInfo } from "@gnu-taler/taler-util"; import { FocusedPage } from "../ui/FocusedPage.js"; import { MoneyAmountInput } from "../ui/MoneyAmountInput.js"; -import { positiveAmountValue } from "../routes/money-flow-model.js"; +import { + amountInputHint, + localizedAmountInput, + positiveAmountValue, +} from "../routes/money-flow-model.js"; export interface DepositDestinationFieldView { label: string; @@ -47,6 +57,9 @@ export interface DepositReviewView { refreshFee: string; destination: DepositDestinationView; kycWarning?: string; + scopeLabel?: string; + creditDiffers?: boolean; + quoteKey?: string; } export function DepositScreen(props: { @@ -54,8 +67,12 @@ export function DepositScreen(props: { initialScopeId?: string; scopes?: DepositScopeView[]; initialPaytoUri?: string; + initialAccountId?: string; initialAmount?: string; initialDestination?: DepositDestinationView; + link?: DepositLinkInstructions; + accountDraft?: DepositAccountDraft; + onCopy?: (value: string) => unknown; accounts?: DepositAccountView[]; loading: boolean; working: boolean; @@ -71,11 +88,34 @@ export function DepositScreen(props: { onConfirm: () => void; onBack: () => void; onCancel: () => void; - onManageAccounts?: () => void; + onManageAccounts?: (draft: DepositAccountDraft) => void; onErrorAction?: () => void; }) { - const [amount, setAmount] = useState(props.initialAmount ?? ""); - const [accountId, setAccountId] = useState(""); + const { language } = useLanguage(); + const bankAccountLabelId = useId(); + const [amount, setAmount] = useState(() => { + if (props.accountDraft?.language === language) + return props.accountDraft.input; + return localizedAmountInput(props.initialAmount ?? "", language); + }); + const [acknowledgment, setAcknowledgment] = useState(""); + const acknowledgmentKey = + props.review && props.link + ? JSON.stringify([props.link, props.review]) + : ""; + const needsAcknowledgment = Boolean( + props.review && + props.link && + (props.link.references.length || + props.link.invalidAmount || + props.review.creditDiffers), + ); + useEffect(() => { + setAcknowledgment(""); + }, [acknowledgmentKey]); + const [accountId, setAccountId] = useState( + props.accountDraft?.accountId ?? props.initialAccountId ?? "", + ); const accounts = useMemo(() => props.accounts ?? [], [props.accounts]); const scopes = useMemo<DepositScopeView[]>( () => @@ -94,7 +134,7 @@ export function DepositScreen(props: { [props.currency, props.scopes], ); const [scopeId, setScopeId] = useState( - props.initialScopeId ?? scopes[0]?.id ?? "", + props.accountDraft?.scopeId || props.initialScopeId || "", ); useEffect(() => { if (accounts[0] && !props.initialPaytoUri) @@ -104,17 +144,30 @@ export function DepositScreen(props: { if (!props.initialPaytoUri) return; setAccountId(""); }, [props.initialPaytoUri]); - const selected = accounts.find((account) => account.id === accountId); + const selected = props.initialPaytoUri + ? undefined + : accountId + ? accounts.find((account) => account.id === accountId) + : accounts[0]; const compatibleScopes = selected?.currencies?.length ? scopes.filter((scope) => selected.currencies?.includes(scope.currency)) : scopes; const selectedScope = compatibleScopes.find((scope) => scope.id === scopeId) ?? - compatibleScopes[0]; + (!scopeId ? compatibleScopes[0] : undefined); + useEffect(() => { + if (!props.loading && !scopeId && selectedScope) + setScopeId(selectedScope.id); + }, [props.loading, scopeId, selectedScope?.id]); const currency = selectedScope?.currency ?? ""; - const paytoUri = selected?.paytoUri ?? props.initialPaytoUri ?? ""; - const destination = selected?.destination ?? props.initialDestination; - const normalizedAmount = positiveAmountValue(currency, amount); + const paytoUri = props.initialPaytoUri ?? selected?.paytoUri ?? ""; + const destination = props.initialDestination ?? selected?.destination; + const normalizedAmount = positiveAmountValue( + currency, + amount, + undefined, + language, + ); const amountInput = useRef<HTMLInputElement>(null); // Once the accounts have loaded (and again when returning from review), the // amount is the first thing to enter. Without a destination the user has to @@ -129,8 +182,13 @@ export function DepositScreen(props: { <div class="flex items-center gap-4"> <button type="button" + disabled={props.working} onClick={props.review ? props.onBack : props.onCancel} - aria-label={i18n.str`Back to balances`} + aria-label={ + props.review + ? i18n.str`Back to deposit form` + : i18n.str`Back to balances` + } class="grid h-11 w-11 place-items-center rounded-full text-2xl hover:bg-secondaryContainer" > ← @@ -154,19 +212,57 @@ export function DepositScreen(props: { <ErrorCard error={props.error}> {props.errorActionLabel && props.onErrorAction && ( <div class="mt-4"> - <Button onClick={props.onErrorAction}> + <Button disabled={props.working} onClick={props.onErrorAction}> {props.errorActionLabel} </Button> </div> )} </ErrorCard> )} + {props.link && ( + <Card class="space-y-2"> + {props.link.suggestedAmount && ( + <p>{i18n.str`Amount requested by the link: ${props.link.suggestedAmount}`}</p> + )} + {props.link.invalidAmount && ( + <p>{i18n.str`The link’s amount is invalid. Choose the amount to deposit.`}</p> + )} + {props.link.references.length > 0 && ( + <> + <p>{i18n.str`The exchange supplies the bank transfer reference. This deposit cannot send the reference from the link.`}</p> + {props.link.references.map((reference, index) => ( + <div key={index} class="flex flex-wrap items-center gap-2"> + <span class="break-all font-medium">{reference}</span> + {props.onCopy && ( + <CopyButton + text={reference} + write={props.onCopy} + label={i18n.str`Copy reference`} + /> + )} + </div> + ))} + </> + )} + <details> + <summary>{i18n.str`Original payment link`}</summary> + <p class="break-all select-all">{props.link.uri}</p> + {props.onCopy && ( + <CopyButton + text={props.link.uri} + write={props.onCopy} + label={i18n.str`Copy link`} + /> + )} + </details> + </Card> + )} {!props.loading && !props.review && ( <form class="space-y-5" onSubmit={(event) => { event.preventDefault(); - if (normalizedAmount && paytoUri && selectedScope) + if (!props.working && normalizedAmount && paytoUri && selectedScope) props.onReview({ currency, amount: normalizedAmount, @@ -175,7 +271,7 @@ export function DepositScreen(props: { }); }} > - <div class="form-field-stack space-y-6"> + <fieldset disabled={props.working} class="form-field-stack space-y-6"> <label class="mx-auto block max-w-xs"> <span class="sr-only">{i18n.str`Currency`}</span> <select @@ -188,6 +284,9 @@ export function DepositScreen(props: { }} class="w-full rounded-full border border-outline bg-surface px-5 py-3 text-center text-xl" > + {!selectedScope && ( + <option value="">{i18n.str`Choose a funding balance`}</option> + )} {compatibleScopes.map((scope) => ( <option key={scope.id} value={scope.id}> {scope.label} @@ -196,7 +295,15 @@ export function DepositScreen(props: { ))} </select> </label> + {!selectedScope && compatibleScopes.length > 0 && ( + <p role="status">{i18n.str`The selected balance is unavailable for this account. Choose a funding balance.`}</p> + )} <MoneyAmountInput + hint={ + amount && currency && !normalizedAmount + ? amountInputHint(language) + : undefined + } inputRef={amountInput} label={i18n.str`Amount`} value={amount} @@ -206,14 +313,18 @@ export function DepositScreen(props: { <Card class="space-y-6"> {!props.initialPaytoUri && accounts.length > 0 && ( <label> - <span class="mb-1 block text-sm text-secondary"> + <span + id={bankAccountLabelId} + class="mb-1 block text-sm text-secondary" + > { // Translators: Saved destination account that will receive the deposit. i18n.str`Bank account` } </span> <select - value={accountId} + aria-labelledby={bankAccountLabelId} + value={selected?.id ?? ""} onChange={(event) => { const nextId = event.currentTarget.value; setAccountId(nextId); @@ -225,11 +336,20 @@ export function DepositScreen(props: { nextAccount.currencies?.includes(scope.currency), ) : scopes; - if (!nextScopes.some((scope) => scope.id === scopeId)) - setScopeId(nextScopes[0]?.id ?? ""); + if ( + !nextScopes.some( + (scope) => scope.id === selectedScope?.id, + ) + ) { + setScopeId(selectedScope?.id ?? scopeId); + setAmount(""); + } }} class="w-full rounded-xl border border-outline bg-surface px-3 py-3" > + {!selected && ( + <option value="">{i18n.str`Bank account`}</option> + )} {accounts.map((account) => ( <option key={account.id} value={account.id}> {account.label} @@ -248,7 +368,15 @@ export function DepositScreen(props: { <div class="mt-3"> <Button tone="secondary" - onClick={props.onManageAccounts} + onClick={() => + props.onManageAccounts?.({ + input: amount, + scopeId: selectedScope?.id ?? scopeId, + currency, + language, + savedAt: Date.now(), + }) + } >{i18n.str`Manage bank accounts`}</Button> </div> )} @@ -261,10 +389,11 @@ export function DepositScreen(props: { >{i18n.str`This account does not support any currency currently held by the wallet.`}</p> )} </Card> - </div> + </fieldset> <div class="flex justify-end gap-3"> <Button tone="secondary" + disabled={props.working} onClick={props.onCancel} >{i18n.str`Cancel`}</Button> <Button @@ -301,6 +430,14 @@ export function DepositScreen(props: { </Card> <Card> <dl class="grid grid-cols-2 gap-3 text-sm"> + {props.review.scopeLabel && ( + <> + <dt class="text-secondary">{i18n.str`Funding balance`}</dt> + <dd class="break-all text-right"> + {props.review.scopeLabel} + </dd> + </> + )} <dt class="text-secondary"> { // Translators: Requested face amount before wallet costs. @@ -329,17 +466,47 @@ export function DepositScreen(props: { <dd class="text-right">{props.review.refreshFee}</dd> </dl> </Card> + {needsAcknowledgment && ( + <Card class="space-y-3 border-warning bg-warningContainer"> + {props.review.creditDiffers && ( + <p>{i18n.str`The bank account is expected to receive ${props.review.effectiveAmount}. The payment link requested ${props.link!.suggestedAmount}.`}</p> + )} + <label class="flex items-start gap-2"> + <input + type="checkbox" + disabled={props.working} + checked={acknowledgment === acknowledgmentKey} + onChange={(e) => + setAcknowledgment( + e.currentTarget.checked ? acknowledgmentKey : "", + ) + } + /> + {i18n.str`I want to deposit with the amount and transfer details shown above.`} + </label> + </Card> + )} {props.review.kycWarning && ( <Card class="border-warning bg-warningContainer"> <p class="text-onWarningContainer">{props.review.kycWarning}</p> </Card> )} <div class="flex justify-end gap-3"> - <Button tone="secondary" onClick={props.onBack}>{ + <Button + tone="secondary" + disabled={props.working} + onClick={props.onBack} + >{ // Translators: Returns from review to editing the amount or destination. i18n.str`Change` }</Button> - <Button onClick={props.onConfirm} disabled={props.working}> + <Button + onClick={props.onConfirm} + disabled={ + props.working || + (needsAcknowledgment && acknowledgment !== acknowledgmentKey) + } + > {props.working ? /* Translators: A deposit sends digital cash from this wallet to an external account, usually a bank account; it does not add funds to the wallet. */ i18n.str`Depositing…` : /* Translators: A deposit sends digital cash from this wallet to an external account, usually a bank account; it does not add funds to the wallet. */ i18n.str`Confirm deposit`} diff --git a/packages/wallet-webui/src/ui/exchange-label.ts b/packages/wallet-webui/src/ui/exchange-label.ts @@ -1,8 +1,9 @@ -function exchangeHost(baseUrl: string): string { +export function scopeProviderLabel(baseUrl: string): string { try { - return new URL(baseUrl).host; + const url = new URL(baseUrl); + return url.host + url.pathname.replace(/\/$/, ""); } catch { - return baseUrl.replace(/^https?:\/\//i, "").replace(/\/.*$/, ""); + return baseUrl; } } @@ -13,13 +14,13 @@ function compactExchangeHost(host: string): string { /** * Apply the presentation-only inverse of DD69 in a constrained picker. * Canonical URLs remain the option values, and ambiguous compact labels fall - * back to their complete host names. + * back to their complete provider names. Paths identify separate exchanges on a host. */ export function exchangePickerLabels( baseUrls: readonly string[], ): ReadonlyMap<string, string> { const candidates = baseUrls.map((baseUrl) => { - const full = exchangeHost(baseUrl); + const full = scopeProviderLabel(baseUrl); return { baseUrl, full, compact: compactExchangeHost(full) }; }); const counts = new Map<string, number>(); diff --git a/packages/wallet-webui/test/deposit-model.test.ts b/packages/wallet-webui/test/deposit-model.test.ts @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { depositDestinationView } from "../src/routes/deposit-model.js"; +import { + depositDestinationView, + depositLinkInstructions, +} from "../src/routes/deposit-model.js"; test("deposit targets are presented by payto type without raw URIs", () => { const iban = depositDestinationView( @@ -98,3 +101,28 @@ test("invalid payto targets use an unavailable-details fallback", () => { assert.equal(view.summary, "Account details unavailable"); assert.deepEqual(view.fields, []); }); + +test("deposit links preserve payment instructions and parse protocol amounts independently of locale", () => { + const base = "payto://iban/CH9300762011623852957?"; + const uri = + base + + "amount=CHF%3A1%2C234.56&message=Order%20A&instruction=Part%202&ch-qrr=123"; + assert.deepEqual(depositLinkInstructions(uri), { + uri, + suggestedAmount: "CHF:1234.56", + invalidAmount: false, + references: ["Order A", "Part 2", "123"], + }); + for (const options of [ + "amount=CHF:1&amount=CHF:2", + "amount=CHF:0", + "amount=CHF:1.234567891", + "amount=", + ]) { + assert.equal( + depositLinkInstructions(base + options).invalidAmount, + true, + options, + ); + } +}); diff --git a/packages/wallet-webui/test/scope-model.test.ts b/packages/wallet-webui/test/scope-model.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { ScopeType } from "@gnu-taler/taler-util"; +import { exchangePickerLabels } from "../src/ui/exchange-label.js"; import { scopeFromIdentity, scopeIdentity, @@ -40,6 +41,23 @@ test("legacy-key balances remain a separate and visible scope", () => { assert.deepEqual(scopeFromIdentity(scopeIdentity(scope)), scope); }); +test("different exchange paths on a shared host identify the funding balance and withdrawal provider", () => { + const first = "https://exchange.example/north/"; + const second = "https://exchange.example/south/"; + const scope = { type: ScopeType.Exchange, currency: "CHF" } as const; + assert.equal( + scopeLabel({ ...scope, url: first }), + "CHF via exchange.example/north", + ); + assert.equal( + scopeLabel({ ...scope, url: second }), + "CHF via exchange.example/south", + ); + const labels = exchangePickerLabels([first, second]); + assert.equal(labels.get(first), "example/north"); + assert.equal(labels.get(second), "example/south"); +}); + test("scope identities recover global and auditor selections", () => { const global = { type: ScopeType.Global, currency: "CHF" } as const; const auditor = { diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -837,6 +837,10 @@ test("an action-provided payto starts with its destination selected", async () = /> </main>, ); + assert.equal( + (view.getByLabelText("Currency") as HTMLSelectElement).value, + "currency:EUR", + ); assert.equal(view.queryByLabelText("Bank account"), null); assert.equal(view.queryByLabelText("Destination payto URI"), null); assert.equal(view.getAllByText("Alice").length, 2); @@ -925,6 +929,7 @@ test("deposit uses an account-compatible wallet scope dropdown", async () => { .default as unknown as { setup(options: { document: Document }): { type(element: Element, text: string): Promise<void>; + selectOptions(element: Element, value: string): Promise<void>; click(element: Element): Promise<void>; }; }; @@ -980,14 +985,17 @@ test("deposit uses an account-compatible wallet scope dropdown", async () => { ); const currency = view.getByLabelText("Currency") as HTMLSelectElement; assert.equal(currency.tagName, "SELECT"); - assert.equal(currency.options.length, 1); + assert.equal(currency.value, ""); + assert.equal(currency.options.length, 2); + assert.ok(view.getByText(/selected balance is unavailable/i)); assert.equal( - currency.options[0]?.textContent, + currency.options[1]?.textContent, "EUR via exchange.example — EUR:8", ); const user = userEvent.setup({ document: window.document as unknown as Document, }); + await user.selectOptions(currency, "exchange:EUR:https://exchange.example/"); await user.type(view.getByLabelText("Amount"), "1"); await user.click(view.getByRole("button", { name: "Review deposit" })); assert.deepEqual(submittedScope, eurScope); @@ -1421,6 +1429,7 @@ test("Penpot balance view selects scopes, opens the balance list, and hands off assert(selectedTab.classList.contains("focus-visible:ring-inset")); await user.click(otherTab); assert.equal(selected.at(-1), "global:EUR"); + window.happyDOM.setWindowSize({ width: 390, height: 844 }); await user.click(view.getByRole("button", { name: "Show all balances" })); assert(view.getByRole("dialog", { name: "Balances" })); await user.click(view.getByRole("button", { name: /EUR 12\.00/ })); @@ -1429,7 +1438,6 @@ test("Penpot balance view selects scopes, opens the balance list, and hands off assert.equal(opened.at(-1), "txn:payment:recent"); await user.click(view.getByRole("button", { name: "Withdraw" })); assert.equal(withdrawalCurrency, "CHF"); - window.happyDOM.setWindowSize({ width: 390, height: 844 }); const result = await axe.run(window.document.body as unknown as Element); assert.deepEqual(result.violations, []); cleanup(); @@ -2523,6 +2531,64 @@ test("cash-acceptor withdrawal submits without an amount", async () => { await window.happyDOM.abort(); }); +test("a changed bank-link quote requires fresh acknowledgment", async () => { + const window = installDom(); + const { render, cleanup } = await import("@testing-library/preact"); + const userEvent = (await import("@testing-library/user-event")) + .default as unknown as { + setup(options: { document: Document }): { + click(element: Element): Promise<void>; + }; + }; + const user = userEvent.setup({ + document: window.document as unknown as Document, + }); + const uri = + "payto://iban/DE75512108001245126199?amount=EUR:2&message=Order%2042"; + const props = { + currency: "EUR", + loading: false, + working: false, + link: { + uri, + suggestedAmount: "EUR:2", + invalidAmount: false, + references: ["Order 42"], + }, + onReview: () => {}, + onConfirm: () => {}, + onBack: () => {}, + onCancel: () => {}, + }; + const review = { + amount: "EUR:2", + totalCost: "EUR:2", + effectiveAmount: "EUR:1.90", + coinFee: "EUR:0.10", + refreshFee: "EUR:0", + wireFee: "EUR:0", + scopeLabel: "EUR via selected.example", + creditDiffers: true, + destination: depositDestinationView(uri), + }; + const view = render(<DepositScreen {...props} review={review} />); + const confirm = view.getByRole("button", { + name: "Confirm deposit", + }) as HTMLButtonElement; + assert.ok(view.getByText("Order 42")); + assert.ok(view.getByText("EUR via selected.example")); + assert.ok(confirm.disabled); + await user.click(view.getByRole("checkbox")); + assert.equal(confirm.disabled, false); + view.rerender( + <DepositScreen {...props} review={{ ...review, totalCost: "EUR:2.01" }} />, + ); + assert.ok(confirm.disabled); + assert.equal((view.getByRole("checkbox") as HTMLInputElement).checked, false); + cleanup(); + await window.happyDOM.abort(); +}); + test("deposit review confirms the checked destination and amounts", async () => { const window = installDom(); const { render, cleanup } = await import("@testing-library/preact");