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
+70 -1
View File
@@ -20,7 +20,7 @@ vi.mock('../Map/tripRouteGeometry', async (importActual) => {
// basemap branch and the outline fallback can be exercised.
vi.mock('./tripMapImage', () => ({ renderTripMapImage: vi.fn(async () => null) }))
const { calculateRouteWithLegs } = await import('../Map/RouteCalculator')
const { calculateRouteWithLegs, RoutingRefusedError } = await import('../Map/RouteCalculator')
const { renderTripMapImage } = await import('./tripMapImage')
const { routeTrip } = await import('../Map/tripRouteGeometry')
const { downloadTripPDF } = await import('./TripPDF')
@@ -324,4 +324,73 @@ describe('trip route map in the PDF', () => {
expect(html).not.toContain('pdf.distanceLabel')
})
// The export used to give the router 8 s: about seven legs at a second each, so a
// month-long trip printed most of its days as straight lines at "0 m" under a total
// that looked final, and every export routed a few more days (#2876).
it('FE-COMP-TRIPPDF-MAP-013: a long trip prints every day on the road, however long the router takes', async () => {
const days = Array.from({ length: 12 }, (_, i) =>
({ id: i + 1, day_number: i + 1, title: null, date: `2025-06-${String(i + 1).padStart(2, '0')}` }))
const assignments = Object.fromEntries(days.map(day => [String(day.id), [
assign(day.id * 10, day.id, 0, 45 + day.id / 10, 4.8),
assign(day.id * 10 + 1, day.id, 1, 45 + day.id / 10, 4.9),
]]))
vi.mocked(calculateRouteWithLegs).mockImplementation(() => new Promise(resolve => {
setTimeout(() => resolve({ coordinates: [[45, 4.8], [45, 4.9]], distance: 12000, duration: 900, legs: [leg(12000)] }), 100)
}))
vi.useFakeTimers()
try {
let settled = false
const pending = downloadTripPDF({ ...args, days: days as never, assignments: assignments as never })
.finally(() => { settled = true })
for (let second = 0; second < 60 && !settled; second++) await vi.advanceTimersByTimeAsync(1000)
await pending
} finally {
vi.useRealTimers()
}
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(12)
const html = srcdoc()
expect(html).toContain('144 km')
expect(html).not.toContain('map.overview.unrouted')
expect(html).not.toContain('map.overview.notRouted')
})
it('FE-COMP-TRIPPDF-MAP-014: a leg the router refused is marked, and the total says it is short', async () => {
vi.mocked(calculateRouteWithLegs).mockRejectedValueOnce(new RoutingRefusedError(400, null))
await downloadTripPDF(args)
const html = srcdoc()
const legend = html.slice(html.indexOf('class="trip-map-legend"'))
// Day 1 drove nowhere the router would say: no "0 m", but that it was not routed...
expect(legend).toContain('<span class="trip-map-leg-dist">map.overview.notRouted</span>')
expect(legend).not.toContain('>0 m<')
// ...and the 12 km of day 2 are a floor for the trip, said as such.
expect(html).toContain('pdf.distanceLabel: map.overview.distanceAtLeast')
expect(html).toContain('<div class="trip-map-note">map.overview.unrouted</div>')
})
it('FE-COMP-TRIPPDF-MAP-015: routes what the planner map routes, and reports its progress to the caller', async () => {
const viasByDay = { 1: [{ id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.88, lng: 2.5, created_at: '' }] }
const tourStageStops = new Map()
const controller = new AbortController()
const onProgress = vi.fn<(done: number, total: number) => void>()
vi.mocked(calculateRouteWithLegs).mockImplementation(async (points) => ({
coordinates: points.map(p => [p.lat, p.lng] as [number, number]),
distance: 0, duration: 0,
legs: points.slice(1).map(() => leg(12000)),
}))
await downloadTripPDF({
...args,
distanceUnit: 'imperial',
route: { viasByDay, tourStageStops, signal: controller.signal, onProgress },
})
const [input, opts] = vi.mocked(routeTrip).mock.calls[0]
expect(input).toMatchObject({ viasByDay, tourStageStops, storedAssignments: args.assignments })
expect(opts).toMatchObject({ unit: 'imperial', signal: controller.signal, onProgress })
// The road picked in the road trip bends day 1 here as it does on the planner map.
expect(vi.mocked(calculateRouteWithLegs).mock.calls[0][0].map(p => [p.lat, p.lng]))
.toEqual([[48.86, 2.35], [48.88, 2.5], [48.90, 2.42]])
expect(onProgress).toHaveBeenLastCalledWith(2, 2)
})
})
+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; }
+72
View File
@@ -0,0 +1,72 @@
import { useSettingsStore } from '../../store/settingsStore';
import type { DistanceUnit } from '../../types';
import type { ViasByDay } from '../../utils/dayRouteVias';
import { formatDistance } from '../../utils/units';
import type { TourStageStops } from '../Map/dayTourProjection';
import {
routeTrip,
type TripRouteInputs,
type TripRouteProgress,
type TripRouteSummary,
} from '../Map/tripRouteGeometry';
import { renderTripMapImage } from './tripMapImage';
import { buildTripMapSvg } from './tripMapSvg';
/** What the planner knows about the trip's route beyond the plan, and how it follows the routing. */
export interface TripPdfRouteOptions {
/** The roads picked in the road trip (#2580), so the print bends where the planner map does. */
viasByDay?: ViasByDay;
/** Where the stages of the trip's multi-day tours run. */
tourStageStops?: TourStageStops;
/** Stops routing early: the legs asked by then are printed, the rest stay straight and are marked. */
signal?: AbortSignal;
onProgress?: TripRouteProgress;
}
interface TripPdfRoute {
route: TripRouteSummary | null;
mapSvg: string | null;
}
const MAP_FRAME = { width: 720, height: 420 };
/**
* The trip's route as one map (#1736), from the builder the planner overview uses and
* fed what the overview is fed, so the document and the screen show the same roads.
*
* Every leg is waited for: a deadline here printed a month-long trip with most of its
* days as straight lines and a total that looked final (#2876). Fail-safe all the same:
* a routing failure means no map rather than no PDF.
*/
export async function drawTripRoute(
input: Omit<TripRouteInputs, 'viasByDay' | 'tourStageStops'>,
{ tripId, unit, options = {} }: { tripId: number; unit: DistanceUnit; options?: TripPdfRouteOptions }
): Promise<TripPdfRoute> {
const route = await routeTrip(
{ ...input, viasByDay: options.viasByDay, tourStageStops: options.tourStageStops },
{ profile: 'driving', tripId, unit, signal: options.signal, onProgress: options.onProgress }
).catch((err: unknown) => {
// 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);
return null;
});
if (!route) return { route: null, mapSvg: null };
// 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 frame = { ...MAP_FRAME, formatDistance: (km: number) => formatDistance(km, unit) };
const style = useSettingsStore.getState().settings.maplibre_style;
const mapSvg = (await renderTripMapImage(route.days, { ...frame, style })) ?? buildTripMapSvg(route.days, frame);
// 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 (!mapSvg && Object.values(input.assignments).some((list) => list?.length)) {
console.warn(
`[tripPdfMap] no map drawn: ${route.days.length} of ${input.days.length} day(s) produced a route.` +
' A day needs two located stops, or one located stop with an accommodation either side of it.'
);
}
return { route, mapSvg };
}