// Trip PDF via browser print window import { createElement } from 'react' import { getCategoryIcon } from '../shared/categoryIcons' import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Sailboat, CableCar, Bike, CarTaxiFront, Route, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, Utensils, Users, ParkingSquare, LucideIcon } from 'lucide-react' import { mapsApi, pluginsApi } from '../../api/client' import { accommodationRepo } from '../../repo/accommodationRepo' import type { Trip, Day, Place, Category, AssignmentsMap, DayNote, DistanceUnit, BudgetItem } from '../../types' import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder' import { hidesOnMiddleDay, getTransportForDay, getMergedItems, getSpanPhase, getDisplayTimeForDay } from '../../utils/dayMerge' import { safeHexColor } from '../../utils/safeColor' import { pdfSwitchOn } from '../../utils/pdfSwitch' import { openPdfPreview, PAGE_BREAK_KEY, TRANSPORT_NOTES_KEY } from './pdfPreview' import { renderIconMarkup } from '../../utils/iconMarkup' import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters' import { useSettingsStore } from '../../store/settingsStore' import { useTripStore } from '../../store/tripStore' import { useAddonStore } from '../../store/addonStore' import { projectDayItinerary } from '../Map/dayTourProjection' import { planCosts } from '../Planner/planCosts' import { routeDistanceLabel } from '../Map/tripRouteLabels' import { drawTripRoute, type TripPdfRouteOptions } from './tripPdfRoute' import { fetchExchangeRates } from '../../hooks/useExchangeRates' import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs' import { onlyMyPlan, planAssignments } from './pdfScope' import { createPdfMarkdown, PDF_MARKDOWN_CSS } from './pdfMarkdown' function renderLucideIcon(icon:LucideIcon, props = {}) { return renderIconMarkup( createElement(icon, props) ); } const NOTE_ICON_MAP = { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } function noteIconSvg(iconId) { const Icon = NOTE_ICON_MAP[iconId] || FileText return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#94a3b8' }) } const RESERVATION_ICON_MAP = { flight: Plane, train: Train, bus: Bus, car: Car, taxi: CarTaxiFront, bicycle: Bike, cruise: Ship, ferry: Sailboat, cable_car: CableCar, transport_other: Route, restaurant: Utensils, event: Ticket, tour: Users, parking: ParkingSquare, other: FileText } const RESERVATION_COLOR_MAP = { flight: '#3b82f6', train: '#06b6d4', bus: '#059669', car: '#6b7280', taxi: '#ca8a04', bicycle: '#84cc16', cruise: '#0ea5e9', ferry: '#0d9488', cable_car: '#dc2626', transport_other: '#6b7280', restaurant: '#ef4444', event: '#f59e0b', tour: '#10b981', parking: '#2563eb', other: '#6b7280' } function reservationIconSvg(type) { const Icon = RESERVATION_ICON_MAP[type] || Ticket const color = RESERVATION_COLOR_MAP[type] || '#3b82f6' return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color }) } const ACCOMMODATION_ICON_MAP = { accommodation: Hotel, checkin: LogIn, checkout: LogOut, location: MapPin, note: FileText, confirmation: KeyRound } function accommodationIconSvg(type) { const Icon = ACCOMMODATION_ICON_MAP[type] || BedDouble return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#03398f', className: 'accommodation-icon' }) } // ── SVG inline icons (for chips) ───────────────────────────────────────────── const svgPin = `` const svgClock = `` const svgClock2= `` const svgCheck = `` const svgMoney = `` function escHtml(str) { if (!str) return '' return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') } // The style attribute is decoded back into raw quotes before the CSS is parsed, so // escHtml alone cannot stop a cover_image from closing the url() and appending its own // declaration. Percent-encoding is transparent to the fetch. function cssUrl(url) { return String(url).replace(/["'()\\\s]/g, c => '%' + c.codePointAt(0).toString(16).padStart(2, '0')) } // The day colours come from a fixed palette, but this is a style attribute being built // by string concatenation — the same place cssUrl exists for. Anything that is not a // plain hex triple is not a colour, and gets the route blue instead of a chance to // close the declaration. function hexColour(value) { return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : '#0a84ff' } function absUrl(url) { if (!url) return null if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url return window.location.origin + (url.startsWith('/') ? '' : '/') + url } function safeImg(url) { if (!url) return null if (url.startsWith('https://') || url.startsWith('http://')) return url // The in-app place-photo proxy always streams a JPEG but has no file extension // (it ends in …/bytes), so the extension check below would wrongly reject it — // which is why persisted place photos showed as category icons in the PDF. if (url.startsWith('/api/maps/place-photo/')) return absUrl(url) // gif is in the list because place-image-upload.ts accepts it; without it an // uploaded GIF hero silently fell back to the category icon in the PDF. return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null } // Generate SVG string from Lucide icon name (for category thumbnails) function categoryIconSvg(iconName, color = '#6366f1', size = 24) { const Icon = getCategoryIcon(iconName) return renderIconMarkup( createElement(Icon, { size, strokeWidth: 1.8, color: 'rgba(255,255,255,0.92)' }) ) } function shortDate(d, locale) { if (!d) return '' return new Date(d + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } function longDateRange(days, locale) { const dd = [...days].filter(d => d.date).sort((a, b) => a.day_number - b.day_number) if (!dd.length) return null const f = new Date(dd[0].date + 'T00:00:00Z') const l = new Date(dd[dd.length - 1].date + 'T00:00:00Z') return `${f.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' })} – ${l.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' })}` } // Pre-fetch place photos for all assigned places. // Assignment places are a server-side projection that drops osm_id, so we recover // the full place from the trip's places pool and key the photo off the same id the // app UI uses (google_place_id || osm_id || coords) — otherwise OSM/coords-only // places fell back to category icons in the PDF even though they show photos in-app. async function fetchPlacePhotos(assignments: AssignmentsMap, places: Place[]) { const photoMap = {} // placeId → photoUrl // The assignment projection drops osm_id, so recover it from the full places pool. const osmById = new Map((places || []).map(p => [p.id, p.osm_id])) const allPlaces = Object.values(assignments).flatMap(a => a.map(x => x.place)).filter(Boolean) const unique = [...new Map(allPlaces.map(p => [p.id, p])).values()] const toFetch = unique .map(p => ({ p, osm_id: osmById.get(p.id) })) .filter(({ p, osm_id }) => !p.image_url && (p.google_place_id || osm_id || (p.lat != null && p.lng != null))) await Promise.allSettled( toFetch.map(async ({ p, osm_id }) => { // Same key the app UI uses: google_place_id || osm_id || coords. const photoId = p.google_place_id || osm_id || `coords:${p.lat}:${p.lng}` try { const data = await mapsApi.placePhoto(photoId, p.lat, p.lng, p.name) if (data.photoUrl) photoMap[p.id] = data.photoUrl } catch {} }) ) return photoMap } interface downloadTripPDFProps { trip: Trip days: Day[] places: Place[] assignments: AssignmentsMap categories: Category[] // Flattened across days: each note carries its own day_id (see downloadTripPDF callers). dayNotes: DayNote[] reservations?: any[] t: (key: string, params?: Record) => string locale: string /** * '12h' | '24h'. The document is a plain HTML string assembled outside React, * so the setting cannot be read with a hook in here — it comes over the same * way `locale` does (#2066). */ timeFormat?: string /** 'metric' | 'imperial'. Same reasoning as `timeFormat` — read as a prop, not a hook. */ distanceUnit?: string /** * The road trip setting "Show in Days too" (`roadtrip_service_stops_in_days`), read as a * prop for the same reason. Off, the day plan keeps petrol stations and rest areas to * the road trip view, and so does the print. */ showServiceStops?: boolean /** The trip's expenses, which the cost figures add up with Costs on (#2551). Read from the trip store when left out. */ budgetItems?: BudgetItem[] /** Whether the Costs addon is on. Read from the addon store when left out. */ costsEnabled?: boolean /** Prints only this member's plan (#2168): the stops and bookings that name them, and the ones that name nobody. */ onlyUserId?: number /** The planner's road trip vias and tour stages, and the routing progress and stop (#2876). */ route?: TripPdfRouteOptions /** Aborted once nobody waits for the document any more (its dialog was closed): it then never opens. */ signal?: AbortSignal } // `assignments` is normalised here once, to the plan's own list; every read below // (and fetchPlacePhotos) relies on it being an object. export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, onlyUserId, route, signal }: downloadTripPDFProps) { const { assignments: stored, reservations } = onlyUserId != null ? onlyMyPlan(allStored, allReservations, onlyUserId) : { assignments: allStored, reservations: allReservations } const assignments = planAssignments(stored, showServiceStops) const breaksPerDay = pdfSwitchOn(PAGE_BREAK_KEY) const showTransportNotes = pdfSwitchOn(TRANSPORT_NOTES_KEY) // Set while the days render: the switch only shows when there is a note to hide. let hasTransportNotes = false const loc = _locale || undefined const tr = _t || (k => k) const markdown = createPdfMarkdown() // The store read is the fallback, not the source: a caller that forgets the // prop still prints the reader's own format instead of silently reverting. const is12h = (_timeFormat || useSettingsStore.getState().settings.time_format || '24h') === '12h' const fmtTime = (v?: string | null) => formatClockTime(v, is12h) const sorted = [...(days || [])].sort((a, b) => a.day_number - b.day_number) const range = longDateRange(sorted, loc) const coverImg = safeImg(trip?.cover_image) //retrieve accommodations for the trip to display on the day sections and prefetch their photos if needed const accommodations = await accommodationRepo.list(trip.id); // The endpoint answers `{ accommodations: [...] }`, not a bare array. Unwrapped once // here so every reader below gets the list itself — passing the envelope on is what // cost the route map its hotel legs, and silently (#1736). const accommodationList = Array.isArray(accommodations?.accommodations) ? accommodations.accommodations : [] // Sections contributed by pdfSectionProvider plugins — server-normalized plain // text (counts + lengths capped), appended after the days. Fail-safe: an error // just means no extra sections, the core export is untouched. const pluginSections = await pluginsApi.pdfSections(trip.id).then(r => r.sections || []).catch(() => []) const unit: DistanceUnit = (_distanceUnit || useSettingsStore.getState().settings.distance_unit) === 'imperial' ? 'imperial' : 'metric' const toursEnabled = useAddonStore.getState().isEnabled('tours') const hasInvalidTour = toursEnabled && Object.values(assignments).some(list => projectDayItinerary(list || [], true, places).some(item => item.kind === 'tour' && !item.valid)) const { route: tripRoute, mapSvg: tripMapSvg } = await drawTripRoute({ days: sorted, assignments, storedAssignments: allStored, reservations, accommodations: accommodationList, optimizeFromAccommodation: useSettingsStore.getState().settings.optimize_from_accommodation, toursEnabled, places, }, { tripId: trip.id, unit, options: route }) // Legs left straight, refused or skipped, make every figure below a floor; each says so. const unroutedLegs = tripRoute?.unroutedLegs ?? 0 const totalDistanceLabel = tripRoute && tripRoute.totalDistance > 0 ? routeDistanceLabel(tripRoute.totalDistance, unroutedLegs, unit, tr) : null // Each day named and coloured exactly as the legend on the planner map, so the two // read as the same picture. Days that routed to nothing are already out of `days`. const tripMapHtml = tripMapSvg ? `
${escHtml(tr('pdf.mapTitle'))} ${totalDistanceLabel ? `${escHtml(tr('pdf.distanceLabel'))}: ${escHtml(totalDistanceLabel)}` : ''}
${unroutedLegs ? `
${escHtml(tr('map.overview.unrouted', { count: unroutedLegs }))}
` : ''} ${tripMapSvg}
${tripRoute.days.filter(d => d.lines.length).map(d => ` ${escHtml(d.title || tr('dayplan.dayN', { n: d.dayNumber }))} ${escHtml(routeDistanceLabel(d.distance, d.unroutedLegs ?? 0, unit, tr))} `).join('')}
${escHtml(tr('pdf.mapCredit'))}
` : '' // Pre-fetch place photos (Google, OSM and coords-only places) const photoMap = await fetchPlacePhotos(assignments, places) const totalAssigned = new Set( Object.values(assignments).flatMap(a => a.map(x => x.place?.id)).filter(Boolean) ).size // The PDF is a trip-scoped, shareable document, so totals stay in the trip's // own currency. Rates are resolved ONCE before any HTML is built so the cover // stat and every day header agree; all-same-currency trips skip the FX fetch // entirely (offline export keeps working), and a failed fetch degrades to // per-currency breakdowns instead of mislabeled sums (#1561). const tripCur = (trip?.currency || 'EUR').toUpperCase() // The same figures the plan shows (#2551): the expenses with Costs on, each once, // else each planned place's own price once. An expense linked to a place finds its // day through every stop, the booked night's included. const withCosts = costsEnabled ?? useAddonStore.getState().isEnabled('budget') const costs = planCosts({ days: sorted, assignments: withCosts ? stored : assignments, reservations, budgetItems: budgetItems ?? useTripStore.getState().budgetItems, costsEnabled: withCosts, tripCurrency: tripCur, }) const allCostEntries: MoneyEntry[] = costs.total const needsFx = allCostEntries.some(e => e.amount !== 0 && e.currency.toUpperCase() !== tripCur) const fxRates = needsFx ? await fetchExchangeRates(tripCur) : null const totalCostLabel = formatMoneySum(allCostEntries, tripCur, loc || 'en', fxRates) // Day totals render in the trip's currency; foreign amounts are converted via the // pre-fetched rates, or listed per-currency when rates are unavailable (#1561). const dayCost = (dayId: number) => formatMoneySum(costs.byDay.get(dayId) || [], tripCur, loc || 'en', fxRates) /* * The span label is the only PDF-specific piece left here. Everything else * about how a day is ordered — which transports belong to it, what time each * one shows, where it sits among the places — comes from utils/dayMerge, the * same functions the day plan itself uses (#1978). * * There used to be a second implementation in this file. It ordered by * `day_plan_position`, which is one global number per booking, seeded from * whichever day happened to render first; on any other day of a span it * pointed at the wrong slot, and when it was still null the export fell back * to the order the API returned. That is why the PDF was right some of the * time and swapped two bookings the rest of it. */ const pdfGetSpanLabel = (r: any, phase: string): string | null => { if (phase === 'single') return null if (r.type === 'flight') return tr(`reservations.span.${phase === 'start' ? 'departure' : phase === 'end' ? 'arrival' : 'inTransit'}`) if (r.type === 'car') return tr(`reservations.span.${phase === 'start' ? 'pickup' : phase === 'end' ? 'return' : 'active'}`) // Parking reuses span.pickup for its end day: you drop the car off and collect it // again later, so the rental car's wording carries over without a second key. if (r.type === 'parking') return tr(`reservations.span.${phase === 'start' ? 'dropOff' : phase === 'end' ? 'pickup' : 'ongoing'}`) return tr(`reservations.span.${phase === 'start' ? 'start' : phase === 'end' ? 'end' : 'ongoing'}`) } // Build day HTML const daysHtml = sorted.map((day, di) => { // What the plan lists (planAssignments): the stop a booked night wrote sat at the // head of its day, so the hotel printed above a morning flight (#2434). const assigned = (assignments[String(day.id)] || []) .slice() .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)) const notes = (dayNotes || []).filter(n => n.day_id === day.id).slice() .sort((a: any, b: any) => (a.sort_order ?? 0) - (b.sort_order ?? 0)) const cost = dayCost(day.id) // Assembled exactly the way DayPlanSidebar assembles it, so the page and the // print cannot disagree about what order a day is in. const dayTransports = getTransportForDay({ reservations: reservations || [], dayId: day.id, dayAssignmentIds: assigned.map((a: any) => a.id), days: sorted, }) // Hotels come out in the accommodations block, a rental car's middle days // appear only in the sidebar header, and a multi-day parking's middle days // nowhere at all. const merged = getMergedItems({ dayAssignments: assigned, dayNotes: notes, dayTransports, dayId: day.id, }).filter(item => { if (item.type !== 'transport') return true const r: any = item.data if (r.type === 'car' && getSpanPhase(r, day.id) === 'middle') return false return !hidesOnMiddleDay(r, day.id) }) let pi = 0 const itemsHtml = merged.length === 0 ? `
${escHtml(tr('dayplan.emptyDay'))}
` : merged.map(item => { if (item.type === 'transport') { const r = item.data const meta = typeof r.metadata === 'string' ? JSON.parse(r.metadata || '{}') : (r.metadata || {}) const icon = reservationIconSvg(r.type) const color = RESERVATION_COLOR_MAP[r.type] || '#3b82f6' let subtitle = '' // Flights render one subtitle line per leg (see below); everything else is a single line. let subtitleLines: string[] = [] /* * A multi-leg booking arrives as one item per leg now, the way the * day plan shows it, because the shared merge expands legs so each * one can sit at its own time among the day's places. Previously * the export printed a single row with every leg as a subtitle * line, which put the second leg's departure next to the first * leg's clock. */ if (r.__leg) { const l = r.__leg // The segment's own booking code, which the leg object does not // carry — read back from the booking by index. At the gate that is // the code the airline asks for (#1943), so losing it here would // have been a real regression for a stopover flight. const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index] subtitleLines = [[ l.airline, l.flight_number, l.train_number, l.platform ? `${tr('reservations.meta.platform')} ${l.platform}` : '', l.seat ? `${tr('reservations.meta.seat')} ${l.seat}` : '', (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', source?.confirmation_number, ].filter(Boolean).join(' · ')].filter(Boolean) } else if (r.type === 'flight') { const legs = getFlightLegs(r) if (legs.length > 1) { // Multi-leg: one line per leg so every flight number + segment route is // shown, with the segment's own booking code where it has one (#1943). // At the gate that is the number the airline asks for. subtitleLines = legs.map(l => [l.airline, l.flight_number, (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', l.confirmation_number] .filter(Boolean).join(' · ')) .filter(Boolean) } else { // Single-leg: full route over all waypoints (FRA → BER → HND), falling back to the // flat metadata pair for legacy single-leg flights without endpoints. const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name) const route = stops.length >= 2 ? stops.join(' → ') : (meta.departure_airport && meta.arrival_airport ? `${meta.departure_airport} → ${meta.arrival_airport}` : '') subtitle = [meta.airline, meta.flight_number, route].filter(Boolean).join(' · ') } } else if (r.type === 'train') { const legs = getTrainLegs(r) if (legs.length > 1) { // Multi-leg: one line per leg so every train number + segment route shows, // with the segment's own booking code where it has one (#1943). subtitleLines = legs.map(l => [l.train_number, l.platform ? `${tr('reservations.meta.platform')} ${l.platform}` : '', (l.from || l.to) ? [l.from, l.to].filter(Boolean).join(' → ') : '', l.confirmation_number] .filter(Boolean).join(' · ')) .filter(Boolean) } else { const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.code || e.name) const route = stops.length >= 2 ? stops.join(' → ') : '' subtitle = [meta.train_number, meta.platform ? `${tr('reservations.meta.platform')} ${meta.platform}` : '', meta.seat ? `${tr('reservations.meta.seat')} ${meta.seat}` : '', route].filter(Boolean).join(' · ') } } else if (r.type === 'car') { // A rental with stops is a drive, and the printout is what people take // into the car (#1797). Without this the route reads as pick-up and return // with everything in between missing. // // Consecutive repeats collapse, and a chain that names one place only is // dropped: the ordinary rental is picked up and returned at the same desk, // which satisfies "two endpoints" and would otherwise print the counter's // name twice with an arrow between. A genuine round trip keeps both ends, // because Dresden sits between them. const stops = (r.endpoints || []).slice() .sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)) .map(e => e.name) .filter((name, i, all) => name && name !== all[i - 1]) subtitle = new Set(stops).size >= 2 ? stops.join(' → ') : '' } else if (r.type === 'restaurant') subtitle = [meta.party_size ? `${meta.party_size} guests` : ''].filter(Boolean).join(' · ') else if (r.type === 'event') subtitle = [meta.venue].filter(Boolean).join(' · ') else if (r.type === 'tour') subtitle = [meta.operator].filter(Boolean).join(' · ') if (subtitleLines.length === 0 && subtitle) subtitleLines = [subtitle] const locationLine = r.location || meta.location || '' const phase = getSpanPhase(r, day.id) const spanLabel = pdfGetSpanLabel(r, phase) const displayTime = getDisplayTimeForDay(r, day.id) // Start and end, the way the day plan draws it (#1310). Without the // landing time a flight reads as an open-ended block and the reader // cannot tell how much of the day is left for anything else. // // Only on a transport that begins and ends on this day: across a // span the arrival belongs to the arrival day, which already shows // it as its own time, and repeating it here would put tomorrow's // clock next to today's departure. const startTime = fmtTime(splitReservationDateTime(displayTime).time) const endTime = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : '' const time = [startTime, endTime].filter(Boolean).join(' – ') const titleHtml = `${spanLabel ? escHtml(spanLabel) + ': ' : ''}${escHtml(r.title)}` const transportNote = typeof r.notes === 'string' ? r.notes.trim() : '' if (transportNote) hasTransportNotes = true return `
${icon}
${titleHtml}${time ? ` ${time}` : ''}
${subtitleLines.filter(Boolean).map(s => `
${escHtml(s)}
`).join('')} ${locationLine ? `
${escHtml(locationLine)}
` : ''} ${r.confirmation_number ? `
Code: ${escHtml(r.confirmation_number)}
` : ''} ${transportNote ? `
${escHtml(transportNote)}
` : ''}
` } if (item.type === 'note') { const note = item.data // A coloured note carries its colour into print the same way a // reservation does (#1629) — the rule and the spine, not a fill, // because a tint costs ink and reads as grey on a mono printer. const noteColor = note.color || '' return `
${noteIconSvg(note.icon)}
${escHtml(note.text)}
${note.time ? `
${escHtml(note.time)}
` : ''}
` } pi++ const place = item.data.place if (!place) return '' const cat = categories.find(c => c.id === place.category_id) const color = safeHexColor(cat?.color, '#6366f1') // Image: direct > google photo > fallback icon. Both go through safeImg // so the proxy path is resolved to an absolute URL the PDF can load. const directImg = safeImg(place.image_url) const googleImg = safeImg(photoMap[place.id]) const img = directImg || googleImg const iconSvg = categoryIconSvg(cat?.icon, color, 24) const thumbHtml = img ? `` : `
${iconSvg}
` const chips = [ place.place_time ? `${svgClock}${escHtml(fmtTime(place.place_time))}` : '', place.price && Number.parseFloat(place.price) > 0 ? `${svgMoney}${formatMoney(Number(place.price), place.currency || trip.currency, loc)}` : '', ].filter(Boolean).join('') return `
${thumbHtml}
${pi} ${escHtml(place.name)} ${cat ? `${escHtml(cat.name)}` : ''}
${place.address ? `
${svgPin}${escHtml(place.address)}
` : ''} ${(place.lat != null && place.lng != null) ? `
${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}
` : ''} ${place.description ? markdown.row(place.description) : ''} ${chips ? `
${chips}
` : ''} ${place.notes ? markdown.row(place.notes) : ''} ${item.data.notes ? markdown.row(item.data.notes) : ''}
` }).join('') const accommodationsForDay = accommodationList.filter(a => day ? isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days) : false ).sort((a, b) => { const startA = days.find(d => d.id === a.start_day_id) const startB = days.find(d => d.id === b.start_day_id) return (startA ? getDayOrder(startA, days) : 0) - (startB ? getDayOrder(startB, days) : 0) }) const accommodationDetails = accommodationsForDay.map(item => { const isCheckIn = day.id === item.start_day_id const isCheckOut = day.id === item.end_day_id const actionLabel = isCheckIn ? tr('reservations.meta.checkIn') : isCheckOut ? tr('reservations.meta.checkOut') : tr('reservations.meta.linkAccommodation') const actionIcon = isCheckIn ? accommodationIconSvg('checkin') : isCheckOut ? accommodationIconSvg('checkout') : accommodationIconSvg('accommodation') const timeStr = isCheckIn ? fmtTime(item.check_in) : isCheckOut ? fmtTime(item.check_out) : '' return `
${actionIcon} ${escHtml(actionLabel)}
${timeStr ? `
${accommodationIconSvg('checkin')} ${escHtml(timeStr)}
` : ''}
${accommodationIconSvg('accommodation')} ${escHtml(item.place_name)}
${item.place_address ? `
${accommodationIconSvg('location')} ${escHtml(item.place_address)}
` : ''} ${item.notes ? `
${accommodationIconSvg('note')} ${escHtml(item.notes)}
` : ''} ${isCheckIn && item.confirmation ? `
${accommodationIconSvg('confirmation')} ${escHtml(item.confirmation)}
` : ''}
` }).join('') const accommodationsHtml = accommodationsForDay.length > 0 ? `
${accommodationDetails}
` : '' // A real so the browser repeats the day header at the top of // every page an overflowing day spills onto (#1471). CSS `table-header-group` // on a
is NOT repeated by Chromium's print engine — only real thead is. return `
${escHtml(tr('dayplan.dayN', { n: day.day_number })).toUpperCase()} ${escHtml(day.title || tr('dayplan.dayN', { n: day.day_number }))} ${day.date ? `${shortDate(day.date, loc)}` : ''} ${cost ? `${cost}` : ''}
${accommodationsHtml}${itemsHtml}
` }).join('') // Plugin sections after the days — every value is host-vetted plain text and // still escHtml'd here (same treatment as the core content above). const pluginSectionsHtml = pluginSections.length === 0 ? '' : `
${pluginSections.map(s => `
${escHtml(s.title)}
${(s.paragraphs || []).map(p => `

${escHtml(p)}

`).join('')} ${s.table ? ` ${s.table.headers.map(h => ``).join('')}${s.table.rows.map(row => `${row.map(cell => ``).join('')}`).join('')}
${escHtml(h)}
${escHtml(cell)}
` : ''}
`).join('')}
` const html = ` ${escHtml(trip?.title || tr('pdf.travelPlan'))}
${coverImg ? `
` : ''}
${coverImg ? `
` : `
`}
${escHtml(tr('pdf.travelPlan'))}
${escHtml(trip?.title || 'My Trip')}
${trip?.description ? `
${escHtml(trip.description)}
` : ''} ${range ? `
${range}
` : ''}
${sorted.length}
${escHtml(tr('dashboard.days', { count: sorted.length }))}
${places?.length || 0}
${escHtml(tr('dashboard.places', { count: places?.length || 0 }))}
${totalAssigned}
${escHtml(tr('pdf.planned'))}
${totalDistanceLabel ? `
${escHtml(totalDistanceLabel)}
${escHtml(tr('pdf.distanceLabel'))}
` : ''} ${totalCostLabel ? `
${totalCostLabel}
${escHtml(tr('pdf.costLabel'))}
` : ''}
${hasInvalidTour ? `

${escHtml(tr('tours.dayRoute.endpointUnknown'))}

` : ''} ${tripMapHtml} ${daysHtml} ${pluginSectionsHtml} ` markdown.dispose() if (signal?.aborted) return openPdfPreview({ html, title: trip?.title || tr('pdf.travelPlan'), tripId: trip?.id, tr, breaksPerDay, showTransportNotes, hasTransportNotes }) } function bodyClassAttr(breaksPerDay: boolean, showTransportNotes: boolean): string { const classes = [!breaksPerDay && 'pdf-flow', !showTransportNotes && 'pdf-no-transport-notes'].filter(Boolean) return classes.length ? ` class="${classes.join(' ')}"` : '' }