taler-typescript-core

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

commit d78f677524661d30db99bad8dd508ab9ff8adf85
parent 353f3ae67b3ec257f8a25f5c247508cfabc4a285
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 04:12:59 +0100

wallet-webui: load older transactions and keep your place in history

History filtered only the newest 100 transactions. Apply the filter in
wallet-core and fetch older pages on demand. Save the filter, balance
and scroll position when opening a transaction so Back returns to the
same row.

Diffstat:
Apackages/wallet-webui/src/api/transaction-history.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/routes/App.tsx | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mpackages/wallet-webui/src/screens/TransactionScreen.tsx | 54+++++++++++++++++++++++++++++++++++++++++-------------
Mpackages/wallet-webui/src/testing/demo-wallet.ts | 49+++++++++++++++++++++++++++++++++++++------------
Apackages/wallet-webui/test/transaction-history.test.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 309 insertions(+), 35 deletions(-)

diff --git a/packages/wallet-webui/src/api/transaction-history.ts b/packages/wallet-webui/src/api/transaction-history.ts @@ -0,0 +1,98 @@ +import type { + GetTransactionsV2Request, + ScopeInfo, +} from "@gnu-taler/taler-util"; +import { + WalletApiOperation, + type WalletCoreResponseType, +} from "@gnu-taler/taler-wallet-core"; +import { useEffect } from "preact/hooks"; +import useSWRInfinite from "swr/infinite"; +import { walletKey, type WalletSWRKey } from "./canonical.js"; +import type { WalletConnection } from "./contracts.js"; +import { notificationFamilies } from "./notifications.js"; +import { watchWalletReconnection } from "../platform/lifecycle.js"; + +export type HistoryFilter = "all" | "pending" | "completed"; +type Page = WalletCoreResponseType<WalletApiOperation.GetTransactionsV2>; +const pageSize = 100; + +export function historyPageRequest( + filter: HistoryFilter, + scope: ScopeInfo | undefined, + previous?: Page, +): GetTransactionsV2Request | undefined { + if (previous && previous.transactions.length < pageSize) return undefined; + const cursor = previous?.transactions.at(-1); + return { + limit: -pageSize, + ...(scope && { scopeInfo: scope }), + ...(filter !== "all" && { + filterByState: filter === "pending" ? "nonfinal" : "final", + }), + ...(cursor && { + offsetTransactionId: cursor.transactionId, + offsetTimestamp: cursor.timestamp, + }), + }; +} + +export function useTransactionHistory( + connection: WalletConnection, + filter: HistoryFilter, + scope: ScopeInfo | undefined, + initialSize: number, +) { + const query = useSWRInfinite<Page, Error>( + (index, previous: Page | null) => { + if (index > 0 && !previous) return null; + const request = historyPageRequest(filter, scope, previous ?? undefined); + return request + ? walletKey(WalletApiOperation.GetTransactionsV2, request) + : null; + }, + (key: WalletSWRKey) => + connection.client.call( + WalletApiOperation.GetTransactionsV2, + JSON.parse(key[2]) as GetTransactionsV2Request, + ), + { initialSize, revalidateAll: true, dedupingInterval: 0 }, + ); + const { mutate } = query; + useEffect(() => { + const unsubscribe = connection.subscribeNotifications((notification) => { + if (notificationFamilies(notification).includes("transactions")) + void mutate(); + }); + const stop = watchWalletReconnection(connection, () => { + void mutate(); + }); + return () => { + unsubscribe(); + stop(); + }; + }, [connection, mutate]); + const transactions = new Map( + query.data?.flatMap((page) => + page.transactions.map( + (transaction) => [transaction.transactionId, transaction] as const, + ), + ), + ); + const hasMore = query.data?.at(-1)?.transactions.length === pageSize; + return { + transactions: [...transactions.values()], + pages: query.size, + loading: !query.data && !query.error, + loadingMore: + !query.error && hasMore && (query.data?.length ?? 0) < query.size, + error: query.error, + hasMore, + loadMore: () => { + void query.setSize(query.size + 1); + }, + retry: () => { + void mutate(); + }, + }; +} diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -46,6 +46,10 @@ import { } from "wouter-preact"; import { useHashLocation } from "wouter-preact/use-hash-location"; import { useSWRConfig } from "swr"; +import { + useTransactionHistory, + type HistoryFilter, +} from "../api/transaction-history.js"; import { isWalletKey } from "../api/canonical.js"; import type { AppServices } from "./context.js"; import { ServicesContext, useServices } from "./context.js"; @@ -4665,28 +4669,77 @@ function PaymentDialog(props: { } function TransactionsRoute() { + const [location] = useHashLocation(); const { connection } = useServices(); const { language } = useLanguage(); const [, navigate] = useLocation(); - const requestedScope = scopeFromIdentity(hashQueryValue("scope")); + const params = new URLSearchParams(location.split("?")[1]); + const stateFilter = params.get("filter"); + const filter: HistoryFilter = + stateFilter === "pending" || stateFilter === "completed" + ? stateFilter + : "all"; + const requestedScope = scopeFromIdentity(params.get("scope") ?? ""); + const saved = useMemo( + () => + window.history.state?.walletHistory as + | { pages: number; scrollY: number; transactionId?: string } + | undefined, + [location], + ); + const restored = useRef<typeof saved>(); const supportedScope = requestedScope?.type === ScopeType.Global || requestedScope?.type === ScopeType.Exchange || requestedScope?.type === ScopeType.ExchangeLegacyKeys ? requestedScope : undefined; - const query = useWalletQuery( + const query = useTransactionHistory( connection, - WalletApiOperation.GetTransactionsV2, - { limit: -100, ...(supportedScope ? { scopeInfo: supportedScope } : {}) }, + filter, + supportedScope, + saved?.pages ?? 1, ); - const transactions = query.data?.transactions + useEffect(() => { + if ( + !saved || + restored.current === saved || + query.loading || + query.loadingMore || + query.error + ) + return; + const frame = window.requestAnimationFrame(() => { + if (saved.transactionId) { + document + .getElementById(`history-${saved.transactionId}`) + ?.focus({ preventScroll: true }); + } + window.scrollTo(0, saved.scrollY); + restored.current = saved; + }); + return () => window.cancelAnimationFrame(frame); + }, [saved, query.loading, query.loadingMore, query.error]); + const transactions = query.transactions .filter(visibleInTransactionHistory) .map((transaction) => transactionHistoryView(transaction, language)); return ( <TransactionScreen transactions={transactions} - loading={query.isLoading} + filter={filter} + onFilter={(next) => { + if (next === "all") params.delete("filter"); + else params.set("filter", next); + const search = params.toString(); + navigateWalletRoute( + search ? `/transactions?${search}` : "/transactions", + { replace: true }, + ); + }} + onLoadMore={query.hasMore ? query.loadMore : undefined} + loadingMore={query.loadingMore} + onRetry={query.retry} + loading={query.loading} error={ query.error ? errorFromException( @@ -4696,14 +4749,33 @@ function TransactionsRoute() { : undefined } scopeLabel={supportedScope ? scopeLabel(supportedScope) : undefined} - onOpen={(transactionId) => navigate(`/transaction/${transactionId}`)} + onOpen={(transactionId) => { + window.history.replaceState( + { + ...window.history.state, + walletHistory: { + pages: query.pages, + scrollY: window.scrollY, + transactionId, + }, + }, + "", + ); + navigate(`/transaction/${transactionId}`, { + state: { fromWalletHistory: true }, + }); + }} /> ); } +function returnToTransactionHistory() { + if (window.history.state?.fromWalletHistory) window.history.back(); + else navigateWalletRoute("/transactions"); +} + function useTransactionActions(transactionId: TransactionIdStr) { const { connection } = useServices(); - const [, navigate] = useLocation(); const callMutation = useWalletMutation(connection); const durability = useDurability(); const [workingAction, setWorkingAction] = useState<TransactionUiAction>(); @@ -4745,7 +4817,7 @@ function useTransactionActions(transactionId: TransactionIdStr) { ), ); } else if (action === "delete") { - navigate("/transactions"); + returnToTransactionHistory(); } else { setMessage( action === "refund" @@ -4916,7 +4988,7 @@ function TransactionDetailView({ } message={message} workingAction={workingAction} - onBack={() => navigate("/transactions")} + onBack={returnToTransactionHistory} onAction={(action) => void runAction(action)} onOpenExternal={(url) => void platform.openExternal(url)} onContinue={() => setContinuingTransfer(true)} diff --git a/packages/wallet-webui/src/screens/TransactionScreen.tsx b/packages/wallet-webui/src/screens/TransactionScreen.tsx @@ -1,4 +1,5 @@ import { useMemo, useState } from "preact/hooks"; +import { Button } from "../ui/Button.js"; import { Card } from "../ui/Card.js"; import { ErrorCard } from "../ui/ErrorCard.js"; import type { ErrorPresentation } from "../ui/error.js"; @@ -12,23 +13,27 @@ function amountLabel(transaction: TransactionHistoryView): string { return transaction.amount; } +type Filter = "all" | "pending" | "completed"; + export function TransactionScreen(props: { transactions?: TransactionHistoryView[]; loading: boolean; error?: ErrorPresentation; scopeLabel?: string; + filter?: Filter; + onFilter?: (filter: Filter) => void; + onLoadMore?: () => void; + loadingMore?: boolean; + onRetry?: () => void; onOpen: (id: string) => void; }) { - const [filter, setFilter] = useState<"all" | "pending" | "completed">("all"); - const transactions = useMemo( - () => - (props.transactions ?? []).filter((transaction) => { - if (filter === "pending" && !transaction.pending) return false; - if (filter === "completed" && transaction.pending) return false; - return true; - }), - [filter, props.transactions], - ); + const [localFilter, setFilter] = useState<Filter>("all"); + const filter = props.filter ?? localFilter; + const transactions = useMemo(() => { + const rows = props.transactions ?? []; + if (props.filter || filter === "all") return rows; + return rows.filter((row) => row.pending === (filter === "pending")); + }, [filter, props.filter, props.transactions]); return ( <div class="mx-auto max-w-3xl space-y-5"> <div> @@ -48,7 +53,7 @@ export function TransactionScreen(props: { <select value={filter} onChange={(event) => - setFilter(event.currentTarget.value as typeof filter) + (props.onFilter ?? setFilter)(event.currentTarget.value as Filter) } class="min-h-11 w-full rounded-full border border-outline bg-surface px-5 text-onSurface sm:w-auto" > @@ -65,12 +70,23 @@ export function TransactionScreen(props: { <p role="status">{i18n.str`Loading history…`}</p> </Card> )} - {props.error && <ErrorCard error={props.error} />} + {props.error && ( + <ErrorCard error={props.error}> + {props.onRetry && ( + <Button onClick={props.onRetry}>{i18n.str`Retry`}</Button> + )} + </ErrorCard> + )} {!props.loading && !props.error && + !props.onLoadMore && (props.transactions?.length ?? 0) === 0 && ( <Card> - <p>{i18n.str`No transactions yet.`}</p> + <p> + {filter === "all" + ? i18n.str`No transactions yet.` + : i18n.str`No transactions match this view.`} + </p> </Card> )} {!props.loading && @@ -85,6 +101,7 @@ export function TransactionScreen(props: { <button type="button" key={transaction.id} + id={`history-${transaction.id}`} onClick={() => props.onOpen(transaction.id)} class="flex w-full items-center gap-4 rounded-2xl border border-outlineVariant bg-surface p-5 text-left text-onSurface transition hover:border-primary focus:outline-none focus:ring-2 focus:ring-primary" > @@ -125,6 +142,17 @@ export function TransactionScreen(props: { </button> ))} </div> + {props.onLoadMore && !props.error && ( + <Button + tone="secondary" + onClick={props.onLoadMore} + disabled={props.loadingMore} + > + {props.loadingMore + ? i18n.str`Loading history…` + : i18n.str`Load older activity`} + </Button> + )} </div> ); } diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts @@ -1,4 +1,6 @@ import { + AbsoluteTime, + type TalerPreciseTimestamp, ConfirmPayResultType, getQrCodesForPayto, observedTransaction, @@ -789,18 +791,41 @@ export class DemoWalletConnection implements WalletConnection { ].includes(transaction.txState.major), ); } - entries.sort((a, b) => { - const pendingA = - a.txState.major === TransactionMajorState.Pending ? 1 : 0; - const pendingB = - b.txState.major === TransactionMajorState.Pending ? 1 : 0; - const timeA = a.timestamp.t_s === "never" ? 0 : a.timestamp.t_s; - const timeB = b.timestamp.t_s === "never" ? 0 : b.timestamp.t_s; - return pendingB - pendingA || timeB - timeA; - }); - const limit = - typeof request.limit === "number" ? Math.abs(request.limit) : undefined; - return { transactions: limit ? entries.slice(0, limit) : entries }; + const limit = typeof request.limit === "number" ? request.limit : undefined; + const direction = limit === undefined || limit >= 0 ? 1 : -1; + const compare = ( + left: Pick<Transaction, "timestamp" | "transactionId">, + right: { timestamp: TalerPreciseTimestamp; transactionId: string }, + ) => { + const time = AbsoluteTime.cmp( + AbsoluteTime.fromPreciseTimestamp(left.timestamp), + AbsoluteTime.fromPreciseTimestamp(right.timestamp), + ); + const id = + left.transactionId < right.transactionId + ? -1 + : left.transactionId > right.transactionId + ? 1 + : 0; + return direction * (time || id); + }; + const offset = this.state.transactions.find( + (t) => t.transactionId === request.offsetTransactionId, + ); + const timestamp = request.offsetTimestamp as + | TalerPreciseTimestamp + | undefined; + const cursor = + offset ?? + (timestamp + ? { timestamp, transactionId: direction > 0 ? "" : "\uffff" } + : undefined); + if (cursor) entries = entries.filter((t) => compare(t, cursor) > 0); + entries.sort(compare); + return { + transactions: + limit === undefined ? entries : entries.slice(0, Math.abs(limit)), + }; } private transition( diff --git a/packages/wallet-webui/test/transaction-history.test.ts b/packages/wallet-webui/test/transaction-history.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { ScopeType } from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { historyPageRequest } from "../src/api/transaction-history.js"; +import { + DemoWalletConnection, + demoActionUris, +} from "../src/testing/demo-wallet.js"; + +test("history reaches older entries through tied timestamps and filters before paging", async () => { + const wallet = new DemoWalletConnection(() => Date.UTC(2026, 10, 26)); + const scope = { + type: ScopeType.Exchange as const, + currency: "CHF", + url: "https://exchange.demo.invalid/", + }; + for (let i = 0; i < 103; i++) { + await wallet.client.call(WalletApiOperation.PreparePayForUriV2, { + talerPayUri: demoActionUris.payment, + }); + } + const history = ( + request: NonNullable<ReturnType<typeof historyPageRequest>>, + ) => wallet.client.call(WalletApiOperation.GetTransactionsV2, request); + const first = await history(historyPageRequest("all", scope)!); + assert.equal(first.transactions.length, 100); + const next = historyPageRequest("all", scope, first)!; + assert.equal(next.offsetTransactionId, first.transactions[99].transactionId); + assert.deepEqual(next.offsetTimestamp, first.transactions[99].timestamp); + assert.deepEqual(next.scopeInfo, scope); + const second = await history(next); + assert.ok(second.transactions.length > 0); + const ids = [...first.transactions, ...second.transactions].map( + (t) => t.transactionId, + ); + assert.equal(new Set(ids).size, ids.length); + assert.equal(historyPageRequest("all", scope, second), undefined); + const filter = historyPageRequest("completed", scope)!; + assert.equal(filter.filterByState, "final"); + assert.equal(historyPageRequest("pending", scope)?.filterByState, "nonfinal"); + const finished = await history(filter); + assert.ok(finished.transactions.length > 0); + assert.ok( + finished.transactions.every((t) => + second.transactions.some( + (older) => older.transactionId === t.transactionId, + ), + ), + ); +});