mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
fix(pdf): give up a routing export once its dialog or sheet is gone
A PDF of a long trip routes for minutes, and only the skip button could stop it. Closing the export dialog, hiding the phone sheet or leaving the trip left the legs going out and opened the document later on whatever page the user was on. Closing now stops the routing and the document never opens; skipping still prints without the remaining legs. The plan filter moves from TripPDF to pdfScope beside the other plan predicate, which keeps TripPDF under its size entry. The routing test name gets its quotes back, and the export dialog and sheet tests cover the leg count, the skip button and closing while routing.
This commit is contained in:
@@ -8,7 +8,7 @@
|
||||
"src/components/Map/MapView.tsx": 1385,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2218,
|
||||
"src/components/PDF/TripPDF.tsx": 1054,
|
||||
"src/components/PDF/TripPDF.tsx": 1039,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2936,
|
||||
|
||||
@@ -108,7 +108,7 @@ describe('tripRouteGeometry', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-006: a caller's own abort cuts the routing short, and what never answered is counted', async () => {
|
||||
it("FE-MAP-TRG-006: a caller's own abort cuts the routing short, and what never answered is counted", async () => {
|
||||
neverAnswers()
|
||||
const controller = new AbortController()
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7, signal: controller.signal })
|
||||
|
||||
@@ -393,4 +393,15 @@ describe('trip route map in the PDF', () => {
|
||||
.toEqual([[48.86, 2.35], [48.88, 2.5], [48.90, 2.42]])
|
||||
expect(onProgress).toHaveBeenLastCalledWith(2, 2)
|
||||
})
|
||||
|
||||
it('FE-COMP-TRIPPDF-MAP-016: an export given up while it routes opens no document', async () => {
|
||||
const givenUp = new AbortController()
|
||||
vi.mocked(calculateRouteWithLegs).mockImplementation(async (points) => {
|
||||
givenUp.abort()
|
||||
return { coordinates: points.map(p => [p.lat, p.lng] as [number, number]), distance: 0, duration: 0, legs: [leg(12000)] }
|
||||
})
|
||||
await downloadTripPDF({ ...args, signal: givenUp.signal })
|
||||
|
||||
expect(document.getElementById('pdf-preview-overlay')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -20,8 +20,7 @@ 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'
|
||||
import { onlyMyPlan } from './pdfScope'
|
||||
import { onlyMyPlan, planAssignments } from './pdfScope'
|
||||
import { createPdfMarkdown, PDF_MARKDOWN_CSS } from './pdfMarkdown'
|
||||
|
||||
/**
|
||||
@@ -201,27 +200,13 @@ interface downloadTripPDFProps {
|
||||
onlyUserId?: number
|
||||
/** The planner's road trip vias and tour stages, and the routing progress and stop (#2876). */
|
||||
route?: TripPdfRouteOptions
|
||||
}
|
||||
|
||||
/**
|
||||
* The stops the day plan lists, out of everything the store holds for the trip.
|
||||
*
|
||||
* The stop a booked night wrote onto its check-in day is out whatever the switch says:
|
||||
* the day already shows that booking as its accommodation block, and the row would be
|
||||
* the same hotel a second time. The service stops go with the setting. One predicate
|
||||
* for the whole document, so the day lists, the route map, the cover's planned count
|
||||
* and every cost total agree with the plan and with each other, whichever shell asked.
|
||||
*/
|
||||
function planAssignments(assignments: AssignmentsMap, showServiceStops: boolean): AssignmentsMap {
|
||||
return Object.fromEntries(Object.entries(assignments).map(([dayId, list]) => [
|
||||
dayId,
|
||||
(list || []).filter(a => a.accommodation_id == null && (showServiceStops || !isServiceStopType(a.place?.stop_type))),
|
||||
]))
|
||||
/** 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 }: 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, signal }: downloadTripPDFProps) {
|
||||
const { assignments: stored, reservations } = onlyUserId != null
|
||||
? onlyMyPlan(allStored, allReservations, onlyUserId)
|
||||
: { assignments: allStored, reservations: allReservations }
|
||||
@@ -904,6 +889,7 @@ ${daysHtml}
|
||||
${pluginSectionsHtml}
|
||||
</body></html>`
|
||||
markdown.dispose()
|
||||
if (signal?.aborted) return
|
||||
|
||||
// Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue)
|
||||
const overlay = document.createElement('div')
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AssignmentsMap } from '../../types'
|
||||
import { isServiceStopType } from '../Roadtrip/roadtripModel'
|
||||
|
||||
interface WithTravelers { travelers?: { user_id: number }[] | null }
|
||||
|
||||
@@ -27,3 +28,19 @@ export function onlyMyPlan<R extends WithTravelers>(
|
||||
reservations: reservations.filter(r => mine(r.travelers)),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stops the day plan lists, out of everything the store holds for the trip.
|
||||
*
|
||||
* The stop a booked night wrote onto its check-in day is out whatever the switch says:
|
||||
* the day already shows that booking as its accommodation block, and the row would be
|
||||
* the same hotel a second time. The service stops go with the setting. One predicate
|
||||
* for the whole document, so the day lists, the route map, the cover's planned count
|
||||
* and every cost total agree with the plan and with each other, whichever shell asked.
|
||||
*/
|
||||
export function planAssignments(assignments: AssignmentsMap, showServiceStops: boolean): AssignmentsMap {
|
||||
return Object.fromEntries(Object.entries(assignments).map(([dayId, list]) => [
|
||||
dayId,
|
||||
(list || []).filter(a => a.accommodation_id == null && (showServiceStops || !isServiceStopType(a.place?.stop_type))),
|
||||
]))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// FE-PLANNER-EXPORTMODAL-001 to FE-PLANNER-EXPORTMODAL-018
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
// FE-PLANNER-EXPORTMODAL-001 to FE-PLANNER-EXPORTMODAL-020
|
||||
import { act, render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { downloadTripPDF } from '../PDF/TripPDF'
|
||||
import { buildDay, buildDayNote, buildTrip, buildUser } from '../../../tests/helpers/factories'
|
||||
@@ -291,4 +291,41 @@ describe('TripExportModal', () => {
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ onlyUserId: 7 })
|
||||
})
|
||||
|
||||
it('FE-PLANNER-EXPORTMODAL-019: while the PDF routes the row counts the legs, and the rest can be left out (#2876)', async () => {
|
||||
const user = userEvent.setup()
|
||||
let finish: (() => void) | null = null
|
||||
vi.mocked(downloadTripPDF).mockImplementationOnce(() => new Promise<void>(res => { finish = res }))
|
||||
const roadtripViasByDay = { 10: [] }
|
||||
const tourStageStops = new Map()
|
||||
render(<TripExportModal {...makeProps({ roadtripViasByDay, tourStageStops })} />)
|
||||
await user.click(screen.getByText('dayplan.pdf'))
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
const { route } = vi.mocked(downloadTripPDF).mock.calls[0][0]
|
||||
expect(route).toMatchObject({ viasByDay: roadtripViasByDay, tourStageStops })
|
||||
|
||||
act(() => route?.onProgress?.(3, 10))
|
||||
expect(screen.getByText('dayplan.pdfRouting|3|10')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'dayplan.pdfSkipRouting' }))
|
||||
expect(route?.signal?.aborted).toBe(true)
|
||||
expect(screen.queryByRole('button', { name: 'dayplan.pdfSkipRouting' })).toBeNull()
|
||||
await act(async () => finish!())
|
||||
})
|
||||
|
||||
it('FE-PLANNER-EXPORTMODAL-020: closing the dialog while the PDF routes gives the export up', async () => {
|
||||
const user = userEvent.setup()
|
||||
let finish: (() => void) | null = null
|
||||
vi.mocked(downloadTripPDF).mockImplementationOnce(() => new Promise<void>(res => { finish = res }))
|
||||
const props = makeProps()
|
||||
const { rerender } = render(<TripExportModal {...props} />)
|
||||
await user.click(screen.getByText('dayplan.pdf'))
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
const { route, signal } = vi.mocked(downloadTripPDF).mock.calls[0][0]
|
||||
|
||||
rerender(<TripExportModal {...props} isOpen={false} />)
|
||||
expect(route?.signal?.aborted).toBe(true)
|
||||
expect(signal?.aborted).toBe(true)
|
||||
await act(async () => finish!())
|
||||
expect(props.onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -66,6 +66,7 @@ export function TripExportModal({
|
||||
fileBase, offerMine, isRunning, anyRunning, exportPdf, pdfRouting, pdfRoutingLabel, skipPdfRouting, downloadIcs, downloadGpx,
|
||||
} = useTripExport({
|
||||
tripId,
|
||||
open: isOpen,
|
||||
data: { trip, days, places, assignments, categories, reservations, dayNotes, viasByDay: roadtripViasByDay, tourStageStops },
|
||||
t,
|
||||
locale,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -011: the trip exports behind the desktop export
|
||||
// FE-PLANNER-TRIPEXPORT-001 to -013: 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';
|
||||
@@ -19,6 +19,7 @@ const NOTES = { '7': [{ id: 1, text: 'Pack' }] as unknown as DayNote[] };
|
||||
function options(overrides: Partial<TripExportOptions> = {}): TripExportOptions {
|
||||
return {
|
||||
tripId: 3,
|
||||
open: true,
|
||||
data: { trip, days: [], places: [], assignments: {}, categories: [], reservations: [], dayNotes: NOTES },
|
||||
t,
|
||||
locale: 'en-US',
|
||||
@@ -264,6 +265,7 @@ describe('useTripExport', () => {
|
||||
// Skipping stops the routing, not the export: the document still comes out.
|
||||
act(() => result.current.skipPdfRouting());
|
||||
expect(route?.signal?.aborted).toBe(true);
|
||||
expect(vi.mocked(downloadTripPDF).mock.calls[0][0].signal?.aborted).toBe(false);
|
||||
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));
|
||||
@@ -276,4 +278,44 @@ describe('useTripExport', () => {
|
||||
expect(result.current.anyRunning).toBe(false);
|
||||
expect(opts.onExported).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-012: closing the dialog while the PDF routes gives the export up, and nothing opens', async () => {
|
||||
const pdf = deferred();
|
||||
vi.mocked(downloadTripPDF).mockReturnValue(pdf.promise);
|
||||
const opts = options();
|
||||
const { result, rerender } = renderHook((open: boolean) => useTripExport({ ...opts, open }), {
|
||||
initialProps: true,
|
||||
});
|
||||
let running!: Promise<void>;
|
||||
act(() => {
|
||||
running = result.current.exportPdf();
|
||||
});
|
||||
await vi.waitFor(() => expect(downloadTripPDF).toHaveBeenCalled());
|
||||
const { route, signal } = vi.mocked(downloadTripPDF).mock.calls[0][0];
|
||||
|
||||
rerender(false);
|
||||
expect(route?.signal?.aborted).toBe(true);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
pdf.resolve();
|
||||
await running;
|
||||
});
|
||||
expect(opts.onExported).not.toHaveBeenCalled();
|
||||
expect(opts.toast.error).not.toHaveBeenCalled();
|
||||
expect(result.current.anyRunning).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRIPEXPORT-013: leaving the trip while the PDF routes gives the export up too', async () => {
|
||||
vi.mocked(downloadTripPDF).mockReturnValue(deferred().promise);
|
||||
const { result, unmount } = renderHook(() => useTripExport(options(PHONE)));
|
||||
act(() => {
|
||||
void result.current.exportPdf();
|
||||
});
|
||||
await vi.waitFor(() => expect(downloadTripPDF).toHaveBeenCalled());
|
||||
const { route, signal } = vi.mocked(downloadTripPDF).mock.calls[0][0];
|
||||
|
||||
unmount();
|
||||
expect(route?.signal?.aborted).toBe(true);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
@@ -36,6 +36,11 @@ interface PdfRouting {
|
||||
|
||||
export interface TripExportOptions {
|
||||
tripId: number;
|
||||
/**
|
||||
* Whether the dialog or sheet is shown. Closing it, or leaving the trip, gives up a
|
||||
* PDF still routing: its legs stop going out and the document never opens.
|
||||
*/
|
||||
open: boolean;
|
||||
data: TripExportData;
|
||||
t: Translate;
|
||||
locale: string;
|
||||
@@ -83,26 +88,37 @@ export function flatDayNotes(dayNotes: Record<string, DayNote[]>) {
|
||||
* 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() {
|
||||
function usePdfRouting(open: boolean) {
|
||||
const [progress, setProgress] = useState<PdfRouting | null>(null);
|
||||
const controller = useRef<AbortController | null>(null);
|
||||
const controller = useRef<{ routing: AbortController; job: AbortController } | null>(null);
|
||||
|
||||
const start = () => {
|
||||
const routing = new AbortController();
|
||||
controller.current = routing;
|
||||
const running = { routing, job: new AbortController() };
|
||||
controller.current = running;
|
||||
// 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 };
|
||||
return { signal: routing.signal, onProgress, givenUp: running.job.signal };
|
||||
};
|
||||
const finish = () => {
|
||||
controller.current = null;
|
||||
setProgress(null);
|
||||
};
|
||||
const skip = () => {
|
||||
controller.current?.abort();
|
||||
controller.current?.routing.abort();
|
||||
setProgress(null);
|
||||
};
|
||||
// Unlike a skip, nobody is left to print for: the export ends without a document.
|
||||
const giveUp = useCallback(() => {
|
||||
controller.current?.routing.abort();
|
||||
controller.current?.job.abort();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!open) giveUp();
|
||||
}, [open, giveUp]);
|
||||
useEffect(() => giveUp, [giveUp]);
|
||||
|
||||
return { progress, start, finish, skip };
|
||||
}
|
||||
|
||||
@@ -114,6 +130,7 @@ function usePdfRouting() {
|
||||
*/
|
||||
export function useTripExport({
|
||||
tripId,
|
||||
open,
|
||||
data,
|
||||
t,
|
||||
locale,
|
||||
@@ -127,7 +144,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();
|
||||
const pdfRouting = usePdfRouting(open);
|
||||
// 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);
|
||||
@@ -157,7 +174,7 @@ export function useTripExport({
|
||||
if ((requireTrip && !data.trip) || running[laneOf(job)]) return;
|
||||
begin(job);
|
||||
const flatNotes = flatDayNotes(data.dayNotes);
|
||||
const routing = pdfRouting.start();
|
||||
const { givenUp, ...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
|
||||
@@ -178,8 +195,9 @@ export function useTripExport({
|
||||
showServiceStops,
|
||||
onlyUserId: mine ? myId : undefined,
|
||||
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
|
||||
signal: givenUp,
|
||||
});
|
||||
if (closeAfterPdf) onExported();
|
||||
if (closeAfterPdf && !givenUp.aborted) onExported();
|
||||
} catch (e) {
|
||||
if (logPdfErrors) console.error('PDF error:', e);
|
||||
toast.error(`${t('dayplan.pdfError')}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
|
||||
@@ -25,6 +25,7 @@ export default function MExportSheet({ planner, shell }: MTripSheetsProps) {
|
||||
// open here; a calendar or GPX file closes the sheet.
|
||||
const { offerMine, isRunning, exportPdf, pdfRouting, pdfRoutingLabel, skipPdfRouting, downloadIcs, downloadGpx } = useTripExport({
|
||||
tripId: planner.tripId,
|
||||
open,
|
||||
data: {
|
||||
trip: planner.trip,
|
||||
days: planner.days,
|
||||
|
||||
@@ -7,9 +7,9 @@ import type { Day, DayNote } from '../../../../src/types'
|
||||
import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'
|
||||
import { server } from '../../../helpers/msw/server'
|
||||
import { resetAllStores, seedStore } from '../../../helpers/store'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../helpers/render'
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
|
||||
|
||||
// FE-MOB-EXPSH-001 to FE-MOB-EXPSH-013
|
||||
// FE-MOB-EXPSH-001 to FE-MOB-EXPSH-015
|
||||
// This sheet reads its copy from useTranslation(), so the assertions are English.
|
||||
|
||||
vi.mock('../../../../src/components/PDF/TripPDF', () => ({ downloadTripPDF: vi.fn() }))
|
||||
@@ -221,4 +221,31 @@ describe('MExportSheet', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(shell.closeSheet).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-MOB-EXPSH-014: while the PDF routes the row counts the legs, and the rest can be left out (#2876)', async () => {
|
||||
let finish: (() => void) | null = null
|
||||
vi.mocked(downloadTripPDF).mockImplementationOnce(() => new Promise<void>(res => { finish = res }))
|
||||
renderSheet()
|
||||
fireEvent.click(screen.getByText('PDF'))
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
const { route } = vi.mocked(downloadTripPDF).mock.calls[0][0]
|
||||
|
||||
act(() => route?.onProgress?.(3, 10))
|
||||
expect(screen.getByText('Calculating routes: 3 of 10')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Export without the remaining routes' }))
|
||||
expect(route?.signal?.aborted).toBe(true)
|
||||
await act(async () => finish!())
|
||||
})
|
||||
|
||||
it('FE-MOB-EXPSH-015: hiding the sheet while the PDF routes gives the export up', async () => {
|
||||
vi.mocked(downloadTripPDF).mockImplementationOnce(() => new Promise<void>(() => undefined))
|
||||
const { rerender, planner } = renderSheet()
|
||||
fireEvent.click(screen.getByText('PDF'))
|
||||
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
|
||||
const { route, signal } = vi.mocked(downloadTripPDF).mock.calls[0][0]
|
||||
|
||||
rerender(<MExportSheet planner={planner} shell={buildShell({ sheet: { id: 'mehr' } })} />)
|
||||
expect(route?.signal?.aborted).toBe(true)
|
||||
expect(signal?.aborted).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user