diff --git a/client/src/mobile/components/MWalletButton.test.tsx b/client/src/mobile/components/MWalletButton.test.tsx
index cd0a8c0d6..32a7fa254 100644
--- a/client/src/mobile/components/MWalletButton.test.tsx
+++ b/client/src/mobile/components/MWalletButton.test.tsx
@@ -3,19 +3,23 @@ import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/rende
import MWalletButton from './MWalletButton';
const wallet = vi.hoisted(() => ({
- can: true,
+ kind: 'apple' as 'apple' | 'google' | null,
add: vi.fn(),
+ addGoogle: vi.fn(),
}));
vi.mock('../../native/wallet', () => ({
- canAddToWallet: () => wallet.can,
+ bookingWallet: () => wallet.kind,
+ useGoogleWalletAvailable: () => wallet.kind === 'google',
addReservationToWallet: wallet.add,
+ addReservationToGoogleWallet: wallet.addGoogle,
}));
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {}, updateRequired: false }) }));
beforeEach(() => {
- wallet.can = true;
+ wallet.kind = 'apple';
wallet.add.mockReset();
+ wallet.addGoogle.mockReset();
});
describe('MWalletButton', () => {
@@ -30,7 +34,7 @@ describe('MWalletButton', () => {
});
it('is not there where the app cannot add a pass', () => {
- wallet.can = false;
+ wallet.kind = null;
render();
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
@@ -56,4 +60,16 @@ describe('MWalletButton', () => {
fireEvent.click(screen.getByRole('button'));
await waitFor(() => expect(onError).toHaveBeenLastCalledWith(expect.stringMatching(/could not be made/i)));
});
+
+ it('on Android adds the booking to Google Wallet, under its own name', async () => {
+ wallet.kind = 'google';
+ wallet.addGoogle.mockResolvedValue('added');
+ const onError = vi.fn();
+ render();
+ expect(screen.getByRole('button')).toHaveTextContent(/Google Wallet/);
+ fireEvent.click(screen.getByRole('button'));
+ await waitFor(() => expect(wallet.addGoogle).toHaveBeenCalledWith(42, 7, expect.any(String)));
+ expect(wallet.add).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/mobile/components/MWalletButton.tsx b/client/src/mobile/components/MWalletButton.tsx
index e687aaa5a..49c052786 100644
--- a/client/src/mobile/components/MWalletButton.tsx
+++ b/client/src/mobile/components/MWalletButton.tsx
@@ -2,7 +2,12 @@ import { Loader2, Wallet } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { useNativeCapabilities } from '../../native/capabilities';
-import { addReservationToGoogleWallet, addReservationToWallet, bookingWallet } from '../../native/wallet';
+import {
+ addReservationToGoogleWallet,
+ addReservationToWallet,
+ bookingWallet,
+ useGoogleWalletAvailable,
+} from '../../native/wallet';
interface MWalletButtonProps {
tripId: number;
@@ -24,6 +29,8 @@ export default function MWalletButton({ tripId, reservationId, onError, classNam
const { t, language } = useTranslation();
// Re-renders once the app binary has said what it can do.
useNativeCapabilities();
+ // Re-renders once the server has said whether Google Wallet works here.
+ useGoogleWalletAvailable(tripId);
const [busy, setBusy] = useState(false);
const wallet = bookingWallet();
if (reservationId === undefined || !wallet) return null;
diff --git a/client/src/native/wallet.test.ts b/client/src/native/wallet.test.ts
index 7a859bc6c..f76042d49 100644
--- a/client/src/native/wallet.test.ts
+++ b/client/src/native/wallet.test.ts
@@ -13,6 +13,7 @@ vi.mock('./trekShell', () => ({ TrekShell: shell }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: report }));
import {
+ _resetGoogleWalletAvailability,
addReservationToGoogleWallet,
addReservationToWallet,
addToWallet,
@@ -20,6 +21,7 @@ import {
canAddToGoogleWallet,
canAddToWallet,
isWalletPassName,
+ loadGoogleWalletAvailability,
} from './wallet';
const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' });
@@ -117,10 +119,49 @@ describe('Google Wallet', () => {
env.android = true;
env.wallet = false;
env.googleWallet = true;
+ _resetGoogleWalletAvailability();
});
- it('is offered only on Android with the googleWallet feature, and names its wallet', () => {
+ const available = (body: unknown, status = 200) =>
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify(body), { status }))
+ );
+
+ it('offers no button until the server says Google Wallet works, and asks it once', async () => {
+ expect(bookingWallet()).toBeNull();
+ available({ available: false });
+ expect(await loadGoogleWalletAvailability(42)).toBe(false);
+ expect(bookingWallet()).toBeNull();
+ available({ available: true });
+ expect(await loadGoogleWalletAvailability(42)).toBe(false);
+ expect(fetch).not.toHaveBeenCalled();
+ _resetGoogleWalletAvailability();
+ expect(await loadGoogleWalletAvailability(42)).toBe(true);
+ expect(fetch).toHaveBeenCalledWith('/api/trips/42/reservations/google-wallet', { credentials: 'include' });
+ expect(bookingWallet()).toBe('google');
+ vi.unstubAllGlobals();
+ });
+
+ it('an older server without the route, or one offline, offers none', async () => {
+ available({}, 404);
+ expect(await loadGoogleWalletAvailability(42)).toBe(false);
+ _resetGoogleWalletAvailability();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new Error('offline');
+ })
+ );
+ expect(await loadGoogleWalletAvailability(42)).toBe(false);
+ vi.unstubAllGlobals();
+ });
+
+ it('is offered only on Android with the googleWallet feature, and names its wallet', async () => {
expect(canAddToGoogleWallet()).toBe(true);
+ available({ available: true });
+ await loadGoogleWalletAvailability(42);
+ vi.unstubAllGlobals();
expect(bookingWallet()).toBe('google');
env.googleWallet = false;
expect(canAddToGoogleWallet()).toBe(false);
diff --git a/client/src/native/wallet.ts b/client/src/native/wallet.ts
index 5b5bedc7d..07c9916b4 100644
--- a/client/src/native/wallet.ts
+++ b/client/src/native/wallet.ts
@@ -1,3 +1,4 @@
+import { useEffect, useSyncExternalStore } from 'react';
import { toBase64 } from './blobBase64';
import { hasNativeFeature } from './capabilities';
import { isNativeAndroid, isNativeIos } from './platform';
@@ -65,13 +66,65 @@ export function canAddToGoogleWallet(): boolean {
return isNativeAndroid() && hasNativeFeature('googleWallet');
}
-/** The wallet a booking's button adds to here, if any: Apple Wallet on iOS, Google Wallet on Android. */
+/**
+ * Whether this server can make Google Wallet passes, asked once per session
+ * (GET /api/trips/:tripId/reservations/google-wallet): the TREK services can
+ * only once liketrek has a Wallet issuer, and an older server has no such route.
+ * Until it says yes the Android app offers no button, so nobody taps one that
+ * can only fail.
+ */
+let googleState: 'unknown' | 'asking' | 'yes' | 'no' = 'unknown';
+const googleListeners = new Set<() => void>();
+
+function setGoogleState(next: typeof googleState): void {
+ googleState = next;
+ for (const listener of googleListeners) listener();
+}
+
+export async function loadGoogleWalletAvailability(tripId: number): Promise {
+ if (!canAddToGoogleWallet()) return false;
+ if (googleState === 'yes' || googleState === 'no') return googleState === 'yes';
+ if (googleState === 'asking') return false;
+ setGoogleState('asking');
+ try {
+ const response = await fetch(`/api/trips/${tripId}/reservations/google-wallet`, { credentials: 'include' });
+ const body = response.ok ? ((await response.json()) as { available?: unknown }) : {};
+ setGoogleState(body.available === true ? 'yes' : 'no');
+ } catch {
+ // Offline: ask again next time.
+ setGoogleState('unknown');
+ }
+ return googleState === 'yes';
+}
+
+/** True once this server has said Google Wallet works; asks it the first time a booking shows. */
+export function useGoogleWalletAvailable(tripId: number): boolean {
+ const available = useSyncExternalStore(
+ (listener) => {
+ googleListeners.add(listener);
+ return () => googleListeners.delete(listener);
+ },
+ () => googleState === 'yes'
+ );
+ useEffect(() => {
+ void loadGoogleWalletAvailability(tripId);
+ }, [tripId]);
+ return available;
+}
+
+/** The wallet a booking's button adds to here, if any: Apple Wallet on iOS, Google Wallet on Android where the server can. */
export function bookingWallet(): 'apple' | 'google' | null {
if (canAddToWallet()) return 'apple';
- if (canAddToGoogleWallet()) return 'google';
+ if (canAddToGoogleWallet() && googleState === 'yes') return 'google';
return null;
}
+/** Test helper: forget what the server said. */
+export function _resetGoogleWalletAvailability(): void {
+ googleState = 'unknown';
+ googleListeners.clear();
+}
+
/**
* A booking as a Google Wallet pass: this server asks the TREK services for a
* save link (GET .../reservations/:id/wallet-pass/google), and the app opens it,
@@ -94,6 +147,8 @@ export async function addReservationToGoogleWallet(
return 'failed';
}
if (response.status === 422) return 'undated';
+ // Google Wallet went away here (switched off, issuer gone): the button goes with it.
+ if (response.status === 404) setGoogleState('no');
if (!response.ok) return 'failed';
try {
const { saveUrl } = (await response.json()) as { saveUrl?: unknown };