feat(tours): plan a multi-day tour as one route split into stages

A hut-to-hut hike or a paddle trip over several days is now planned in the
Tours planner as one tour: the whole route is planned as before, and stops
along it are marked as stage ends (MDT-01). The stages are read off that one
route in its order, never kept as copies, so a change inside a stage changes
the whole tour and every figure on it.

- A Day tour / Multi-day tour switch beside the tour type; a stop's menu
  ends a stage there or lets it go on. Back to a day tour removes every stage
  end after a confirmation, as one step undo brings back.
- The list of points is headed per stage with its distance and moving time;
  a stop that ends a stage carries a moon at its number, on the map too.
- The overview lists the stages from stop to stop with distance, climb,
  descent and time (hiking rule per stage, paddle estimate per stage, the
  router's time shared by distance otherwise), marks where each ends across
  the elevation profile, and a stage of more than a day on the move warns.
- A stage end a change cannot keep (its stop removed, moved to an end or
  made a shaping point) is dropped and said so, with undo, never moved
  to another point.
- A multi-day tour may take a day a stage, so its time limit grows with its
  stages; the tour keeps its one type, portages included.
- The list and the MCP tools show the stage count and where stages end.

Stage ends are a flag on the waypoint (migration 046000); a tour without one
is a day tour, as every tour saved before.
This commit is contained in:
Maurice
2026-10-20 12:39:08 +02:00
parent acc294dd8e
commit 2449616ee9
76 changed files with 2669 additions and 55 deletions
@@ -31,6 +31,10 @@ import { SkiTrackCard } from '../ski/SkiTrackCard'
import type { SkiClassification } from '../ski/useSkiClassification'
import { TourTypeFields } from './TourTypeFields'
import TourWaypointList from './TourWaypointList'
import { TourStageLossNotice } from '../stages/TourStageLossNotice'
import { TourStageModeField } from '../stages/TourStageModeField'
import { TourStagesSection } from '../stages/TourStagesSection'
import { stageBoundariesM } from '../stages/tourStages'
import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry'
import type { TourPlannerController, TourPlannerStatus } from './useTourPlanner'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
@@ -462,10 +466,14 @@ export function TourPlannerRail({ planner,
<TourTypeFields planner={planner} locked={locked} />
<TourStageModeField planner={planner} locked={locked} />
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
<UnreachableNotice planner={planner} />
<TourStageLossNotice planner={planner} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<BikeWaysCard planner={planner} />
@@ -603,6 +611,7 @@ function ElevationSection({ id, samples, gradientId, planner }: {
onFocusChange={planner.setRouteProfileFocus}
formatFocus={focus => profileFocusLabel(focus, t, distanceUnit)}
bands={crossings}
marks={stageBoundariesM(planner.stages.stages)}
/>}
</div>
</TourSection>
@@ -784,6 +793,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
<div className="flex flex-col gap-3">
<FerrataCrossingBadges />
<RailFacts facts={tourMetricFacts(routeAnalysis, distanceUnit, t, tourTimeFields)} />
<TourStagesSection planner={planner} />
{routeAnalysis && !planner.isPaddle && (
<ElevationSection
id="tour-planner-editable-elevation-profile"
@@ -1,7 +1,7 @@
// FE-TOUR-WAYPOINT-LIST-001 to FE-TOUR-WAYPOINT-LIST-015: shaping points, the water router's answers
// FE-TOUR-WAYPOINT-LIST-001 to FE-TOUR-WAYPOINT-LIST-016: shaping points, the water router's answers
// and a city walk's stops in the list, with their arrivals and opening hours on a day of the walk,
// other ways for a hike's leg and round hikes out of a stop (P2A-03, P2A-05, PAD-11, CW-01, CW-02,
// CW-04, RTE-02, RTE-03).
// other ways for a hike's leg and round hikes out of a stop, and the stages of a multi-day tour
// (P2A-03, P2A-05, PAD-11, CW-01, CW-02, CW-04, RTE-02, RTE-03, MDT-01).
import userEvent from '@testing-library/user-event';
import type { PaddleRouteLeg } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -392,4 +392,47 @@ describe('TourWaypointList', () => {
expect(screen.queryByTestId('walk-station-schedule')).not.toBeInTheDocument();
});
});
it('FE-TOUR-WAYPOINT-LIST-016: heads each stage where it begins, marks the stop that ends one, and ends a stage from the menu', async () => {
const stage = (number: number, from: number, to: number, fromId: string, toId: string) => ({
number,
from,
to,
fromId,
toId,
distanceKm: 4.2,
gain: null,
loss: null,
minutes: 75,
fromM: null,
toM: null,
overDay: false,
});
const stages = {
multiDay: true,
stages: [stage(1, 0, 2, 'a', 'b'), stage(2, 2, 3, 'b', 'c')],
endCount: 1,
lost: 0,
setMultiDay: vi.fn(),
toggleStageEnd: vi.fn(),
canEnd: vi.fn((id: string) => id === 'b'),
};
const controller = planner({
waypoints: [START, SHAPE, { ...STOP, stageEnd: true }, END],
selectedWaypointId: 'b',
stages,
} as Partial<TourPlannerController>);
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
const heads = screen.getAllByTestId('tour-stage-divider');
expect(heads.map((head) => head.getAttribute('data-stage'))).toEqual(['1', '2']);
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
expect(at(rows, 2).querySelector('[data-waypoint-stage-end]')).not.toBeNull();
expect(within(at(rows, 2)).getByLabelText('Waypoint 2, End of stage 1')).toBeInTheDocument();
expect(at(rows, 0).querySelector('[data-waypoint-stage-end]')).toBeNull();
// The head of the second stage follows the stop that ends the first.
expect(at(rows, 2).compareDocumentPosition(at(heads, 1)) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
await userEvent.click(within(at(rows, 2)).getByRole('button', { name: 'More actions' }));
await userEvent.click(screen.getByRole('button', { name: 'Remove stage end' }));
expect(stages.toggleStageEnd).toHaveBeenCalledWith('b');
});
});
@@ -39,6 +39,7 @@ import { PaddleRolePill } from '../paddle/PaddleWaypointParts';
import { usePaddleRegionLoad } from '../paddle/usePaddleRegionLoad';
import { usePaddleWaypointActions } from '../paddle/usePaddleWaypointActions';
import { usePortageRouting } from '../paddle/usePortageRouting';
import { StageDivider, StageEndCorner, stageMenuItems } from '../stages/StageParts';
import { RailCard } from '../tourParts';
import { StationScheduleRow } from '../walk/StationSchedule';
import { usePlannerWalkSchedule } from '../walk/useWalkSchedule';
@@ -180,10 +181,11 @@ function numberNote(
ferrata: TourWaypointFerrata | null,
poiCategory: TourPoiCategory | null,
station: StationMarks,
t: Translate
t: Translate,
stageNote?: string
): { note: string | null; poi: TourPoiCategory | null } {
const marks = station ? stationMarkNote(station, t) : null;
const join = (first: string | null) => [first, marks].filter(Boolean).join(', ') || null;
const join = (first: string | null) => [first, marks, stageNote].filter(Boolean).join(', ') || null;
if (ferrata) return { note: join(t('tours.ferrata.waypointAtEnd', { name: ferrata.name })), poi: null };
if (poiCategory) return { note: join(t(TOUR_POI_LOOKS[poiCategory].labelKey)), poi: poiCategory };
return { note: join(null), poi: null };
@@ -205,6 +207,8 @@ function WaypointNumber({
station = null,
loopEnd = false,
shaping = false,
stageNote,
corner,
}: {
/** The stop's number; shaping points do not count, as on the map. */
stop: number;
@@ -218,6 +222,10 @@ function WaypointNumber({
loopEnd?: boolean;
/** P2A-03: a shaping point, a small dot as on the map. */
shaping?: boolean;
/** MDT-01: the stage of a multi-day tour that ends at this stop, said with the number. */
stageNote?: string;
/** MDT-01: a mark at the number's corner, the moon where a stage ends. */
corner?: ReactNode;
}) {
const { t } = useTranslation();
if (shaping) {
@@ -245,7 +253,7 @@ function WaypointNumber({
);
}
const label = t('tours.planner.waypointLabel', { n: stop });
const { note, poi } = numberNote(ferrata, poiCategory, station, t);
const { note, poi } = numberNote(ferrata, poiCategory, station, t, stageNote);
const number = (
<span
aria-label={[label, note].filter(Boolean).join(', ')}
@@ -258,6 +266,7 @@ function WaypointNumber({
{ferrata && <FerrataGlyph size={22} className="absolute -bottom-2.5 -start-2.5" />}
{poi && <PoiCornerIcon category={poi} />}
{station?.protected && <StationShield />}
{corner}
</span>
);
if (!ferrata) return note ? <Tooltip label={note}>{number}</Tooltip> : number;
@@ -494,6 +503,7 @@ function WaypointRowActions({
},
...routeMenuItems(planner, point, index, lastIndex, t),
...roundMenuItems(planner, point, t),
...stageMenuItems(planner.stages, point, t),
...(planner.isPaddle ? paddleMenuItems(paddle, point, index < lastIndex, t) : []),
...(onUnlink
? [{ divider: true } as const, { label: t('tours.placePicker.unlink'), icon: Unlink, onClick: onUnlink }]
@@ -702,6 +712,15 @@ export default function TourWaypointList({
// PAD-11C: where a leg lacks the water data of its region, TREK fetches it and plans the leg again.
const regionLoad = usePaddleRegionLoad(routedLegs?.failures, planner.retry);
const stopNumbers = stopNumbersOf(planner.waypoints);
// MDT-01: a multi-day tour's stages, each headed where it begins; the stop that ends one carries its number.
const stageStarts = new Map(planner.stages.stages.map((stage) => [stage.from, stage]));
const stageEnds = new Map(planner.stages.stages.slice(0, -1).map((stage) => [stage.toId, stage.number]));
const stageHead = (index: number) => {
const stage = stageStarts.get(index);
return stage ? <StageDivider stage={stage} /> : null;
};
const stageMarkOf = (stage: number | undefined) =>
stage ? { stageNote: t('tours.stages.endOf', { number: stage }), corner: <StageEndCorner /> } : {};
const endDrag = () => {
setDraggedWaypointId(null);
setDropTarget(null);
@@ -753,6 +772,7 @@ export default function TourWaypointList({
const stop = stopNumbers.get(point.id) ?? index + 1;
return (
<Fragment key={point.id}>
{index === 0 && stageHead(0)}
<li
data-testid="tour-planner-waypoint-row"
onDragStart={(event) => {
@@ -814,6 +834,7 @@ export default function TourWaypointList({
station={point}
loopEnd={loopEnd}
shaping={!!point.shaping}
{...stageMarkOf(stageEnds.get(point.id))}
/>
<button
type="button"
@@ -845,6 +866,7 @@ export default function TourWaypointList({
</div>
<StationScheduleRow schedule={walk.schedule} point={point} placeName={placeName} number={stop} />
</li>
{index > 0 && stageHead(index)}
<WaypointLegRows
planner={planner}
point={point}
@@ -88,7 +88,8 @@ function validDraftWaypoint(point: TourPlannerWaypoint): boolean {
Math.abs(point.lat) <= 90 &&
Number.isFinite(point.lng) &&
Math.abs(point.lng) <= 180 &&
(point.lock == null || paddleLockSchema.safeParse(point.lock).success)
(point.lock == null || paddleLockSchema.safeParse(point.lock).success) &&
(point.stageEnd === undefined || typeof point.stageEnd === 'boolean')
);
}
@@ -1,5 +1,6 @@
import {
MAX_PLANNED_TOUR_DURATION_MINUTES,
maxTourMinutesFor,
plannableTourTypeSchema,
runMinutesAtPace,
tourWebsiteSchema,
@@ -72,6 +73,8 @@ export interface TourPlannerFactsInput {
stays?: Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'> | null;
/** The router's own time, seconds: a bike tour's riding time; stands in for a hike until the heights are in. */
durationSeconds: number | null;
/** MDT-01: the stages the tour is split into, one for a day tour; a day each is what the times may take. */
stageCount?: number;
}
function invalidMinutes(value: number | null): boolean {
@@ -191,7 +194,7 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
plannedTotalInvalid:
plannedDurationMinutes === null &&
automaticPlannedTotalMinutes !== null &&
automaticPlannedTotalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES,
automaticPlannedTotalMinutes > maxTourMinutesFor(input.stageCount ?? 1),
// A city walk's stops are its stays: it saves no breaks, so a cafe never counts as a stay and a break at once.
savedBreakAdditionalMinutes: input.tourType === 'walk' ? null : breakAdditionalMinutes,
// The router's own time stands in for a hike without heights; a paddle tour has only its speed, a run its pace, a ride none.
@@ -224,6 +224,15 @@ describe('tourPlannerFacts', () => {
).toBe(true);
expect(tourPlannerFacts(hike({ durationSeconds: 600 })).stationStays).toBeNull();
});
it('MDT-01: a multi-day tour may take a day a stage on the move, a day tour one day', () => {
// 30 hours on the move: too long for a day, room enough for two stages.
const long = hike({ tourType: 'bike', durationSeconds: 30 * 3600 });
expect(tourPlannerFacts(long).plannedTotalInvalid).toBe(true);
expect(tourPlannerFacts({ ...long, stageCount: 2 }).plannedTotalInvalid).toBe(false);
const withBreaks = { ...long, stageCount: 2, breakAdditionalMinutes: 19 * 60 };
expect(tourPlannerFacts(withBreaks).plannedTotalInvalid).toBe(true);
});
});
describe('usePlannerHistory', () => {
@@ -1,5 +1,6 @@
// FE-TOUR-WAYPOINTS-001 to FE-TOUR-WAYPOINTS-012: the editor's waypoint model, shaping points, drawn legs
// and a city walk's stations with the keys a save answers (P2A-03, PAD-11, CW-01 to CW-04, RTE-02).
// FE-TOUR-WAYPOINTS-001 to FE-TOUR-WAYPOINTS-013: the editor's waypoint model, shaping points, drawn legs,
// a city walk's stations with the keys a save answers and the stage ends of a multi-day tour
// (P2A-03, PAD-11, CW-01 to CW-04, RTE-02, MDT-01).
import type { TourWaypoint } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import {
@@ -255,4 +256,23 @@ describe('tourPlannerWaypoints', () => {
['c', 2],
]);
});
it('FE-TOUR-WAYPOINTS-013: a stage end is saved and read with its stop, plans no route, and holds only between start and end', () => {
const saved = savedWaypointsOf([A, { ...B, stageEnd: true }, C]);
expect(saved[1]).toEqual({ lat: 49.01, lng: 12.01, role: 'via', sequence: 1, stage_end: true });
expect(saved[0]).not.toHaveProperty('stage_end');
let next = 0;
const read = plannerWaypointsOf(saved, () => `p${(next += 1)}`);
expect(read[1]).toMatchObject({ id: 'p2', stageEnd: true });
expect(read[0]).not.toHaveProperty('stageEnd');
// The route does not depend on it; the history does.
expect(routeInputsKey([A, { ...B, stageEnd: true }, C])).toBe(routeInputsKey([A, B, C]));
expect(sameWaypointSnapshot([A, { ...B, stageEnd: true }, C], [A, B, C])).toBe(false);
// Moved to an end, or made a shaping point, a stop ends no stage.
const moved = normalizePlannerWaypoints([{ ...B, stageEnd: true }, A, C]);
expect(moved[0]).not.toHaveProperty('stageEnd');
const shaped = normalizePlannerWaypoints([A, { ...B, stageEnd: true, shaping: true }, C]);
expect(shaped[1]).not.toHaveProperty('stageEnd');
expect(normalizePlannerWaypoints([A, { ...B, stageEnd: true }, C])[1].stageEnd).toBe(true);
});
});
@@ -44,6 +44,8 @@ export interface TourPlannerWaypoint {
openingHours?: string | null;
/** PLN-03: the kind of place the point was taken in from along the tour, whose icon its row carries. */
poiCategory?: TourPoiCategory | null;
/** MDT-01: a stop where a stage of a multi-day tour ends and the next begins. */
stageEnd?: boolean;
}
/** Stops are numbered on their own, as on the map: a shaping point (P2A-03) takes no number. */
@@ -71,6 +73,7 @@ export function plannerWaypointsOf(saved: readonly TourWaypoint[], newId: () =>
...(point.protected ? { protected: true } : {}),
...(point.opening_hours ? { openingHours: point.opening_hours } : {}),
...(point.poi_category ? { poiCategory: point.poi_category } : {}),
...(point.stage_end ? { stageEnd: true } : {}),
}));
}
@@ -98,6 +101,7 @@ export function savedWaypointsOf(points: readonly TourPlannerWaypoint[], tourTyp
...(walk && point.protected ? { protected: true } : {}),
...(point.openingHours ? { opening_hours: point.openingHours } : {}),
...(point.poiCategory ? { poi_category: point.poiCategory } : {}),
...(point.stageEnd ? { stage_end: true } : {}),
}));
}
@@ -119,6 +123,10 @@ export function ridablePoints(points: TourPlannerWaypoint[]): TourPlannerWaypoin
* Roles from the order; free legs follow their points, and a paddle tour keeps
* its portages and locks. A ride (HOR-01) has every leg on a horse route or
* drawn by hand; any other type gives a horse route section back to the router.
* A stage end (MDT-01) stays only where one can be: at a stop between start and
* end. A mark that ends up elsewhere after a change (its point moved to an end,
* made a shaping point) is dropped here, and the planner says so rather than
* move it to another point.
*/
export function normalizePlannerWaypoints(
points: TourPlannerWaypoint[],
@@ -126,10 +134,12 @@ export function normalizePlannerWaypoints(
): TourPlannerWaypoint[] {
const joined = keepJoinedFixedLegs(alignFreeLegs(points, tourType === 'kayak'));
const typed = tourType === 'horse' ? rideLegs(joined) : withoutHorseRoutes(joined);
return typed.map((point, index) => ({
...point,
role: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via',
}));
return typed.map((point, index) => {
const role = index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via';
if (!point.stageEnd || (role === 'via' && !point.shaping)) return { ...point, role };
const { stageEnd: _dropped, ...rest } = point;
return { ...rest, role };
});
}
function fixedLegKey(leg: TourFixedLeg | null | undefined): string {
@@ -170,8 +180,9 @@ export function routeExtrasKey(points: TourPlannerWaypoint[]): string {
/**
* CW-02: everything a route is planned from: every point with all it holds but
* a station's own fields (its name, stay, importance, protection, opening
* hours and the kind of place it was found as) and the key a save gave it. A change to those alone leaves the route
* as it is; any other change plans it again.
* hours and the kind of place it was found as), the key a save gave it and
* (MDT-01) whether a stage ends there. A change to those alone leaves the
* route as it is; any other change plans it again.
*/
export function routeInputsKey(points: readonly TourPlannerWaypoint[]): string {
return JSON.stringify(
@@ -184,6 +195,7 @@ export function routeInputsKey(points: readonly TourPlannerWaypoint[]): string {
openingHours: _hours,
poiCategory: _kind,
key: _key,
stageEnd: _stage,
...routed
}) => routed
)
@@ -204,12 +216,18 @@ function stationFieldsKey(points: TourPlannerWaypoint[]): string {
);
}
/** The same step of the history: the line, what was planned along it, and every station's own fields. */
/** MDT-01: where the stages end, which the route does not depend on either. */
function stageEndsKey(points: TourPlannerWaypoint[]): string {
return points.map((point) => (point.stageEnd ? '1' : '0')).join('');
}
/** The same step of the history: the line, what was planned along it, every station's own fields and the stage ends. */
export function sameWaypointSnapshot(a: TourPlannerWaypoint[], b: TourPlannerWaypoint[]): boolean {
return (
tourWaypointKey(a) === tourWaypointKey(b) &&
routeExtrasKey(a) === routeExtrasKey(b) &&
stationFieldsKey(a) === stationFieldsKey(b)
stationFieldsKey(a) === stationFieldsKey(b) &&
stageEndsKey(a) === stageEndsKey(b)
);
}
@@ -0,0 +1,232 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { routeWalkingTour, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(() => ({
routeWalkingTour: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
}));
vi.mock('./tourRouting', () => ({ routeWalkingTour, enrichTourElevations }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
vi.mock('../useTourPermissions', () => ({
useTourPermissions: ({ canEdit = true, canAssign = true }: { canEdit?: boolean; canAssign?: boolean }) => ({
canEdit,
canAssign,
}),
}));
import { validDraft } from './tourPlannerDraft';
import { useTourPlanner } from './useTourPlanner';
// FE-TOUR-STAGES-001 to FE-TOUR-STAGES-008 (MDT-01)
const POINTS: Array<[number, number]> = [
[48, 11],
[48.01, 11.02],
[48.02, 11.04],
[48.03, 11.06],
];
const routed = {
coordinates: POINTS,
parts: [{ coordinates: POINTS, free: false }],
distanceMeters: 6000,
durationSeconds: 5400,
};
const enriched = POINTS.map(([lat, lng], index): [number, number, number] => [lat, lng, [500, 560, 520, 600][index]]);
const savedHike = {
place_id: 81,
name: 'Hut to hut',
tour_type: 'hike' as const,
distance: 6,
elevation_gain: 140,
elevation_loss: 40,
duration: 90,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: 2,
planned: false,
caution: false,
revision: 2,
stage_count: 2,
};
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
}
/** A planner with the four points set and their route planned. */
async function plannedHike(tripId: number) {
const hook = renderHook(() => useTourPlanner({ tripId }));
act(() => {
for (const [lat, lng] of POINTS) hook.result.current.addWaypoint(lat, lng);
});
await settle();
return hook;
}
describe('useTourPlanner, multi-day tours (MDT-01)', () => {
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
routeWalkingTour.mockReset().mockResolvedValue(routed);
enrichTourElevations.mockReset().mockResolvedValue(enriched);
createTour.mockReset();
detailTour.mockReset();
updateTour.mockReset();
});
afterEach(() => vi.useRealTimers());
it('FE-TOUR-STAGES-001: a stage end splits the one route into stages, measured from its line, without planning it again', async () => {
const { result } = await plannedHike(61);
expect(result.current.stages.multiDay).toBe(false);
expect(result.current.stages.stages).toEqual([]);
const stop = result.current.waypoints[1].id;
routeWalkingTour.mockClear();
act(() => result.current.stages.toggleStageEnd(stop));
await settle();
expect(routeWalkingTour).not.toHaveBeenCalled();
expect(result.current.waypoints[1].stageEnd).toBe(true);
expect(result.current.stages.multiDay).toBe(true);
expect(result.current.stages.stages.map((stage) => [stage.number, stage.gain, stage.loss])).toEqual([
[1, 60, 0],
[2, 80, 40],
]);
expect(result.current.stages.stages[0].toId).toBe(stop);
expect(result.current.stages.stages[1].fromId).toBe(stop);
expect(result.current.hasUnsavedChanges).toBe(true);
// One step of the history: undo takes the stage end back.
act(() => result.current.undo());
expect(result.current.waypoints[1].stageEnd).toBeUndefined();
expect(result.current.stages.multiDay).toBe(false);
});
it('FE-TOUR-STAGES-002: a stage end whose stop is removed is said to be lost, and undo brings it back', async () => {
const { result } = await plannedHike(62);
const stop = result.current.waypoints[2].id;
act(() => result.current.stages.toggleStageEnd(stop));
act(() => result.current.removeWaypoint(stop));
expect(result.current.stages.lost).toBe(1);
expect(result.current.stages.endCount).toBe(0);
act(() => result.current.undo());
expect(result.current.stages.lost).toBe(0);
expect(result.current.waypoints[2].stageEnd).toBe(true);
});
it('FE-TOUR-STAGES-003: a stop made a shaping point or moved to the end cannot end a stage, and says so', async () => {
const { result } = await plannedHike(63);
const stop = result.current.waypoints[1].id;
act(() => result.current.stages.toggleStageEnd(stop));
act(() => result.current.setWaypointShaping(stop, true));
expect(result.current.waypoints[1].stageEnd).toBeUndefined();
expect(result.current.stages.lost).toBe(1);
act(() => result.current.undo());
act(() => result.current.reorderWaypoint(stop, result.current.waypoints[3].id, 'after'));
expect(result.current.waypoints[3].id).toBe(stop);
expect(result.current.waypoints[3].stageEnd).toBeUndefined();
expect(result.current.stages.lost).toBe(1);
// A later change that loses nothing clears the notice.
act(() => result.current.setWaypointPosition(result.current.waypoints[1].id, 48.011, 11.021));
expect(result.current.stages.lost).toBe(0);
});
it('FE-TOUR-STAGES-004: a stage end taken away on purpose is no loss, and the order of the stages follows the route', async () => {
const { result } = await plannedHike(64);
const [, first, second] = result.current.waypoints.map((point) => point.id);
act(() => result.current.stages.toggleStageEnd(second));
act(() => result.current.stages.toggleStageEnd(first));
expect(result.current.stages.stages.map((stage) => stage.toId)).toEqual([
first,
second,
result.current.waypoints[3].id,
]);
act(() => result.current.stages.toggleStageEnd(first));
expect(result.current.stages.lost).toBe(0);
expect(result.current.stages.endCount).toBe(1);
// Reversed, the stages run the other way and keep their stops.
act(() => result.current.reverse());
expect(result.current.waypoints[1].id).toBe(second);
expect(result.current.waypoints[1].stageEnd).toBe(true);
// The tour keeps its one type for all its stages; another type keeps the stages.
act(() => result.current.setTourType('kayak'));
expect(result.current.tourType).toBe('kayak');
expect(result.current.stages.endCount).toBe(1);
});
it('FE-TOUR-STAGES-005: choosing a multi-day tour changes nothing yet; back to a day tour removes every stage end as one step', async () => {
const { result } = await plannedHike(65);
act(() => result.current.stages.setMultiDay(true));
expect(result.current.stages.multiDay).toBe(true);
expect(result.current.stages.stages).toHaveLength(1);
expect(result.current.waypoints.some((point) => point.stageEnd)).toBe(false);
act(() => {
result.current.stages.toggleStageEnd(result.current.waypoints[1].id);
result.current.stages.toggleStageEnd(result.current.waypoints[2].id);
});
expect(result.current.stages.stages).toHaveLength(3);
act(() => result.current.stages.setMultiDay(false));
expect(result.current.stages.multiDay).toBe(false);
expect(result.current.waypoints.some((point) => point.stageEnd)).toBe(false);
expect(result.current.stages.lost).toBe(0);
act(() => result.current.undo());
expect(result.current.stages.endCount).toBe(2);
// A fresh draft forgets the choice of a multi-day tour.
act(() => result.current.startNewTour(true));
act(() => result.current.stages.setMultiDay(true));
expect(result.current.stages.multiDay).toBe(true);
act(() => result.current.startNewTour(true));
expect(result.current.stages.multiDay).toBe(false);
});
it('FE-TOUR-STAGES-006: saves the stage ends with their stops and opens a saved tour with its stages', async () => {
detailTour.mockResolvedValue({
tour: savedHike,
waypoints: [
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
{ lat: 48.01, lng: 11.02, role: 'via', sequence: 1, stage_end: true },
{ lat: 48.02, lng: 11.04, role: 'via', sequence: 2 },
{ lat: 48.03, lng: 11.06, role: 'end', sequence: 3 },
],
});
updateTour.mockResolvedValue({ tour: { ...savedHike, revision: 3 }, waypoints: [] });
const { result } = renderHook(() => useTourPlanner({ tripId: 66 }));
await act(async () => {
await result.current.openTour({ place_id: 81 });
});
expect(result.current.stages.multiDay).toBe(true);
expect(result.current.waypoints[1].stageEnd).toBe(true);
act(() => result.current.setName('Hut to hut, three days'));
act(() => result.current.stages.toggleStageEnd(result.current.waypoints[2].id));
await settle();
await act(async () => {
await result.current.save();
});
const payload = updateTour.mock.calls[0]?.[2] as { waypoints: Array<{ stage_end?: boolean }> };
expect(payload.waypoints.map((point) => point.stage_end ?? false)).toEqual([false, true, true, false]);
});
it('FE-TOUR-STAGES-007: a viewer who may not edit sets no stage end', () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 68, canEdit: false, canAssign: false }));
act(() => result.current.stages.setMultiDay(true));
expect(result.current.stages.multiDay).toBe(false);
act(() => result.current.stages.toggleStageEnd('anything'));
expect(result.current.stages.endCount).toBe(0);
});
it('FE-TOUR-STAGES-008: the draft kept between visits holds the stage ends, and one with a broken mark is dropped', async () => {
const { result } = await plannedHike(69);
act(() => result.current.stages.toggleStageEnd(result.current.waypoints[1].id));
const draft = JSON.parse(localStorage.getItem('tour-draft-69') || 'null');
expect(draft.waypoints[1].stageEnd).toBe(true);
expect(validDraft(draft)).toBe(true);
draft.waypoints[1].stageEnd = 'yes';
expect(validDraft(draft)).toBe(false);
});
});
@@ -23,6 +23,8 @@ import { adoptChangedPoints } from './paddleRouting'
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
import { useRunPace } from '../run/useRunPace'
import { lostStageEnds } from '../stages/tourStages'
import { useTourStages } from '../stages/useTourStages'
/** What a tour planned from an import starts with. */
export interface DerivedTourDraft {
@@ -160,6 +162,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const [routeProfileFocus, setRouteProfileFocus] = useState<RouteProfileFocus | null>(null)
const [newDraftGeneration, setNewDraftGeneration] = useState(0)
const [mapFocusKey, setMapFocusKey] = useState(0)
// MDT-01: stage ends a change of the points could not keep, said while those points are the planner's.
const [stageLoss, setStageLoss] = useState<{ count: number; after: TourPlannerWaypoint[] } | null>(null)
const draftRevisionRef = useRef(0)
const saveRequestIdRef = useRef(0)
const saveInFlightRef = useRef(false)
@@ -263,6 +267,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
recordStep(snapshot())
waypointsRef.current = next
setWaypoints(next)
const lost = lostStageEnds(current, changed, next)
setStageLoss(lost > 0 ? { count: lost, after: next } : null)
// CW-02: a station's own fields (its stay, its name) plan no route: the routing goes on, and Save stays as it was.
if (routeInputsKey(current) === routeInputsKey(next)) {
markEdited()
@@ -277,6 +283,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setError(null)
}, [recordStep, invalidateDetailRequest, interruptRouting, markEdited, snapshot])
/** Whether the points may change now: the viewer may edit and no save is on its way. */
const mayEditPoints = useCallback(() => editPermissionRef.current && !saveInFlightRef.current, [])
// Detail laid in after the step that asked for it (a portage's way on land), with no step of its own.
const amendWaypoints = useCallback((change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => {
if (!editPermissionRef.current || saveInFlightRef.current) return
@@ -534,14 +543,25 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
// CW-02: a city walk's stays, what of them is known.
const stays = useMemo(() => (tourType === 'walk' ? walkTimes(waypoints, null) : null), [tourType, waypoints])
const runPaceSecondsPerKm = runPace.paceSecondsPerKm
// MDT-01: the stages, cut from the route while it is the one planned for these points.
const stagePaddle = useMemo(() => isPaddle
? { effectiveSpeedKmh, portageSpeedKmh, speedInvalid: paddleSpeedInvalid, legLengths: routedLegLengths }
: null, [effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths])
const stages = useTourStages({
waypoints, line: routeCurrent ? (enrichedGeometry ?? route) : null, tourType, routerSeconds: durationSeconds,
paddle: stagePaddle, commit: commitWaypoints, mayEdit: mayEditPoints,
draftKey: `${editingPlaceId ?? 'new'}:${newDraftGeneration}`,
lost: stageLoss?.after === waypoints ? stageLoss.count : 0,
})
const stageCount = Math.max(1, stages.stages.length)
const facts = useMemo(() => tourPlannerFacts({
tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, winterActivity, runProfile, runPaceSecondsPerKm, website,
plannedDurationMinutes, breakAdditionalMinutes,
paddle: { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle },
paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds, stays,
paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds, stays, stageCount,
}), [bikeProfile, boatType, breakAdditionalMinutes, durationSeconds, hikingPreferences, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, runPaceSecondsPerKm, runProfile, speedKmh, stays, tourType, waterContext, website,
winterActivity])
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, runPaceSecondsPerKm, runProfile, speedKmh, stageCount, stays, tourType, waterContext,
website, winterActivity])
// CW-02: a city walk's times as the overview says them, from the same derivation as its planned total.
const { websiteInvalid, plannedDurationInvalid, breakAdditionalInvalid, paddleIncomplete, walkingDurationMinutes,
plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, savedBreakAdditionalMinutes, typeFields, stationStays,
@@ -794,21 +814,20 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
}, [interruptRouting])
// P2A-03/P2A-05/PAD-11: shaping points, a leg planned afresh, drawn legs handed back to the router.
const mayEditRoute = useCallback(() => editPermissionRef.current && !saveInFlightRef.current, [])
const shaping = useRouteShaping({
commit: commitWaypoints, waypointsRef, retry, mayEdit: mayEditRoute,
commit: commitWaypoints, waypointsRef, retry, mayEdit: mayEditPoints,
isPaddle: useCallback(() => tourTypeRef.current === 'kayak', []),
forgetLeg: useCallback((from: TourPlannerWaypoint, to: TourPlannerWaypoint) =>
paddleRouteRepo.forget(tripId, from, to, { boat: paddleBoat ?? 'kayak', lakeStyle: paddleLakeStyle }), [paddleBoat, paddleLakeStyle, tripId]),
})
// RTE-02: other ways for one routed section of a hike, compared and taken on purpose.
const legVariants = useLegVariants({
waypoints, route, enrichedGeometry, routeCurrent, tourType, maxHikingDifficulty, hikingPreferences, undo, mayEdit: mayEditRoute,
waypoints, route, enrichedGeometry, routeCurrent, tourType, maxHikingDifficulty, hikingPreferences, undo, mayEdit: mayEditPoints,
insertShapingPoints: shaping.insertShapingPoints,
})
// RTE-03: round hikes of about a wished length out of a stop, put in place of the plan on purpose.
const roundHikes = useRoundHikes({
waypoints, tourType, maxHikingDifficulty, hikingPreferences, replaceWaypoints: commitWaypoints, undo, mayEdit: mayEditRoute,
waypoints, tourType, maxHikingDifficulty, hikingPreferences, replaceWaypoints: commitWaypoints, undo, mayEdit: mayEditPoints,
})
const readOnlyGpxAnalysis = useMemo(
@@ -941,7 +960,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
waypoints, selectedWaypointId, setSelectedWaypointId,
addWaypoint, appendFixedLeg, setWaypointPosition, removeWaypoint, moveWaypoint, reorderWaypoint, editWaypoints: commitWaypoints,
reverse, returnToStart, isLoop: isClosedLoop(waypoints), toggleWaypointFreeLeg, editPaddlePoints, amendWaypoints, paddleEstimate,
...shaping, legVariants, roundHikes, paddleRoute, routeCurrent,
...shaping, legVariants, roundHikes, paddleRoute, routeCurrent, stages,
undo, redo, canUndo: history.canUndo, canRedo: history.canRedo,
status, error, retry, isSaving,
route, routeParts, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds, unreachable,