taler-typescript-core

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

commit 91d5b91183bd832f843af79ef7982cc57ef06d6c
parent d67fc037f535e9737ad86180be2597470b10de25
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 01:19:22 +0100

wallet-webui: count down the time left to pay an order

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

Diffstat:
Mpackages/wallet-webui/src/routes/App.tsx | 4++++
Mpackages/wallet-webui/src/routes/payment-actions.ts | 23+++++++++++++++++++++--
Mpackages/wallet-webui/src/routes/payment-model.ts | 4++++
Mpackages/wallet-webui/src/screens/PaymentScreen.tsx | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mpackages/wallet-webui/src/screens/TransactionDetailScreen.tsx | 4++++
Mpackages/wallet-webui/test/payment-model.test.ts | 9++++++++-
Mpackages/wallet-webui/test/screens.test.tsx | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
8 files changed, 290 insertions(+), 29 deletions(-)

diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -4619,6 +4619,8 @@ function PaymentDialog(props: { summary={review?.summary ?? transaction?.info?.summary} order={review?.order} minimumAge={review?.minimumAge} + payDeadlineMs={review?.payDeadlineMs} + deadlineExpired={actions.deadlineExpired} choices={review?.choices} selectedChoice={selectedChoice} error={ @@ -4951,6 +4953,8 @@ function TransactionDetailView({ : { state: actions.confirming ? "paying" : "ready", confirmDisabled: !actions.canConfirm || !!workingAction, + payDeadlineMs: paymentReview.payDeadlineMs, + deadlineExpired: actions.deadlineExpired, choices: paymentReview.choices, selectedChoice: actions.selectedChoice, useDonau: actions.useDonau, diff --git a/packages/wallet-webui/src/routes/payment-actions.ts b/packages/wallet-webui/src/routes/payment-actions.ts @@ -44,10 +44,17 @@ import { interface PaymentRequest { kind: "confirm" | "unclaim" | "reclaim"; + submitted?: boolean; acknowledged: boolean; keepHere: boolean; } +function paymentDeadlinePassed(review: PaymentReviewView | undefined): boolean { + return ( + review?.payDeadlineMs !== undefined && Date.now() >= review.payDeadlineMs + ); +} + export interface PaymentActions { review?: PaymentReviewView; selectedChoice?: number; @@ -55,6 +62,7 @@ export interface PaymentActions { useDonau: boolean; setUseDonau: (enabled: boolean) => void; canConfirm: boolean; + deadlineExpired: boolean; confirming: boolean; unclaiming: boolean; reclaiming: boolean; @@ -163,7 +171,13 @@ export function usePaymentActions( } }; const confirm = async (collect = useDonau, index = choiceIndex) => { - if (active.current || !canConfirm || !transactionId || index === undefined) + if ( + active.current || + !canConfirm || + !transactionId || + index === undefined || + paymentDeadlinePassed(review) + ) return; const current = begin("confirm"); let success = false; @@ -173,6 +187,7 @@ export function usePaymentActions( if ( !isActive(current) || !latestView.canConfirm || + paymentDeadlinePassed(latestView.review) || latestView.snapshot?.transaction.transactionId !== transactionId ) return; @@ -180,6 +195,8 @@ export function usePaymentActions( (candidate) => candidate.index === index, ); if (!choice) return; + current.submitted = true; + setRequest({ ...current }); const result = await callMutation( WalletApiOperation.ConfirmPay, paymentConfirmationRequest( @@ -324,7 +341,9 @@ export function usePaymentActions( useDonau, setUseDonau, canConfirm: canConfirm && !request, - confirming: request?.kind === "confirm", + deadlineExpired: + snapshot?.confirmation.unavailableReasons.includes("expired") ?? false, + confirming: request?.kind === "confirm" && !!request.submitted, unclaiming: request?.kind === "unclaim", reclaiming: request?.kind === "reclaim" || !!request?.keepHere, recovery, diff --git a/packages/wallet-webui/src/routes/payment-model.ts b/packages/wallet-webui/src/routes/payment-model.ts @@ -37,6 +37,7 @@ export interface PaymentReviewView { summary: string; order: OrderSummaryView; minimumAge?: number; + payDeadlineMs?: number; choices: PaymentChoiceView[]; defaultChoiceIndex?: number; automaticChoiceIndex?: number; @@ -305,6 +306,9 @@ export function paymentReviewView( terms, Amounts.parse(choices[0]?.amountRaw ?? "")?.currency, ), + ...(typeof terms.pay_deadline?.t_s === "number" + ? { payDeadlineMs: terms.pay_deadline.t_s * 1000 } + : {}), ...(terms.minimum_age ? { minimumAge: terms.minimum_age } : {}), choices, ...(result.defaultChoiceIndex !== undefined diff --git a/packages/wallet-webui/src/screens/PaymentScreen.tsx b/packages/wallet-webui/src/screens/PaymentScreen.tsx @@ -7,7 +7,7 @@ import type { ErrorPresentation } from "../ui/error.js"; import type { PaymentInsufficientBalanceDetails } from "@gnu-taler/taler-util"; import { ConfirmationDialog } from "../ui/ConfirmationDialog.js"; import { QrFrame } from "../ui/QrFrame.js"; -import { useState } from "preact/hooks"; +import { useLayoutEffect, useState } from "preact/hooks"; export interface PaymentChoiceView { index: number; @@ -165,6 +165,52 @@ export type PaymentScreenState = | "done" | "error"; +const countdownWindowMs = 5 * 60 * 1000; + +function usePaymentCountdown( + deadlineMs: number | undefined, +): number | undefined { + const [seconds, setSeconds] = useState<number>(); + useLayoutEffect(() => { + if (deadlineMs === undefined) { + setSeconds(undefined); + return; + } + let timer: number; + const update = () => { + window.clearTimeout(timer); + const remaining = deadlineMs - Date.now(); + if (remaining > countdownWindowMs) { + setSeconds(undefined); + timer = window.setTimeout( + update, + Math.min(remaining - countdownWindowMs, 2_147_483_647), + ); + } else { + const secondsLeft = Math.max(0, Math.ceil(remaining / 1000)); + setSeconds(secondsLeft); + if (secondsLeft > 0) { + // Align every tick with the deadline, including after a late callback. + timer = window.setTimeout( + update, + remaining - (secondsLeft - 1) * 1000, + ); + } + } + }; + const onVisibilityChange = () => { + if (!document.hidden) update(); + }; + update(); + document.addEventListener("visibilitychange", onVisibilityChange); + return () => { + window.clearTimeout(timer); + document.removeEventListener("visibilitychange", onVisibilityChange); + }; + }, [deadlineMs]); + return seconds; +} + export function PaymentOptions(props: { state: "ready" | "paying"; onBack?: () => void; @@ -175,6 +221,8 @@ export function PaymentOptions(props: { useDonau?: boolean; cancelling?: boolean; confirmDisabled?: boolean; + deadlineExpired?: boolean; + payDeadlineMs?: number; unclaiming?: boolean; reclaiming?: boolean; onSelectChoice: (index: number) => void; @@ -188,6 +236,11 @@ export function PaymentOptions(props: { onUnclaim?: () => void; onKeepHere?: () => void; }) { + const reviewing = props.state === "ready"; + const seconds = usePaymentCountdown( + reviewing && !props.deadlineExpired ? props.payDeadlineMs : undefined, + ); + const expired = reviewing && (props.deadlineExpired || seconds === 0); const selected = props.choices?.find( (choice) => choice.index === props.selectedChoice, ); @@ -335,6 +388,14 @@ export function PaymentOptions(props: { : i18n.str`Preparing the payment for another wallet…`} </p> )} + {reviewing && !expired && seconds !== undefined && ( + <p role="timer" class="text-right text-sm font-medium"> + { + // Translators: The placeholder is the time remaining to pay, in minutes and seconds. + i18n.str`Time to pay: ${Math.floor(seconds / 60) + ":" + String(seconds % 60).padStart(2, "0")}` + } + </p> + )} <div class="flex flex-wrap justify-end gap-3 border-t border-outlineVariant pt-5"> {props.onUnclaim && ( <Button @@ -384,28 +445,35 @@ export function PaymentOptions(props: { /* Translators: Add digital cash to this wallet by withdrawing it from a bank or exchange. */ i18n.str`Withdraw funds` }</Button> )} - <Button - onClick={() => props.onConfirm(props.useDonau === true)} - disabled={ - props.confirmDisabled || - !selected?.payable || - props.state === "paying" || - props.cancelling || - props.unclaiming || - props.reclaiming - } - > - <span aria-live="polite"> - {props.state === "paying" - ? props.returning - ? i18n.str`Returning to merchant…` - : i18n.str`Paying…` - : selected - ? // Translators: Button label; the placeholder is a fully formatted payment amount. - i18n.str`Pay ${selected.amountRaw}` - : i18n.str`Pay`} - </span> - </Button> + {expired ? ( + <p + role="status" + class="self-center font-medium" + >{i18n.str`Payment deadline passed`}</p> + ) : ( + <Button + onClick={() => props.onConfirm(props.useDonau === true)} + disabled={ + props.confirmDisabled || + !selected?.payable || + props.state === "paying" || + props.cancelling || + props.unclaiming || + props.reclaiming + } + > + <span aria-live="polite"> + {props.state === "paying" + ? props.returning + ? i18n.str`Returning to merchant…` + : i18n.str`Paying…` + : selected + ? // Translators: Button label; the placeholder is a fully formatted payment amount. + i18n.str`Pay ${selected.amountRaw}` + : i18n.str`Pay`} + </span> + </Button> + )} </div> </> ); @@ -511,6 +579,8 @@ export function PaymentScreen(props: { cancelling?: boolean; resuming?: boolean; confirmDisabled?: boolean; + deadlineExpired?: boolean; + payDeadlineMs?: number; unclaiming?: boolean; reclaiming?: boolean; talerPayUri?: string; @@ -659,6 +729,8 @@ export function PaymentScreen(props: { onBack={props.processing ? props.onBack : undefined} state={props.state} confirmDisabled={props.confirmDisabled} + payDeadlineMs={props.payDeadlineMs} + deadlineExpired={props.deadlineExpired} choices={props.choices} selectedChoice={props.selectedChoice} useDonau={props.useDonau} diff --git a/packages/wallet-webui/src/screens/TransactionDetailScreen.tsx b/packages/wallet-webui/src/screens/TransactionDetailScreen.tsx @@ -32,6 +32,8 @@ export type TransactionPaymentReview = selectedChoice?: number; useDonau?: boolean; confirmDisabled?: boolean; + deadlineExpired?: boolean; + payDeadlineMs?: number; unclaiming?: boolean; reclaiming?: boolean; }; @@ -336,6 +338,8 @@ export function TransactionDetailScreen(props: { selectedChoice={props.paymentReview.selectedChoice} useDonau={props.paymentReview.useDonau} confirmDisabled={props.paymentReview.confirmDisabled} + payDeadlineMs={props.paymentReview.payDeadlineMs} + deadlineExpired={props.paymentReview.deadlineExpired} unclaiming={props.paymentReview.unclaiming} reclaiming={props.paymentReview.reclaiming} onSelectChoice={(index) => props.onSelectPaymentChoice?.(index)} diff --git a/packages/wallet-webui/test/payment-model.test.ts b/packages/wallet-webui/test/payment-model.test.ts @@ -300,7 +300,14 @@ test("payment review preserves core choice availability", () => { ], } as unknown as GetChoicesForPaymentResult; const view = paymentReviewView(transaction.contractTerms!, choices); - assert(view); + assert.equal(view.payDeadlineMs, undefined); + assert.equal( + paymentReviewView( + { ...transaction.contractTerms!, pay_deadline: { t_s: "never" } }, + choices, + ).payDeadlineMs, + undefined, + ); assert.equal(view.choices[0].description, "Member"); assert.equal(view.choices[0].forceTokenSelection, true); assert.equal(view.choices[1].payable, false); diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -9,7 +9,7 @@ import { import { BalanceScreen } from "../src/screens/BalanceScreen.js"; import { ActionScreen } from "../src/screens/ActionScreen.js"; import { BankConfirmationScreen } from "../src/screens/BankConfirmationScreen.js"; -import { PaymentScreen } from "../src/screens/PaymentScreen.js"; +import { PaymentOptions, PaymentScreen } from "../src/screens/PaymentScreen.js"; import { PaymentTemplateScreen } from "../src/screens/PaymentTemplateScreen.js"; import { DepositScreen } from "../src/screens/DepositScreen.js"; import { depositDestinationView } from "../src/routes/deposit-model.js"; @@ -1685,6 +1685,59 @@ test("withdrawal transfer callbacks label their authoritative handoff", async () await window.happyDOM.abort(); }); +test("payment countdown ticks on deadline boundaries and recovers from late wakeups", async (t) => { + const dom = installDom(); + const { render, act, cleanup } = await import("@testing-library/preact"); + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 }); + const timer = t.mock.method(window, "setTimeout", setTimeout); + t.mock.method(window, "clearTimeout", clearTimeout); + const options = (payDeadlineMs?: number) => ( + <PaymentOptions + state="ready" + payDeadlineMs={payDeadlineMs} + onSelectChoice={() => {}} + onConfirm={() => {}} + onWithdraw={() => {}} + /> + ); + try { + const view = render(options()); + const countdown = () => view.queryByRole("timer")?.textContent; + assert.equal(countdown(), undefined); + assert.equal(timer.mock.callCount(), 0); + view.rerender(options(Date.now() + 30 * 86_400_000)); + assert.equal(countdown(), undefined); + assert.equal(timer.mock.calls.at(-1)?.arguments[1], 2_147_483_647); + view.rerender(options(Date.now() + 300_250)); + act(() => t.mock.timers.tick(249)); + assert.equal(countdown(), undefined); + act(() => t.mock.timers.tick(1)); + assert.equal(countdown(), "Time to pay: 5:00"); + + view.rerender(options(Date.now() + 3250)); + assert.equal(countdown(), "Time to pay: 0:04"); + act(() => t.mock.timers.tick(249)); + assert.equal(countdown(), "Time to pay: 0:04"); + act(() => t.mock.timers.tick(1)); + assert.equal(countdown(), "Time to pay: 0:03"); + act(() => t.mock.timers.tick(1150)); + assert.equal(countdown(), "Time to pay: 0:02"); + act(() => t.mock.timers.tick(849)); + assert.equal(countdown(), "Time to pay: 0:02"); + act(() => t.mock.timers.tick(1)); + assert.equal(countdown(), "Time to pay: 0:01"); + act(() => t.mock.timers.tick(1000)); + assert.equal(countdown(), undefined); + assert.ok(view.getByText("Payment deadline passed")); + assert.equal(view.queryByRole("button", { name: "Pay" }), null); + } finally { + cleanup(); + t.mock.restoreAll(); + t.mock.timers.reset(); + await dom.happyDOM.abort(); + } +}); + test("payment choices are keyboard-operable and accessible", async () => { const window = installDom(); const { render, cleanup } = await import("@testing-library/preact"); diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -88,6 +88,7 @@ async function harness( | "withdrawal-new" | "bank-withdrawal", fulfillmentUrl?: string, + payDeadlineSeconds?: number, ) { const dom = installRouteDom(); const { render, cleanup, act } = await import("@testing-library/preact"); @@ -162,6 +163,8 @@ async function harness( if (transaction.type === TransactionType.Payment) { assert.ok(transaction.contractTerms); transaction.contractTerms.fulfillment_url = fulfillmentUrl; + if (payDeadlineSeconds !== undefined) + transaction.contractTerms.pay_deadline = { t_s: payDeadlineSeconds }; assert.ok(transaction.info); transaction.info.fulfillmentUrl = fulfillmentUrl; if (kind === "payment-done" || kind === "payment-details") @@ -885,6 +888,95 @@ for (const [minor, label] of [ }); } +for (const route of ["payment-review", "payment-review-details"] as const) { + test(`${route} shows the contract countdown and expires without a snapshot`, async (t) => { + let now = Math.floor(Date.now() / 1000) * 1000; + t.mock.method(Date, "now", () => now); + const h = await harness(route, undefined, now / 1000 + 240); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => + assert.equal( + h.view.getByRole("timer").textContent, + "Time to pay: 4:00", + ), + ); + const pay = h.view.getByRole("button", { + name: /^Pay CHF:/, + }) as HTMLButtonElement; + assert.equal(pay.disabled, false); + // Expire while confirmation is awaiting the storage guard. + await h.act(async () => { + pay.click(); + now += 240_000; + document.dispatchEvent(new Event("visibilitychange")); + }); + await h.waitFor(() => + assert.ok(h.view.getByText("Payment deadline passed")), + ); + assert.equal(h.view.queryByRole("button", { name: /^Pay CHF:/ }), null); + assert.equal(h.paymentRequests.length, 0); + } 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); + const h = await harness("payment-review", undefined, now / 1000 + 1); + try { + await h.act(async () => h.releaseDocument()); + await h.waitFor(() => assert.ok(h.view.getByRole("timer"))); + await h.act(async () => + h.view.getByRole("button", { name: /^Pay CHF:/ }).click(), + ); + await h.waitFor(() => assert.equal(h.paymentRequests.length, 1)); + now += 1000; + const snapshot = h.readySnapshot; + assert.ok(snapshot.type === TransactionType.Payment); + await h.act(async () => + h.publish({ + ...snapshot, + confirmation: { unavailableReasons: ["expired"] }, + }), + ); + assert.ok(h.view.getByRole("button", { name: "Paying…" })); + assert.equal(h.view.queryByText("Payment deadline passed"), null); + h.paymentRequests[0].resolve( + Result.of({ type: ConfirmPayResultType.Done }), + ); + } finally { + await h.close(); + } +}); + +test("an expired order cannot start automatic payment on reopening", async () => { + const h = await harness("payment-review", undefined, 1); + try { + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment && initial.payment); + await h.act(async () => { + h.publish({ + ...initial, + payment: { + ...initial.payment!, + automaticExecution: true, + automaticExecutableIndex: 0, + }, + }); + h.releaseDocument(); + }); + await h.waitFor(() => + assert.ok(h.view.getByText("Payment deadline passed")), + ); + assert.equal(h.paymentRequests.length, 0); + } finally { + await h.close(); + } +}); + test("payment review shares its observer and document while choices and blockers update", async () => { const h = await harness("payment-review"); try { @@ -918,7 +1010,10 @@ test("payment review shares its observer and document while choices and blockers confirmation: { unavailableReasons: ["expired"] }, }), ); - await h.waitFor(() => assert.equal(payButton().disabled, true)); + await h.waitFor(() => + assert.ok(h.view.getByText("Payment deadline passed")), + ); + assert.equal(h.view.queryByRole("button", { name: /^Pay CHF:/ }), null); await h.act(async () => h.failObservation()); await h.waitFor(() => assert.ok(h.view.getByRole("button", { name: "Retry updates" })), @@ -926,7 +1021,10 @@ test("payment review shares its observer and document while choices and blockers await h.act(async () => h.view.getByRole("button", { name: "Retry updates" }).click(), ); - await h.waitFor(() => assert.equal(payButton().disabled, true)); + await h.waitFor(() => + assert.ok(h.view.getByText("Payment deadline passed")), + ); + assert.equal(h.view.queryByRole("button", { name: /^Pay CHF:/ }), null); assert.equal(h.registrations.length, 2); assert.equal(h.documentReads(), 1); await h.act(async () => h.publish(snapshot));