taler-typescript-core

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

commit f09ad203cc8b653fb2d4aaf58ac1eb5a71c02ff6
parent 9412b54c7eade1da709cf8effbf8b2f75d5d42c5
Author: Florian Dold <dold@taler.net>
Date:   Wed, 11 Nov 2026 11:39:28 +0100

wallet-webui: observe payments

Diffstat:
Mpackages/wallet-webui/src/routes/App.tsx | 699++++++++++++++++++++++---------------------------------------------------------
Mpackages/wallet-webui/src/routes/payment-model.ts | 8--------
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 539+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 735 insertions(+), 511 deletions(-)

diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -1,12 +1,12 @@ -import { usePaymentActions } from "./payment-actions.js"; +import { usePaymentActions, type PaymentActions } from "./payment-actions.js"; import { peerCreditConfirmationView } from "./peer-credit-review-model.js"; import { useTransactionObservation, usePaymentContract, type TransactionObservationView, + type PaymentContractView, } from "../api/observations.js"; import { - ConfirmPayResultType, Amounts, ExchangeTosStatus, Paytos, @@ -24,7 +24,6 @@ import { import type { AcceptManualWithdrawalResult, PrepareBankIntegratedWithdrawalResponse, - TransactionPayment, AmountString, CheckDepositResponse, ScopeInfo, @@ -47,7 +46,6 @@ import { import { useHashLocation } from "wouter-preact/use-hash-location"; import { useSWRConfig } from "swr"; import { isWalletKey } from "../api/canonical.js"; -import type { ExternalNavigationTarget } from "../api/contracts.js"; import type { AppServices } from "./context.js"; import { ServicesContext, useServices } from "./context.js"; import { operationsForNotification } from "../api/notifications.js"; @@ -121,9 +119,6 @@ import { } from "../ui/error.js"; import { connectionStatus } from "../stores/ui.js"; import { - activePaymentChoiceIndex, - paymentConfirmationRequest, - paymentReviewView, paymentRepurchaseTarget, paymentResultState, safeWebUrl, @@ -4204,7 +4199,7 @@ function PaymentRoute() { const callMutation = useWalletMutation(connection); const [, params] = useRoute("/pay/:transactionId/:actionId"); const [, navigate] = useLocation(); - const transactionId = params?.transactionId ?? ""; + const transactionId = (params?.transactionId ?? "") as TransactionIdStr; const actionId = params?.actionId ?? ""; const { fulfillmentTarget, @@ -4214,88 +4209,68 @@ function PaymentRoute() { const [actionError, setActionError] = useState<ErrorPresentation>(); const [resuming, setResuming] = useState(false); const [cancelling, setCancelling] = useState(false); - const [reclaiming, setReclaiming] = useState(false); - const query = useWalletQuery( - connection, - WalletApiOperation.GetTransactionById, - { transactionId, includeContractTerms: true }, + const view = useTransactionObservation(connection, transactionId); + const snapshot = + view.snapshot?.type === TransactionType.Payment ? view.snapshot : undefined; + const payment = snapshot?.transaction; + const contract = usePaymentContract(connection, payment, view.ready); + const actions = usePaymentActions( + view, + contract, + actionError, + setActionError, + { automatic: fulfillmentTarget !== undefined }, ); - const payment = - query.data?.type === TransactionType.Payment ? query.data : undefined; - const reclaim = async () => { - if (reclaiming) return; - setReclaiming(true); - setActionError(undefined); - try { - const result = await callMutation( - WalletApiOperation.ReclaimPayment, - { transactionId: transactionId as TransactionIdStr }, - ["transactions"], - ); - if (Result.isError(result)) { - setActionError( - walletCoreError( - result.detail, - i18n.str`The payment could not continue with this wallet.`, - ), - ); - } - } catch (cause) { - setActionError( - errorFromException( - cause, - i18n.str`Continuing the payment with this wallet failed.`, - ), - ); - } finally { - setReclaiming(false); - } - }; const repurchaseTransactionId = paymentRepurchaseTarget(payment); - const repurchaseQuery = useWalletQuery( + const repurchaseView = useTransactionObservation( connection, - WalletApiOperation.GetTransactionById, - { - transactionId: repurchaseTransactionId ?? "", - includeContractTerms: false, - }, - { enabled: repurchaseTransactionId !== undefined }, + repurchaseTransactionId, ); const replayPayment = - repurchaseQuery.data?.type === TransactionType.Payment - ? repurchaseQuery.data + repurchaseView.snapshot?.transaction?.type === TransactionType.Payment + ? repurchaseView.snapshot?.transaction : undefined; const paymentActionTransactionId = replayPayment?.transactionId ?? transactionId; - const paymentDone = - payment !== undefined && - paymentResultState(payment, replayPayment) === "done"; - const fulfillmentUrl = payment?.contractTerms?.fulfillment_url; + const resultState = payment + ? paymentResultState(payment, replayPayment) + : "pending"; + const paymentDone = !!payment && resultState === "done"; + const fulfillmentUrl = payment?.info?.fulfillmentUrl; + const completionReady = + view.ready && + !!payment?.info && + (!repurchaseTransactionId || repurchaseView.ready); + useEffect(() => { + if (paymentDone && completionReady) void completePayment(fulfillmentUrl); + }, [completePayment, completionReady, fulfillmentUrl, paymentDone]); + const pendingActionCompleted = useRef(false); useEffect(() => { - if (paymentDone) void completePayment(fulfillmentUrl); - }, [completePayment, fulfillmentUrl, paymentDone]); - const waitingForContract = + if ( + !view.ready || + !payment || + fulfillmentTarget === undefined || + browserCheckout || + resultState !== "pending" || + payment.txState.minor === TransactionMinorState.ClaimProposal || + pendingActionCompleted.current + ) + return; + pendingActionCompleted.current = true; + void completeActionBestEffort(platform.actionInbox, actionId); + }, [ + view.ready, + payment, + fulfillmentTarget, + browserCheckout, + resultState, + platform, + actionId, + ]); + const waitingForClaim = payment?.txState.minor === TransactionMinorState.ClaimProposal && payment.txState.working === true && - !payment.contractTerms; - const refreshPayment = query.mutate; - useEffect(() => { - if (!waitingForContract) return; - let active = true; - let timer: number | undefined; - const refresh = async () => { - try { - await refreshPayment(); - } finally { - if (active) timer = window.setTimeout(() => void refresh(), 250); - } - }; - timer = window.setTimeout(() => void refresh(), 250); - return () => { - active = false; - if (timer !== undefined) window.clearTimeout(timer); - }; - }, [refreshPayment, waitingForContract]); + !payment.info; const completeAndReturn = () => { void completeActionBestEffort(platform.actionInbox, actionId); navigate("/"); @@ -4326,7 +4301,7 @@ function PaymentRoute() { setResuming(false); } }; - const cancelPausedPayment = async () => { + const cancelPayment = async () => { if (resuming || cancelling) return; setCancelling(true); setActionError(undefined); @@ -4334,7 +4309,9 @@ function PaymentRoute() { const outcome = await cancelTransactionBeforeCompleting( () => callMutation( - WalletApiOperation.AbortTransaction, + payment?.txState.major === TransactionMajorState.Dialog + ? WalletApiOperation.DeleteTransaction + : WalletApiOperation.AbortTransaction, { transactionId: paymentActionTransactionId }, ["balances", "transactions"], ), @@ -4359,10 +4336,15 @@ function PaymentRoute() { setCancelling(false); } }; - if (query.isLoading || waitingForContract || fulfillmentTarget === undefined) + if (view.error || (view.snapshot && !snapshot)) return ( <PaymentScreen - state="loading" + onRetryObservation={view.canRetry ? view.retry : undefined} + state="error" + error={errorFromException( + view.error, + i18n.str`The payment transaction is unavailable.`, + )} onSelectChoice={() => {}} onConfirm={() => {}} onWithdraw={() => navigate("/withdraw")} @@ -4371,14 +4353,16 @@ function PaymentRoute() { onOpenFulfillment={() => {}} /> ); - if (query.error || !query.data || query.data.type !== TransactionType.Payment) + if ( + view.loading || + waitingForClaim || + fulfillmentTarget === undefined || + !payment + ) return ( <PaymentScreen - state="error" - error={errorFromException( - query.error, - i18n.str`The payment transaction is unavailable.`, - )} + onRetryObservation={view.canRetry ? view.retry : undefined} + state="loading" onSelectChoice={() => {}} onConfirm={() => {}} onWithdraw={() => navigate("/withdraw")} @@ -4387,12 +4371,13 @@ function PaymentRoute() { onOpenFulfillment={() => {}} /> ); - const transaction = query.data; - const terms = transaction.contractTerms; - if (!terms) { + const transaction = payment; + const terms = contract.terms; + if (!transaction.info) { const claimError = transactionErrorPresentation(transaction); return ( <PaymentScreen + onRetryObservation={view.canRetry ? view.retry : undefined} state="error" error={ claimError ?? @@ -4414,42 +4399,50 @@ function PaymentRoute() { ) return ( <PaymentScreen + onRetryObservation={view.canRetry ? view.retry : undefined} state="handoff" - merchantName={terms.merchant.name} + merchantName={transaction.info.merchant.name} talerPayUri={transaction.unclaimedPayUri} error={actionError} - reclaiming={reclaiming} + reclaiming={actions.reclaiming} onSelectChoice={() => {}} onConfirm={() => {}} onWithdraw={() => navigate("/withdraw")} onBack={completeAndReturn} onCancel={completeAndReturn} onOpenFulfillment={() => {}} - onReclaim={() => void reclaim()} + onReclaim={() => void actions.reclaim()} /> ); if (transaction.txState.major === TransactionMajorState.Dialog) return ( <PaymentDialog - transaction={transaction} + view={view} + contract={contract} + transactionId={transaction.transactionId} actionId={actionId} - fulfillmentTarget={fulfillmentTarget} - browserCheckout={Boolean(browserCheckout)} - onPaymentDone={completePayment} + actions={actions} + error={actionError} + cancelling={cancelling} + onCancel={() => void cancelPayment()} + onBack={completeAndReturn} /> ); - const resultState = paymentResultState(transaction, replayPayment); const statusTransaction = repurchaseTransactionId ? (replayPayment ?? transaction) : transaction; + const recovery = + actions.recovery ?? exchangeKeyRecoveryFromError(statusTransaction.error); const statusFallback = /* Translators: %1$s is a translated transaction-status label, which may be a phrase rather than an adjective. */ i18n.str`Payment status: ${transactionStateView(statusTransaction).label}`; const repurchaseError = - repurchaseQuery.error && repurchaseTransactionId + repurchaseView.error && repurchaseTransactionId ? errorFromException( - repurchaseQuery.error, + repurchaseView.error, i18n.str`The payment transaction is unavailable.`, ) - : repurchaseTransactionId && repurchaseQuery.data && !replayPayment + : repurchaseTransactionId && + repurchaseView.snapshot?.transaction && + !replayPayment ? localError(i18n.str`The payment transaction is unavailable.`) : undefined; const terminalError = @@ -4465,17 +4458,48 @@ function PaymentRoute() { : undefined; return ( <PaymentScreen + onRetryObservation={ + repurchaseView.canRetry + ? repurchaseView.retry + : view.canRetry + ? view.retry + : undefined + } state={repurchaseError ? "error" : resultState} - merchantName={terms.merchant.name} - merchantWebsite={terms.merchant.website} - summary={terms.summary} - minimumAge={terms.minimum_age} - fulfillmentMessage={terms.fulfillment_message} - fulfillmentUrl={ - safeWebUrl(terms.fulfillment_url) ? terms.fulfillment_url : undefined + contractLoading={contract.loading} + contractError={ + contract.error + ? errorFromException( + contract.error, + i18n.str`The payment contract details are unavailable.`, + ) + : undefined + } + onRetryContract={ + view.ready && contract.error ? contract.retry : undefined } + merchantName={transaction.info.merchant.name} + merchantWebsite={transaction.info.merchant.website} + summary={transaction.info.summary} + minimumAge={terms?.minimum_age} + fulfillmentMessage={ + terms?.fulfillment_message ?? transaction.info.fulfillmentMessage + } + fulfillmentUrl={safeWebUrl(fulfillmentUrl) ? fulfillmentUrl : undefined} posConfirmation={transaction.posConfirmation} error={repurchaseError ?? pausedError ?? terminalError} + recoveryActionLabel={recovery?.actionLabel} + onRecoveryAction={ + recovery + ? () => + navigate( + exchangeRecoveryRoute( + recovery, + `/pay/${transactionId}/${actionId}`, + ), + ) + : undefined + } resuming={resuming} cancelling={cancelling} onSelectChoice={() => {}} @@ -4485,12 +4509,12 @@ function PaymentRoute() { onBack={completeAndReturn} onCancel={ resultState === "paused" - ? () => void cancelPausedPayment() + ? () => void cancelPayment() : completeAndReturn } onOpenFulfillment={() => { - if (safeWebUrl(terms.fulfillment_url)) - void platform.openExternal(terms.fulfillment_url, fulfillmentTarget); + if (safeWebUrl(fulfillmentUrl)) + void platform.openExternal(fulfillmentUrl, fulfillmentTarget); }} onCopyPosConfirmation={(code) => void navigator.clipboard.writeText(code)} /> @@ -4498,376 +4522,56 @@ function PaymentRoute() { } function PaymentDialog(props: { - transaction: TransactionPayment; + view: TransactionObservationView; + contract: PaymentContractView; + actions: PaymentActions; + transactionId: TransactionIdStr; actionId: string; - fulfillmentTarget: ExternalNavigationTarget; - browserCheckout: boolean; - onPaymentDone: (url?: string) => Promise<void>; + error?: ErrorPresentation; + cancelling: boolean; + onCancel: () => void; + onBack: () => void; }) { - const { browserCheckout, onPaymentDone } = props; - const { connection, platform } = useServices(); - const { language } = useLanguage(); + const { view, contract, actions } = props; const [, navigate] = useLocation(); - const callMutation = useWalletMutation(connection); - const { controller: unclaimRequest } = useWalletProgress(connection, { - visible: false, - }); - const durability = useDurability(); - const choicesQuery = useWalletQuery( - connection, - WalletApiOperation.GetChoicesForPayment, - { transactionId: props.transaction.transactionId }, - ); - const exchanges = useWalletQuery( - connection, - WalletApiOperation.ListExchanges, - {}, - ); - const donauQuery = useWalletQuery( - connection, - WalletApiOperation.GetDonau, - {}, - ); - const review = useMemo( - () => - choicesQuery.data - ? paymentReviewView( - choicesQuery.data.contractTerms, - choicesQuery.data, - donauQuery.data?.currentDonauInfo, - language, - ) - : undefined, - [ - choicesQuery.data, - donauQuery.data?.currentDonauInfo, - language, - props.transaction, - ], - ); - const [selectedChoice, setSelectedChoice] = useState<number>(); - const [useDonau, setUseDonau] = useState(false); - const [state, setState] = useState< - | "loading" - | "ready" - | "paying" - | "handoff" - | "pending" - | "paused" - | "done" - | "error" - >("ready"); - const [error, setError] = useState<ErrorPresentation>(); - const [errorRecovery, setErrorRecovery] = useState<ExchangeKeyRecovery>(); - const [cancelling, setCancelling] = useState(false); - const [resuming, setResuming] = useState(false); - const [unclaiming, setUnclaiming] = useState(false); - const [reclaiming, setReclaiming] = useState(false); - const [talerPayUri, setTalerPayUri] = useState<string>(); - const automaticStarted = useRef(false); - const handoffTarget = useRef<"other" | "current">("other"); - const reclaimingRef = useRef(false); - useEffect(() => { - setSelectedChoice(undefined); - setUseDonau(false); - setState("ready"); - setError(undefined); - setErrorRecovery(undefined); - setCancelling(false); - setResuming(false); - setUnclaiming(false); - setReclaiming(false); - setTalerPayUri(undefined); - automaticStarted.current = false; - handoffTarget.current = "other"; - reclaimingRef.current = false; - }, [props.actionId, props.transaction.transactionId]); - const activeChoice = activePaymentChoiceIndex(review, selectedChoice); - const choiceRecovery = exchangeKeyRecoveryFromInsufficientBalance( - review?.choices.find((choice) => choice.index === activeChoice) - ?.balanceDetails, - exchanges.data?.exchanges, - ); - const recovery = errorRecovery ?? choiceRecovery; - const confirm = useCallback( - async (choiceIndex = activeChoice, collectDonationReceipt = useDonau) => { - if (choiceIndex === undefined) return; - if (!(await durability.guardValueOperation())) return; - setState("paying"); - setError(undefined); - setErrorRecovery(undefined); - try { - const choice = review?.choices.find( - (choice) => choice.index === choiceIndex, - ); - const result = await callMutation( - WalletApiOperation.ConfirmPay, - paymentConfirmationRequest( - props.transaction.transactionId, - choiceIndex, - choice, - collectDonationReceipt, - ), - ["balances", "transactions"], - ); - if (Result.isError(result)) { - setErrorRecovery(exchangeKeyRecoveryFromError(result.detail)); - setError( - walletCoreError( - result.detail, - /* Translators: wallet-core is the background wallet engine; keep the component name unchanged. */ i18n.str`Wallet-core could not confirm this payment.`, - ), - ); - setState("error"); - return; - } - if (result.value.type === ConfirmPayResultType.Done) { - setState("done"); - void onPaymentDone(result.value.contractTerms.fulfillment_url); - } else if (result.value.lastError) { - setErrorRecovery( - exchangeKeyRecoveryFromError(result.value.lastError), - ); - setError( - walletCoreError( - result.value.lastError, - i18n.str`The merchant cannot process this payment right now.`, - ), - ); - setState("paused"); - } else { - setState("pending"); - if (!browserCheckout) - void completeActionBestEffort(platform.actionInbox, props.actionId); - } - } catch (cause) { - setError( - errorFromException(cause, i18n.str`Payment confirmation failed`), - ); - setState("error"); - } - }, - [ - activeChoice, - callMutation, - durability, - platform, - props.actionId, - browserCheckout, - onPaymentDone, - props.transaction.transactionId, - review, - useDonau, - ], - ); - useEffect(() => { - setUseDonau(false); - }, [activeChoice]); - useEffect(() => { - if (review?.automaticChoiceIndex === undefined || automaticStarted.current) - return; - automaticStarted.current = true; - void confirm(review.automaticChoiceIndex); - }, [confirm, review?.automaticChoiceIndex]); - const cancel = async () => { - if (cancelling) return; - setCancelling(true); - setError(undefined); - try { - const outcome = await cancelTransactionBeforeCompleting( - () => - callMutation( - WalletApiOperation.DeleteTransaction, - { transactionId: props.transaction.transactionId }, - ["balances", "transactions"], - ), - () => - void completeActionBestEffort(platform.actionInbox, props.actionId), - ); - if (!outcome.cancelled) { - setError( - outcome.kind === "wallet" - ? walletCoreError( - outcome.detail, - i18n.str`The payment could not be cancelled.`, - ) - : errorFromException( - outcome.cause, - i18n.str`Payment cancellation failed`, - ), - ); - setState("error"); - return; - } - } finally { - setCancelling(false); - } - navigate("/"); - }; - const resume = async () => { - if (resuming || cancelling) return; - setResuming(true); - setError(undefined); - try { - const result = await callMutation( - WalletApiOperation.ResumeTransaction, - { transactionId: props.transaction.transactionId }, - ["transactions"], - ); - if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`The payment could not be resumed.`, - ), - ); - setState("paused"); - return; - } - setState("pending"); - } catch (cause) { - setError(errorFromException(cause, i18n.str`Payment resume failed`)); - setState("paused"); - } finally { - setResuming(false); - } - }; - const reclaim = async () => { - if (reclaimingRef.current) return; - reclaimingRef.current = true; - setReclaiming(true); - setError(undefined); - const returnState = talerPayUri ? "handoff" : "ready"; - try { - const result = await callMutation( - WalletApiOperation.ReclaimPayment, - { transactionId: props.transaction.transactionId }, - ["transactions"], - ); - if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`The payment could not continue with this wallet.`, - ), - ); - setState(returnState); - return; - } - setTalerPayUri(undefined); - setState("loading"); - } catch (cause) { - setError( - errorFromException( - cause, - i18n.str`Continuing the payment with this wallet failed.`, - ), - ); - setState(returnState); - } finally { - reclaimingRef.current = false; - setReclaiming(false); - } - }; - const keepPaymentHere = () => { - if (!unclaiming || handoffTarget.current === "current") return; - handoffTarget.current = "current"; - setReclaiming(true); - void unclaimRequest.cancel().catch((cause) => { - setError( - errorFromException( - cause, - /* Translators: Claiming a merchant order assigns it to a wallet for payment; it does not mean that payment has completed. */ i18n.str`Cancelling the payment handoff failed.`, - ), - ); - }); - }; - const wantsCurrentWallet = () => handoffTarget.current === "current"; - const unclaim = async () => { - if (unclaiming) return; - handoffTarget.current = "other"; - setUnclaiming(true); - setError(undefined); - let reclaimAfterward = false; - try { - const result = await unclaimRequest.callAndInvalidate( - WalletApiOperation.UnclaimPayment, - { transactionId: props.transaction.transactionId }, - ["transactions"], - ); - if (wantsCurrentWallet()) { - reclaimAfterward = true; - } else if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`The payment could not be handed off to another wallet.`, - ), - ); - setState("ready"); - return; - } else { - setTalerPayUri(result.value.talerPayUri); - setState("handoff"); - } - } catch (cause) { - if (wantsCurrentWallet()) { - reclaimAfterward = true; - } else if (!isProgressRequestCancelled(cause)) { - setError( - errorFromException( - cause, - /* Translators: Claiming a merchant order assigns it to a wallet for payment; it does not mean that payment has completed. */ i18n.str`Payment handoff failed`, - ), - ); - setState("ready"); - } - } finally { - setUnclaiming(false); - } - if (reclaimAfterward) await reclaim(); - }; - if (choicesQuery.isLoading || !review) - return ( - <PaymentScreen - state={choicesQuery.error ? `error` : `loading`} - error={ - choicesQuery.error - ? errorFromException( - choicesQuery.error, - i18n.str`Payment options could not be loaded.`, - ) - : undefined - } - onSelectChoice={() => {}} - onConfirm={() => {}} - onWithdraw={() => navigate("/withdraw")} - onBack={() => { - void completeActionBestEffort(platform.actionInbox, props.actionId); - navigate("/"); - }} - onCancel={() => void cancel()} - onOpenFulfillment={() => {}} - cancelling={cancelling} - /> - ); - const fulfillmentUrl = safeWebUrl(review.fulfillmentUrl) - ? review.fulfillmentUrl - : undefined; + const { review, recovery } = actions; + const loadError = view.error ?? contract.error; + const onRetry = view.canRetry + ? view.retry + : contract.error + ? contract.retry + : undefined; return ( <PaymentScreen - state={state} - talerPayUri={talerPayUri} - merchantName={review.merchantName} - merchantWebsite={review.merchantWebsite} - merchantAddress={review.merchantAddress} - merchantLogo={review.merchantLogo} - summary={review.summary} - order={review.order} - minimumAge={review.minimumAge} - choices={review.choices} - selectedChoice={activeChoice} - error={error} + state={ + !review + ? loadError + ? "error" + : "loading" + : actions.confirming + ? "paying" + : "ready" + } + onRetryObservation={onRetry} + confirmDisabled={!actions.canConfirm || props.cancelling} + merchantName={review?.merchantName} + merchantWebsite={review?.merchantWebsite} + merchantAddress={review?.merchantAddress} + merchantLogo={review?.merchantLogo} + summary={review?.summary} + order={review?.order} + minimumAge={review?.minimumAge} + choices={review?.choices} + selectedChoice={actions.selectedChoice} + error={ + props.error ?? + (loadError + ? errorFromException( + loadError, + i18n.str`Payment options could not be loaded.`, + ) + : undefined) + } recoveryActionLabel={recovery?.actionLabel} onRecoveryAction={ recovery @@ -4875,40 +4579,29 @@ function PaymentDialog(props: { navigate( exchangeRecoveryRoute( recovery, - `/pay/${props.transaction.transactionId}/${props.actionId}`, + `/pay/${props.transactionId}/${props.actionId}`, ), ) : undefined } - fulfillmentMessage={review.fulfillmentMessage} - fulfillmentUrl={fulfillmentUrl} - useDonau={useDonau} - cancelling={cancelling} - resuming={resuming} - unclaiming={unclaiming} - reclaiming={reclaiming} - onSelectChoice={setSelectedChoice} - onToggleDonau={setUseDonau} + useDonau={actions.useDonau} + cancelling={props.cancelling} + unclaiming={actions.unclaiming} + reclaiming={actions.reclaiming} + onSelectChoice={actions.selectChoice} + onToggleDonau={actions.setUseDonau} onConfigureDonau={(baseUrl) => navigate( - `/donations?suggested=${encodeURIComponent(baseUrl)}&returnTo=${encodeURIComponent(`/pay/${props.transaction.transactionId}/${props.actionId}`)}`, + `/donations?suggested=${encodeURIComponent(baseUrl)}&returnTo=${encodeURIComponent(`/pay/${props.transactionId}/${props.actionId}`)}`, ) } - onConfirm={(collect) => void confirm(activeChoice, collect)} - onResume={() => void resume()} - onUnclaim={() => void unclaim()} - onKeepHere={keepPaymentHere} - onReclaim={() => void reclaim()} + onConfirm={(collect) => void actions.confirm(collect)} + onUnclaim={() => void actions.unclaim()} + onKeepHere={actions.keepHere} onWithdraw={() => navigate("/withdraw")} - onBack={() => { - void completeActionBestEffort(platform.actionInbox, props.actionId); - navigate("/"); - }} - onCancel={() => void cancel()} - onOpenFulfillment={() => { - if (fulfillmentUrl) - void platform.openExternal(fulfillmentUrl, props.fulfillmentTarget); - }} + onBack={props.onBack} + onCancel={props.onCancel} + onOpenFulfillment={() => {}} /> ); } diff --git a/packages/wallet-webui/src/routes/payment-model.ts b/packages/wallet-webui/src/routes/payment-model.ts @@ -32,8 +32,6 @@ export interface PaymentReviewView { summary: string; order: OrderSummaryView; minimumAge?: number; - fulfillmentMessage?: string; - fulfillmentUrl?: string; choices: PaymentChoiceView[]; defaultChoiceIndex?: number; automaticChoiceIndex?: number; @@ -264,12 +262,6 @@ export function paymentReviewView( Amounts.parse(choices[0]?.amountRaw ?? "")?.currency, ), ...(terms.minimum_age ? { minimumAge: terms.minimum_age } : {}), - ...(terms.fulfillment_message - ? { fulfillmentMessage: terms.fulfillment_message } - : {}), - ...(safeWebUrl(terms.fulfillment_url) - ? { fulfillmentUrl: terms.fulfillment_url } - : {}), choices, ...(result.defaultChoiceIndex !== undefined ? { defaultChoiceIndex: result.defaultChoiceIndex } diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -414,6 +414,59 @@ async function harness( }; } +for (const url of ["https://merchant.example/fulfilled", undefined]) { + test(`reopened browser checkout uses observed fulfillment without waiting for its contract: ${url}`, async () => { + const h = await harness("payment-done", url); + try { + await h.waitFor(() => assert.equal(h.documentReads(), 1)); + await h.waitFor(() => assert.deepEqual(h.completions, [h.entry.id])); + await h.waitFor(() => + assert.deepEqual( + h.navigations, + url ? [{ url, target: "current-tab" }] : [], + ), + ); + assert.equal( + await h.services.platform.actionInbox.get(h.entry.id), + undefined, + ); + await h.act(async () => { + h.releaseDocument(); + h.publish(); + }); + assert.deepEqual(h.completions, [h.entry.id]); + assert.equal(h.navigations.length, url ? 1 : 0); + } finally { + await h.close(); + } + }); +} + +test("a failed claim observation shows retry despite retained claim progress", async () => { + const h = await harness("payment-claim"); + try { + await h.waitFor(() => assert.equal(h.registrations.length, 1)); + assert.ok(h.view.getByText("Loading payment details…")); + await h.act(async () => h.failObservation()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Retry updates" })), + ); + assert.equal(h.view.queryByText("Loading payment details…"), null); + assert.ok(await h.services.platform.actionInbox.get(h.entry.id)); + h.publish(h.readySnapshot); + h.releaseDocument(); + await h.act(async () => + h.view.getByRole("button", { name: "Retry updates" }).click(), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("heading", { name: "Review payment" })), + ); + assert.notEqual(h.registrations[0], h.registrations[1]); + } finally { + await h.close(); + } +}); + for (const [minor, label] of [ [TransactionMinorState.KycRequired, "Identity verification required"], [ @@ -463,6 +516,57 @@ for (const [minor, label] of [ }); } +test("payment review shares its observer and document while choices and blockers update", async () => { + const h = await harness("payment-review"); + try { + await h.waitFor(() => assert.equal(h.documentReads(), 1)); + await h.act(async () => h.releaseDocument()); + const payButton = () => + h.view.getByRole("button", { name: /^Pay CHF:/ }) as HTMLButtonElement; + await h.waitFor(() => assert.equal(payButton().disabled, false)); + assert.equal(h.registrations.length, 1); + assert.equal(h.documentReads(), 1); + 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.waitFor(() => + assert.ok(h.view.getByText("Total including fees: CHF:7.5")), + ); + await h.act(async () => + h.publish({ + ...snapshot, + confirmation: { unavailableReasons: ["expired"] }, + }), + ); + await h.waitFor(() => assert.equal(payButton().disabled, true)); + await h.act(async () => h.failObservation()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Retry updates" })), + ); + await h.act(async () => + h.view.getByRole("button", { name: "Retry updates" }).click(), + ); + await h.waitFor(() => assert.equal(payButton().disabled, true)); + assert.equal(h.registrations.length, 2); + assert.equal(h.documentReads(), 1); + await h.act(async () => h.publish(snapshot)); + await h.waitFor(() => assert.equal(payButton().disabled, false)); + } finally { + await h.close(); + } +}); + test("payment details keep live status visible while the order document loads or fails", async () => { const h = await harness( "payment-details", @@ -584,3 +688,438 @@ for (const next of ["kyc", "done", "failed", "deleted"] as const) { } }); } + +for (const route of ["payment-review", "payment-review-details"] as const) { + for (const order of ["response-first", "snapshot-first"] as const) { + test(`${route} takes completion from snapshots when ${order}`, async () => { + const h = await harness( + route, + "https://merchant.example/snapshot-fulfillment", + ); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: /^Pay CHF:/ })), + ); + await h.act(async () => { + const button = h.view.getByRole("button", { name: /^Pay CHF:/ }); + button.click(); + button.click(); + }); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + const request = h.paymentRequests[0]; + assert.equal(request.operation, WalletApiOperation.ConfirmPay); + assert.deepEqual(request.args, { + transactionId: h.transactionId, + choiceIndex: 0, + noWait: true, + }); + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment); + const done: TransactionSnapshot = { + ...initial, + transaction: { + ...initial.transaction, + txState: { major: TransactionMajorState.Done }, + }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }; + // Deliberately return a different URL: navigation must use the snapshot. + const reply = { + tag: "ok", + value: { + type: ConfirmPayResultType.Done, + contractTerms: { + fulfillment_url: "https://merchant.example/response-fulfillment", + }, + }, + }; + if (order === "response-first") { + await h.act(async () => request.resolve(reply)); + assert.equal( + h.view.queryByRole("heading", { name: "Payment complete" }), + null, + ); + assert.deepEqual(h.navigations, []); + assert.deepEqual(h.completions, []); + assert.equal( + ( + h.view.getByRole("button", { + name: "Paying…", + }) as HTMLButtonElement + ).disabled, + true, + ); + await h.act(async () => h.publish(done)); + } else { + await h.act(async () => h.publish(done)); + await h.waitFor(() => + assert.ok( + h.view.getByText( + route === "payment-review" ? "Payment complete" : "Completed", + ), + ), + ); + await h.act(async () => request.resolve(reply)); + } + await h.waitFor(() => + assert.ok( + h.view.getByText( + route === "payment-review" ? "Payment complete" : "Completed", + ), + ), + ); + assert.equal(h.paymentRequests.length, 1); + assert.deepEqual( + h.navigations, + route === "payment-review" + ? [ + { + url: "https://merchant.example/snapshot-fulfillment", + target: "current-tab", + }, + ] + : [], + ); + assert.deepEqual( + h.completions, + route === "payment-review" ? [h.entry.id] : [], + ); + assert.equal(h.registrations.length, 1); + assert.equal(h.documentReads(), 1); + } finally { + await h.close(); + } + }); + } + + test(`${route} keeps submission errors retryable in the observed review`, async () => { + const h = await harness(route); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: /^Pay CHF:/ })), + ); + await h.act(async () => + h.view.getByRole("button", { name: /^Pay CHF:/ }).click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + await h.act(async () => + h.paymentRequests[0].reject(new Error("confirmation failed")), + ); + await h.waitFor(() => + assert.equal( + ( + h.view.getByRole("button", { + name: /^Pay CHF:/, + }) as HTMLButtonElement + ).disabled, + false, + ), + ); + assert.ok(h.view.getByText("Payment confirmation failed")); + await h.act(async () => + h.view.getByRole("button", { name: /^Pay CHF:/ }).click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 2)); + assert.equal(h.registrations.length, 1); + } finally { + await h.close(); + } + }); + + test(`${route} uses observed handoff links and waits for observed reclaim`, async () => { + const h = await harness(route); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => + assert.ok( + h.view.getByRole("button", { name: "Continue with another wallet" }), + ), + ); + await h.act(async () => + h.view + .getByRole("button", { name: "Continue with another wallet" }) + .click(), + ); + await h.act(async () => + h.view + .getAllByRole("button", { name: "Continue with another wallet" }) + .at(-1)! + .click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + assert.equal( + h.paymentRequests[0].operation, + WalletApiOperation.UnclaimPayment, + ); + await h.act(async () => + h.paymentRequests[0].resolve({ + tag: "ok", + value: { talerPayUri: "taler://pay/merchant.example/response" }, + }), + ); + assert.equal( + h.view.queryByRole("heading", { name: "Continue in another wallet" }), + null, + ); + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment); + const handoff: TransactionSnapshot = { + ...initial, + transaction: { + ...initial.transaction, + txState: { + major: TransactionMajorState.Dialog, + minor: TransactionMinorState.WaitingForOtherWallet, + }, + unclaimedPayUri: "taler://pay/merchant.example/observed" as never, + }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }; + await h.act(async () => h.publish(handoff)); + await h.waitFor(() => + assert.ok( + h.view.getByRole("heading", { name: "Continue in another wallet" }), + ), + ); + let copied = ""; + Object.assign(h.dom.navigator.clipboard, { + writeText: async (value: string) => { + copied = value; + }, + }); + await h.act(async () => + h.view.getByRole("button", { name: "Copy payment link" }).click(), + ); + assert.equal(copied, "taler://pay/merchant.example/observed"); + await h.act(async () => + h.view + .getByRole("button", { name: "Continue with this wallet" }) + .click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 2)); + assert.equal( + h.paymentRequests[1].operation, + WalletApiOperation.ReclaimPayment, + ); + await h.act(async () => + h.paymentRequests[1].resolve({ tag: "ok", value: {} }), + ); + assert.ok( + h.view.getByRole("heading", { name: "Continue in another wallet" }), + ); + assert.equal( + ( + h.view.getByRole("button", { + name: "Continuing with this wallet…", + }) as HTMLButtonElement + ).disabled, + true, + ); + await h.act(async () => h.publish(initial)); + await h.waitFor(() => + assert.equal( + ( + h.view.getByRole("button", { + name: /^Pay CHF:/, + }) as HTMLButtonElement + ).disabled, + false, + ), + ); + assert.equal( + h.view.queryByRole("heading", { name: "Continue in another wallet" }), + null, + ); + assert.equal(h.registrations.length, 1); + assert.equal(h.documentReads(), 1); + } finally { + await h.close(); + } + }); + + for (const unclaimResult of ["released", "failed"] as const) { + test(`${route} reconciles keeping a payment when unclaim finishes late: ${unclaimResult}`, async () => { + const h = await harness(route); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => + assert.ok( + h.view.getByRole("button", { + name: "Continue with another wallet", + }), + ), + ); + await h.act(async () => + h.view + .getByRole("button", { name: "Continue with another wallet" }) + .click(), + ); + await h.act(async () => + h.view + .getAllByRole("button", { name: "Continue with another wallet" }) + .at(-1)! + .click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + await h.act(async () => + h.view + .getByRole("button", { name: "Continue with this wallet" }) + .click(), + ); + await h.waitFor(() => assert.equal(h.cancelledRequests(), 1)); + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment); + await h.act(async () => + h.publish({ + ...initial, + transaction: { + ...initial.transaction, + txState: { + major: TransactionMajorState.Dialog, + minor: TransactionMinorState.WaitingForOtherWallet, + }, + unclaimedPayUri: "taler://pay/merchant.example/late" as never, + }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }), + ); + await h.act(async () => { + if (unclaimResult === "failed") + h.paymentRequests[0].reject(new Error("unclaim response lost")); + else + h.paymentRequests[0].resolve({ + tag: "ok", + value: { talerPayUri: "taler://pay/merchant.example/late" }, + }); + }); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 2)); + assert.equal( + h.paymentRequests[1].operation, + WalletApiOperation.ReclaimPayment, + ); + await h.act(async () => { + h.publish(initial); + h.paymentRequests[1].resolve({ tag: "ok", value: {} }); + }); + await h.waitFor(() => + assert.equal( + ( + h.view.getByRole("button", { + name: /^Pay CHF:/, + }) as HTMLButtonElement + ).disabled, + false, + ), + ); + assert.equal( + h.view.queryByRole("heading", { name: "Continue in another wallet" }), + null, + ); + assert.equal(h.registrations.length, 1); + } finally { + await h.close(); + } + }); + } +} + +for (const route of ["payment-review", "payment-review-details"] as const) { + test(`${route} runs automatic choices only in checkout after the contract loads`, async () => { + const h = await harness(route); + try { + await h.waitFor(() => assert.equal(h.registrations.length, 1)); + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment && initial.payment); + const automatic: TransactionSnapshot = { + ...initial, + payment: { + ...initial.payment, + automaticExecution: true, + automaticExecutableIndex: 0, + }, + }; + await h.act(async () => h.publish(automatic)); + assert.equal(h.paymentRequests.length, 0); + await h.act(async () => h.releaseDocument()); + if (route === "payment-review") { + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + await h.act(async () => + h.paymentRequests[0].reject( + new Error("automatic confirmation failed"), + ), + ); + } + await h.waitFor(() => + assert.equal( + ( + h.view.getByRole("button", { + name: /^Pay CHF:/, + }) as HTMLButtonElement + ).disabled, + false, + ), + ); + await h.act(async () => h.publish({ ...automatic })); + assert.equal( + h.paymentRequests.length, + route === "payment-review" ? 1 : 0, + ); + } finally { + await h.close(); + } + }); +} + +test("checkout follows observed suspension and resume without changing status on acknowledgement", async () => { + const h = await harness("payment-review"); + try { + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment); + const suspended: TransactionSnapshot = { + ...initial, + transaction: { + ...initial.transaction, + txState: { major: TransactionMajorState.Suspended }, + }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }; + await h.waitFor(() => assert.equal(h.registrations.length, 1)); + await h.act(async () => h.publish(suspended)); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Resume payment" })), + ); + await h.act(async () => + h.view.getByRole("button", { name: "Resume payment" }).click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + assert.equal( + h.paymentRequests[0].operation, + WalletApiOperation.ResumeTransaction, + ); + await h.act(async () => + h.paymentRequests[0].resolve({ tag: "ok", value: {} }), + ); + assert.ok(h.view.getByText("Payment paused")); + assert.deepEqual(h.completions, []); + await h.act(async () => + h.publish({ + ...suspended, + transaction: { + ...suspended.transaction, + txState: { major: TransactionMajorState.Pending }, + }, + }), + ); + await h.waitFor(() => assert.ok(h.view.getByText("Payment submitted"))); + assert.equal(h.view.queryByText("Payment paused"), null); + assert.deepEqual(h.completions, []); + } finally { + await h.close(); + } +});