fix(wallet): date a booking's pass by its stay or linked day when it has no time of its own

The Wallet pass took its date only from the booking's own time or, for a
journey, its departure stop. A hotel whose check-in and check-out live on its
stay, and a booking linked to a day that carries only a clock, have neither,
so Wallet answered "Give the booking a date first" for a booking the app
shows with its dates. A TestFlight tester hit it with a hotel booked from
8 to 11 January.

The pass context now reads the dates of the days a booking is linked to and,
for a hotel, the first and last day of its stay with its check-in and
check-out times. The pass falls back to them in the order the app uses
(bookingDates): the booking's own time first, then the stay or the linked
day, with the booking's or the stay's clock. A booking with no date anywhere
is still refused.
This commit is contained in:
Maurice
2026-11-25 10:25:10 +01:00
parent c1c77d89b5
commit b6c50eb146
6 changed files with 237 additions and 7 deletions
@@ -3,7 +3,7 @@ import { accommodationIdMatches } from './reservation-accommodation';
import type { SqlEntityManager } from '@mikro-orm/sql';
/** The tables `passContextQuery` reads. */
type PassContextDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations'>;
type PassContextDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations' | 'days'>;
/** What a booking's Wallet pass needs beyond the booking: where it is, and the trip's name. */
export interface ReservationPassContext {
@@ -11,11 +11,21 @@ export interface ReservationPassContext {
place_lat: number | null;
place_lng: number | null;
place_name: string | null;
/** The date of the day the booking is linked to, and of the day it ends on. */
day_date: string | null;
end_day_date: string | null;
/** A hotel's stay: its first and last day, and its check-in and check-out times. */
stay_start_date: string | null;
stay_end_date: string | null;
stay_check_in: string | null;
stay_check_out: string | null;
}
/**
* The trip's title and the place a booking is at (its own place, else its
* stay's), for its Apple Wallet pass (`ReservationsRepository.findPassContext`).
* stay's), for its Apple Wallet pass (`ReservationsRepository.findPassContext`),
* and the dates of the days it is linked to: a day-linked booking, or a hotel
* whose dates live on its stay, carries no date of its own.
* Scoped to the trip, so a booking of another trip reads as none. Kept out of
* the repository file, which is at its size baseline. `em` is the repository's
* own, which has checked the request context.
@@ -35,6 +45,10 @@ export async function passContextQuery(
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'ap.id')),
)
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.leftJoin('days as rd', 'rd.id', 'r.day_id')
.leftJoin('days as red', 'red.id', 'r.end_day_id')
.leftJoin('days as asd', 'asd.id', 'ap.start_day_id')
.leftJoin('days as aed', 'aed.id', 'ap.end_day_id')
.where('r.id', '=', id)
.where('r.trip_id', '=', trip_id)
.select([
@@ -42,6 +56,12 @@ export async function passContextQuery(
(eb) => eb.fn.coalesce('p.lat', 'acc_p.lat').as('place_lat'),
(eb) => eb.fn.coalesce('p.lng', 'acc_p.lng').as('place_lng'),
(eb) => eb.fn.coalesce('p.name', 'acc_p.name').as('place_name'),
'rd.date as day_date',
'red.date as end_day_date',
'asd.date as stay_start_date',
'aed.date as stay_end_date',
'ap.check_in as stay_check_in',
'ap.check_out as stay_check_out',
])
.executeTakeFirst();
return row as ReservationPassContext | undefined;
@@ -83,6 +83,18 @@ export interface WalletPassSource {
tripTitle: string | null;
/** The booking's place (the hotel, the restaurant), when it has coordinates. */
place: { lat: number; lng: number; name: string | null } | null;
/**
* The dates the booking sits on when its own time carries none: the day it is
* linked to and the day it ends on, or for a hotel the first and last day of its
* stay with the stay's check-in and check-out times. The app shows these dates,
* so the pass reads them too.
*/
linked?: {
startDate: string | null;
endDate: string | null;
checkIn?: string | null;
checkOut?: string | null;
} | null;
}
const KIND_OF: Record<string, WalletPassKind> = {
@@ -127,6 +139,20 @@ function splitLocal(value: string | null | undefined): { date: string; time: str
return { date: match[1] as string, time: match[2] ?? null };
}
/** The clock of a time-only value ("12:40", "15:00:00"), which a day-linked booking may carry. */
function clockOnly(value: string | null | undefined): string | null {
return /^\s*(\d{2}:\d{2})/.exec(value ?? '')?.[1] ?? null;
}
/** A linked day's date with the first clock the booking or its stay gives for it. */
function onLinkedDay(
date: string | null | undefined,
...clocks: (string | null | undefined)[]
): { date: string; time: string | null } | null {
if (!date) return null;
return { date, time: clocks.map(clockOnly).find((clock) => clock !== null) ?? null };
}
/** The UTC offset of a zone at a wall-clock time, in minutes ("+09:00" is 540). */
function offsetMinutes(timeZone: string, wallClockAsUtc: number): number {
const parts = new Intl.DateTimeFormat('en-US', {
@@ -233,14 +259,27 @@ export function buildWalletPassRequest(src: WalletPassSource, words: WalletWords
const toEnd = [...endpoints].reverse().find((e) => e.role === 'to');
const journey = kind === 'flight' || kind === 'train' || kind === 'bus' || kind === 'boat';
// When it starts: the departure as the endpoint knows it, else the booking's own time.
// When it starts: the departure as the endpoint knows it, else the booking's own
// time, else the day it is linked to (a hotel's stay), with the clock it has.
const linked = src.linked;
const hotel = kind === 'hotel';
const startLocal =
(journey && fromEnd?.local_date ? { date: fromEnd.local_date, time: fromEnd.local_time } : null) ??
splitLocal(reservation.reservation_time);
splitLocal(reservation.reservation_time) ??
onLinkedDay(
linked?.startDate,
reservation.reservation_time,
...(hotel ? [text(meta, 'check_in_time', 8), linked?.checkIn] : []),
);
if (!startLocal) return null;
const endLocal =
(journey && toEnd?.local_date ? { date: toEnd.local_date, time: toEnd.local_time } : null) ??
splitLocal(reservation.reservation_end_time);
splitLocal(reservation.reservation_end_time) ??
onLinkedDay(
linked?.endDate,
reservation.reservation_end_time,
...(hotel ? [text(meta, 'check_out_time', 8), linked?.checkOut] : []),
);
const place = src.place ?? (fromEnd && !journey ? { lat: fromEnd.lat, lng: fromEnd.lng, name: fromEnd.name } : null);
const startZone =
@@ -5,7 +5,7 @@ import { logWarn } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { RateLimitService } from '../common/rate-limit.service';
import { ReservationsReadService } from '../reservations/reservations-read.service';
import { buildWalletPassRequest, type WalletPassEndpoint } from './wallet-pass.builder';
import { buildWalletPassRequest, type WalletPassEndpoint, type WalletPassSource } from './wallet-pass.builder';
import { loadWalletWords } from './wallet-pass.words';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
@@ -27,6 +27,26 @@ const PKPASS = 'application/vnd.apple.pkpass';
/** Every ZIP, and so every .pkpass, starts with a local file header. */
const ZIP_LOCAL_HEADER = 0x04034b50;
/**
* The dates a booking sits on through the days it is linked to, as the app reads
* them (bookingDates): a hotel's stay when it has one, else the booking's own days.
*/
function linkedDates(
type: string | null | undefined,
context: Awaited<ReturnType<ReservationsReadService['passContext']>>,
): WalletPassSource['linked'] {
if (!context) return null;
if (type === 'hotel' && (context.stay_start_date || context.stay_end_date)) {
return {
startDate: context.stay_start_date,
endDate: context.stay_end_date,
checkIn: context.stay_check_in,
checkOut: context.stay_check_out,
};
}
return { startDate: context.day_date, endDate: context.end_day_date };
}
export interface WalletPass {
bytes: Buffer;
filename: string;
@@ -143,6 +163,7 @@ export class WalletPassService {
typeof context?.place_lat === 'number' && typeof context.place_lng === 'number'
? { lat: context.place_lat, lng: context.place_lng, name: context.place_name ?? null }
: null,
linked: linkedDates(row.type, context),
},
await loadWalletWords(language),
);
@@ -1058,7 +1058,7 @@ describe('ReservationsRepository — findPassContext', () => {
await setReservation(room.id, { accommodation_id: String(stay.id) });
const bare = createReservation(testDb, trip.id, { title: 'Museum', type: 'event' });
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toEqual({
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toMatchObject({
trip_title: 'Japan 2027',
place_lat: 35.0,
place_lng: 135.77,
@@ -1073,10 +1073,44 @@ describe('ReservationsRepository — findPassContext', () => {
place_lat: null,
place_lng: null,
place_name: null,
day_date: null,
end_day_date: null,
stay_start_date: null,
stay_end_date: null,
stay_check_in: null,
stay_check_out: null,
});
const other = createTrip(testDb, user.id, { title: 'Elsewhere' });
expect(await reservationsRepo.findPassContext(dinner.id, other.id)).toBeUndefined();
});
it('RES-PASS-002: reads the dates of the linked days and of a hotel stay, with its check-in and check-out', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Valencia', start_date: '2027-01-08', end_date: '2027-01-11' });
const first = createDay(testDb, trip.id, { date: '2027-01-08' });
const last = createDay(testDb, trip.id, { date: '2027-01-11' });
const hotel = createPlace(testDb, trip.id, { name: 'Only You Hotel Valencia', lat: 39.47, lng: -0.376 });
const stay = createDayAccommodation(testDb, trip.id, hotel.id, first.id, last.id);
await updateRows(await orm(), DayAccommodations, { id: stay.id }, { check_in: '15:00', check_out: '10:00' });
const room = createReservation(testDb, trip.id, { title: 'Only You', type: 'hotel' });
await setReservation(room.id, { accommodation_id: String(stay.id) });
const dinner = createReservation(testDb, trip.id, { title: 'Dinner', type: 'restaurant' });
await setReservation(dinner.id, { day: first.id, endDay: last.id });
expect(await reservationsRepo.findPassContext(room.id, trip.id)).toMatchObject({
stay_start_date: '2027-01-08',
stay_end_date: '2027-01-11',
stay_check_in: '15:00',
stay_check_out: '10:00',
day_date: null,
});
expect(await reservationsRepo.findPassContext(dinner.id, trip.id)).toMatchObject({
day_date: '2027-01-08',
end_day_date: '2027-01-11',
stay_start_date: null,
});
});
});
describe('ReservationsRepository — the origin of an imported booking', () => {
@@ -292,4 +292,66 @@ describe('wallet pass builder', () => {
expect(request?.back).toBeUndefined();
expect(request?.start).toBe('2027-04-02T15:00:00+00:00');
});
// A hotel whose dates live on its stay, and a booking linked to a day, carry no
// date of their own. The app shows the stay's and the day's dates, so the pass
// used to refuse a booking the user could see dated ("give the booking a date").
it('WALLET-B-011: a hotel without its own time takes the dates and times of its stay', () => {
const request = buildWalletPassRequest(
source(
{ reservation_time: null, reservation_end_time: null, metadata: {} },
{ linked: { startDate: '2027-01-08', endDate: '2027-01-11', checkIn: '15:00', checkOut: '10:00:00' } },
),
WORDS,
);
expect(request).toMatchObject({
kind: 'hotel',
start: '2027-01-08T15:00:00+09:00',
end: '2027-01-11T10:00:00+09:00',
});
expect(request?.details).toEqual([
{ label: 'Check-in', value: displayTime('en-GB', '2027-01-08', '15:00') },
{ label: 'Check-out', value: displayTime('en-GB', '2027-01-11', '10:00') },
]);
});
it('WALLET-B-012: the booking own check-in time comes before the stay one', () => {
const request = buildWalletPassRequest(
source(
{ reservation_time: null, reservation_end_time: null, metadata: { check_in_time: '16:30' } },
{ linked: { startDate: '2027-01-08', endDate: null, checkIn: '15:00', checkOut: null } },
),
WORDS,
);
expect(request?.start).toBe('2027-01-08T16:30:00+09:00');
expect(request?.end).toBeUndefined();
});
it('WALLET-B-013: a day-linked booking with only a clock is dated by its day', () => {
const request = buildWalletPassRequest(
source(
{
type: 'restaurant',
title: 'Gion Karyo',
reservation_time: '19:30',
reservation_end_time: null,
metadata: {},
},
{ linked: { startDate: '2027-04-03', endDate: null } },
),
WORDS,
);
expect(request).toMatchObject({ kind: 'restaurant', start: '2027-04-03T19:30:00+09:00' });
});
it('WALLET-B-014: its own date still wins over the linked day, and nothing at all still means no pass', () => {
const own = buildWalletPassRequest(
source({}, { linked: { startDate: '2027-01-08', endDate: '2027-01-11' } }),
WORDS,
);
expect(own?.start).toBe('2027-04-02T15:00:00+09:00');
expect(
buildWalletPassRequest(source({ reservation_time: null }, { linked: { startDate: null, endDate: null } }), WORDS),
).toBeNull();
});
});
@@ -145,6 +145,60 @@ describe('WalletPassService', () => {
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('WALLET-S-003b: a hotel dated only by its stay gets a pass with the stay dates', async () => {
const { service, reservations } = make();
signerAnswers(200, PASS);
reservations.getReservationWithJoins.mockResolvedValueOnce({
...ROW,
reservation_time: null,
reservation_end_time: null,
metadata: '{}',
});
reservations.passContext.mockResolvedValueOnce({
trip_title: 'Valencia',
place_lat: 39.47,
place_lng: -0.376,
place_name: 'Only You Hotel Valencia',
day_date: null,
end_day_date: null,
stay_start_date: '2027-01-08',
stay_end_date: '2027-01-11',
stay_check_in: '15:00',
stay_check_out: '10:00',
});
await service.passFor(1, 42, 7, 'en');
const body = JSON.parse(String((safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit])[1].body));
expect(body).toMatchObject({ kind: 'hotel', start: '2027-01-08T15:00:00+01:00', end: '2027-01-11T10:00:00+01:00' });
});
it('WALLET-S-003c: any other booking reads the dates of the days it is linked to', async () => {
const { service, reservations } = make();
signerAnswers(200, PASS);
reservations.getReservationWithJoins.mockResolvedValueOnce({
...ROW,
type: 'restaurant',
reservation_time: '19:30',
reservation_end_time: null,
metadata: '{}',
});
reservations.passContext.mockResolvedValueOnce({
trip_title: 'Japan 2027',
place_lat: 35.0,
place_lng: 135.77,
place_name: 'Gion Karyo',
day_date: '2027-04-03',
end_day_date: null,
// A stay the restaurant happens to share is not its date.
stay_start_date: '2027-04-01',
stay_end_date: '2027-04-06',
stay_check_in: '15:00',
stay_check_out: '11:00',
});
await service.passFor(1, 42, 7, 'en');
const body = JSON.parse(String((safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit])[1].body));
expect(body).toMatchObject({ kind: 'restaurant', start: '2027-04-03T19:30:00+09:00' });
});
it('WALLET-S-004: a user asking too often is slowed down before anything is read', async () => {
const { service, rateLimit, reservations } = make();
rateLimit.check.mockResolvedValueOnce(false);