Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

merge dev and reconcile roadtrip planning

Mauriceac57321840e1
diff --cc client/src/hooks/useRouteCalculation.ts
index bc7fb3393,ef4f9a8fe..06e0a358f
--- a/client/src/hooks/useRouteCalculation.ts
+++ b/client/src/hooks/useRouteCalculation.ts
@@@ -47,174 -40,16 +43,16 @@@ export function useRouteCalculation(tri
if (!dayId || !enabled) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
// Read directly from store (not a render-phase ref) so callers after optimistic
// updates or non-optimistic deletes always see the latest assignments.
- const currentAssignments = useTripStore.getState().assignments || {}
- const da = (currentAssignments[String(dayId)] || []).filter(a => mirrorServiceStops || !isServiceStopType(a.place?.stop_type)).slice().sort((a, b) => a.order_index - b.order_index)
- const allReservations = useTripStore.getState().reservations || []
- const allDays = useTripStore.getState().days || []
- const dayOrder = (id: number | null | undefined): number | null => {
- if (id == null) return null
- const d = allDays.find(x => x.id === id)
- return d ? ((d as any).day_number ?? allDays.indexOf(d)) : null
- }
- const thisOrder = dayOrder(dayId)
-
- // The order the day plan shows is the order the map has to draw, so take it from
- // the same place the plan does rather than rebuilding it here. The old builder
- // read the BOOKING's position and never expanded metadata.legs, while a
- // multi-leg booking stores its position per leg — so a layover flight was
- // dropped from the waypoint list entirely and the airport before it was joined
- // to the airport after it in one road run across an ocean (#2071).
- //
- // getTransportForDay brings the span filter, the hotel/assignment exclusions and
- // the leg expansion with it; getMergedItems places each leg by its own saved
- // position, falling back to its time. Notes carry no coordinates, so none are
- // passed.
- const dayTransports = thisOrder == null ? [] : getTransportForDay({
- reservations: allReservations.filter(r => TRANSPORT_TYPES.includes(r.type)),
- dayId,
- dayAssignmentIds: da.map(a => a.id),
+ const state = useTripStore.getState()
+ const allDays = state.days || []
+ const runsWithHotel = buildDayRouteRuns(dayId, {
days: allDays,
- assignments: state.assignments || {},
++ assignments: Object.fromEntries(Object.entries(state.assignments || {}).map(([id, entries]) => [id, entries.filter(a => mirrorServiceStops || !isServiceStopType(a.place?.stop_type))])),
+ reservations: state.reservations || [],
+ accommodations,
+ optimizeFromAccommodation,
})
- const merged = getMergedItems({ dayAssignments: da, dayNotes: [], dayTransports, dayId })
-
- // Build a unified list of places + transports sorted by effective position.
- type Entry =
- | { kind: 'place'; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
- | { kind: 'transport'; from: { lat: number; lng: number } | null; to: { lat: number; lng: number } | null; pos: number; carrier: boolean }
- const entries: Entry[] = merged.flatMap((item): Entry[] => {
- if (item.type === 'place') {
- const a = item.data
- if (!a.place?.lat || !a.place?.lng) return []
- return [{
- kind: 'place', lat: a.place.lat, lng: a.place.lng, pos: item.sortKey, time: a.place?.place_time ?? null,
- // Per-segment travel mode (#1281): mode of the leg leaving this place.
- mode: (a as { leg_transport_mode?: string | null }).leg_transport_mode ?? null,
- // Boundary-leg mode (#1281 follow-up): mode of the leg arriving at this place.
- incoming: (a as { incoming_leg_transport_mode?: string | null }).incoming_leg_transport_mode ?? null,
- }]
- }
- if (item.type !== 'transport') return []
- const { from, to } = getTransportRouteEndpoints(item.data, dayId)
- return [{ kind: 'transport', from, to, pos: item.sortKey, carrier: isCarrierTransport(item.data) }]
- })
-
- // Group located places into driving runs.
- // - A transport WITH a location anchors the route to its departure point (you
- // travel there), then breaks the run (you don't drive the flight/train); its
- // arrival point starts the next run.
- // - A transport WITHOUT a location is ignored entirely — the places around it
- // connect directly, as if the booking weren't there.
- // A run is only a real drive when it contains at least one actual place. Two
- // back-to-back transports (e.g. two flights on one day) would otherwise pair the
- // first's arrival point with the second's departure point into a phantom
- // [airport → airport] road route — that is the flight itself, not a drive (#1394).
- //
- // A booking endpoint also has to be REACHABLE from the stop before it. The day's
- // order is a wall clock with no timezone behind it, so a long-haul arrival whose
- // departure clock reads late sorts after the day's local stops — and its departure
- // airport, an ocean away, then gets stapled to the last of them. The router answers
- // that pair with NoRoute and the whole chunk falls back to a straight line, which is
- // the long ray the map draws (#2133). Distance is only ever consulted for a leg
- // touching a transport endpoint: two real places far apart are a drive someone
- // planned, an airport that far from the stop before it never is.
- type RunPoint = { lat: number; lng: number; isPlace: boolean; leg_transport_mode?: string | null; incoming_leg_transport_mode?: string | null }
- const runs: RunPoint[][] = []
- let currentRun: RunPoint[] = []
- let runHasPlace = false
- const closeRun = () => {
- if (currentRun.length >= 2 && runHasPlace) runs.push(currentRun)
- currentRun = []
- runHasPlace = false
- }
- for (const entry of entries) {
- if (entry.kind === 'place') {
- const prev = currentRun[currentRun.length - 1]
- // The open run may be nothing but a far-away arrival endpoint — break rather
- // than draw the ocean.
- if (prev && !prev.isPlace && !withinDriveRange(prev, entry)) closeRun()
- currentRun.push({ lat: entry.lat, lng: entry.lng, isPlace: true, leg_transport_mode: entry.mode, incoming_leg_transport_mode: entry.incoming })
- runHasPlace = true
- } else if (entry.from || entry.to) {
- const prev = currentRun[currentRun.length - 1]
- if (entry.from && (!prev || withinDriveRange(prev, entry.from))) currentRun.push({ ...entry.from, isPlace: false })
- closeRun()
- if (entry.to) currentRun.push({ ...entry.to, isPlace: false })
- }
- }
- closeRun()
-
- // Bookend the route with the day's accommodation: a hotel → first-stop run and
- // a last-stop → hotel run, so the drawn line matches the sidebar's hotel legs.
- // getDayBookendHotels returns the morning/evening hotel (they differ only on a
- // transfer day) and already filters to accommodations that have coordinates.
const day = allDays.find(d => d.id === dayId)
- const bookends = day && optimizeFromAccommodation !== false
- ? getDayBookendHotels(day, allDays, accommodations)
- : null
- const flatPts: RunPoint[] = []
- for (const e of entries) {
- if (e.kind === 'place') flatPts.push({ lat: e.lat, lng: e.lng, isPlace: true, leg_transport_mode: e.mode, incoming_leg_transport_mode: e.incoming })
- else { if (e.from) flatPts.push({ ...e.from, isPlace: false }); if (e.to) flatPts.push({ ...e.to, isPlace: false }) }
- }
- // A hotel bookend point is not a place-assignment, so isPlace: false — resolveLegMode
- // falls through to the day default for hotel-adjacent legs unless the place endpoint
- // carries its own override.
- const hotelPt = (a?: Accommodation): RunPoint | null =>
- a && a.place_lat != null && a.place_lng != null ? { lat: a.place_lat, lng: a.place_lng, isPlace: false } : null
- // Only draw a hotel bookend when the leg is a real drive. You start/end the day at a hotel
- // when you slept there / sleep there tonight; on the hotel's own check-in or check-out day
- // the leg holds only when the edge stop is a PLACE timed after check-in / before check-out
- // (you dropped bags first, or swung back before checking out). A place before check-in (an
- // airport you reach first, #1465), a later "home" stop on the checkout day (#1465), or a
- // transport endpoint on an arrival/departure day (#1321, S7) all draw no bookend.
- // A carrier endpoint at an edge additionally kills its own leg outright, however
- // near the hotel it sits: you flew out of that airport, so nothing drove back from
- // it tonight, and you flew into that one, so nothing drove to it this morning
- // (#2133). Which of a transport's two points sits at the edge depends on its span —
- // an overnight flight contributes only its departure on the day it leaves.
- const contributes = (e: Entry) => e.kind === 'place' || !!e.from || !!e.to
- const firstStop = entries.find(contributes)
- const lastStop = [...entries].reverse().find(contributes)
- const edgeInfo = (e: Entry | undefined, side: 'first' | 'last') => {
- if (!e) return undefined
- if (e.kind === 'place') return { isPlace: true, time: e.time, lat: e.lat, lng: e.lng }
- const role: CarrierEdge = side === 'first'
- ? (e.from ? 'departure' : 'arrival')
- : (e.to ? 'arrival' : 'departure')
- return { isPlace: false, time: null, carrierEdge: e.carrier ? role : null }
- }
- // A carrier with a located endpoint today means the day changes geography by
- // air/rail/sea — the check-in hotel is then the day's destination and the
- // check-out hotel its origin, which the no-time bookend default respects (#2157).
- const dayHasCarrier = dayTransports.some(r => hasCarrierEndpointOnDay(r, dayId))
- const firstWay = flatPts[0]
- const lastWay = flatPts[flatPts.length - 1]
- const morningHotel = hotelPt(bookends?.morning)
- const eveningHotel = hotelPt(bookends?.evening)
- // Same reachability test as the run builder: a hotel is not joined to a point no
- // one could have driven between.
- const drawMorning = !!bookends && !!day && shouldDrawMorningLeg(bookends, day, edgeInfo(firstStop, 'first'), dayHasCarrier)
- && (!morningHotel || !firstWay || firstWay.isPlace || withinDriveRange(morningHotel, firstWay))
- const drawEvening = !!bookends && !!day && shouldDrawEveningLeg(bookends, day, edgeInfo(lastStop, 'last'), dayHasCarrier)
- && (!eveningHotel || !lastWay || lastWay.isPlace || withinDriveRange(eveningHotel, lastWay))
- const runsWithHotel: RunPoint[][] = withHotelBookends(
- runs,
- firstWay,
- lastWay,
- drawMorning ? morningHotel : null,
- drawEvening ? eveningHotel : null,
- )
-
- // Transfer day with no activities: you check out of one accommodation and into
- // another, so there are no waypoints for withHotelBookends to attach a leg to.
- // Draw the hotel → hotel transfer directly. Gated on both bookends being real
- // (drawMorning/drawEvening already exclude the #1321 arrival fallback) and the two
- // hotels being distinct, so an ordinary same-hotel rest day still draws nothing.
- if (runsWithHotel.length === 0 && drawMorning && drawEvening) {
- const m = hotelPt(bookends?.morning)
- const e = hotelPt(bookends?.evening)
- if (m && e && (m.lat !== e.lat || m.lng !== e.lng)) runsWithHotel.push([m, e])
- }
const straightLines = (): [number, number][][] =>
runsWithHotel.map(r => r.map(p => [p.lat, p.lng] as [number, number]))
diff --cc client/src/pages/TripPlannerPage.tsx
index 1ee132c84,6e3c6dd9f..511f9f431
--- a/client/src/pages/TripPlannerPage.tsx
+++ b/client/src/pages/TripPlannerPage.tsx
@@@ -405,10 -408,9 +408,10 @@@ function TripPlannerPageDesktop(): Reac
tripId={tripId}
places={roadtripActive ? roadtripMapPlaces : mapPlaces}
dayPlaces={dayPlaces}
- route={roadtripActive ? roadtripMapLines : route}
- routeColors={roadtripActive ? roadtripLineColors : undefined}
+ route={roadtripActive ? roadtripMapLines : overviewActive ? tripOverview.lines : route}
+ routeColors={roadtripActive ? roadtripLineColors : overviewActive ? tripOverview.lineColors : undefined}
- routeVias={roadtripActive ? roadtripRoutes.vias : routeVias}
+ routeVias={roadtripActive ? roadtripMapVias : routeVias}
+ dayBoundaryControls={roadtripActive ? dayBoundaryControls : undefined}
accessLines={roadtripActive ? roadtripRoutes.accessLines : undefined}
showTransitRoutes={transitRoutesShown}
// The route toggle belongs to one day, so the map needs that day to
diff --cc client/src/pages/tripPlanner/useTripPlanner.ts
index baafa87d8,13d74eb37..1d1e71782
--- a/client/src/pages/tripPlanner/useTripPlanner.ts
+++ b/client/src/pages/tripPlanner/useTripPlanner.ts
@@@ -25,11 -22,8 +25,12 @@@ import { useAuthStore } from '../../sto
import { useResizablePanels } from '../../hooks/useResizablePanels'
import { useTripWebSocket } from '../../hooks/useTripWebSocket'
import { useRouteCalculation } from '../../hooks/useRouteCalculation'
+import { useRoadtripRoutes, type RoadtripStop } from '../../components/Roadtrip/useRoadtripRoutes'
+import { useAutomaticDayPoints } from '../../components/Roadtrip/useAutomaticDayPoints'
+import { useDayBoundaries } from '../../components/Roadtrip/useDayBoundaries'
+import type { DayBoundaryControls } from '../../components/Map/dayBoundaryDrag'
+import { dayWindow, roadtripInsertion } from '../../components/Roadtrip/dayWindow'
+ import { useTripRouteOverview } from '../../components/Map/useTripRouteOverview'
-import { useRoadtripRoutes } from '../../components/Roadtrip/useRoadtripRoutes'
import { useRoadtripCorridor } from '../../components/Roadtrip/useRoadtripCorridor'
import { useRoadtripVias } from '../../components/Roadtrip/useRoadtripVias'
import { useRefuelSearch } from '../../components/Roadtrip/useRefuelSearch'
diff --cc server/src/db/migrations.ts
index 34e72fe26,57299604f..e162c82c8
--- a/server/src/db/migrations.ts
+++ b/server/src/db/migrations.ts
@@@ -4535,27 -4534,26 +4535,47 @@@ function runMigrations(db: Database.Dat
db.exec('ALTER TABLE places ADD COLUMN fill_percent INTEGER');
}
},
+ () => {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS school_holiday_countries (
+ code TEXT PRIMARY KEY, name TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS school_holiday_regions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ country TEXT NOT NULL REFERENCES school_holiday_countries(code),
+ name TEXT NOT NULL COLLATE NOCASE, revision INTEGER NOT NULL DEFAULT 1,
+ UNIQUE(country, name)
+ );
+ CREATE TABLE IF NOT EXISTS school_holiday_periods (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ region_id INTEGER NOT NULL REFERENCES school_holiday_regions(id) ON DELETE CASCADE,
+ name TEXT NOT NULL, start_date TEXT NOT NULL, end_date TEXT NOT NULL,
+ CHECK (end_date >= start_date)
+ );
+ CREATE INDEX IF NOT EXISTS idx_school_holiday_periods_region ON school_holiday_periods(region_id);
+ `);
+ },
+ () => {
+ const cols = db.prepare("SELECT name FROM pragma_table_info('day_assignments')").all() as Array<{ name: string }>;
+ if (!cols.some(c => c.name === 'end_day')) {
+ db.exec('ALTER TABLE day_assignments ADD COLUMN end_day INTEGER NOT NULL DEFAULT 0');
+ }
+ },
+ () => {
+ db.exec(`CREATE TABLE IF NOT EXISTS roadtrip_day_boundaries (
+ trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+ day_number INTEGER NOT NULL CHECK (day_number BETWEEN 1 AND 366),
+ from_assignment_id INTEGER NOT NULL REFERENCES day_assignments(id) ON DELETE CASCADE,
+ to_assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE CASCADE,
+ fraction REAL NOT NULL CHECK (fraction BETWEEN 0 AND 1),
+ PRIMARY KEY (trip_id, day_number)
+ )`);
+ },
+ () => {
+ db.exec('CREATE TABLE IF NOT EXISTS roadtrip_preferences (trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (trip_id, key))');
+ const inherit = db.prepare('INSERT OR IGNORE INTO roadtrip_preferences (trip_id, key, value) SELECT t.id, s.key, s.value FROM trips t JOIN settings s ON s.user_id = t.user_id WHERE s.key = ? AND s.value IS NOT NULL');
+ for (const key of ROADTRIP_PREFERENCE_KEYS) inherit.run(key);
+ },
];
if (currentVersion < migrations.length) {
diff --cc shared/src/index.ts
index 35b55b6de,36b0d7453..1e70a09c2
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@@ -76,9 -75,5 +76,11 @@@ export * from './i18n/languages'
export * from './plugin-permissions';
// Plugin settings contracts: the settings-field descriptor + admin instance-config wire shapes.
export * from './plugins/plugins.schema';
+export * from './roadtrip/preferences.schema';
+export * from './roadtrip/hazards.schema';
+export * from './roadtrip/planning.schema';
+export * from './roadtrip/search.schema';
+export * from './roadtrip/google-import.schema';
+export * from './roadtrip/charging.schema';
+
+ export * from './vacay/school-holiday-catalog.schema';
diff --cc shared/src/roadtrip/assemble.ts
index 24615ba05,000000000..03c1b5f68
mode 100644,000000..100644
--- a/shared/src/roadtrip/assemble.ts
+++ b/shared/src/roadtrip/assemble.ts
@@@ -1,279 -1,0 +1,295 @@@
+import { spurFor } from './accessSpur';
+import { pointAtMeters } from './corridor';
+import type { RoadtripDayBoundary } from './day-boundary.schema';
+import { planDayWindow, type DayWindow } from './dayWindow';
+import { spillChains } from './nightSpill';
+import type {
+ PlanDay,
+ QuietDay,
+ RoadtripStop,
+ RoadtripDay,
+ RoadtripRoutes,
+ RoutedLeg,
+ RouteSegment,
+ SnappedWaypoint,
+ RouteAvoidClass,
+ DistanceUnit,
+} from './planning-types';
+import {
+ computeSchedule,
+ parseClock,
+ deriveDriveWarnings,
+ refuelsRange,
+ isServiceStopType,
+ type DryPoint,
+ type DriveLimits,
+ type VehicleKind,
+} from './roadtripModel';
+import { splitScheduledDays } from './splitScheduledDays';
+
+const stopKey = (s: RoadtripStop): string =>
+ `${s.lat.toFixed(5)},${s.lng.toFixed(5)},${s.legMode ?? ''},${s.incomingLegMode ?? ''}`;
+
+const legKey = (from: RoadtripStop, to: RoadtripStop): string => `${stopKey(from)}>${stopKey(to)}`;
+
+export function assembleRoadtrip({
+ plan,
+ quietDays,
+ window,
+ distanceUnit,
+ allLegs,
+ snapByDay,
+ missedByDay,
+ loading,
+ limits,
+ vehicleKind,
+ connectDays,
+ boundaries,
+ labels,
+}: {
+ plan: PlanDay[];
+ quietDays: QuietDay[];
+ window: DayWindow | null;
+ distanceUnit: DistanceUnit;
+ allLegs: Record<string, RoutedLeg>;
+ snapByDay: Record<number, Record<string, SnappedWaypoint>>;
+ missedByDay: Record<number, RouteAvoidClass[]>;
+ loading: boolean;
+ limits: DriveLimits;
+ vehicleKind: VehicleKind | null;
+ connectDays: boolean;
+ boundaries: RoadtripDayBoundary[];
+ labels: { start: string; end: string };
+}): RoadtripRoutes {
+ const chains = spillChains(plan, quietDays, (a, b) => allLegs[legKey(a, b)]);
+
+ const allSnaps: Record<string, SnappedWaypoint> = {};
+ for (const day of plan) Object.assign(allSnaps, snapByDay[day.dayId] ?? {});
+ const storedLegFor = (from: RoadtripStop, to: RoadtripStop): RoutedLeg | undefined => allLegs[legKey(from, to)];
+ const timed = window
+ ? planDayWindow(
+ [...plan, ...quietDays],
+ window,
+ storedLegFor,
+ distanceUnit,
+ { start: labels.start, end: labels.end },
+ boundaries,
+ )
+ : null;
+ const automaticSchedule = !!timed && timed.issue === null;
+ const displayChains = automaticSchedule
+ ? timed.chains
+ : timed?.issue
+ ? [...plan, ...quietDays]
+ .sort((a, b) => a.dayNumber - b.dayNumber)
+ .filter((d) => d.stops.length)
+ .map((d) => ({
+ ...d,
+ spills: [],
+ schedule: computeSchedule(
+ d.stops.map((s) => ({
+ anchor: s.time,
+ dwellMinutes: s.dwellMinutes,
+ departureAt: s.checkoutAt === undefined ? undefined : s.checkoutAt - d.dayNumber * 1440,
+ })),
+ d.stops.slice(0, -1).map((s, i) => storedLegFor(s, d.stops[i + 1]!)?.seg.duration),
+ ),
+ }))
+ : splitScheduledDays(chains, [...plan, ...quietDays], storedLegFor);
+ const legFor = automaticSchedule ? timed.legFor : storedLegFor;
+
+ const lines: [number, number][][] = [];
+ const lineDays: number[] = [];
+ const segments: RouteSegment[] = [];
+ const accessLines: RoadtripRoutes['accessLines'] = [];
+
+ const out: RoadtripDay[] = [];
+ let carryKm: number | null = 0;
+
+ let previousStop: RoadtripStop | undefined;
+
+ let previousDayNumber: number | undefined;
+ for (const chain of displayChains) {
+ const routed = chain.stops.slice(0, -1).map((s, i) => legFor(s, chain.stops[i + 1]!));
+
+ const inboundAt = new Map<number, { seg: RouteSegment | undefined; line: [number, number][]; drawnAs: number }>();
+ if (connectDays && !automaticSchedule) {
+ for (const spill of chain.spills) {
+ inboundAt.set(spill.at, { seg: spill.leg, line: spill.line, drawnAs: spill.fromDayNumber });
+ }
+
+ const joined = inboundAt.has(0) ? undefined : previousStop && legFor(previousStop, chain.stops[0]!);
+ if (joined)
+ inboundAt.set(0, { seg: joined.seg, line: joined.line, drawnAs: previousDayNumber ?? chain.dayNumber });
+ }
+ previousStop = chain.stops[chain.stops.length - 1]! ?? previousStop;
+ previousDayNumber = chain.stops.length ? chain.dayNumber : previousDayNumber;
+ for (let i = 0; i < chain.stops.length; i++) {
+ const inbound = inboundAt.get(i);
+ if (inbound) {
+ if (inbound.line.length > 1) {
+ lines.push(inbound.line);
+ lineDays.push(inbound.drawnAs);
+ }
+ if (inbound.seg) segments.push(inbound.seg);
+ }
+ const leg = routed[i];
+ if (!leg) continue;
+ if (leg.line.length > 1) {
+ lines.push(leg.line);
+ lineDays.push(chain.dayNumber);
+ }
+ segments.push(leg.seg);
+ }
+
+ const geometry: [number, number][] = [];
+ for (let i = 0; i < chain.stops.length; i++) {
+ const inbound = inboundAt.get(i);
+ if (inbound) geometry.push(...inbound.line);
+ geometry.push(...(routed[i]?.line ?? []));
+ }
+ const legs = routed.map((l) => l?.seg);
+ const inbound = [...inboundAt.values()].map((l) => l.seg);
+ const distance =
+ legs.reduce((sum, l) => sum + (l?.distance ?? 0), 0) + inbound.reduce((sum, l) => sum + (l?.distance ?? 0), 0);
+ const duration =
+ legs.reduce((sum, l) => sum + (l?.duration ?? 0), 0) + inbound.reduce((sum, l) => sum + (l?.duration ?? 0), 0);
+ const schedule = chain.schedule;
+ const legVias = routed.map((l) => l?.vias ?? []);
+ const stops = chain.stops.map((s, index) => {
+ const snap = s.automaticNight ? undefined : allSnaps[stopKey(s)];
+ const line = spurFor(snap);
+ if (line) accessLines.push({ line, meters: snap!.meters, stopKey: stopKey(s) });
+ const entry = schedule.entries[index];
+ const arrival = parseClock(entry?.arrival);
+ const dwellMinutes =
+ s.checkoutAt !== undefined && arrival !== null
+ ? Math.max(0, s.checkoutAt - ((chain.dayNumber + (entry?.dayOffset ?? 0)) * 1440 + arrival))
+ : s.checkoutAt !== undefined
+ ? null
+ : s.dwellMinutes;
+ return { ...s, dwellMinutes, offRoadMeters: line ? snap!.meters : null };
+ });
+
- const drive = { warnings: [] as ReturnType<typeof deriveDriveWarnings>['warnings'], day: null as ReturnType<typeof deriveDriveWarnings>['day'] };
++ const drive = {
++ warnings: [] as ReturnType<typeof deriveDriveWarnings>['warnings'],
++ day: null as ReturnType<typeof deriveDriveWarnings>['day'],
++ };
+ const dryPoints: (DryPoint & { lat: number; lng: number })[] = [];
+ const drivingLine: [number, number][] = [];
+ let drivenMeters = 0;
+ let drivingSeconds = 0;
+ for (let i = 0; i < stops.length; i++) {
+ const incoming = inboundAt.get(i);
+ if (incoming?.seg) {
+ const incomingDrive = deriveDriveWarnings([incoming.seg], [false, false], limits, carryKm);
+ carryKm = incomingDrive.carryKm;
- drive.warnings.push(...incomingDrive.warnings.map(w => ({ ...w, index: i })));
++ drive.warnings.push(...incomingDrive.warnings.map((w) => ({ ...w, index: i })));
+ for (const dry of incomingDrive.emptyAt) {
- const at = pointAtMeters(incoming.line.map(([lat, lng]) => ({ lat, lng })), dry.drivenMeters);
++ const at = pointAtMeters(
++ incoming.line.map(([lat, lng]) => ({ lat, lng })),
++ dry.drivenMeters,
++ );
+ if (at) dryPoints.push({ ...dry, legIndex: -i - 1, inboundLine: incoming.line, lat: at.lat, lng: at.lng });
+ }
+ if (!incoming.seg.mode || incoming.seg.mode === 'driving') drivingSeconds += incoming.seg.duration ?? 0;
+ }
+ const leg = routed[i];
+ const outgoing = deriveDriveWarnings(
+ i < stops.length - 1 ? [leg?.seg] : [],
+ [refuelsRange(stops[i]!.stopType, vehicleKind), false],
+ limits,
+ carryKm,
+ [stops[i]!.fillPercent],
+ );
+ carryKm = outgoing.carryKm;
- drive.warnings.push(...outgoing.warnings.map(w => ({ ...w, index: i + 1 })));
++ drive.warnings.push(...outgoing.warnings.map((w) => ({ ...w, index: i + 1 })));
+ for (const dry of outgoing.emptyAt) {
- const at = pointAtMeters((leg?.line ?? []).map(([lat, lng]) => ({ lat, lng })), dry.intoLegKm * 1000);
- if (at) dryPoints.push({ ...dry, legIndex: i, drivenMeters: drivenMeters + dry.intoLegKm * 1000, lat: at.lat, lng: at.lng });
++ const at = pointAtMeters(
++ (leg?.line ?? []).map(([lat, lng]) => ({ lat, lng })),
++ dry.intoLegKm * 1000,
++ );
++ if (at)
++ dryPoints.push({
++ ...dry,
++ legIndex: i,
++ drivenMeters: drivenMeters + dry.intoLegKm * 1000,
++ lat: at.lat,
++ lng: at.lng,
++ });
+ }
+ if (leg && (!leg.seg.mode || leg.seg.mode === 'driving')) {
+ drivingLine.push(...leg.line);
+ drivenMeters += leg.seg.distance ?? 0;
+ drivingSeconds += leg.seg.duration ?? 0;
+ }
+ }
+ const drivingMinutes = Math.round(drivingSeconds / 60);
+ if (limits.dayMinutes && drivingMinutes > limits.dayMinutes) {
+ drive.day = { code: 'dayDriving', minutes: drivingMinutes, limitMinutes: limits.dayMinutes };
+ }
+ const drivingGeometry = drivingLine.length === geometry.length ? geometry : drivingLine;
+ out.push({
+ automaticSchedule,
+ dayId: chain.dayId,
+ dayNumber: chain.dayNumber,
+ date: chain.date,
+ title: chain.title,
+ avoidMissed: missedByDay[chain.dayId],
+ spills: chain.spills,
+ stops,
+ legs,
+ legVias,
+ schedule,
+ geometry,
+ distance,
+ duration,
+ dryPoints,
+ drivingGeometry,
+ driveWarnings: drive.warnings,
+ dayWarning: drive.day,
+ });
+ }
+ const drives = out.filter((d) => d.stops.length > 1 || !!d.spills?.length || d.stops.some((s) => s.automaticNight));
+ const originalStops = [...plan, ...quietDays].sort((a, b) => a.dayNumber - b.dayNumber).flatMap((day) => day.stops);
+ const boundaryPath = originalStops.slice(0, -1).flatMap((from, position) => {
+ const to = originalStops[position + 1]!;
+ const leg = storedLegFor(from, to);
+ return leg && (!leg.seg.mode || leg.seg.mode === 'driving') && from.assignmentId > 0 && to.assignmentId > 0
+ ? [{ from, to, position, line: leg.line }]
+ : [];
+ });
+ return {
+ boundaryPath,
+ validateBoundaries: (next: RoadtripDayBoundary[]) =>
+ window
+ ? planDayWindow(
+ [...plan, ...quietDays],
+ window,
+ storedLegFor,
+ distanceUnit,
+ { start: labels.start, end: labels.end },
+ next,
+ ).issue
+ : 'conflict',
+ dayWindowIssue: timed?.issue ?? null,
+ days: drives,
+ lines,
+ lineDays,
+ segments,
+ accessLines,
+ vias: out.flatMap((d) => d.legVias.flat()),
+ totalDistance: drives.reduce((s, d) => s + d.distance, 0),
+ totalDuration: drives.reduce((s, d) => s + d.duration, 0),
+
+ totalStops: drives.reduce(
+ (s, d) => s + d.stops.filter((st) => !st.automaticNight && !isServiceStopType(st.stopType)).length,
+ 0,
+ ),
+
+ quietDays: out
+ .filter((d) => d.stops.length < 2 && !d.spills?.length && !d.stops.some((s) => s.automaticNight))
+ .map((d) => ({ dayId: d.dayId, dayNumber: d.dayNumber, date: d.date, title: d.title, stops: d.stops })),
+ loading,
+ };
+}