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
@@ -1455,7 +1455,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
days={days}
places={places}
categories={categories}
assignments={assignments}
assignments={assignments} roadtripViasByDay={props.roadtripViasByDay} tourStageStops={props.tourStageStops}
reservations={reservations}
allConnectionsShown={allConnectionsShown}
onToggleAllConnections={onToggleAllConnections}
@@ -10,6 +10,8 @@ import { isRoutableReservation } from '../../utils/reservationRoutes'
import type { DayAddControls } from '../../utils/dayAdd'
import type { DayDeleteQuestion } from '../../utils/dayImpactLines'
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
import type { TourStageStops } from '../Map/dayTourProjection'
import type { ViasByDay } from '../../utils/dayRouteVias'
interface DayPlanSidebarToolbarProps {
tripId: number
@@ -19,6 +21,9 @@ interface DayPlanSidebarToolbarProps {
categories: Category[]
assignments: AssignmentsMap
reservations: Reservation[]
/** Handed on to the export, so the PDF's route map bends where the planner's does. */
roadtripViasByDay?: ViasByDay
tourStageStops?: TourStageStops
allConnectionsShown?: boolean
onToggleAllConnections?: () => void
dayNotes: Record<string, DayNote[]>
@@ -50,7 +55,7 @@ interface DayPlanSidebarToolbarProps {
}
export function DayPlanSidebarToolbar({
tripId, trip, days, places, categories, assignments, reservations, dayNotes,
tripId, trip, days, places, categories, assignments, reservations, dayNotes, roadtripViasByDay, tourStageStops,
allConnectionsShown = false, onToggleAllConnections,
t, locale, toast,
expandedDays, setExpandedDays, onUndo, canUndo, undoHover, setUndoHover, lastActionLabel,
@@ -95,6 +100,8 @@ export function DayPlanSidebarToolbar({
assignments={assignments}
reservations={reservations}
dayNotes={dayNotes}
roadtripViasByDay={roadtripViasByDay}
tourStageStops={tourStageStops}
t={t}
locale={locale}
toast={toast}
@@ -6,6 +6,8 @@ import { IcsSubscribeModal } from './IcsSubscribeModal'
import { SoftPill } from './planParts'
import { useToast } from '../shared/Toast'
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
import type { TourStageStops } from '../Map/dayTourProjection'
import type { ViasByDay } from '../../utils/dayRouteVias'
import { useTripExport } from './useTripExport'
/**
@@ -31,6 +33,9 @@ interface TripExportModalProps {
assignments: AssignmentsMap
reservations: Reservation[]
dayNotes: Record<string, DayNote[]>
/** The road trip's vias and the tour stages, so the PDF's route map matches the planner's. */
roadtripViasByDay?: ViasByDay
tourStageStops?: TourStageStops
t: (key: string, params?: Record<string, string | number>) => string
locale: string
toast: ReturnType<typeof useToast>
@@ -53,15 +58,15 @@ interface TripExportModalProps {
*/
export function TripExportModal({
isOpen, onClose, tripId, trip, days, places, categories, assignments, reservations, dayNotes,
t, locale, toast, canManageShare = true,
roadtripViasByDay, tourStageStops, t, locale, toast, canManageShare = true,
}: TripExportModalProps) {
const [subscribeOpen, setSubscribeOpen] = useState(false)
const titleId = useId()
const {
fileBase, offerMine, isRunning, anyRunning, exportPdf, downloadIcs, downloadGpx,
fileBase, offerMine, isRunning, anyRunning, exportPdf, pdfRouting, pdfRoutingLabel, skipPdfRouting, downloadIcs, downloadGpx,
} = useTripExport({
tripId,
data: { trip, days, places, assignments, categories, reservations, dayNotes },
data: { trip, days, places, assignments, categories, reservations, dayNotes, viasByDay: roadtripViasByDay, tourStageStops },
t,
locale,
toast,
@@ -94,7 +99,7 @@ export function TripExportModal({
<ExportRow
icon={FileText}
title={t('dayplan.pdf')}
sub={t('dayplan.pdfTooltip')}
sub={pdfRoutingLabel('pdf') ?? t('dayplan.pdfTooltip')}
busy={isRunning('pdf')}
disabled={anyRunning}
onClick={() => exportPdf()}
@@ -103,12 +108,22 @@ export function TripExportModal({
<ExportRow
icon={UserRound}
title={t('dayplan.pdfMine')}
sub={t('dayplan.pdfMineSub')}
sub={pdfRoutingLabel('pdf:mine') ?? t('dayplan.pdfMineSub')}
busy={isRunning('pdf:mine')}
disabled={anyRunning}
onClick={() => exportPdf(true)}
/>
)}
{pdfRouting && (
<button
type="button"
onClick={skipPdfRouting}
className="self-end rounded-lg px-2 py-1 text-content-muted transition-colors hover:bg-surface-hover hover:text-content"
style={fs(11.5)}
>
{t('dayplan.pdfSkipRouting')}
</button>
)}
</div>
</DialogSection>
@@ -1,4 +1,4 @@
// FE-PLANNER-TRIPEXPORT-001 to -010: the trip exports behind the desktop export
// FE-PLANNER-TRIPEXPORT-001 to -011: the trip exports behind the desktop export
// dialog and the phone's export sheet.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
@@ -238,4 +238,42 @@ describe('useTripExport', () => {
expect(opts.onExported).toHaveBeenCalledTimes(1);
expect(result.current.anyRunning).toBe(false);
});
it('FE-PLANNER-TRIPEXPORT-011: the PDF routes what the planner draws, counts its legs and can print without the rest', async () => {
const pdf = deferred();
vi.mocked(downloadTripPDF).mockReturnValue(pdf.promise);
const viasByDay = { 7: [] };
const tourStageStops = new Map();
const opts = options({ data: { ...options().data, viasByDay, tourStageStops } });
const { result } = renderHook(() => useTripExport(opts));
let running!: Promise<void>;
act(() => {
running = result.current.exportPdf();
});
await vi.waitFor(() => expect(downloadTripPDF).toHaveBeenCalled());
const { route } = vi.mocked(downloadTripPDF).mock.calls[0][0];
expect(route).toMatchObject({ viasByDay, tourStageStops });
expect(result.current.pdfRouting).toBeNull();
act(() => route?.onProgress?.(0, 60));
act(() => route?.onProgress?.(23, 60));
expect(result.current.pdfRouting).toEqual({ done: 23, total: 60 });
expect(result.current.pdfRoutingLabel('pdf')).toBe('dayplan.pdfRouting');
expect(result.current.pdfRoutingLabel('pdf:mine')).toBeNull();
// Skipping stops the routing, not the export: the document still comes out.
act(() => result.current.skipPdfRouting());
expect(route?.signal?.aborted).toBe(true);
expect(result.current.pdfRouting).toBeNull();
// The leg that was already on its way still reports; the row does not come back for it.
act(() => route?.onProgress?.(24, 60));
expect(result.current.pdfRouting).toBeNull();
expect(result.current.isRunning('pdf')).toBe(true);
await act(async () => {
pdf.resolve();
await running;
});
expect(result.current.anyRunning).toBe(false);
expect(opts.onExported).toHaveBeenCalledTimes(1);
});
});
+51 -1
View File
@@ -1,10 +1,12 @@
import { useState } from 'react';
import { useRef, useState } from 'react';
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';
import { importChunk } from '../../utils/chunkReload';
import type { ViasByDay } from '../../utils/dayRouteVias';
import type { TourStageStops } from '../Map/dayTourProjection';
import { hasPersonalPlan } from '../PDF/pdfScope';
type Translate = (key: string, params?: Record<string, string | number>) => string;
@@ -21,6 +23,15 @@ export interface TripExportData {
categories: Category[];
reservations: Reservation[];
dayNotes: Record<string, DayNote[]>;
/** The road trip's vias and the multi-day tour stages, so the PDF map routes what the planner map does. */
viasByDay?: ViasByDay;
tourStageStops?: TourStageStops;
}
/** How far the PDF's route map has got: legs answered or given up on, out of all of them. */
interface PdfRouting {
done: number;
total: number;
}
export interface TripExportOptions {
@@ -67,6 +78,34 @@ export function flatDayNotes(dayNotes: Record<string, DayNote[]>) {
return Object.entries(dayNotes).flatMap(([dayId, notes]) => notes.map((n) => ({ ...n, day_id: Number(dayId) })));
}
/**
* The PDF's routing round as the export rows show it. A cold month-long trip routes for
* minutes, one leg a second against the shared router, so the row counts the legs and
* offers to print without the ones still to come; those are marked in the document (#2876).
*/
function usePdfRouting() {
const [progress, setProgress] = useState<PdfRouting | null>(null);
const controller = useRef<AbortController | null>(null);
const start = () => {
const routing = new AbortController();
controller.current = routing;
// A leg already on its way still reports after a skip; the row stays quiet about it.
const onProgress = (done: number, total: number) =>
setProgress(!routing.signal.aborted && done < total ? { done, total } : null);
return { signal: routing.signal, onProgress };
};
const finish = () => {
controller.current = null;
setProgress(null);
};
const skip = () => {
controller.current?.abort();
setProgress(null);
};
return { progress, start, finish, skip };
}
/**
* Every way a trip leaves TREK, behind the desktop export dialog and the phone's
* export sheet: the day plan as a PDF (the whole plan, or my plan once somebody
@@ -88,6 +127,7 @@ export function useTripExport({
// Which export is working, per lane, so a row can say so instead of looking inert
// while a 226 kB PDF builder is fetched and a document is rendered.
const [running, setRunning] = useState<Record<string, ExportJob>>({});
const pdfRouting = usePdfRouting();
// The PDF is built outside React, so it cannot read these itself (#2066).
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
const distanceUnit = useSettingsStore((s) => s.settings.distance_unit);
@@ -108,11 +148,16 @@ export function useTripExport({
return next;
});
/** What a PDF row says while its route map is still being routed, instead of its own line. */
const pdfRoutingLabel = (job: ExportJob) =>
isRunning(job) && pdfRouting.progress ? t('dayplan.pdfRouting', { ...pdfRouting.progress }) : null;
const exportPdf = async (mine = false) => {
const job: ExportJob = mine ? 'pdf:mine' : 'pdf';
if ((requireTrip && !data.trip) || running[laneOf(job)]) return;
begin(job);
const flatNotes = flatDayNotes(data.dayNotes);
const routing = pdfRouting.start();
try {
// Loaded on click: the PDF builder is ~226 kB, so every trip used to pay for it
// whether or not anyone exported. A missing chunk lands in the catch and shows
@@ -132,12 +177,14 @@ export function useTripExport({
distanceUnit,
showServiceStops,
onlyUserId: mine ? myId : undefined,
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
});
if (closeAfterPdf) onExported();
} catch (e) {
if (logPdfErrors) console.error('PDF error:', e);
toast.error(`${t('dayplan.pdfError')}: ${e instanceof Error ? e.message : String(e)}`);
} finally {
pdfRouting.finish();
end(job);
}
};
@@ -187,6 +234,9 @@ export function useTripExport({
isRunning,
anyRunning: Object.keys(running).length > 0,
exportPdf,
pdfRouting: pdfRouting.progress,
pdfRoutingLabel,
skipPdfRouting: pdfRouting.skip,
downloadIcs,
downloadGpx,
};