commit 52466e91ab92ef1ff76b5e41c6f50c388665b450 parent 419fb95a04a04a0b8336bd7bd447ec94bd4e6b12 Author: Florian Dold <dold@taler.net> Date: Wed, 25 Nov 2026 21:50:36 +0100 wallet web UI: show refund and order details before collection Read the merchant’s order status to show the amount still available and the total already collected. Let the customer open the original payment or cancel before starting refund collection. Issue: https://bugs.taler.net/n/10618 Diffstat:
12 files changed, 425 insertions(+), 88 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-refund-incremental.ts b/packages/taler-harness/src/integrationtests/test-refund-incremental.ts @@ -133,6 +133,17 @@ export async function runRefundIncrementalTest(t: GlobalTestState) { console.log("third refund increase response", ref); + const preview = await walletClient.call( + WalletApiOperation.GetRefundDetailsForUri, + { + talerRefundUri: ref.taler_refund_uri, + }, + ); + t.assertDeepEqual(preview.transactionId, payment.transactionId); + t.assertTrue(!!preview.details); + t.assertAmountEquals(preview.details.amountTaken, "TESTKUDOS:2.5"); + t.assertAmountEquals(preview.details.amountAvailable, "TESTKUDOS:7.5"); + { let wr = await walletClient.call(WalletApiOperation.StartRefundQuery, { transactionId: payment.transactionId, @@ -155,6 +166,14 @@ export async function runRefundIncrementalTest(t: GlobalTestState) { t.assertAmountEquals(orderStatus.refund_amount, "TESTKUDOS:10"); + const collected = await walletClient.call( + WalletApiOperation.GetRefundDetailsForUri, + { talerRefundUri: ref.taler_refund_uri }, + ); + t.assertTrue(!!collected.details); + t.assertAmountEquals(collected.details.amountAvailable, "TESTKUDOS:0"); + t.assertAmountEquals(collected.details.amountTaken, "TESTKUDOS:10"); + console.log(JSON.stringify(orderStatus, undefined, 2)); await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {}); diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-chrome-extension-refund.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-chrome-extension-refund.ts @@ -75,6 +75,8 @@ export async function runWalletWebUiChromeExtensionRefundDeletionTest( goto: (url) => page.goto(url), click: (name) => page.getByRole("button", { name, exact: true }).click(), + openLink: (name) => + page.getByRole("link", { name, exact: true }).click(), waitHeading: (name) => page.getByRole("heading", { name, exact: true }).waitFor(), waitText: (text) => diff --git a/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-withdrawal.ts b/packages/taler-harness/src/integrationtests/test-wallet-web-ui-pwa-withdrawal.ts @@ -357,7 +357,7 @@ async function runPwaWithdrawalTest( const input = page.getByLabel("Wallet link"); await input.fill("not a Taler link"); await page.getByRole("button", { name: "Open link" }).click(); - await page.getByText("Enter a valid taler:// wallet link.").waitFor(); + await page.getByText("Enter a valid taler:// or payto:// link.").waitFor(); await input.fill("taler://withdraw/bank.example/operation"); await input.press("Enter"); await page.getByRole("heading", { name: "Wallet action" }).waitFor(); @@ -868,8 +868,9 @@ async function runPwaWithdrawalTest( await page.goto(`${pwaUrl}#/enter`); await page.getByLabel("Wallet link").fill(refund.taler_refund_uri); await page.getByLabel("Wallet link").press("Enter"); - await page.getByRole("heading", { name: "Wallet action" }).waitFor(); - await page.getByRole("button", { name: "Continue" }).click(); + await page.getByRole("heading", { name: "Review refund" }).waitFor(); + await page.getByText(ageOrder.order_id, { exact: true }).waitFor(); + await page.getByRole("button", { name: "Collect refund" }).click(); await page.getByRole("heading", { name: "Default Instance" }).waitFor(); await page.getByText("Refunded", { exact: true }).waitFor({ timeout: 90_000, diff --git a/packages/taler-harness/src/integrationtests/wallet-web-ui-refund-test-support.ts b/packages/taler-harness/src/integrationtests/wallet-web-ui-refund-test-support.ts @@ -27,6 +27,7 @@ export interface RefundDeletionBrowser { walletUrl: string; goto(url: string): Promise<unknown>; click(label: string): Promise<unknown>; + openLink(label: string): Promise<unknown>; waitHeading(label: string | RegExp): Promise<unknown>; waitText(text: string): Promise<unknown>; textCount(text: string): Promise<number>; @@ -119,10 +120,26 @@ export async function exerciseBrowserRefundDeletion( reason: "Browser refund", }), ); - await browser.goto( - `${browser.walletUrl}?talerUri=${encodeURIComponent(refund.taler_refund_uri)}#/`, + const refundUrl = `${browser.walletUrl}?talerUri=${encodeURIComponent(refund.taler_refund_uri)}#/`; + await browser.goto(refundUrl); + await browser.waitHeading("Review refund"); + await browser.waitText("TESTKUDOS:5"); + await browser.waitText("Previously refunded"); + await browser.waitText("TESTKUDOS:0"); + await browser.waitText("Default Instance"); + await browser.waitText("Buy me!"); + await browser.waitText(created.order_id); + await browser.openLink("Full details"); + await browser.waitText("Purchase price"); + await browser.goto(refundUrl); + await browser.waitText(created.order_id); + await browser.click("Cancel"); + const afterCancel = succeedOrThrow( + await client.getOrderDetails(merchantAdminAccessToken, created.order_id), ); - await browser.click("Continue"); + assert.ok(afterCancel.order_status === "paid" && afterCancel.refund_pending); + await browser.goto(refundUrl); + await browser.click("Collect refund"); try { await browser.waitText("Purchase price"); } catch (cause) { diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts @@ -3414,6 +3414,21 @@ export interface PrepareRefundRequest { talerRefundUri: string; } +export interface GetRefundDetailsForUriResponse { + /** Original payment, or the retained refund transaction if the payment was deleted. */ + transactionId: TransactionIdStr; + /** Present when the merchant can report a refund offer for this payment. */ + details?: { + merchantName: string; + summary: string; + orderId: string; + /** Gross amount still available for collection. */ + amountAvailable: AmountString; + /** Cumulative gross amount already taken, as reported by the merchant. */ + amountTaken: AmountString; + }; +} + export interface StartRefundQueryForUriResponse { /** * Transaction id of the *payment* where the refund query was started. diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts @@ -115,6 +115,7 @@ import { setRefundGroupEffectiveAmount, splitPaymentOutputTokenSignatures, startRefundQueryForUri, + getRefundDetailsForUri, storeFirstPaySuccess, storeRefunds, validateClaimResponseBindings, @@ -1116,6 +1117,13 @@ for (const makeRunner of runnerFactories) { ); assert.strictEqual(response.transactionId, refundCtx.transactionId); + assert.deepStrictEqual( + await getRefundDetailsForUri( + wex, + "taler://refund/merchant.example/order/", + ), + response, + ); assert.deepStrictEqual(requestUrls, []); const groups = await runner.runReadWriteTx((tx) => tx.getRefundGroupsByProposal(proposalId), diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -59,6 +59,7 @@ import { ExchangeRefundRequest, ForcedCoinSel, GetChoicesForPaymentResult, + GetRefundDetailsForUriResponse, getRandomBytes, HashCodeString, hash, @@ -93,6 +94,7 @@ import { SelectedProspectiveCoin, SignedTokenEnvelope, StartRefundQueryForUriResponse, + StatusPaid, stringToBytes, TalerError, TalerErrorCode, @@ -6060,15 +6062,10 @@ export async function releasePaymentTokensInTx( } } -async function processPurchaseQueryRefund( +async function getMerchantRefundStatus( wex: WalletExecutionContext, - purchase: WalletPurchase, -): Promise<TaskRunResult> { - const proposalId = purchase.proposalId; - logger.trace(`processing query-refund for proposal ${proposalId}`); - - const download = await expectProposalDownload(wex, purchase); - + download: DownloadedContractData, +): Promise<StatusPaid | undefined> { const merchantClient = walletMerchantClient( download.contractTerms.merchant_base_url, wex, @@ -6080,9 +6077,36 @@ async function processPurchaseQueryRefund( }, ); + if (isOrderUnknown(resp)) return undefined; + if (resp.case !== "ok") { + throw TalerError.fromDetail( + TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR, + getHttpResponseErrorDetails(resp.response), + "expected paid order status", + ); + } + return resp.body; +} + +function availableRefundAmount(status: StatusPaid): AmountString { + return Amounts.stringify( + status.refund_pending + ? Amounts.sub(status.refund_amount, status.refund_taken).amount + : Amounts.zeroOfAmount(status.refund_amount), + ); +} + +async function processPurchaseQueryRefund( + wex: WalletExecutionContext, + purchase: WalletPurchase, +): Promise<TaskRunResult> { + const proposalId = purchase.proposalId; + logger.trace(`processing query-refund for proposal ${proposalId}`); + const download = await expectProposalDownload(wex, purchase); + const orderStatus = await getMerchantRefundStatus(wex, download); const ctx = new PayMerchantTransactionContext(wex, proposalId); - if (isOrderUnknown(resp)) { + if (!orderStatus) { // The merchant deleted the order, so it can never report a refund for it. // The payment itself remains valid, so the transaction goes back to being // a plain successful payment. @@ -6098,11 +6122,6 @@ async function processPurchaseQueryRefund( return TaskRunResult.progress(); } - if (resp.case !== "ok") { - throw Error(`expected paid order status, got HTTP ${resp.response.status}`); - } - const orderStatus = resp.body; - if (!orderStatus.refund_pending) { await wex.runWalletDbTx(async (tx) => { const [p, h] = await ctx.getRecordHandle(tx); @@ -6114,17 +6133,13 @@ async function processPurchaseQueryRefund( await h.update(p, "query-refund-done"); }); } else { - const refundAwaiting = Amounts.sub( - Amounts.parseOrThrow(orderStatus.refund_amount), - Amounts.parseOrThrow(orderStatus.refund_taken), - ).amount; - + const refundAwaiting = availableRefundAmount(orderStatus); await wex.runWalletDbTx(async (tx) => { const [p, h] = await ctx.getRecordHandle(tx); if (p?.purchaseStatus !== PurchaseStatus.PendingQueryingRefund) { return; } - p.refundAmountAwaiting = Amounts.stringify(refundAwaiting); + p.refundAmountAwaiting = refundAwaiting; p.purchaseStatus = PurchaseStatus.PendingAcceptRefund; await h.update(p, "query-refund-found"); }); @@ -6212,46 +6227,94 @@ function makeRefundTransactionId(refundGroupId: string): TransactionIdStr { }); } -export async function startRefundQueryForUri( - wex: WalletExecutionContext, +async function resolveRefundUriInTx( + tx: WalletDbTransaction, talerUri: string, -): Promise<StartRefundQueryForUriResponse> { +): Promise<{ transactionId: TransactionIdStr; purchase?: WalletPurchase }> { const parsedUri = TalerUris.parseRestrictedOrThrow( talerUri, TalerUriAction.Refund, ); + const purchase = await tx.getPurchaseByUrlAndOrderId( + parsedUri.merchantBaseUrl, + parsedUri.orderId, + ); + if (purchase) { + return { + purchase, + transactionId: constructTransactionIdentifier({ + tag: TransactionType.Payment, + proposalId: purchase.proposalId, + }), + }; + } + const matchingGroups = (await tx.listAllRefundGroups()).filter( + (group) => + group.purchaseSnapshot?.merchantBaseUrl === parsedUri.merchantBaseUrl && + group.purchaseSnapshot.orderId === parsedUri.orderId, + ); + const existingGroup = selectRelevantRefundGroup(matchingGroups); + if (!existingGroup) { + // The order may have been paid with a different wallet. + throw TalerError.fromDetail( + TalerErrorCode.WALLET_PURCHASE_NOT_FOUND, + { + merchantBaseUrl: parsedUri.merchantBaseUrl, + orderId: parsedUri.orderId, + }, + "no purchase found for the refund", + ); + } + return { + transactionId: makeRefundTransactionId(existingGroup.refundGroupId), + }; +} + +export async function getRefundDetailsForUri( + wex: WalletExecutionContext, + talerUri: string, +): Promise<GetRefundDetailsForUriResponse> { + const { transactionId, download } = await wex.runWalletDbTx(async (tx) => { + const { transactionId, purchase } = await resolveRefundUriInTx( + tx, + talerUri, + ); + const download = + purchase?.purchaseStatus === PurchaseStatus.Done + ? await expectProposalDownloadInTx(wex, tx, purchase) + : undefined; + return { transactionId, download }; + }); + if (!download) return { transactionId }; + const status = await getMerchantRefundStatus(wex, download); + if (!status) return { transactionId }; + const { merchant, summary, order_id } = download.contractTerms; + return { + transactionId, + details: { + merchantName: merchant.name, + summary, + orderId: order_id, + amountAvailable: availableRefundAmount(status), + amountTaken: status.refund_taken, + }, + }; +} + +export async function startRefundQueryForUri( + wex: WalletExecutionContext, + talerUri: string, +): Promise<StartRefundQueryForUriResponse> { return wex.runWalletDbTx(async (tx) => { - const purchase = await tx.getPurchaseByUrlAndOrderId( - parsedUri.merchantBaseUrl, - parsedUri.orderId, + const { purchase, transactionId } = await resolveRefundUriInTx( + tx, + talerUri, ); if (purchase) { const ctx = new PayMerchantTransactionContext(wex, purchase.proposalId); await startQueryRefundInTx(ctx, tx); - return { transactionId: ctx.transactionId }; - } - const matchingGroups = (await tx.listAllRefundGroups()).filter( - (group) => - group.purchaseSnapshot?.merchantBaseUrl === parsedUri.merchantBaseUrl && - group.purchaseSnapshot.orderId === parsedUri.orderId, - ); - const existingGroup = selectRelevantRefundGroup(matchingGroups); - if (!existingGroup) { - // Scanning a refund QR code for an order that was paid with a different - // wallet is a normal user mistake, so the caller must be able to tell it - // apart from an internal failure. - throw TalerError.fromDetail( - TalerErrorCode.WALLET_PURCHASE_NOT_FOUND, - { - merchantBaseUrl: parsedUri.merchantBaseUrl, - orderId: parsedUri.orderId, - }, - "no purchase found for the refund", - ); } - return { - transactionId: makeRefundTransactionId(existingGroup.refundGroupId), - }; + return { transactionId }; }); } diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -383,6 +383,7 @@ import { collectLeftoverClaims, confirmPay, getChoicesForPayment, + getRefundDetailsForUri, preparePayForTemplateV2, preparePayForUriV2, reclaimPayment, @@ -2884,6 +2885,10 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = { codec: codecForEmptyObject(), handler: handleTestingGetSampleTransactions, }, + [WalletApiOperation.GetRefundDetailsForUri]: { + codec: codecForPrepareRefundRequest(), + handler: (wex, req) => getRefundDetailsForUri(wex, req.talerRefundUri), + }, [WalletApiOperation.StartRefundQueryForUri]: { codec: codecForPrepareRefundRequest(), handler: (wex, req) => startRefundQueryForUri(wex, req.talerRefundUri), diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts @@ -92,6 +92,7 @@ import { GetBankingChoicesForPaytoResponse, GetChoicesForPaymentRequest, GetChoicesForPaymentResult, + GetRefundDetailsForUriResponse, GetCurrencySpecificationRequest, GetCurrencySpecificationResponse, GetDepositWireTypesRequest, @@ -330,6 +331,7 @@ export enum WalletApiOperation { UnclaimPayment = "unclaimPayment", ReclaimPayment = "reclaimPayment", CheckPayForTemplate = "checkPayForTemplate", + GetRefundDetailsForUri = "getRefundDetailsForUri", StartRefundQueryForUri = "startRefundQueryForUri", StartRefundQuery = "startRefundQuery", ConfirmPay = "confirmPay", @@ -995,7 +997,16 @@ export type ConfirmPayOp = { }; /** - * Check for a refund based on a taler://refund URI. + * Preview the merchant's refund offer without starting collection. + */ +export type GetRefundDetailsForUriOp = { + op: WalletApiOperation.GetRefundDetailsForUri; + request: PrepareRefundRequest; + response: GetRefundDetailsForUriResponse; +}; + +/** + * Start collecting a refund based on a taler://refund URI. */ export type StartRefundQueryForUriOp = { op: WalletApiOperation.StartRefundQueryForUri; @@ -1973,6 +1984,11 @@ export const walletApiExpectedErrors = { TalerErrorCode.WALLET_TRANSACTION_NOT_FOUND, TalerErrorCode.WALLET_REQUEST_TRANSACTION_STATE_UNSUPPORTED, ], + [WalletApiOperation.GetRefundDetailsForUri]: [ + TalerErrorCode.WALLET_TALER_URI_MALFORMED, + TalerErrorCode.WALLET_PURCHASE_NOT_FOUND, + TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR, + ], [WalletApiOperation.StartRefundQueryForUri]: [ TalerErrorCode.WALLET_TALER_URI_MALFORMED, TalerErrorCode.WALLET_PURCHASE_NOT_FOUND, @@ -2244,6 +2260,7 @@ export type WalletOperations = { [WalletApiOperation.ForceRefresh]: ForceRefreshOp; [WalletApiOperation.DeleteTransaction]: DeleteTransactionOp; [WalletApiOperation.RetryTransaction]: RetryTransactionOp; + [WalletApiOperation.GetRefundDetailsForUri]: GetRefundDetailsForUriOp; [WalletApiOperation.StartRefundQueryForUri]: StartRefundQueryForUriOp; [WalletApiOperation.StartRefundQuery]: StartRefundQueryOp; [WalletApiOperation.GetWithdrawalDetailsForAmount]: GetWithdrawalDetailsForAmountOp; diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -74,6 +74,7 @@ import { SettingsScreen, type DiagnosticsExportOptions, } from "../screens/SettingsScreen.js"; +import { RefundActionRoute } from "./RefundActionRoute.js"; import { RestoreBackupRoute } from "./RestoreBackupRoute.js"; import { StorybookScreen } from "../screens/StorybookScreen.js"; import { PaymentScreen } from "../screens/PaymentScreen.js"; @@ -195,7 +196,6 @@ import { import { cancelTransactionBeforeCompleting, restoreActionGateReason, - runGuardedValueOperation, unsupportedQrCodeHint, withdrawalTransferResultHint, } from "./action-model.js"; @@ -3178,9 +3178,7 @@ function ActionRoute() { const { connection, platform } = useServices(); const [, params] = useRoute("/action/:id"); const [, navigate] = useLocation(); - const callMutation = useWalletMutation(connection); const { controller: progressRequest } = useWalletProgress(connection); - const durability = useDurability(); const { mutate } = useSWRConfig(); const [entry, setEntry] = useState<Awaited<ReturnType<typeof platform.actionInbox.get>>>(); @@ -3407,35 +3405,6 @@ function ActionRoute() { navigate(`/transaction/${result.value.transactionId}`); void completeActionBestEffort(platform.actionInbox, entry.id); return; - } else if (parsed.value.type === TalerUriAction.Refund) { - const guarded = await runGuardedValueOperation( - () => durability.guardValueOperation(), - () => - callMutation( - WalletApiOperation.StartRefundQueryForUri, - { talerRefundUri: entry.uri }, - ["balances", "transactions"], - ), - ); - if (!guarded.started) { - setState("ready"); - return; - } - const result = guarded.value; - if (Result.isError(result)) { - setActionError( - walletCoreError( - result.detail, - /* Translators: wallet-core is the background wallet engine; keep the component name unchanged. */ i18n.str`Wallet-core could not prepare this refund.`, - ), - ); - setCanRetry(true); - setState("error"); - return; - } - navigate(`/transaction/${result.value.transactionId}`); - void completeActionBestEffort(platform.actionInbox, entry.id); - return; } else if ( parsed.value.type === TalerUriAction.PayPush || parsed.value.type === TalerUriAction.PayPull @@ -3499,6 +3468,14 @@ function ActionRoute() { } } }; + if ( + entry && + parsed && + Result.isOk(parsed) && + parsed.value.type === TalerUriAction.Refund + ) { + return <RefundActionRoute entry={entry} onCancel={discard} />; + } return ( <ActionScreen state={ diff --git a/packages/wallet-webui/src/routes/RefundActionRoute.tsx b/packages/wallet-webui/src/routes/RefundActionRoute.tsx @@ -0,0 +1,145 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { + Amounts, + Result, + type GetRefundDetailsForUriResponse, +} from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { useEffect, useRef, useState } from "preact/hooks"; +import { useLocation } from "wouter-preact"; +import type { ActionEntry } from "../api/contracts.js"; +import { useWalletMutation } from "../api/wallet.js"; +import { i18n } from "../i18n/runtime.js"; +import { completeActionBestEffort } from "../platform/action-inbox.js"; +import { useDurability } from "../platform/durability.js"; +import { ActionScreen } from "../screens/ActionScreen.js"; +import { RefundReviewScreen } from "../screens/RefundReviewScreen.js"; +import { + errorFromException, + walletCoreError, + type ErrorPresentation, +} from "../ui/error.js"; +import { runGuardedValueOperation } from "./action-model.js"; +import { useServices } from "./context.js"; + +export function RefundActionRoute({ + entry, + onCancel, +}: { + entry: ActionEntry; + onCancel: () => void; +}) { + const { connection, platform } = useServices(); + const [, navigate] = useLocation(); + const durability = useDurability(); + const callMutation = useWalletMutation(connection); + const [preview, setPreview] = useState<GetRefundDetailsForUriResponse>(); + const [error, setError] = useState<ErrorPresentation>(); + const [working, setWorking] = useState(false); + const [attempt, setAttempt] = useState(0); + const mounted = useRef(true); + + useEffect(() => { + let active = true; + mounted.current = true; + setPreview(undefined); + setError(undefined); + void connection.client + .call(WalletApiOperation.GetRefundDetailsForUri, { + talerRefundUri: entry.uri, + }) + .then((result) => { + if (!active) return; + if (!result.details) { + // A retained refund or a payment already being processed has its own transaction screen. + void completeActionBestEffort(platform.actionInbox, entry.id); + navigate(`/transaction/${result.transactionId}`, { replace: true }); + return; + } + setPreview(result); + }) + .catch((cause) => { + if (active) + setError( + errorFromException( + cause, + i18n.str`Wallet-core could not prepare this refund.`, + ), + ); + }); + return () => { + active = false; + mounted.current = false; + }; + }, [connection, entry, platform, navigate, attempt]); + + async function collect() { + if ( + working || + !preview?.details || + !Amounts.isNonZero(preview.details.amountAvailable) + ) + return; + setWorking(true); + try { + const guarded = await runGuardedValueOperation( + async () => (await durability.guardValueOperation()) && mounted.current, + () => + callMutation( + WalletApiOperation.StartRefundQueryForUri, + { talerRefundUri: entry.uri }, + ["balances", "transactions"], + ), + ); + if (!guarded.started) return; + const result = guarded.value; + if (Result.isError(result)) { + if (mounted.current) + setError( + walletCoreError( + result.detail, + i18n.str`Wallet-core could not prepare this refund.`, + ), + ); + return; + } + void completeActionBestEffort(platform.actionInbox, entry.id); + if (mounted.current) + navigate(`/transaction/${result.value.transactionId}`); + } catch (cause) { + if (mounted.current) + setError( + errorFromException(cause, i18n.str`Transaction action failed`), + ); + } finally { + if (mounted.current) setWorking(false); + } + } + + if (error) { + return ( + <ActionScreen + state="error" + error={error} + onRetry={() => setAttempt((n) => n + 1)} + onBack={() => navigate("/")} + onDiscard={onCancel} + onCancel={onCancel} + onContinue={() => {}} + /> + ); + } + return ( + <RefundReviewScreen + preview={preview} + working={working} + onCollect={() => void collect()} + onCancel={onCancel} + /> + ); +} diff --git a/packages/wallet-webui/src/screens/RefundReviewScreen.tsx b/packages/wallet-webui/src/screens/RefundReviewScreen.tsx @@ -0,0 +1,68 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { + Amounts, + type GetRefundDetailsForUriResponse, +} from "@gnu-taler/taler-util"; +import { i18n } from "../i18n/runtime.js"; +import { Button } from "../ui/Button.js"; +import { Card } from "../ui/Card.js"; +import { FocusedPage } from "../ui/FocusedPage.js"; + +export function RefundReviewScreen(props: { + preview?: GetRefundDetailsForUriResponse; + working: boolean; + onCollect: () => void; + onCancel: () => void; +}) { + const details = props.preview?.details; + const available = details && Amounts.isNonZero(details.amountAvailable); + return ( + <FocusedPage class="space-y-4"> + <h1 class="text-2xl font-medium">{i18n.str`Review refund`}</h1> + {details && props.preview ? ( + <Card> + <p class="text-sm text-secondary">{i18n.str`Refund available`}</p> + <p class="mt-1 text-3xl font-semibold">{details.amountAvailable}</p> + <dl class="mt-5 grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-3 text-sm"> + <dt class="text-secondary">{i18n.str`Previously refunded`}</dt> + <dd>{details.amountTaken}</dd> + <dt class="text-secondary">{i18n.str`Merchant`}</dt> + <dd class="break-words">{details.merchantName}</dd> + <dt class="text-secondary">{i18n.str`Order summary`}</dt> + <dd class="break-words">{details.summary}</dd> + <dt class="text-secondary">{i18n.str`Order ID`}</dt> + <dd class="break-all">{details.orderId}</dd> + </dl> + <a + class="mt-3 inline-block py-2 font-semibold text-primary underline" + href={`#/transaction/${props.preview.transactionId}`} + > + {i18n.str`Full details`} + </a> + </Card> + ) : ( + <p role="status">{i18n.str`Loading order details…`}</p> + )} + <div class="flex gap-3"> + {available && ( + <Button + disabled={props.working} + onClick={props.onCollect} + >{i18n.str`Collect refund`}</Button> + )} + <Button + tone="secondary" + disabled={props.working} + onClick={props.onCancel} + > + {details && !available ? i18n.str`Done` : i18n.str`Cancel`} + </Button> + </div> + </FocusedPage> + ); +}