feat: Apple Wallet passes for bookings

"Add to Apple Wallet" on a booking in the iOS app turns it into a TREK pass:
a boarding pass from and to for flights, trains, buses and boats, check-in and
check-out for a stay, pickup and drop-off for a car, the time for anything
else, with the confirmation code as a QR code. Wallet brings it up on the lock
screen around its time and place: times carry the offset of the endpoint's zone
(looked up from the coordinates where the endpoint has none), stays and
restaurants their place's coordinates. The labels come from the booking forms'
own strings, so nothing new to translate on the pass.

Only liketrek holds the Pass Type ID certificate, so the server sends the pass's
texts to the TREK services' signer (TREK_WALLET_PASS_URL, push.liketrek.com)
once per tap; it stores nothing, and TREK_SERVICES=off turns it off with the
other services. Texts are cleaned of links and shortened here, the answer must
be a .pkpass within 512 KB, and a user gets 20 passes a minute.

- New wallet-pass domain: GET /api/trips/:tripId/reservations/:id/wallet-pass
  behind the trip guard, the booking checked to belong to the trip; trip title
  and place come from the reservations domain (findPassContext)
- MWalletButton in the transport and booking sheets, only where the app binary
  has the wallet feature; undated bookings and failures are told apart
- TREK_WALLET_PASS_URL in .env.example, compose, Helm and the wiki
This commit is contained in:
Maurice
2026-11-07 10:40:41 +01:00
parent 794da3be72
commit 37a4e84360
56 changed files with 1873 additions and 113 deletions
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import MWalletButton from './MWalletButton';
const wallet = vi.hoisted(() => ({
can: true,
add: vi.fn(),
}));
vi.mock('../../native/wallet', () => ({
canAddToWallet: () => wallet.can,
addReservationToWallet: wallet.add,
}));
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {}, updateRequired: false }) }));
beforeEach(() => {
wallet.can = true;
wallet.add.mockReset();
});
describe('MWalletButton', () => {
it('is not there for a booking that is not saved yet', () => {
render(<MWalletButton tripId={42} reservationId={undefined} onError={vi.fn()} />);
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
it('sits in a wrapper when the sheet places it', () => {
const { container } = render(<MWalletButton tripId={42} reservationId={7} onError={vi.fn()} className="mt-2" />);
expect(container.querySelector('div.mt-2 > button')).not.toBeNull();
});
it('is not there where the app cannot add a pass', () => {
wallet.can = false;
render(<MWalletButton tripId={42} reservationId={7} onError={vi.fn()} />);
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
it('adds the booking and says nothing when Wallet took it', async () => {
wallet.add.mockResolvedValue('added');
const onError = vi.fn();
render(<MWalletButton tripId={42} reservationId={7} onError={onError} />);
fireEvent.click(screen.getByRole('button'));
await waitFor(() => expect(wallet.add).toHaveBeenCalledWith(42, 7, expect.any(String)));
await waitFor(() => expect(screen.getByRole('button')).not.toBeDisabled());
expect(onError).not.toHaveBeenCalled();
});
it('explains an undated booking and a failure apart', async () => {
const onError = vi.fn();
render(<MWalletButton tripId={42} reservationId={7} onError={onError} />);
wallet.add.mockResolvedValueOnce('undated');
fireEvent.click(screen.getByRole('button'));
await waitFor(() => expect(onError).toHaveBeenCalledWith('reservations.wallet.undated'));
await waitFor(() => expect(screen.getByRole('button')).not.toBeDisabled());
wallet.add.mockResolvedValueOnce('failed');
fireEvent.click(screen.getByRole('button'));
await waitFor(() => expect(onError).toHaveBeenLastCalledWith('reservations.wallet.failed'));
});
});
@@ -0,0 +1,55 @@
import { Loader2, Wallet } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { useNativeCapabilities } from '../../native/capabilities';
import { addReservationToWallet, canAddToWallet } from '../../native/wallet';
interface MWalletButtonProps {
tripId: number;
/** None yet (a booking being created): no button. */
reservationId: number | undefined;
/** Placement in the hosting sheet, on a wrapper around the button. */
className?: string;
/** Shown when the pass could not be made (a toast in the sheet that hosts the button). */
onError: (message: string) => void;
}
/**
* "Add to Apple Wallet" on a booking, in the iOS app only (feature wallet): the
* booking becomes a TREK pass that shows up on the lock screen around its time
* and place. Black like Apple's own badge, so it reads as Wallet at a glance.
*/
export default function MWalletButton({ tripId, reservationId, onError, className }: MWalletButtonProps) {
const { t, language } = useTranslation();
// Re-renders once the app binary has said what it can do.
useNativeCapabilities();
const [busy, setBusy] = useState(false);
if (reservationId === undefined || !canAddToWallet()) return null;
const id = reservationId;
const add = async () => {
if (busy) return;
setBusy(true);
try {
const outcome = await addReservationToWallet(tripId, id, language);
if (outcome === 'undated') onError(t('reservations.wallet.undated'));
else if (outcome === 'failed') onError(t('reservations.wallet.failed'));
} finally {
setBusy(false);
}
};
const button = (
<button
type="button"
onClick={() => void add()}
disabled={busy}
aria-busy={busy}
className="flex items-center gap-[6px] rounded-full bg-black px-3 py-[7px] text-[length:calc(12px*var(--fs-scale-body,1))] font-semibold text-white transition-transform active:scale-[.97] disabled:opacity-70" // theme-lint-disable: Apple Wallet's badge is black in either theme
>
{busy ? <Loader2 size={13} className="animate-spin" /> : <Wallet size={13} strokeWidth={2} />}
{t('reservations.wallet.add')}
</button>
);
return className ? <div className={className}>{button}</div> : button;
}
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from 'react'
import { Link2, Ticket } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import MWalletButton from '../../../components/MWalletButton'
import { MBookingCodeStatus, MBookingNotes, MBookingTravelers } from './MBookingFields'
import { useAddonStore } from '../../../../store/addonStore'
import { useTranslation } from '../../../../i18n'
@@ -36,6 +37,9 @@ const EMPTY = {
hotel_address: '',
}
/** A booking that is saved already has an id; one being created has none. */
const savedId = (res: { id: number } | null | undefined): number | undefined => res?.id
/**
* Add/edit booking sheet — the mobile counterpart of the desktop ReservationModal,
* driven by the planner's own editor flags (showReservationModal / editingReservation /
@@ -187,6 +191,9 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
/>
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[6px] pt-[2px]">
{/* A saved booking goes into Apple Wallet (iOS app only). */}
<MWalletButton tripId={tripId} reservationId={savedId(res)} onError={toast.error} className="mb-1 mt-2 flex" />
{/* BOOKING TYPE */}
<Eyebrow className="mb-[6px] mt-2 uppercase">{t('reservations.bookingType')}</Eyebrow>
<div className="flex flex-wrap gap-[6px]">
@@ -398,7 +405,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
{/* FILES + COSTS */}
<MBookingFilesCosts
planner={planner}
reservationId={res?.id}
reservationId={savedId(res)}
pendingFiles={pendingFiles}
setPendingFiles={setPendingFiles}
canUploadFiles={canUploadFiles}
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { ArrowRight, Footprints, Paperclip, Pencil, Route as RouteIcon, Trash2 } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import MWalletButton from '../../../components/MWalletButton'
import type { MTripSheetsProps } from '../MTripShell'
import { useTranslation } from '../../../../i18n'
import { useSettingsStore } from '../../../../store/settingsStore'
@@ -348,6 +349,7 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
<RouteIcon size={13} strokeWidth={2} />
{t('mobileTrip.onMap')}
</button>
<MWalletButton tripId={planner.tripId} reservationId={payload.reservationId} onError={planner.toast.error} />
{resFiles.map(f => (
<button
key={f.id}
+35 -1
View File
@@ -9,7 +9,7 @@ vi.mock('./capabilities', () => ({ hasNativeFeature: (name: string) => name ===
vi.mock('./trekShell', () => ({ TrekShell: shell }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: report }));
import { addToWallet, canAddToWallet, isWalletPassName } from './wallet';
import { addReservationToWallet, addToWallet, canAddToWallet, isWalletPassName } from './wallet';
const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' });
@@ -62,3 +62,37 @@ describe('Apple Wallet', () => {
expect(shell.addToWallet).not.toHaveBeenCalled();
});
});
describe('a booking into Wallet', () => {
const answer = (status: number) =>
vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(status === 200 ? pass : '{}', { status }));
it('fetches the booking pass in the user language and hands it to Wallet', async () => {
const fetchSpy = answer(200);
shell.addToWallet.mockResolvedValue({ result: 'added' });
expect(await addReservationToWallet(42, 7, 'de')).toBe('added');
expect(fetchSpy).toHaveBeenCalledWith('/api/trips/42/reservations/7/wallet-pass?lang=de', {
credentials: 'include',
});
fetchSpy.mockRestore();
});
it('tells an undated booking from a failure', async () => {
let fetchSpy = answer(422);
expect(await addReservationToWallet(42, 7, 'en')).toBe('undated');
fetchSpy.mockRestore();
fetchSpy = answer(502);
expect(await addReservationToWallet(42, 7, 'en')).toBe('failed');
fetchSpy.mockRestore();
fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline'));
expect(await addReservationToWallet(42, 7, 'en')).toBe('failed');
fetchSpy.mockRestore();
});
it('fails when Wallet does not take the pass', async () => {
const fetchSpy = answer(200);
shell.addToWallet.mockRejectedValue({ code: 'INVALID' });
expect(await addReservationToWallet(42, 7, 'en')).toBe('failed');
fetchSpy.mockRestore();
});
});
+27
View File
@@ -32,3 +32,30 @@ export async function addToWallet(blob: Blob): Promise<boolean> {
return false;
}
}
/** What a tap on "Add to Apple Wallet" came to. */
export type ReservationWalletOutcome = 'added' | 'undated' | 'failed';
/**
* A booking's pass, made by this server (GET .../reservations/:id/wallet-pass,
* signed by the TREK services) and handed to Apple Wallet's sheet. `undated`:
* the booking has no date yet, which Wallet needs to bring the pass up.
*/
export async function addReservationToWallet(
tripId: number,
reservationId: number,
language: string
): Promise<ReservationWalletOutcome> {
let response: Response;
try {
response = await fetch(
`/api/trips/${tripId}/reservations/${reservationId}/wallet-pass?lang=${encodeURIComponent(language)}`,
{ credentials: 'include' }
);
} catch {
return 'failed';
}
if (response.status === 422) return 'undated';
if (!response.ok) return 'failed';
return (await addToWallet(await response.blob())) ? 'added' : 'failed';
}