commit 6adac325f9dc9fe1f94e276f1e1a5c29bf5d9852
parent b1bb8ca90c338dd1eaf657495adadf6e67496534
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 04:13:24 +0100
wallet-webui: show current passes and discounts in the wallet language
An open list could still show a pass as active after it expired, and its
date followed the browser language. Refresh the list at expiry and use
the wallet language for validity dates and merchant descriptions.
Diffstat:
6 files changed, 147 insertions(+), 163 deletions(-)
diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx
@@ -184,7 +184,7 @@ import {
type WithdrawalPreparation,
} from "./withdrawal-review-model.js";
import { downloadCurrentWallet, downloadWalletBlob } from "./backup-review.js";
-import { tokenListView } from "./token-model.js";
+import { useTokenListView } from "./token-model.js";
import {
balancesToView,
balanceTrendView,
@@ -1215,22 +1215,18 @@ function DiscountsRoute() {
WalletApiOperation.ListDiscounts,
{},
);
- const languages = navigator.languages?.length
- ? navigator.languages
- : [navigator.language];
+ const { language } = useLanguage();
+ const languages = [language, ...(navigator.languages ?? [])];
+ const items = useTokenListView(
+ "discounts",
+ query.data?.discounts,
+ languages,
+ query.mutate,
+ );
return (
<TokenListScreen
kind="discounts"
- items={
- query.data
- ? tokenListView(
- "discounts",
- query.data.discounts,
- undefined,
- languages,
- )
- : undefined
- }
+ items={items}
loading={query.isLoading}
error={
query.error
@@ -1253,22 +1249,18 @@ function PassesRoute() {
WalletApiOperation.ListSubscriptions,
{},
);
- const languages = navigator.languages?.length
- ? navigator.languages
- : [navigator.language];
+ const { language } = useLanguage();
+ const languages = [language, ...(navigator.languages ?? [])];
+ const items = useTokenListView(
+ "passes",
+ query.data?.subscriptions,
+ languages,
+ query.mutate,
+ );
return (
<TokenListScreen
kind="passes"
- items={
- query.data
- ? tokenListView(
- "passes",
- query.data.subscriptions,
- undefined,
- languages,
- )
- : undefined
- }
+ items={items}
loading={query.isLoading}
error={
query.error
diff --git a/packages/wallet-webui/src/routes/token-model.ts b/packages/wallet-webui/src/routes/token-model.ts
@@ -1,19 +1,19 @@
-import type {
- DiscountListDetail,
- SubscriptionListDetail,
- TalerProtocolTimestamp,
+import {
+ languageFallbackChain,
+ type DiscountListDetail,
+ type SubscriptionListDetail,
+ type TalerProtocolTimestamp,
} from "@gnu-taler/taler-util";
+import { useEffect, useState } from "preact/hooks";
import { i18n } from "../i18n/runtime.js";
export type TokenKind = "discounts" | "passes";
-export type TokenState = "active" | "future" | "expired";
export interface TokenItemView {
id: string;
name: string;
description: string;
merchant: string;
- state: TokenState;
validity: string;
quantity?: number;
}
@@ -22,10 +22,9 @@ function timestampSeconds(value: TalerProtocolTimestamp): number {
return value.t_s === "never" ? Number.POSITIVE_INFINITY : value.t_s;
}
-function formatDate(value: TalerProtocolTimestamp, language: string): string {
- if (value.t_s === "never") return i18n.str`No expiry`;
+function formatDate(seconds: number, language: string): string {
return new Intl.DateTimeFormat(language, { dateStyle: "medium" }).format(
- new Date(value.t_s * 1000),
+ new Date(seconds * 1000),
);
}
@@ -40,14 +39,17 @@ function localizedDescription(
Array.isArray(translations)
)
return item.description;
- for (const language of languages) {
- const exact = (translations as Record<string, unknown>)[language];
- if (typeof exact === "string") return exact;
- const base = (translations as Record<string, unknown>)[
- language.split("-", 1)[0]
- ];
- if (typeof base === "string") return base;
- }
+ const byLanguage = new Map(
+ Object.entries(translations).map(([tag, value]) => [
+ tag.toLowerCase().replaceAll("_", "-"),
+ value,
+ ]),
+ );
+ for (const language of languages)
+ for (const candidate of languageFallbackChain(language).reverse()) {
+ const description = byLanguage.get(candidate);
+ if (typeof description === "string" && description) return description;
+ }
return item.description;
}
@@ -62,6 +64,41 @@ function merchantName(
}
}
+export function useTokenListView(
+ kind: TokenKind,
+ items: Array<DiscountListDetail | SubscriptionListDetail> | undefined,
+ languages: readonly string[],
+ refresh: () => Promise<unknown>,
+): TokenItemView[] | undefined {
+ const [checkedUntil, setCheckedUntil] = useState(0);
+ let nextExpiry = Infinity;
+ for (const item of items ?? []) {
+ const expiresAt = timestampSeconds(item.validityEnd) * 1000 + 1;
+ if (expiresAt > checkedUntil) nextExpiry = Math.min(nextExpiry, expiresAt);
+ }
+ useEffect(() => {
+ if (!Number.isFinite(nextExpiry)) return;
+ let timer: number;
+ const checkExpiry = () => {
+ const now = Date.now();
+ const remaining = nextExpiry - now;
+ if (remaining > 0) {
+ timer = window.setTimeout(
+ checkExpiry,
+ Math.min(remaining, 2_147_483_647),
+ );
+ return;
+ }
+ // The expired token might share a family with other still-usable tokens.
+ setCheckedUntil(now);
+ void refresh();
+ };
+ checkExpiry();
+ return () => window.clearTimeout(timer);
+ }, [nextExpiry, refresh]);
+ return items && tokenListView(kind, items, undefined, languages);
+}
+
export function tokenListView(
kind: TokenKind,
items: Array<DiscountListDetail | SubscriptionListDetail>,
@@ -70,21 +107,16 @@ export function tokenListView(
): TokenItemView[] {
const language = languages[0] ?? "en";
return items
+ .filter(
+ (item) =>
+ timestampSeconds(item.validityStart) <= nowSeconds &&
+ nowSeconds <= timestampSeconds(item.validityEnd),
+ )
.map((item) => {
- const start = timestampSeconds(item.validityStart);
- const end = timestampSeconds(item.validityEnd);
- const state: TokenState =
- end <= nowSeconds
- ? "expired"
- : start > nowSeconds
- ? "future"
- : "active";
const validity =
- state === "active"
- ? i18n.str`Valid until ${formatDate(item.validityEnd, language)}`
- : state === "future"
- ? i18n.str`Valid from ${formatDate(item.validityStart, language)}`
- : /* Translators: %1$s and %2$s are the start and end dates of a merchant-issued token's validity. */ i18n.str`Validity period ${formatDate(item.validityStart, language)} – ${formatDate(item.validityEnd, language)}`;
+ item.validityEnd.t_s === "never"
+ ? i18n.str`No expiry`
+ : i18n.str`Valid until ${formatDate(item.validityEnd.t_s, language)}`;
const quantity =
kind === "discounts" && "tokensAvailable" in item
? item.tokensAvailable
@@ -94,13 +126,9 @@ export function tokenListView(
name: item.name,
description: localizedDescription(item, languages),
merchant: merchantName(item),
- state,
validity,
...(quantity !== undefined ? { quantity } : {}),
};
})
- .sort((a, b) => {
- const rank = { active: 0, future: 1, expired: 2 };
- return rank[a.state] - rank[b.state] || a.name.localeCompare(b.name);
- });
+ .sort((a, b) => a.name.localeCompare(b.name, language));
}
diff --git a/packages/wallet-webui/src/screens/StorybookScreen.tsx b/packages/wallet-webui/src/screens/StorybookScreen.tsx
@@ -758,20 +758,10 @@ export function StorybookScreen(props: {
name: "Member price",
description: "Reduced admission for wallet holders",
merchant: "City Museum",
- state: "active",
// Translators: %1$s is a localized example date.
validity: i18n.str`Valid until ${"31 Aug 2026"}`,
quantity: 3,
},
- {
- id: "future",
- name: "Autumn offer",
- description: "A seasonal bakery discount",
- merchant: "Example Bakery",
- state: "future",
- // Translators: %1$s is a localized example date.
- validity: i18n.str`Valid from ${"1 Sep 2026"}`,
- },
]}
onBack={() => {}}
/>
@@ -790,19 +780,9 @@ export function StorybookScreen(props: {
name: "Premium pass",
description: "Provides access to this member benefit",
merchant: "City Museum",
- state: "active",
// Translators: %1$s is a localized example date.
validity: i18n.str`Valid until ${"31 Aug 2026"}`,
},
- {
- id: "future",
- name: "Autumn pass",
- description: "Provides access during the autumn season",
- merchant: "Example Museum",
- state: "future",
- // Translators: %1$s is a localized example date.
- validity: i18n.str`Valid from ${"1 Sep 2026"}`,
- },
]}
onBack={() => {}}
/>
@@ -814,10 +794,7 @@ export function StorybookScreen(props: {
</h2>
<ShoppingScreen
currency="CHF"
- urls={[
- "https://taler-ops.ch/",
- "https://shopping.example/",
- ]}
+ urls={["https://taler-ops.ch/", "https://shopping.example/"]}
loading={false}
onOpen={() => {}}
onBack={() => {}}
diff --git a/packages/wallet-webui/src/screens/TokenListScreen.tsx b/packages/wallet-webui/src/screens/TokenListScreen.tsx
@@ -1,4 +1,3 @@
-import { useState } from "preact/hooks";
import type { TokenItemView, TokenKind } from "../routes/token-model.js";
import { Card } from "../ui/Card.js";
import { ErrorCard } from "../ui/ErrorCard.js";
@@ -12,12 +11,8 @@ export function TokenListScreen(props: {
error?: ErrorPresentation;
onBack: () => void;
}) {
- const [filter, setFilter] = useState<"available" | "expired">("available");
const title =
props.kind === "discounts" ? i18n.str`Discounts` : i18n.str`Passes`;
- const items = props.items?.filter((item) =>
- filter === "expired" ? item.state === "expired" : item.state !== "expired",
- );
return (
<div class="mx-auto max-w-md space-y-5">
<header class="flex min-h-14 items-center gap-4">
@@ -31,33 +26,6 @@ export function TokenListScreen(props: {
</button>
<h1 class="text-2xl font-normal">{title}</h1>
</header>
- <div
- role="tablist"
- // Translators: %1$s is the localized plural heading “Discounts” or “Passes”; this labels the status tabs.
- aria-label={i18n.str`${title} status`}
- class="grid grid-cols-2 border-b border-outlineVariant"
- >
- <button
- type="button"
- role="tab"
- aria-selected={filter === "available"}
- onClick={() => setFilter("available")}
- class={`min-h-12 border-b-2 px-4 py-2 font-medium ${filter === "available" ? "border-primary text-primary" : "border-transparent text-secondary"}`}
- >
- {/* Translators: Adjective used as a token-status tab label. */}
- {i18n.str`Available`}
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={filter === "expired"}
- onClick={() => setFilter("expired")}
- class={`min-h-12 border-b-2 px-4 py-2 font-medium ${filter === "expired" ? "border-primary text-primary" : "border-transparent text-secondary"}`}
- >
- {/* Translators: Adjective used as a token-status tab label. */}
- {i18n.str`Expired`}
- </button>
- </div>
{props.loading && (
<Card>
<p role="status">
@@ -68,21 +36,17 @@ export function TokenListScreen(props: {
</Card>
)}
{props.error && <ErrorCard error={props.error} />}
- {!props.loading && !props.error && items?.length === 0 && (
+ {!props.loading && !props.error && props.items?.length === 0 && (
<Card>
<p>
- {filter === "expired"
- ? props.kind === "discounts"
- ? i18n.str`You don't have any expired discounts.`
- : i18n.str`You don't have any expired passes.`
- : props.kind === "discounts"
- ? i18n.str`You don't have any available discounts.`
- : i18n.str`You don't have any available passes.`}
+ {props.kind === "discounts"
+ ? i18n.str`You don't have any available discounts.`
+ : i18n.str`You don't have any available passes.`}
</p>
</Card>
)}
<div class="space-y-5">
- {items?.map((item) => (
+ {props.items?.map((item) => (
<article
key={item.id}
class="overflow-hidden rounded-xl border border-outlineVariant bg-surface"
@@ -104,15 +68,13 @@ export function TokenListScreen(props: {
×{item.quantity}
</span>
)}
- {props.kind === "passes" && item.state === "active" && (
+ {props.kind === "passes" && (
<span class="shrink-0 rounded-full bg-secondaryContainer px-2.5 py-1 text-xs font-medium text-onSecondaryContainer">{
/* Translators: A merchant-issued pass whose validity period includes the present time. */ i18n.str`Active`
}</span>
)}
</div>
- <div
- class={`border-t border-outlineVariant px-4 py-3 text-center text-xs font-medium ${item.state === "active" ? "bg-secondaryContainer text-onSecondaryContainer" : "bg-surface text-secondary"}`}
- >
+ <div class="border-t border-outlineVariant bg-secondaryContainer px-4 py-3 text-center text-xs font-medium text-onSecondaryContainer">
{item.validity}
</div>
</article>
diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx
@@ -30,6 +30,7 @@ import { WireTransferScreen } from "../src/screens/WireTransferScreen.js";
import { UriInputScreen } from "../src/screens/UriInputScreen.js";
import { ImportRecoveryScreen } from "../src/screens/ImportRecoveryScreen.js";
import { TokenListScreen } from "../src/screens/TokenListScreen.js";
+import { useTokenListView } from "../src/routes/token-model.js";
import { StorageMigrationCard } from "../src/screens/StorageMigrationCard.js";
import { RecoveryScreen } from "../src/screens/RecoveryScreen.js";
import { DonauSettingsScreen } from "../src/screens/DonauSettingsScreen.js";
@@ -4628,15 +4629,48 @@ test("restore progress exposes actual record counts", async () => {
await window.happyDOM.abort();
});
-test("DD 94 discounts separate available and expired cards accessibly", async () => {
+test("an open benefit list hides expired tokens and refreshes the family count", async (t) => {
+ const window = installDom();
+ const { renderHook, cleanup, act } = await import("@testing-library/preact");
+ const end = Date.UTC(2026, 7, 11);
+ let now = end;
+ t.mock.method(Date, "now", () => now);
+ const tokens = [
+ {
+ tokenFamilyHash: "family",
+ tokenIssuePubHash: "issue",
+ name: "City pass",
+ description: "Admission",
+ descriptionI18n: undefined,
+ merchantBaseUrl: "https://museum.example/",
+ validityStart: { t_s: end / 1000 - 100 },
+ validityEnd: { t_s: end / 1000 },
+ tokensAvailable: 2,
+ },
+ ];
+ let refreshed!: () => void;
+ const revalidation = new Promise<void>((resolve) => (refreshed = resolve));
+ const refresh = t.mock.fn(async () => refreshed());
+ try {
+ const view = renderHook(() =>
+ useTokenListView("discounts", tokens, ["en"], refresh),
+ );
+ assert.equal(view.result.current?.[0].quantity, 2);
+ await act(async () => {
+ now = end + 1;
+ await revalidation;
+ });
+ assert.deepEqual(view.result.current, []);
+ assert.equal(refresh.mock.callCount(), 1);
+ } finally {
+ cleanup();
+ await window.happyDOM.abort();
+ }
+});
+
+test("discounts display currently available items without history tabs", async () => {
const window = installDom();
const { render, cleanup } = await import("@testing-library/preact");
- const userEvent = (await import("@testing-library/user-event"))
- .default as unknown as {
- setup(options: { document: Document }): {
- click(element: Element): Promise<void>;
- };
- };
const axe = (await import("axe-core")).default as unknown as {
run(context: Element): Promise<{ violations: unknown[] }>;
};
@@ -4651,18 +4685,9 @@ test("DD 94 discounts separate available and expired cards accessibly", async ()
name: "Member price",
description: "Admission discount",
merchant: "City Museum",
- state: "active",
validity: "Valid until 20 Aug 2026",
quantity: 3,
},
- {
- id: "expired",
- name: "Old offer",
- description: "No longer valid",
- merchant: "City Museum",
- state: "expired",
- validity: "Validity period 1 Jul 2026 – 31 Jul 2026",
- },
]}
onBack={() => {}}
/>
@@ -4670,12 +4695,7 @@ test("DD 94 discounts separate available and expired cards accessibly", async ()
);
assert(view.getByText("Member price"));
assert(view.getByText("×3"));
- assert.equal(view.queryByText("Old offer"), null);
- await userEvent
- .setup({ document: window.document as unknown as Document })
- .click(view.getByRole("tab", { name: "Expired" }));
- assert(view.getByText("Old offer"));
- assert.equal(view.queryByText("Member price"), null);
+ assert.equal(view.queryByRole("tab"), null);
const result = await axe.run(window.document.body as unknown as Element);
assert.deepEqual(result.violations, []);
cleanup();
diff --git a/packages/wallet-webui/test/token-model.test.ts b/packages/wallet-webui/test/token-model.test.ts
@@ -4,7 +4,7 @@ import { tokenListView } from "../src/routes/token-model.js";
const now = Date.UTC(2026, 7, 11) / 1000;
-test("DD 94 token views distinguish active, future and expired benefits", () => {
+test("available benefits exclude future and expired tokens and use the wallet locale", () => {
const items = tokenListView(
"discounts",
[
@@ -15,7 +15,11 @@ test("DD 94 token views distinguish active, future and expired benefits", () =>
merchantInfo: { name: "City Museum" },
name: "Member price",
description: "Admission discount",
- descriptionI18n: { de: "Eintrittsrabatt" },
+ descriptionI18n: {
+ "DE-ch": "Eintrittsrabatt",
+ de: "Rabatt",
+ en: "Discount",
+ },
validityStart: { t_s: now - 10 },
validityEnd: { t_s: now + 10 },
tokensAvailable: 3,
@@ -47,18 +51,19 @@ test("DD 94 token views distinguish active, future and expired benefits", () =>
["de-CH", "en"],
);
assert.deepEqual(
- items.map((item) => item.state),
- ["active", "future", "expired"],
+ items.map((item) => item.id),
+ ["active"],
);
assert.equal(items[0].description, "Eintrittsrabatt");
assert.equal(items[0].quantity, 3);
- assert.equal(items[1].merchant, "bakery.example");
- assert.equal(items[1].quantity, 1);
- assert.equal(items[2].quantity, 1);
- assert.match(items[2].validity, /^Validity period/);
+ assert.equal(items[0].merchant, "City Museum");
+ const expectedDate = new Intl.DateTimeFormat("de-CH", {
+ dateStyle: "medium",
+ }).format(new Date((now + 10) * 1000));
+ assert.ok(items[0].validity.endsWith(expectedDate));
});
-test("passes show active state without a quantity", () => {
+test("available passes show the issuing merchant without a quantity", () => {
const [item] = tokenListView(
"passes",
[
@@ -75,6 +80,6 @@ test("passes show active state without a quantity", () => {
] as any,
now,
);
- assert.equal(item.state, "active");
+ assert.equal(item.merchant, "transit.example");
assert.equal(item.quantity, undefined);
});