fix(pdf): route every leg of the trip map and mark what is left unrouted

The PDF export routed the whole trip under an 8 s deadline while the router
is asked one leg at a time, a second apart. A cold month-long trip got about
seven legs routed per export; the rest printed as straight lines at "0 m"
under a total that looked final, and every further export routed a few more
days from the device cache.

The export now waits for every leg, bounded by the request pacing, the
rate-limit retries and a per-leg timeout. The export dialog and the phone
sheet count the legs while they route and offer to print without the rest.
Any leg left without a road is marked in the document: the day reads "not
routed" or "at least ...", the total says it is a floor, and a note names
how many legs are missing. The planner overview shares the same wording.

The PDF also routes what the planner map routes now: the road trip's vias,
the multi-day tour stages and the reader's distance unit.

Closes #2876
This commit is contained in:
Maurice
2026-10-29 14:48:13 +01:00
parent c03c40d287
commit 3238fbc517
69 changed files with 506 additions and 99 deletions
+21 -50
View File
@@ -16,10 +16,8 @@ import { useTripStore } from '../../store/tripStore'
import { useAddonStore } from '../../store/addonStore'
import { projectDayItinerary } from '../Map/dayTourProjection'
import { planCosts } from '../Planner/planCosts'
import { routeTrip, type TripRouteSummary } from '../Map/tripRouteGeometry'
import { buildTripMapSvg } from './tripMapSvg'
import { renderTripMapImage } from './tripMapImage'
import { formatDistance } from '../../utils/units'
import { routeDistanceLabel } from '../Map/tripRouteLabels'
import { drawTripRoute, type TripPdfRouteOptions } from './tripPdfRoute'
import { fetchExchangeRates } from '../../hooks/useExchangeRates'
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs'
import { isServiceStopType } from '../Roadtrip/roadtripModel'
@@ -201,6 +199,8 @@ interface downloadTripPDFProps {
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
}
/**
@@ -221,7 +221,7 @@ function planAssignments(assignments: AssignmentsMap, showServiceStops: boolean)
// `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 }: downloadTripPDFProps) {
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 }: downloadTripPDFProps) {
const { assignments: stored, reservations } = onlyUserId != null
? onlyMyPlan(allStored, allReservations, onlyUserId)
: { assignments: allStored, reservations: allReservations }
@@ -252,56 +252,25 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
// just means no extra sections, the core export is untouched.
const pluginSections = await pluginsApi.pdfSections(trip.id).then(r => r.sections || []).catch(() => [])
// The trip's route as one map (#1736), drawn from the same builder the planner map
// uses so the document and the screen agree. Fail-safe and time-boxed: whatever the
// router answered inside the budget is drawn, the rest stay straight lines, and any
// failure at all simply means no map rather than no PDF.
const unit: DistanceUnit = (_distanceUnit || useSettingsStore.getState().settings.distance_unit) === 'imperial'
? 'imperial' : 'metric'
let tripRoute: TripRouteSummary | null = null
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))
try {
tripRoute = await routeTrip(
{
days: sorted,
assignments,
reservations,
accommodations: accommodationList,
optimizeFromAccommodation: useSettingsStore.getState().settings.optimize_from_accommodation,
toursEnabled,
places,
},
{ profile: 'driving', tripId: trip.id, timeoutMs: 8000 },
)
} catch (err) {
// Logged rather than swallowed: a map that is silently absent looks exactly like a
// trip that has no route, and the two need different answers from whoever is
// looking. The export itself carries on — the itinerary matters more than the map.
console.warn('[tripPdfMap] routing the trip failed; the export continues without a map', err)
}
// A real basemap first — at city scale the bundled outlines are a country-sized
// blank, and only streets carry context that small. The outline map is what is left
// when there is no WebGL, no network, or a style that will not load.
const mapFrame = { width: 720, height: 420, formatDistance: (km: number) => formatDistance(km, unit) }
const tripMapSvg = tripRoute
? (await renderTripMapImage(tripRoute.days, {
...mapFrame,
style: useSettingsStore.getState().settings.maplibre_style,
})) ?? buildTripMapSvg(tripRoute.days, mapFrame)
: null
// The other way to end up mapless, and the one that is not a failure: nothing in the
// trip routed. Only worth saying when there were stops to route — a trip nobody has
// planned yet is meant to print without a map.
if (tripRoute && !tripMapSvg && Object.values(assignments).some(list => list?.length)) {
console.warn(
`[tripPdfMap] no map drawn: ${tripRoute.days.length} of ${sorted.length} day(s) produced a route.`
+ ' A day needs two located stops, or one located stop with an accommodation either side of it.',
)
}
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
? formatDistance(tripRoute.totalDistance / 1000, unit)
? 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`.
@@ -311,12 +280,13 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
<span class="trip-map-title">${escHtml(tr('pdf.mapTitle'))}</span>
${totalDistanceLabel ? `<span class="trip-map-total">${escHtml(tr('pdf.distanceLabel'))}: ${escHtml(totalDistanceLabel)}</span>` : ''}
</div>
${unroutedLegs ? `<div class="trip-map-note">${escHtml(tr('map.overview.unrouted', { count: unroutedLegs }))}</div>` : ''}
${tripMapSvg}
<div class="trip-map-legend">
${tripRoute.days.filter(d => d.lines.length).map(d => `<span class="trip-map-leg">
<span class="trip-map-dot" style="background:${hexColour(d.color.line)}"></span>
${escHtml(d.title || tr('dayplan.dayN', { n: d.dayNumber }))}
<span class="trip-map-leg-dist">${escHtml(formatDistance(d.distance / 1000, unit))}</span>
<span class="trip-map-leg-dist">${escHtml(routeDistanceLabel(d.distance, d.unroutedLegs ?? 0, unit, tr))}</span>
</span>`).join('')}
</div>
<div class="trip-map-credit">${escHtml(tr('pdf.mapCredit'))}</div>
@@ -744,6 +714,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
.trip-map-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-bottom: 12px; }
.trip-map-title { font-size: 11px; font-weight: 600; letter-spacing: 1.4px; text-transform: uppercase; color: #64748b; }
.trip-map-total { font-size: 12px; font-weight: 600; color: #334155; }
.trip-map-note { font-size: 9px; font-weight: 600; margin: -4px 0 10px; }
.trip-map-svg { width: 100%; height: auto; border-radius: 8px; border: 1px solid #e2e8f0; display: block; }
.trip-map-legend { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 12px; }
.trip-map-leg { display: flex; align-items: center; gap: 6px; font-size: 9px; color: #475569; }