commit e1425a652c155e1306665046992b42edd523da07
parent 71c39f0ab41c83c6f5490c5604e706d007912e6b
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 04:15:09 +0100
wallet-webui: show and confirm the selected price including fees
Switching currencies could leave product prices in the first currency
and the Pay button could omit fees. Use the chosen offer for both, pass
its full debit to wallet-core, and ask again if the choice changes
during confirmation.
Diffstat:
11 files changed, 230 insertions(+), 42 deletions(-)
diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx
@@ -4638,7 +4638,7 @@ function PaymentDialog(props: {
}
processing={props.processing}
returning={props.returning}
- paidAmount={transaction?.amountRaw}
+ paidAmount={transaction?.amountEffective}
onRetryObservation={onRetry}
confirmDisabled={!actions.canConfirm || props.cancelling}
merchantName={review?.merchantName ?? transaction?.info?.merchant.name}
@@ -4937,9 +4937,14 @@ function TransactionDetailView({
const transaction = useMemo(
() =>
observed
- ? transactionDetailView(observed, language, contract.terms)
+ ? transactionDetailView(
+ observed,
+ language,
+ contract.terms,
+ paymentDialog ? paymentReview : undefined,
+ )
: undefined,
- [language, observed, contract.terms],
+ [language, observed, contract.terms, paymentDialog, paymentReview],
);
if (
continuingTransfer &&
diff --git a/packages/wallet-webui/src/routes/order-model.ts b/packages/wallet-webui/src/routes/order-model.ts
@@ -21,7 +21,7 @@ function priceFor(
...(product.prices ?? []),
...(product.price ? [product.price] : []),
];
- if (!currency) return candidates[0];
+ if (!currency) return undefined;
return candidates.find(
(amount) => Amounts.parse(amount)?.currency === currency,
);
diff --git a/packages/wallet-webui/src/routes/payment-actions.ts b/packages/wallet-webui/src/routes/payment-actions.ts
@@ -6,6 +6,7 @@
import {
Result,
+ TalerErrorCode,
TransactionMajorState,
TransactionMinorState,
TransactionType,
@@ -91,6 +92,7 @@ export function usePaymentActions(
const snapshot =
view.snapshot?.type === TransactionType.Payment ? view.snapshot : undefined;
const transactionId = snapshot?.transaction.transactionId;
+ const [selectedChoice, setSelectedChoice] = useState<number>();
const review = useMemo(
() =>
snapshot?.payment && contract.terms
@@ -99,11 +101,11 @@ export function usePaymentActions(
snapshot.payment,
snapshot.currentDonauInfo,
language,
+ selectedChoice,
)
: undefined,
- [snapshot, contract.terms, language],
+ [snapshot, contract.terms, language, selectedChoice],
);
- const [selectedChoice, setSelectedChoice] = useState<number>();
const [useDonau, setUseDonau] = useState(false);
const [request, setRequest] = useState<PaymentRequest>();
const active = useRef<PaymentRequest>();
@@ -112,9 +114,9 @@ export function usePaymentActions(
view.ready &&
!!review &&
snapshot?.confirmation.unavailableReasons.length === 0;
- const latest = useRef({ snapshot, canConfirm, review });
- latest.current = { snapshot, canConfirm, review };
const choiceIndex = activePaymentChoiceIndex(review, selectedChoice);
+ const latest = useRef({ snapshot, canConfirm, review, choiceIndex });
+ latest.current = { snapshot, canConfirm, review, choiceIndex };
const recovery =
exchangeKeyRecoveryFromError(error?.detail) ??
exchangeKeyRecoveryFromError(snapshot?.transaction.error) ??
@@ -170,17 +172,30 @@ export function usePaymentActions(
setRequest(undefined);
}
};
- const confirm = async (collect = useDonau, index = choiceIndex) => {
+ const confirm = async (collect = useDonau, automatic = false) => {
+ const index = automatic ? review?.automaticChoiceIndex : choiceIndex;
+ const reviewedChoice = review?.choices.find(
+ (choice) => choice.index === index,
+ );
if (
active.current ||
!canConfirm ||
!transactionId ||
index === undefined ||
+ !reviewedChoice?.payable ||
paymentDeadlinePassed(review)
)
return;
const current = begin("confirm");
let success = false;
+ const showError = (error: ErrorPresentation) => {
+ setError(error);
+ if (
+ error.detail?.code === TalerErrorCode.WALLET_CORE_API_BAD_REQUEST &&
+ error.detail.parameter === "expectedAmountEffective"
+ )
+ view.retry();
+ };
try {
if (!(await durability.guardValueOperation())) return;
const latestView = latest.current;
@@ -194,7 +209,22 @@ export function usePaymentActions(
const choice = latestView.review?.choices.find(
(candidate) => candidate.index === index,
);
- if (!choice) return;
+ if (!choice?.payable) return;
+ if (
+ (automatic
+ ? latestView.review?.automaticChoiceIndex
+ : latestView.choiceIndex) !== index ||
+ choice.amountEffective !== reviewedChoice.amountEffective ||
+ choice.forceTokenSelection !== reviewedChoice.forceTokenSelection ||
+ (collect &&
+ choice.donationReceipt?.status !==
+ reviewedChoice.donationReceipt?.status)
+ ) {
+ setError({
+ message: i18n.str`The payment details changed. Review them before confirming.`,
+ });
+ return;
+ }
current.submitted = true;
setRequest({ ...current });
const result = await callMutation(
@@ -210,7 +240,7 @@ export function usePaymentActions(
);
if (!isActive(current)) return;
if (Result.isError(result))
- setError(
+ showError(
walletCoreError(
result.detail,
i18n.str`Wallet-core could not confirm this payment.`,
@@ -219,7 +249,7 @@ export function usePaymentActions(
else success = true;
} catch (cause) {
if (isActive(current))
- setError(
+ showError(
errorFromException(cause, i18n.str`Payment confirmation failed`),
);
} finally {
@@ -236,7 +266,7 @@ export function usePaymentActions(
)
return;
automaticStarted.current = true;
- void confirm(false, review.automaticChoiceIndex);
+ void confirm(false, true);
}, [options.automatic, canConfirm, review]);
const reclaim = async () => {
diff --git a/packages/wallet-webui/src/routes/payment-model.ts b/packages/wallet-webui/src/routes/payment-model.ts
@@ -36,6 +36,7 @@ export interface PaymentReviewView {
merchantLogo?: string;
summary: string;
order: OrderSummaryView;
+ displayChoice?: PaymentChoiceView;
minimumAge?: number;
payDeadlineMs?: number;
choices: PaymentChoiceView[];
@@ -55,6 +56,9 @@ export function paymentConfirmationRequest(
...(sessionId === undefined ? {} : { sessionId }),
transactionId,
choiceIndex,
+ ...(choice?.amountEffective !== undefined
+ ? { expectedAmountEffective: Amounts.stringify(choice.amountEffective) }
+ : {}),
...(choice?.forceTokenSelection ? { forcedTokenSel: true } : {}),
...(collectDonationReceipt &&
choice?.donationReceipt?.status === "available"
@@ -65,15 +69,14 @@ export function paymentConfirmationRequest(
/** Choose what the payment review should display and submit. */
export function activePaymentChoiceIndex(
- review: PaymentReviewView | undefined,
+ review: Pick<PaymentReviewView, "choices" | "defaultChoiceIndex"> | undefined,
selectedChoice: number | undefined,
): number | undefined {
- return (
- selectedChoice ??
- review?.defaultChoiceIndex ??
- review?.choices.find((choice) => choice.payable)?.index ??
- review?.choices[0]?.index
- );
+ if (!review || selectedChoice !== undefined) return selectedChoice;
+ if (review.defaultChoiceIndex !== undefined) return review.defaultChoiceIndex;
+ const payable = review.choices.filter((choice) => choice.payable);
+ if (payable.length > 1) return undefined;
+ return (payable[0] ?? review.choices[0])?.index;
}
/** Return the original payment that wallet-core is replaying for a repurchase. */
@@ -157,6 +160,7 @@ export function paymentReviewView(
result: ObservedPaymentChoices,
currentDonauInfo?: { donauBaseUrl: string },
language = "en",
+ selectedChoice?: number,
): PaymentReviewView {
const contractChoices =
terms.version === MerchantContractVersion.V1 ? terms.choices : undefined;
@@ -293,6 +297,12 @@ export function paymentReviewView(
: choices.find(
(choice) => choice.index === result.automaticExecutableIndex,
);
+ const displayIndex = activePaymentChoiceIndex(
+ { choices, defaultChoiceIndex: result.defaultChoiceIndex },
+ selectedChoice,
+ );
+ const displayChoice =
+ displayIndex === undefined ? undefined : choices[displayIndex];
const merchantAddress = merchantAddressView(terms.merchant.address);
return {
merchantName: terms.merchant.name,
@@ -302,9 +312,10 @@ export function paymentReviewView(
...(merchantAddress ? { merchantAddress } : {}),
...(terms.merchant.logo ? { merchantLogo: terms.merchant.logo } : {}),
summary: terms.summary,
+ displayChoice,
order: orderSummaryView(
terms,
- Amounts.parse(choices[0]?.amountRaw ?? "")?.currency,
+ displayChoice ? Amounts.currencyOf(displayChoice.amountRaw) : undefined,
),
...(typeof terms.pay_deadline?.t_s === "number"
? { payDeadlineMs: terms.pay_deadline.t_s * 1000 }
diff --git a/packages/wallet-webui/src/routes/transaction-model.ts b/packages/wallet-webui/src/routes/transaction-model.ts
@@ -10,7 +10,7 @@ import {
type MerchantContractTerms,
} from "@gnu-taler/taler-util";
import { parseTransactionIdentifier } from "@gnu-taler/taler-wallet-core";
-import { safeWebUrl } from "./payment-model.js";
+import { safeWebUrl, type PaymentReviewView } from "./payment-model.js";
import type { OrderSummaryView } from "../ui/OrderSummary.js";
import { orderSummaryView } from "./order-model.js";
import { depositDestinationView } from "./deposit-model.js";
@@ -401,21 +401,24 @@ export function transactionErrorPresentation(
);
}
-function fieldsFor(transaction: ObservedTransaction): TransactionDetailField[] {
+function fieldsFor(
+ transaction: ObservedTransaction,
+ review?: PaymentReviewView,
+): TransactionDetailField[] {
const fields: TransactionDetailField[] = [];
switch (transaction.type) {
- case TransactionType.Payment:
- if (transaction.info) {
- fields.push(
- {
- label: /* Translators: The nominal order price, before additional wallet payment fees. */ i18n.str`Purchase price`,
- value: transaction.amountRaw,
- },
- {
+ case TransactionType.Payment: {
+ const amounts = review ? review.displayChoice : transaction;
+ if (transaction.info && amounts) {
+ fields.push({
+ label: /* Translators: The nominal order price, before additional wallet payment fees. */ i18n.str`Purchase price`,
+ value: amounts.amountRaw,
+ });
+ if (amounts.amountEffective)
+ fields.push({
label: i18n.str`Wallet spends`,
- value: transaction.amountEffective,
- },
- );
+ value: amounts.amountEffective,
+ });
}
if (transaction.info?.orderId)
fields.push({
@@ -434,6 +437,7 @@ function fieldsFor(transaction: ObservedTransaction): TransactionDetailField[] {
value: transaction.refundPending,
});
break;
+ }
case TransactionType.Refund:
fields.push(
{ label: i18n.str`Refund amount`, value: transaction.amountRaw },
@@ -744,6 +748,7 @@ export function transactionDetailView(
transaction: ObservedTransaction,
language?: string,
contractTerms?: MerchantContractTerms,
+ review?: PaymentReviewView,
): TransactionDetailView {
const base = transactionHistoryView(transaction, language);
const state = transactionStateView(transaction);
@@ -841,10 +846,11 @@ export function transactionDetailView(
: undefined;
const order =
transaction.type === TransactionType.Payment && contractTerms
- ? orderSummaryView(
+ ? (review?.order ??
+ orderSummaryView(
contractTerms,
Amounts.parse(transaction.amountRaw)?.currency,
- )
+ ))
: undefined;
const technicalFields: TransactionDetailField[] = [];
if (transaction.type === TransactionType.Refresh) {
@@ -902,6 +908,12 @@ export function transactionDetailView(
const error = transactionErrorPresentation(transaction);
return {
...base,
+ ...(review
+ ? {
+ amount: review.displayChoice?.amountEffective ?? "—",
+ amountUnavailable: !review.displayChoice?.amountEffective,
+ }
+ : {}),
...(transaction.localTransactionId
? { localId: transaction.localTransactionId }
: {}),
@@ -910,7 +922,7 @@ export function transactionDetailView(
? i18n.str`Waiting for review`
: state.detail,
fields: [
- ...fieldsFor(transaction),
+ ...fieldsFor(transaction, review),
...(transaction.amountEffectiveFinal !== undefined
? [
{
diff --git a/packages/wallet-webui/src/screens/PaymentScreen.tsx b/packages/wallet-webui/src/screens/PaymentScreen.tsx
@@ -252,6 +252,7 @@ export function PaymentOptions(props: {
<legend class="mb-2 font-semibold">{
/* Translators: Alternative offers for the same purchase, possibly with different prices or required merchant-issued tokens. */ i18n.str`Payment options`
}</legend>
+ {!selected && <p>{i18n.str`Choose a payment option to continue.`}</p>}
{props.choices.map((choice) => (
<label
key={choice.index}
@@ -470,7 +471,7 @@ export function PaymentOptions(props: {
: i18n.str`Paying…`
: selected
? // Translators: Button label; the placeholder is a fully formatted payment amount.
- i18n.str`Pay ${selected.amountRaw}`
+ i18n.str`Pay ${selected.amountEffective ?? selected.amountRaw}`
: i18n.str`Pay`}
</span>
</Button>
diff --git a/packages/wallet-webui/src/ui/error.ts b/packages/wallet-webui/src/ui/error.ts
@@ -22,6 +22,10 @@ export function localError(message: string): ErrorPresentation {
function errorMessage(detail: TalerErrorDetail, fallback: string): string {
switch (detail.code) {
+ case TalerErrorCode.WALLET_CORE_API_BAD_REQUEST:
+ return detail.parameter === "expectedAmountEffective"
+ ? i18n.str`The payment details changed. Review them before confirming.`
+ : fallback;
case TalerErrorCode.WALLET_ORDER_ALREADY_CLAIMED:
return /* Translators: Claiming a merchant order assigns it to a wallet for payment; it does not mean that payment has completed. */ i18n.str`This order was already claimed by another wallet.`;
case TalerErrorCode.WALLET_ORDER_ALREADY_PAID:
diff --git a/packages/wallet-webui/test/payment-model.test.ts b/packages/wallet-webui/test/payment-model.test.ts
@@ -105,6 +105,7 @@ test("payment confirmation always returns immediately", () => {
index: 2,
description: "Donation",
amountRaw: "CHF:5",
+ amountEffective: "CHF:5.25",
payable: true,
forceTokenSelection: true,
inputs: [],
@@ -119,6 +120,7 @@ test("payment confirmation always returns immediately", () => {
{
transactionId: "txn:payment:test",
choiceIndex: 2,
+ expectedAmountEffective: "CHF:5.25",
forcedTokenSel: true,
useDonau: true,
noWait: true,
@@ -336,6 +338,35 @@ test("payment review preserves core choice availability", () => {
assert.equal(safeWebUrl("javascript:alert(1)"), false);
});
+test("product prices follow the payer's explicit choice across currencies", () => {
+ const terms = {
+ version: MerchantContractVersion.V1,
+ summary: "Lunch",
+ merchant: { name: "Cafe" },
+ products: [{ description: "Soup", prices: ["CHF:5", "EUR:6"] }],
+ choices: ["CHF:5", "EUR:6"].map((amount) => ({
+ amount,
+ inputs: [],
+ outputs: [],
+ })),
+ } as unknown as NonNullable<TransactionPayment["contractTerms"]>;
+ const choices = {
+ choices: ["CHF:5", "EUR:6"].map((amountRaw) => ({
+ status: ChoiceSelectionDetailType.PaymentPossible,
+ amountRaw,
+ amountEffective: amountRaw,
+ })),
+ } as GetChoicesForPaymentResult;
+ const review = paymentReviewView(terms, choices);
+ assert.equal(activePaymentChoiceIndex(review, undefined), undefined);
+ assert.equal(review.order.products[0].price, undefined);
+ assert.equal(
+ paymentReviewView(terms, choices, undefined, "en", 1).order.products[0]
+ .price,
+ "EUR:6",
+ );
+});
+
test("payment review selects merchant token descriptions for the active language", () => {
const transaction = {
contractTerms: {
diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx
@@ -4000,14 +4000,14 @@ test("transaction details confirm a payment and expose insufficient balance acti
const user = userEvent.setup({
document: window.document as unknown as Document,
});
- await user.click(view.getByRole("button", { name: "Pay CHF:5" }));
+ await user.click(view.getByRole("button", { name: "Pay CHF:5.10" }));
assert.equal(confirmed, true);
assert.equal(view.queryByRole("button", { name: "Cancel" }), null);
view.rerender(renderDetail(false));
assert(view.getByRole("alert").textContent?.includes("CHF:2"));
assert(
- view.getByRole("button", { name: "Pay CHF:5" }).hasAttribute("disabled"),
+ view.getByRole("button", { name: "Pay CHF:5.10" }).hasAttribute("disabled"),
);
await user.click(view.getByRole("button", { name: "Withdraw funds" }));
assert.equal(withdrew, true);
diff --git a/packages/wallet-webui/test/transaction-model.test.ts b/packages/wallet-webui/test/transaction-model.test.ts
@@ -379,6 +379,52 @@ test("payment details include the Penpot order summary when contract terms are r
});
});
+test("proposed payment history shows only amounts for the selected offer", () => {
+ const tx = payment({
+ txState: {
+ major: TransactionMajorState.Dialog,
+ minor: TransactionMinorState.Proposed,
+ working: false,
+ },
+ });
+ const review = {
+ order: { summary: "Entry", products: [] },
+ summary: "Entry",
+ merchantName: "Museum",
+ choices: [],
+ };
+ const selected = {
+ index: 1,
+ description: "Euros",
+ amountRaw: "EUR:6",
+ amountEffective: "EUR:6.20",
+ payable: true,
+ inputs: [],
+ outputs: [],
+ };
+ const empty = transactionDetailView(tx, "en", undefined, review);
+ assert.equal(empty.amount, "—");
+ assert.ok(
+ !empty.fields.some(
+ (field) =>
+ field.label === "Wallet spends" || field.label === "Purchase price",
+ ),
+ );
+ const chosen = transactionDetailView(tx, "en", undefined, {
+ ...review,
+ displayChoice: selected,
+ });
+ assert.equal(chosen.amount, "EUR:6.20");
+ assert.equal(
+ chosen.fields.find((field) => field.label === "Wallet spends")?.value,
+ "EUR:6.20",
+ );
+ assert.equal(
+ chosen.fields.find((field) => field.label === "Purchase price")?.value,
+ "EUR:6",
+ );
+});
+
test("external transaction actions require a safe URL and non-final state", () => {
const unsafe = transactionDetailView(
payment({ kycUrl: "javascript:alert(1)" }),
diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx
@@ -89,13 +89,15 @@ async function harness(
| "bank-withdrawal",
fulfillmentUrl?: string,
payDeadlineSeconds?: number,
+ withStoragePrompt = false,
) {
const dom = installRouteDom();
const { render, cleanup, act } = await import("@testing-library/preact");
const { SWRConfig } = await import("swr");
const { App } = await import("../src/routes/App.js");
const services = createDemoServices();
- Object.assign(services.platform, { target: "chrome" });
+ if (!withStoragePrompt)
+ Object.assign(services.platform, { target: "chrome" });
const entry = await services.platform.actionInbox.put(
kind === "bank-withdrawal"
? demoActionUris.withdrawal
@@ -353,7 +355,7 @@ async function harness(
: `#/pay/${transactionId}/${entry.id}`;
const view = render(
<SWRConfig value={{ provider: () => new Map(), shouldRetryOnError: false }}>
- <App {...services} />
+ <App {...services} demo={withStoragePrompt ? undefined : services.demo} />
</SWRConfig>,
);
const waitFor = async (check: () => void) => {
@@ -922,6 +924,51 @@ for (const route of ["payment-review", "payment-review-details"] as const) {
});
}
+test("a changed debit during the storage prompt requires another confirmation", async () => {
+ const h = await harness("payment-review", undefined, undefined, true);
+ try {
+ await h.act(async () => h.releaseDocument());
+ const pay = () => h.view.getByRole("button", { name: /^Pay CHF:/ });
+ await h.waitFor(() => assert.ok(pay()));
+ await h.act(() => pay().click());
+ const approve = () =>
+ h.view.getByRole("button", { name: "Continue without protection" });
+ await h.waitFor(() => assert.ok(approve()));
+ const snapshot = h.readySnapshot;
+ assert.ok(snapshot.type === TransactionType.Payment && snapshot.payment);
+ await h.act(async () =>
+ h.publish({
+ ...snapshot,
+ payment: {
+ ...snapshot.payment!,
+ choices: snapshot.payment!.choices.map((choice) => ({
+ ...choice,
+ amountEffective: "CHF:7.5",
+ })),
+ },
+ }),
+ );
+ await h.act(() => approve().click());
+ await h.waitFor(() =>
+ assert.ok(
+ h.view.getByText(
+ "The payment details changed. Review them before confirming.",
+ ),
+ ),
+ );
+ assert.equal(h.paymentRequests.length, 0);
+ await h.act(() => pay().click());
+ await h.waitFor(() => assert.equal(h.paymentRequests.length, 1));
+ assert.equal(
+ (h.paymentRequests[0].args as { expectedAmountEffective: string })
+ .expectedAmountEffective,
+ "CHF:7.5",
+ );
+ } finally {
+ await h.close();
+ }
+});
+
test("checkout keeps a submitted payment in progress past its deadline", async (t) => {
let now = Math.floor(Date.now() / 1000) * 1000;
t.mock.method(Date, "now", () => now);
@@ -1334,6 +1381,7 @@ for (const route of ["payment-review", "payment-review-details"] as const) {
...(route === "payment-review" ? { sessionId: "session" } : {}),
transactionId: h.transactionId,
choiceIndex: 0,
+ expectedAmountEffective: "CHF:5.1",
noWait: true,
});
const initial = h.readySnapshot;