// FE-COMP-TRIPPDF-001 to FE-COMP-TRIPPDF-010 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { http, HttpResponse } from 'msw' import { downloadTripPDF } from './TripPDF' import { server } from '../../../tests/helpers/msw/server' import { clearExchangeRateCache } from '../../hooks/useExchangeRates' import { getMergedItems, getTransportForDay } from '../../utils/dayMerge' // ── Helpers ─────────────────────────────────────────────────────────────────── const minimalArgs = { trip: { id: 1, title: 'My Trip', description: null, cover_image: null } as any, days: [{ id: 1, day_number: 1, title: null, date: '2025-06-01' }] as any[], places: [], assignments: {}, categories: [], dayNotes: [], reservations: [], t: (key: string, params?: any) => { if (params?.n !== undefined) return `Day ${params.n}` return key }, locale: 'en-US', } function getOverlay(): HTMLElement | null { return document.getElementById('pdf-preview-overlay') } function getIframe(): HTMLIFrameElement | null { return document.querySelector('#pdf-preview-overlay iframe') } /** The cover's "Planned" figure. The stat is read off its label, since days and places print the same markup. */ function plannedStat(html: string): number | null { const match = /
')
// Day content still renders inside the new structure.
expect(srcdoc).toContain('Rome Day')
expect(srcdoc).toContain('Colosseum')
})
it('FE-COMP-TRIPPDF-005c: the gap under the day header lives in the repeated thead cell (#1531)', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
const srcdoc = iframe!.srcdoc
// The thead is repeated on every overflow page, so the spacing below the header bar
// must be declared on its cell...
expect(srcdoc).toContain('.day-header > tr > td { padding: 0 var(--gutter) 5mm; }')
// ...and not as a block-start padding on .day-body, which the print engine only paints
// on the first fragment of the (fragmented) body cell.
expect(srcdoc).toContain('.day-body { padding: 0 var(--gutter) 4mm; }')
})
it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => {
const args = {
...minimalArgs,
trip: { id: 1, title: '', description: null, cover_image: null } as any,
}
await downloadTripPDF(args)
const iframe = getIframe()
expect(iframe!.srcdoc).not.toContain('')
expect(iframe!.srcdoc).toContain('<script>')
})
it('FE-COMP-TRIPPDF-007: close button removes the overlay from the DOM', async () => {
await downloadTripPDF(minimalArgs)
const closeBtn = document.getElementById('pdf-close-btn') as HTMLButtonElement
expect(closeBtn).not.toBeNull()
closeBtn.click()
expect(document.getElementById('pdf-preview-overlay')).toBeNull()
})
it('FE-COMP-TRIPPDF-008: clicking backdrop outside the card removes the overlay', async () => {
await downloadTripPDF(minimalArgs)
const overlay = getOverlay()!
overlay.click()
expect(document.getElementById('pdf-preview-overlay')).toBeNull()
})
it('FE-COMP-TRIPPDF-009: works with no days (empty itinerary)', async () => {
const args = { ...minimalArgs, days: [] }
await expect(downloadTripPDF(args)).resolves.not.toThrow()
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('')
// No day sections — should not contain day-section class
expect(iframe!.srcdoc).not.toContain('class="day-section')
})
it('FE-COMP-TRIPPDF-010: calls accommodationsApi.list with the trip id', async () => {
const { accommodationsApi } = await import('../../api/client')
const spy = vi.spyOn(accommodationsApi, 'list')
await downloadTripPDF(minimalArgs)
expect(spy).toHaveBeenCalledWith(1)
})
it('FE-COMP-TRIPPDF-011: renders place cards with name, address and category badge', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Colosseum')
expect(iframe!.srcdoc).toContain('Piazza del Colosseo, Rome')
expect(iframe!.srcdoc).toContain('Landmark')
})
it('FE-COMP-TRIPPDF-012: renders note cards in day body', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Remember sunscreen')
})
it('FE-COMP-TRIPPDF-013: renders transport reservation cards', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Flight to Rome')
expect(iframe!.srcdoc).toContain('ABC123')
// Single-leg flight keeps its full route, then airline and number as badges.
expect(bookingLines(iframe!.srcdoc)).toContain('CDG → FCO · Air Italia · AI123')
})
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
const stopover = {
...multiLegFlight,
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
],
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
}),
}
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
const lines = bookingLines(getIframe()?.srcdoc ?? '')
expect(lines).toContain('CDG → FCO · Air Italia · AI123 · reservations.meta.seat 31A')
expect(lines).toContain('BER → HND · Lufthansa · LH2 · reservations.meta.seat 14C')
expect(lines).toContain('FRA → BER · Lufthansa · LH1')
})
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
// The desktop toolbar hands the export the store's assignments, hidden stop and
// all, and that stop heads its check-in day. The day plan hides it and shows the
// booking as the accommodation block, and the print lists what the plan lists.
const hotelPlace = { id: 101, name: 'Hotel Hafen Hamburg', address: 'Seewartenstr. 9', place_time: null, price: '120' } as any
const hotelStop = { id: 201, day_id: 10, place_id: 101, order_index: 0, accommodation_id: 30, place: hotelPlace }
const flight = { ...transportReservation, title: 'Morning flight', reservation_time: '2025-06-01T08:00:00' }
await downloadTripPDF({
...richArgs,
assignments: { '10': [hotelStop, { ...assignmentForDay, order_index: 1 }] } as any,
reservations: [flight],
})
const html = getIframe()!.srcdoc
expect(html).not.toContain('Seewartenstr. 9')
expect(html.indexOf('Morning flight')).toBeLessThan(html.indexOf('Colosseum'))
expect(html.indexOf('Morning flight')).toBeGreaterThan(-1)
// The cover and the day header read the same list: the hidden stop is not a planned
// stop and its hotel's price is not part of the day, whichever shell asked.
expect(plannedStat(html)).toBe(1)
const money = html.replace(/[\u00a0\u202f]/g, ' ')
expect(money).toContain('15,00 €')
expect(money).not.toContain('135,00 €')
})
it('FE-COMP-TRIPPDF-013g: a service stop the plan keeps to the road trip view is not printed either, and comes back with the switch', async () => {
// "Show in Days too" off keeps petrol stations and rest areas out of the day lists.
// The print follows the same switch, so the desktop, which hands over the store's
// assignments, and the phone print the same day.
const pump = { id: 102, name: 'Aral Autohof', address: 'Autobahnkreuz 1', stop_type: 'fuel', place_time: null } as any
const pumpStop = { id: 202, day_id: 10, place_id: 102, order_index: 1, place: pump }
const assignments = { '10': [assignmentForDay, pumpStop] } as any
await downloadTripPDF({ ...richArgs, assignments, showServiceStops: false })
const hidden = getIframe()!.srcdoc
expect(hidden).not.toContain('Aral Autohof')
expect(hidden).toContain('Colosseum')
expect(plannedStat(hidden)).toBe(1)
// On, and by default, the stop prints where the plan lists it.
getOverlay()?.remove()
await downloadTripPDF({ ...richArgs, assignments })
const shown = getIframe()!.srcdoc
expect(shown).toContain('Aral Autohof')
expect(plannedStat(shown)).toBe(2)
})
it('FE-COMP-TRIPPDF-013c: a flight that lands the same day shows both times (#1310)', async () => {
const sameDay = { ...transportReservation, reservation_end_time: '2025-06-01T16:45:00' }
await downloadTripPDF({ ...richArgs, reservations: [sameDay] })
const iframe = getIframe()
// Without the landing time the reader cannot tell what is left of the day.
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '16:45' })
})
it('FE-COMP-TRIPPDF-013d: a flight without a landing time still shows its departure', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '' })
})
it('FE-COMP-TRIPPDF-013e: an overnight flight keeps its arrival on the arrival day (#1310)', async () => {
// Landing tomorrow: the departure day must not carry tomorrow's clock next
// to today's departure — the arrival day shows it as its own time.
const overnight = { ...transportReservation, day_id: 10, end_day_id: 11, reservation_end_time: '2025-06-02T06:15:00' }
await downloadTripPDF({
...richArgs,
days: [dayWithPlaces, { id: 11, day_number: 2, title: null, date: '2025-06-02' } as never],
reservations: [overnight],
})
const iframe = getIframe()
const html = iframe!.srcdoc
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.departure')).toMatchObject({ start: '14:30', end: '' })
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.arrival')).toMatchObject({ start: '06:15' })
})
it('FE-COMP-TRIPPDF-013b: renders every flight number for a multi-leg flight', async () => {
await downloadTripPDF({ ...richArgs, reservations: [multiLegFlight] })
const iframe = getIframe()
// One line per leg, each with its own flight number and segment route.
expect(bookingLines(iframe!.srcdoc)).toEqual(['FRA → BER · Lufthansa · LH1', 'BER → HND · Lufthansa · LH2'])
})
it('FE-COMP-TRIPPDF-014: renders cover image when trip has cover_image', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
// Cover image rendered as background-image on .cover-bg
expect(iframe!.srcdoc).toContain('cover.jpg')
})
it('FE-COMP-TRIPPDF-023: a cover url cannot close url() and add a second declaration', async () => {
// cover_image is a free string on the write path, and the style attribute is decoded
// before the CSS is parsed, so the quote and the paren have to be encoded.
const hostile = "http://host/a.jpg');background-image:url('http://elsewhere/leak.jpg"
await downloadTripPDF({ ...richArgs, trip: { ...richArgs.trip, cover_image: hostile } as any })
const iframe = getIframe()
const style = / {
server.use(
http.get('/api/trips/:id/accommodations', () =>
HttpResponse.json({
accommodations: [{
id: 1,
start_day_id: 10,
end_day_id: 10,
place_name: 'Hotel Roma',
place_address: 'Via Roma 1',
check_in: '15:00',
check_out: '11:00',
notes: 'Breakfast included',
confirmation: 'CONF999',
}],
})
),
)
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Hotel Roma')
expect(iframe!.srcdoc).toContain('CONF999')
})
it('FE-COMP-TRIPPDF-016: renders place description and a currency-formatted price chip', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Ancient amphitheater')
// richArgs trip has no explicit currency, place has no currency override —
// formatMoney falls back to EUR, formatted via Intl (symbol, not literal "EUR" text).
expect(iframe!.srcdoc).toContain('15,00')
expect(iframe!.srcdoc).toContain('€')
})
// #2692: a place's description and notes print as the planner shows them, not as raw markdown.
it('FE-COMP-TRIPPDF-016c: renders markdown in a place description, sanitized', async () => {
const description = ['**Colosseum** tickets', '', '| Gate | Time |', '| --- | --- |', '| A | 9:00 |', '', ''].join('\n')
const place = { ...placeWithDetails, description }
const md = { ...richArgs, places: [place], assignments: { '10': [{ ...assignmentForDay, place }] } as typeof richArgs.assignments }
await downloadTripPDF(md)
const html = getIframe()?.srcdoc ?? ''
expect(html).toContain('Colosseum')
expect(html).toContain(' 9:00 | ')
expect(html).not.toContain('**Colosseum**')
expect(html).not.toContain('')
})
it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => {
const usdArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'USD' },
}
await downloadTripPDF(usdArgs)
const iframe = getIframe()
// Place price chip: place has no currency override, falls back to trip.currency (USD).
expect(iframe!.srcdoc).toContain('$15.00')
// No literal "EUR" text should leak into a USD trip's export.
expect(iframe!.srcdoc).not.toContain('EUR')
// Price chip icon must stay currency-neutral — not the euro-shaped glyph.
expect(iframe!.srcdoc).not.toContain('M14 5c-3.87 0-7 3.13-7 7s3.13 7 7 7c2.17 0 4.1-.99 5.4-2.55')
})
it('FE-COMP-TRIPPDF-016c: a place with its own currency overrides the trip currency for its price chip', async () => {
const mixedArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'EUR' },
assignments: {
'10': [{
...assignmentForDay,
place: { ...placeWithDetails, currency: 'JPY', price: '1500' },
}],
} as any,
}
await downloadTripPDF(mixedArgs)
const iframe = getIframe()
// JPY is a zero-decimal currency (currencyDecimals) and uses its own symbol, not EUR.
// Note: Intl renders JPY with the fullwidth yen sign (U+FFE5 "¥"), not U+00A5 "¥".
expect(iframe!.srcdoc).toContain('¥1,500')
})
it('FE-COMP-TRIPPDF-016d: converts foreign-currency prices into the trip currency for day and cover totals (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', ({ request }) => {
expect(new URL(request.url).searchParams.get('base')).toBe('NOK')
return HttpResponse.json([{ quote: 'USD', rate: 0.1 }]) // 1 NOK = 0.1 USD
}))
const mixedArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'NOK' },
assignments: {
'10': [
{ ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '273' } },
{ ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } },
],
} as any,
}
await downloadTripPDF(mixedArgs)
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
// 2500 NOK + 273 USD / 0.1 = 5230 NOK, marked approximate, in day header AND cover stat.
expect(srcdoc).toContain('≈ 5 230,00 kr')
expect((srcdoc.match(/≈ 5 230,00 kr/g) || []).length).toBeGreaterThanOrEqual(2)
})
it('FE-COMP-TRIPPDF-016e: falls back to per-currency breakdowns when the FX fetch fails (#1561)', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error()))
const mixedArgs = {
...richArgs,
trip: { ...richArgs.trip, currency: 'NOK' },
assignments: {
'10': [
{ ...assignmentForDay, place: { ...placeWithDetails, currency: 'USD', price: '2730.27' } },
{ ...assignmentForDay, id: 201, place: { ...placeWithDetails, id: 101, name: 'Museum', currency: null, price: '2500' } },
],
} as any,
}
// Export still resolves — a dead FX endpoint must never break the PDF.
await expect(downloadTripPDF(mixedArgs)).resolves.not.toThrow()
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
// Honest breakdown, base currency first; the USD amount is never NOK-labeled.
expect(srcdoc).toContain('2 500,00 kr + $2,730.27')
expect(srcdoc).not.toContain('≈')
expect(srcdoc).not.toMatch(/5 ?230/)
})
it('FE-COMP-TRIPPDF-016g: with Costs on, the day and cover totals are the expenses, not the place prices (#2551)', async () => {
const args = {
...richArgs,
trip: { ...richArgs.trip, currency: 'USD' },
costsEnabled: true,
budgetItems: [
{ id: 1, trip_id: 10, category: 'activities', name: 'Tickets', total_price: 42, currency: null, place_id: 100 },
{ id: 2, trip_id: 10, category: 'other', name: 'Insurance', total_price: 8, currency: null },
],
}
await downloadTripPDF(args)
const srcdoc = getIframe()!.srcdoc
// The day carries the ticket linked to its place, the cover the whole trip.
expect(srcdoc).toContain('$42.00')
expect(srcdoc).toContain('$50.00')
document.getElementById('pdf-preview-overlay')?.remove()
// Every expense deleted: nothing is left to add up, whatever price the place carries.
await downloadTripPDF({ ...args, budgetItems: [] })
const after = getIframe()!.srcdoc
expect(after).not.toContain('$42.00')
expect(after).not.toContain('$50.00')
expect(after).toContain('$15.00') // the place's own price chip stays on its card
})
it('FE-COMP-TRIPPDF-016f: an all-same-currency trip makes no FX request', async () => {
let fxCalled = false
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => {
fxCalled = true
return HttpResponse.json([])
}))
await downloadTripPDF({ ...richArgs, trip: { ...richArgs.trip, currency: 'EUR' } })
expect(fxCalled).toBe(false)
// Totals render exactly as before for the single-currency case.
const srcdoc = getIframe()!.srcdoc.replace(/[\u00A0\u202F]/g, ' ')
expect(srcdoc).toContain('15,00 €')
expect(srcdoc).not.toContain('≈')
})
it('FE-COMP-TRIPPDF-017: renders trip description on cover', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Summer adventure')
})
it('FE-COMP-TRIPPDF-018: renders place with direct image URL', async () => {
const argsWithImg = {
...richArgs,
assignments: {
'10': [{
...assignmentForDay,
place: { ...placeWithDetails, image_url: '/uploads/colosseum.jpg' },
}],
} as any,
}
await downloadTripPDF(argsWithImg)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('colosseum.jpg')
})
it('FE-COMP-TRIPPDF-018b: renders a persisted place-photo proxy image_url as an ')
expect(html).toContain('class="place-thumb-fallback"')
})
it('FE-W5PDF-013: coordinates are printed for a place that has no address', async () => {
await downloadTripPDF(spanArgs([], {
assignments: {
'10': [{ id: 1, day_id: 10, order_index: 0, place: { id: 71, name: 'Pin Only', lat: 48.858093, lng: 2.294694 } }],
} as any,
}))
expect(srcdoc()).toContain('48.85809, 2.29469')
})
it('FE-W5PDF-014: a note without a time renders only its text and falls back to the default icon', async () => {
await downloadTripPDF(spanArgs([], {
dayNotes: [{ id: 1, day_id: 10, text: 'Just a note', time: null, icon: 'NotAnIcon', sort_order: 0 }] as any,
}))
const html = srcdoc()
expect(html).toContain('Just a note')
expect(html).not.toContain('class="note-time"')
})
it('FE-W5PDF-015: check-in, middle and check-out days each get their own accommodation block', async () => {
server.use(
http.get('/api/trips/:id/accommodations', () =>
HttpResponse.json({
accommodations: [{
id: 1, start_day_id: 10, end_day_id: 12, place_name: 'Hotel Nord', place_address: 'Main St',
check_in: '15:00', check_out: '10:00', confirmation: 'CONF-9', notes: 'Late arrival',
}],
}),
),
)
await downloadTripPDF(spanArgs([]))
const html = srcdoc()
expect(html).toContain('reservations.meta.checkIn')
expect(html).toContain('reservations.meta.linkAccommodation')
expect(html).toContain('reservations.meta.checkOut')
expect(html).toContain('Hotel Nord')
expect(html).toContain('Main St')
expect(html).toContain('Late arrival')
expect(html).toContain('CONF-9')
expect(html).toContain('class="day-accommodations single"')
})
it('FE-W5PDF-016: two accommodations on one day are ordered by their start day', async () => {
server.use(
http.get('/api/trips/:id/accommodations', () =>
HttpResponse.json({
accommodations: [
{ id: 2, start_day_id: 11, end_day_id: 12, place_name: 'Later Inn', place_address: null, check_in: null, check_out: null, confirmation: null },
{ id: 1, start_day_id: 10, end_day_id: 12, place_name: 'Earlier Inn', place_address: null, check_in: null, check_out: null, confirmation: null },
],
}),
),
)
await downloadTripPDF(spanArgs([]))
const html = srcdoc()
const days = daysOf(html)
expect(days.indexOf('Earlier Inn')).toBeGreaterThan(-1)
expect(days.indexOf('Earlier Inn')).toBeLessThan(days.indexOf('Later Inn'))
// the shared days list two hotels, so they lose the single-column class
expect(html).toContain('class="day-accommodations"')
})
it('FE-W5PDF-017: a trip without dated days prints no date range and no day dates', async () => {
await downloadTripPDF({
...minimalArgs,
trip: { id: 1, title: 'Undated', description: null, cover_image: null } as any,
days: [{ id: 1, day_number: 1, title: null, date: null }] as any[],
})
const html = srcdoc()
expect(html).not.toContain('class="cover-dates"')
expect(html).not.toContain('class="day-date"')
expect(html).toContain(' Item | ')
expect(html).toContain('Socks | ')
expect(html).toContain('Bare')
})
})
// FE-W5PDF-021 to FE-W5PDF-026 — the defaulting arms of the exporter.
describe('downloadTripPDF defaults', () => {
type Args = ParametersMy Trip') expect(html).toContain('0 ')
})
it('FE-W5PDF-022: an accommodations response without the key degrades to no hotels', async () => {
server.use(
http.get('/api/trips/:id/accommodations', () => HttpResponse.json({})),
http.get('/api/pdf-sections/:tripId', () => HttpResponse.json({})),
)
await downloadTripPDF({ ...minimalArgs } as unknown as Args)
expect(srcdoc()).not.toContain('day-accommodations-overview"')
expect(srcdoc()).not.toContain('class="plugin-sections')
})
it('FE-W5PDF-023: items without an explicit order fall back to position zero', async () => {
await downloadTripPDF({
...minimalArgs,
days: [{ id: 1, day_number: 1, title: 'Only Day', date: '2025-06-01' }] as any[],
assignments: { '1': [{ id: 1, day_id: 1, order_index: null, place: { id: 5, name: 'Unordered Place' } }] } as any,
dayNotes: [{ id: 2, day_id: 1, text: 'Unordered Note', sort_order: null, icon: 'Info' }] as any,
})
const html = srcdoc()
expect(html).toContain('Unordered Place')
expect(html).toContain('Unordered Note')
})
it('FE-W5PDF-024: an empty metadata string and a missing title are handled', async () => {
await downloadTripPDF({
...minimalArgs,
trip: { id: 1, title: null, description: null, cover_image: null } as any,
days: [{ id: 1, day_number: 1, title: null, date: '2025-06-01' }] as any[],
reservations: [{ id: 1, title: null, type: 'restaurant', day_id: 1, metadata: '' }] as any[],
})
const html = srcdoc()
expect(html).toContain(' |