finish overnight stops and cross-day range warnings

This commit is contained in:
Maurice
2026-09-12 15:37:09 +02:00
parent f56e7a161e
commit b10b02c685
58 changed files with 777 additions and 185 deletions
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'العثور على إقامة',
'roadtrip.stay.portalHint': 'تحقق من الوجهة والتواريخ والضيوف في الموقع. ابحث يدوياً في CHECK24.',
'roadtrip.charging.available': 'متاح',
'roadtrip.charging.unknown': 'لا تتوفر بيانات موثوقة',
'roadtrip.charging.stale': 'الحالة قديمة',
+9 -6
View File
@@ -1,12 +1,15 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.charging.available': "disponíveis",
'roadtrip.charging.unknown': "Sem dados confiáveis",
'roadtrip.charging.stale': "Status desatualizado",
'roadtrip.charging.prices': "Tarifas publicadas",
'roadtrip.charging.note': "Tarifa publicada; impostos, condições e taxas extras podem se aplicar. O preço do seu cartão pode variar.",
'roadtrip.charging.coverage': "Dados abertos; cobertura varia por região e operador.",
'roadtrip.stay.portals': 'Encontrar hospedagem',
'roadtrip.stay.portalHint': 'Confira destino, datas e hóspedes no portal. No CHECK24, pesquise manualmente.',
'roadtrip.charging.available': 'disponíveis',
'roadtrip.charging.unknown': 'Sem dados confiáveis',
'roadtrip.charging.stale': 'Status desatualizado',
'roadtrip.charging.prices': 'Tarifas publicadas',
'roadtrip.charging.note':
'Tarifa publicada; impostos, condições e taxas extras podem se aplicar. O preço do seu cartão pode variar.',
'roadtrip.charging.coverage': 'Dados abertos; cobertura varia por região e operador.',
'roadtrip.import.title': 'Importar rota do Google Maps',
'roadtrip.import.note': 'As paradas são adicionadas ao dia escolhido. O TREK recalcula a rota.',
'roadtrip.import.unresolved': 'Local não encontrado; esta parada será ignorada.',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Troba allotjament',
'roadtrip.stay.portalHint': 'Comprova la destinació, les dates i els hostes al portal. A CHECK24, cerca manualment.',
'roadtrip.charging.available': 'disponibles',
'roadtrip.charging.unknown': 'No hi ha dades fiables',
'roadtrip.charging.stale': 'Estat desactualitzat',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Najít ubytování',
'roadtrip.stay.portalHint': 'Na portálu ověřte cíl, termín a hosty. Na CHECK24 hledejte ručně.',
'roadtrip.charging.available': 'volné',
'roadtrip.charging.unknown': 'Spolehlivá data nejsou dostupná',
'roadtrip.charging.stale': 'Zastaralý stav',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Unterkunft finden',
'roadtrip.stay.portalHint': 'Ziel, Daten und Gäste im Portal prüfen. Bei CHECK24 manuell suchen.',
'roadtrip.charging.available': 'frei',
'roadtrip.charging.unknown': 'Keine verlässlichen Daten verfügbar',
'roadtrip.charging.stale': 'Status veraltet',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Find accommodation',
'roadtrip.stay.portalHint': 'Check destination, dates and guests on the portal. CHECK24 requires a manual search.',
'roadtrip.charging.available': 'available',
'roadtrip.charging.unknown': 'No reliable data available',
'roadtrip.charging.stale': 'Status outdated',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Buscar alojamiento',
'roadtrip.stay.portalHint':
'Comprueba el destino, las fechas y los huéspedes en el portal. En CHECK24, busca manualmente.',
'roadtrip.charging.available': 'disponibles',
'roadtrip.charging.unknown': 'No hay datos fiables',
'roadtrip.charging.stale': 'Estado desactualizado',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Trouver un hébergement',
'roadtrip.stay.portalHint':
'Vérifiez la destination, les dates et les voyageurs sur le portail. Recherche manuelle sur CHECK24.',
'roadtrip.charging.available': 'disponibles',
'roadtrip.charging.unknown': 'Aucune donnée fiable disponible',
'roadtrip.charging.stale': 'État périmé',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Βρείτε κατάλυμα',
'roadtrip.stay.portalHint':
'Ελέγξτε προορισμό, ημερομηνίες και επισκέπτες στην πύλη. Στο CHECK24 αναζητήστε χειροκίνητα.',
'roadtrip.charging.available': 'διαθέσιμα',
'roadtrip.charging.unknown': 'Δεν υπάρχουν αξιόπιστα δεδομένα',
'roadtrip.charging.stale': 'Παρωχημένη κατάσταση',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Szállás keresése',
'roadtrip.stay.portalHint':
'Ellenőrizd az úti célt, dátumokat és vendégeket a portálon. A CHECK24 oldalon keress kézzel.',
'roadtrip.charging.available': 'szabad',
'roadtrip.charging.unknown': 'Nincs megbízható adat',
'roadtrip.charging.stale': 'Elavult állapot',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Cari penginapan',
'roadtrip.stay.portalHint': 'Periksa tujuan, tanggal, dan tamu di portal. Cari secara manual di CHECK24.',
'roadtrip.charging.available': 'tersedia',
'roadtrip.charging.unknown': 'Tidak ada data terpercaya',
'roadtrip.charging.stale': 'Status kedaluwarsa',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Trova un alloggio',
'roadtrip.stay.portalHint': 'Verifica destinazione, date e ospiti sul portale. Su CHECK24 cerca manualmente.',
'roadtrip.charging.available': 'disponibili',
'roadtrip.charging.unknown': 'Nessun dato affidabile',
'roadtrip.charging.stale': 'Stato non aggiornato',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': '宿泊施設を探す',
'roadtrip.stay.portalHint':
'予約サイトで目的地、日付、宿泊人数を確認してください。CHECK24では手動で検索してください。',
'roadtrip.charging.available': '空き',
'roadtrip.charging.unknown': '信頼できるデータがありません',
'roadtrip.charging.stale': '古い状態情報',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': '숙소 찾기',
'roadtrip.stay.portalHint': '포털에서 목적지, 날짜, 인원을 확인하세요. CHECK24에서는 직접 검색하세요.',
'roadtrip.charging.available': '이용 가능',
'roadtrip.charging.unknown': '신뢰할 수 있는 데이터 없음',
'roadtrip.charging.stale': '오래된 상태',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Accommodatie zoeken',
'roadtrip.stay.portalHint': 'Controleer bestemming, datums en gasten op het portaal. Zoek handmatig op CHECK24.',
'roadtrip.charging.available': 'beschikbaar',
'roadtrip.charging.unknown': 'Geen betrouwbare gegevens',
'roadtrip.charging.stale': 'Status verouderd',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Znajdź nocleg',
'roadtrip.stay.portalHint': 'Sprawdź cel, daty i gości na portalu. W CHECK24 wyszukaj ręcznie.',
'roadtrip.charging.available': 'wolne',
'roadtrip.charging.unknown': 'Brak wiarygodnych danych',
'roadtrip.charging.stale': 'Nieaktualny status',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Найти жильё',
'roadtrip.stay.portalHint': 'Проверьте место, даты и гостей на портале. В CHECK24 ищите вручную.',
'roadtrip.charging.available': 'свободно',
'roadtrip.charging.unknown': 'Нет надёжных данных',
'roadtrip.charging.stale': 'Статус устарел',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Hitta boende',
'roadtrip.stay.portalHint': 'Kontrollera resmål, datum och gäster på portalen. Sök manuellt på CHECK24.',
'roadtrip.charging.available': 'lediga',
'roadtrip.charging.unknown': 'Inga tillförlitliga uppgifter',
'roadtrip.charging.stale': 'Inaktuell status',
+3
View File
@@ -1,6 +1,9 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Konaklama bul',
'roadtrip.stay.portalHint':
'Portalda varış yerini, tarihleri ve konukları kontrol edin. CHECK24 üzerinde elle arayın.',
'roadtrip.charging.available': 'boş',
'roadtrip.charging.unknown': 'Güvenilir veri yok',
'roadtrip.charging.stale': 'Durum güncel değil',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Знайти житло',
'roadtrip.stay.portalHint': 'Перевірте місце, дати та гостей на порталі. У CHECK24 шукайте вручну.',
'roadtrip.charging.available': 'вільні',
'roadtrip.charging.unknown': 'Немає надійних даних',
'roadtrip.charging.stale': 'Статус застарів',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': 'Tìm chỗ ở',
'roadtrip.stay.portalHint': 'Kiểm tra điểm đến, ngày và khách trên cổng đặt chỗ. Tìm thủ công trên CHECK24.',
'roadtrip.charging.available': 'còn trống',
'roadtrip.charging.unknown': 'Không có dữ liệu đáng tin cậy',
'roadtrip.charging.stale': 'Trạng thái đã cũ',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': '尋找住宿',
'roadtrip.stay.portalHint': '請在平台核對目的地、日期和入住人數。CHECK24需手動搜尋。',
'roadtrip.charging.available': '可用',
'roadtrip.charging.unknown': '暫無可靠資料',
'roadtrip.charging.stale': '狀態已過時',
+2
View File
@@ -1,6 +1,8 @@
import type { TranslationStrings } from '../types';
const roadtrip: TranslationStrings = {
'roadtrip.stay.portals': '查找住宿',
'roadtrip.stay.portalHint': '请在平台核对目的地、日期和入住人数。CHECK24需手动搜索。',
'roadtrip.charging.available': '可用',
'roadtrip.charging.unknown': '暂无可靠数据',
'roadtrip.charging.stale': '状态已过时',
+24 -13
View File
@@ -29,23 +29,26 @@ export const hexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}
* against — the escaping in the marker builders stops being the only thing
* standing between the database and the DOM.
*/
export const placeImageUrlSchema = z.string().max(2048).refine(
v =>
v.startsWith('/uploads/')
|| v.startsWith('/api/maps/place-photo/')
|| /^data:image\/(png|jpe?g|webp|gif|avif);base64,/i.test(v)
|| /^https:\/\//i.test(v),
{ message: 'must be an uploaded path, a photo-proxy path, an inline image or an https URL' },
);
export const placeImageUrlSchema = z
.string()
.max(2048)
.refine(
(v) =>
v.startsWith('/uploads/') ||
v.startsWith('/api/maps/place-photo/') ||
/^data:image\/(png|jpe?g|webp|gif|avif);base64,/i.test(v) ||
/^https:\/\//i.test(v),
{ message: 'must be an uploaded path, a photo-proxy path, an inline image or an https URL' },
);
/**
* A place's homepage. It reaches window.open() on the client, where a
* javascript: value would run in this origin rather than opening a page.
*/
export const placeWebsiteSchema = z.string().max(500).refine(
v => /^https?:\/\//i.test(v),
{ message: 'must be an http or https URL' },
);
export const placeWebsiteSchema = z
.string()
.max(500)
.refine((v) => /^https?:\/\//i.test(v), { message: 'must be an http or https URL' });
/**
* Embedded category as returned on a place — a trimmed projection of the
@@ -91,7 +94,15 @@ export type PlaceRatingVote = z.infer<typeof placeRatingVoteSchema>;
* to the column, where `isServiceStopType` then read it as false and the stop quietly
* counted as a destination.
*/
export const roadtripStopTypeSchema = z.enum(['fuel', 'charging', 'rest_area', 'campsite', 'restaurant', 'sights']);
export const roadtripStopTypeSchema = z.enum([
'fuel',
'charging',
'rest_area',
'campsite',
'restaurant',
'sights',
'hotel',
]);
export type RoadtripStopType = z.infer<typeof roadtripStopTypeSchema>;
/**
+61 -35
View File
@@ -17,6 +17,7 @@ import type {
} from './planning-types';
import {
computeSchedule,
parseClock,
deriveDriveWarnings,
refuelsRange,
isServiceStopType,
@@ -24,6 +25,7 @@ import {
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 ?? ''}`;
@@ -85,11 +87,15 @@ export function assembleRoadtrip({
...d,
spills: [],
schedule: computeSchedule(
d.stops.map((s) => ({ anchor: s.time, dwellMinutes: s.dwellMinutes })),
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),
),
}))
: chains;
: splitScheduledDays(chains, [...plan, ...quietDays], storedLegFor);
const legFor = automaticSchedule ? timed.legFor : storedLegFor;
const lines: [number, number][][] = [];
@@ -150,42 +156,62 @@ export function assembleRoadtrip({
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) => {
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) });
return { ...s, offRoadMeters: line ? snap!.meters : null };
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 inboundKm =
inbound
.filter((l) => l && (l.mode === undefined || l.mode === 'driving'))
.reduce((sum, l) => sum + (l?.distance ?? 0), 0) / 1000;
const startKm = carryKm === null ? null : carryKm + inboundKm;
const drive = deriveDriveWarnings(
legs,
stops.map((s) => refuelsRange(s.stopType, vehicleKind)),
limits,
startKm,
stops.map((s) => s.fillPercent),
);
carryKm = drive.carryKm;
const drivingLine = routed
.filter((l) => l && l.seg.mode !== undefined && l.seg.mode === 'driving')
.flatMap((l) => l?.line ?? []);
const dryPoints = drive.emptyAt
.map((dry) => {
const at = pointAtMeters(
drivingLine.map(([lat, lng]) => ({ lat, lng })),
dry.drivenMeters,
);
return at ? { ...dry, lat: at.lat, lng: at.lng } : null;
})
.filter((d): d is DryPoint & { lat: number; lng: number } => d !== null);
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 })));
for (const dry of incomingDrive.emptyAt) {
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 })));
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 });
}
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,
@@ -208,7 +234,7 @@ export function assembleRoadtrip({
dayWarning: drive.day,
});
}
const drives = out.filter((d) => d.stops.length > 1 || d.stops.some((s) => s.automaticNight));
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]!;
@@ -246,7 +272,7 @@ export function assembleRoadtrip({
),
quietDays: out
.filter((d) => d.stops.length < 2 && !d.stops.some((s) => s.automaticNight))
.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,
};
@@ -0,0 +1,31 @@
import { continueSchedule } from './continueSchedule';
import type { RoadtripStop } from './planning-types';
import type { Schedule } from './roadtripModel';
import { describe, expect, it } from 'vitest';
const stops = [0, 60, 60, 60].map((dwellMinutes) => ({ dwellMinutes }) as RoadtripStop);
const schedule = (): Schedule => ({
entries: [
{ arrival: '18:15', departure: '18:15', dayOffset: 0, anchored: false },
...[1, 2, 3].map(() => ({ arrival: null, departure: null, dayOffset: 0, anchored: false })),
],
warnings: [],
});
describe('continuing after a moved day group', () => {
it('carries Munich departure into the original day stops and over midnight', () => {
const original = schedule();
const completed = continueSchedule(stops, original, [237 * 60, 198 * 60, 206 * 60], 2);
expect(completed.entries.map((entry) => entry.arrival)).toEqual(['18:15', '22:12', '02:30', '06:56']);
expect(completed.entries[2]!.dayOffset).toBe(1);
expect(original.entries[1]!.arrival).toBeNull();
});
it('keeps manual times and stops at an unknown route duration', () => {
const original = schedule();
original.entries[2] = { arrival: '07:00', departure: '08:00', dayOffset: 1, anchored: true };
const completed = continueSchedule(stops, original, [undefined, 3600, 3600], 2);
expect(completed.entries[1]!.arrival).toBeNull();
expect(completed.entries[2]).toEqual(original.entries[2]);
expect(completed.entries[3]!.arrival).toBe('09:00');
});
});
+36
View File
@@ -0,0 +1,36 @@
import type { RoadtripStop } from './planning-types';
import { formatClock, parseClock, type Schedule } from './roadtripModel';
export function continueSchedule(
stops: RoadtripStop[],
schedule: Schedule,
legs: (number | undefined)[],
dayNumber: number,
): Schedule {
const entries = schedule.entries.map((entry) => ({ ...entry }));
const warnings = [...schedule.warnings];
for (let i = 1; i < stops.length; i++) {
const entry = entries[i]!;
if (entry.arrival !== null) continue;
const previous = entries[i - 1]!;
const departure = parseClock(previous.departure);
const duration = legs[i - 1];
if (departure === null || duration === undefined) continue;
const previousArrival = parseClock(previous.arrival);
const departureAt =
stops[i - 1]!.checkoutAt !== undefined
? stops[i - 1]!.checkoutAt! - dayNumber * 1440
: previous.dayOffset * 1440 + departure + (previousArrival !== null && departure < previousArrival ? 1440 : 0);
const arrivalAt = departureAt + Math.round(duration / 60);
const stop = stops[i]!;
const leaveAt =
stop.checkoutAt === undefined
? arrivalAt + (stop.dwellMinutes ?? 0)
: Math.max(arrivalAt, stop.checkoutAt - dayNumber * 1440);
entry.arrival = formatClock(arrivalAt);
entry.departure = formatClock(leaveAt);
entry.dayOffset = Math.floor(arrivalAt / 1440);
if (entry.dayOffset > previous.dayOffset) warnings.push({ index: i, code: 'overnight' });
}
return { entries, warnings };
}
+25
View File
@@ -365,3 +365,28 @@ describe('daily travel window', () => {
expect(planned.chains[1]!.schedule.entries[1]!.arrival).toBe('10:00');
});
});
describe('booked checkout', () => {
it('waits at the hotel until noon on the checkout day', () => {
const hotel = stop(2, { checkoutAt: 2 * 1440 + 720, dwellMinutes: 30 });
const stops = [stop(1), hotel, stop(3)];
const plan = calculate(stops, [60, 60]);
expect(plan.issue).toBeNull();
expect(plan.chains[0]!.schedule.entries[1]!.arrival).toBe('09:00');
expect(plan.chains[0]!.schedule.entries[1]!.departure).toBe('12:00');
expect(plan.chains[1]!.schedule.entries[0]!.arrival).toBe('12:00');
expect(plan.chains[1]!.schedule.entries[1]!.arrival).toBe('13:00');
});
it('honours an early checkout and multiple nights', () => {
const stops = [stop(1, { checkoutAt: 3 * 1440 + 420 }), stop(2)];
const plan = calculate(stops, [60], [day(2), day(3)]);
expect(plan.issue).toBeNull();
expect(plan.chains[2]!.schedule.entries[0]!.arrival).toBe('07:00');
expect(plan.chains[2]!.schedule.entries[1]!.arrival).toBe('08:00');
});
it('does not move time backwards when arrival is after checkout', () => {
const stops = [stop(1, { time: '13:00', checkoutAt: 1440 + 720 }), stop(2)];
const plan = calculate(stops, [60]);
expect(plan.chains[0]!.schedule.entries[1]!.arrival).toBe('14:00');
});
});
+21
View File
@@ -181,6 +181,7 @@ export function planDayWindow(
name: labels.end,
time: null,
dwellMinutes: 0,
checkoutAt: undefined,
stopType: null,
fillPercent: null,
automaticNight: { phase: 'end', fromDayNumber: number, position, manual: targets.has(number) },
@@ -275,6 +276,26 @@ export function planDayWindow(
append(stop, clock);
previous = stop;
if (stop.checkoutAt !== undefined) {
const checkoutDay = Math.floor(stop.checkoutAt / 1440);
const checkoutTime = stop.checkoutAt % 1440;
const arrivalAt = number * 1440 + clock;
if (stop.checkoutAt > arrivalAt) {
const entries = chainAt(number).schedule.entries;
entries[entries.length - 1]!.departure = formatClock(checkoutTime);
while (number < checkoutDay) {
previous = night(previous);
if (issue) return failed(issue);
}
clock = checkoutTime;
if (previous.automaticNight?.phase === 'start') {
const entries = chainAt(number).schedule.entries;
entries[entries.length - 1]!.arrival = formatClock(clock);
entries[entries.length - 1]!.departure = formatClock(clock);
}
}
continue;
}
let dwell = Math.max(0, stop.dwellMinutes ?? 0);
while (dwell > 0) {
const remaining = targets.has(number) ? dwell : Math.max(0, window.end - clock);
+6 -2
View File
@@ -73,7 +73,11 @@ export function spillChains(plan: PlanDay[], quietDays: QuietDay[], legFor: LegL
const routed = d.stops.slice(0, -1).map((s, i) => legFor(s, d.stops[i + 1]!));
const legs = routed.map((l) => l?.seg);
const schedule = computeSchedule(
d.stops.map((s) => ({ anchor: s.time, dwellMinutes: s.dwellMinutes })),
d.stops.map((s) => ({
anchor: s.time,
dwellMinutes: s.dwellMinutes,
departureAt: s.checkoutAt === undefined ? undefined : s.checkoutAt - d.dayNumber * 1440,
})),
legs.map((l) => l?.duration),
);
@@ -86,7 +90,7 @@ export function spillChains(plan: PlanDay[], quietDays: QuietDay[], legFor: LegL
if (previous !== null && clock < previous) day += 1;
previous = clock;
}
const offset = day;
const offset = d.stops.some((s) => s.checkoutAt !== undefined) ? (entry?.dayOffset ?? day) : day;
const marks = schedule.warnings.filter((w) => w.index === i);
const reachable = offset > 0 && numbers.has(d.dayNumber + offset);
+1
View File
@@ -18,6 +18,7 @@ export interface RoadtripStop {
time: string | null;
dwellMinutes: number | null;
checkoutAt?: number;
endDay?: boolean;
legMode: string | null;
+31
View File
@@ -791,3 +791,34 @@ describe('deriveDriveWarnings — filling only part way', () => {
expect(out.emptyAt).toEqual([]);
});
});
describe('checkout without daily travel times', () => {
it('keeps the car at the hotel until the next day', () => {
const schedule = computeSchedule(
[
{ anchor: '16:00', dwellMinutes: 30, departureAt: 1440 + 720 },
{ anchor: null, dwellMinutes: 0 },
],
[3600],
);
expect(schedule.entries[0]!.departure).toBe('12:00');
expect(schedule.entries[1]!.arrival).toBe('13:00');
expect(schedule.entries[1]!.dayOffset).toBe(1);
});
});
it('uses checkout as departure even without an arrival or daily start', () => {
const schedule = computeSchedule(
[
{ anchor: null, dwellMinutes: 60 },
{ anchor: null, dwellMinutes: 60, departureAt: 1440 + 480 },
{ anchor: null, dwellMinutes: 0 },
],
[3600, 7200],
);
expect(schedule.entries[0]!.arrival).toBeNull();
expect(schedule.entries[1]!.arrival).toBeNull();
expect(schedule.entries[1]!.departure).toBe('08:00');
expect(schedule.entries[2]!.arrival).toBe('10:00');
expect(schedule.entries[2]!.dayOffset).toBe(1);
});
+35 -5
View File
@@ -1,6 +1,14 @@
import type { RouteAvoidClass } from './planning-types';
export const SERVICE_STOP_TYPES = ['fuel', 'charging', 'rest_area', 'campsite', 'restaurant', 'sights'] as const;
export const SERVICE_STOP_TYPES = [
'fuel',
'charging',
'rest_area',
'campsite',
'restaurant',
'sights',
'hotel',
] as const;
export const SERVICE_COLORS: Record<string, string> = {
fuel: '#E8590C',
@@ -9,6 +17,7 @@ export const SERVICE_COLORS: Record<string, string> = {
campsite: '#16A34A',
restaurant: '#EF4444',
sights: '#EC4899',
hotel: '#2563EB',
};
export function serviceColor(stopType: string | null | undefined): string {
@@ -48,6 +57,7 @@ export function formatClock(minutes: number): string {
}
export interface ScheduleStop {
departureAt?: number;
anchor: string | null;
dwellMinutes: number | null;
@@ -143,7 +153,11 @@ export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | und
const { arrival, lateBy } = resolveArrival(anchor, cursor, dayOffset);
if (lateBy !== null) warnings.push({ index: i, code: 'late', minutes: lateBy });
if (arrival === null) continue;
if (arrival === null) {
const leg = legSeconds[i];
if (stop.departureAt !== undefined && leg !== undefined) cursor = stop.departureAt + Math.round(leg / 60);
continue;
}
const offset = Math.floor(arrival / DAY_MINUTES);
if (offset > dayOffset) dayOffset = offset;
@@ -152,11 +166,16 @@ export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | und
anchored[i]! = anchor !== null;
const leg = legSeconds[i];
cursor = leg === undefined ? null : arrival + (stop.dwellMinutes ?? 0) + Math.round(leg / 60);
cursor =
leg === undefined
? null
: (stop.departureAt === undefined ? arrival + (stop.dwellMinutes ?? 0) : Math.max(arrival, stop.departureAt)) +
Math.round(leg / 60);
}
const firstKnown = arrivals.findIndex((a) => a !== null);
for (let i = firstKnown - 1; i >= 0; i--) {
if (stops[i]!.departureAt !== undefined) break;
const leg = legSeconds[i];
const next = arrivals[i + 1]!;
if (leg === undefined || next === null) break;
@@ -171,7 +190,12 @@ export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | und
for (let i = 0; i < stops.length; i++) {
const raw = arrivals[i]!;
if (raw === null) {
entries.push({ arrival: null, departure: null, anchored: false, dayOffset: 0 });
entries.push({
arrival: null,
departure: stops[i]!.departureAt === undefined ? null : formatClock(stops[i]!.departureAt!),
anchored: false,
dayOffset: 0,
});
continue;
}
const arrival = raw + shift;
@@ -181,7 +205,11 @@ export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | und
lastOffset = offset;
entries.push({
arrival: formatClock(arrival),
departure: formatClock(arrival + (stops[i]!.dwellMinutes ?? 0)),
departure: formatClock(
stops[i]!.departureAt === undefined
? arrival + (stops[i]!.dwellMinutes ?? 0)
: Math.max(arrival, stops[i]!.departureAt! + shift),
),
anchored: anchored[i]!,
dayOffset: offset,
});
@@ -217,6 +245,8 @@ export function sumLegSeconds(legSeconds: (number | undefined)[]): number {
}
export interface DryPoint {
inboundLine?: [number, number][];
legIndex: number;
intoLegKm: number;
@@ -0,0 +1,57 @@
import type { SpillChain } from './nightSpill';
import type { RoadtripStop, RoutedLeg } from './planning-types';
import { splitScheduledDays } from './splitScheduledDays';
import { describe, expect, it } from 'vitest';
const chain = (): SpillChain => ({
dayId: 2,
dayNumber: 2,
date: '2026-09-12',
title: null,
stops: [0, 1, 2].map((i) => ({ placeId: i + 1, dwellMinutes: 60, time: null }) as RoadtripStop),
schedule: {
entries: [
{ arrival: '22:12', departure: '23:12', anchored: false, dayOffset: 0 },
...[1, 2].map(() => ({ arrival: null, departure: null, anchored: false, dayOffset: 0 })),
],
warnings: [],
},
spills: [],
});
const lookup = (): RoutedLeg =>
({
seg: { duration: 198 * 60 },
line: [
[0, 0],
[1, 1],
],
vias: [],
}) as RoutedLeg;
describe('scheduled day overflow', () => {
it('creates a display day for the stops after midnight', () => {
const source = chain();
const days = splitScheduledDays([source], [source], lookup);
expect(days.map((day) => day.dayNumber)).toEqual([2, 3]);
expect(days[1]!.dayId).toBe(-1000000003);
expect(days[1]!.date).toBe('2026-09-13');
expect(days[1]!.schedule.entries.map((entry) => entry.arrival)).toEqual(['02:30', '06:48']);
expect(days[1]!.schedule.entries.every((entry) => entry.dayOffset === 0)).toBe(true);
expect(days[1]!.spills[0]).toMatchObject({ fromDayNumber: 2, at: 0, count: 2, departure: '23:12' });
expect(source.stops).toHaveLength(3);
});
it('uses an existing empty day and keeps an earlier spill group', () => {
const source = chain();
source.spills = [
{ at: 0, count: 1, fromDayNumber: 1, departure: '18:00', leg: undefined, line: [], fromStop: undefined },
];
const days = splitScheduledDays(
[source],
[source, { dayId: 99, dayNumber: 3, date: '2026-09-13', title: 'Rome', stops: [] }],
lookup,
);
expect(days[1]!.dayId).toBe(99);
expect(days[0]!.spills[0]!.fromDayNumber).toBe(1);
expect(days[1]!.spills[0]!.fromDayNumber).toBe(2);
});
});
+75
View File
@@ -0,0 +1,75 @@
import { continueSchedule } from './continueSchedule';
import type { SpillChain, SpillMark } from './nightSpill';
import type { PlanDay, RoadtripStop, RoutedLeg } from './planning-types';
export function splitScheduledDays(
chains: SpillChain[],
days: PlanDay[],
legFor: (from: RoadtripStop, to: RoadtripStop) => RoutedLeg | undefined,
): SpillChain[] {
const grouped = new Map<number, SpillChain>();
for (const chain of chains) {
const schedule = continueSchedule(
chain.stops,
chain.schedule,
chain.stops.slice(0, -1).map((stop, i) => legFor(stop, chain.stops[i + 1]!)?.seg.duration),
chain.dayNumber,
);
chain.stops.forEach((stop, i) => {
const entry = schedule.entries[i]!;
const offset = Math.max(0, entry.dayOffset);
const number = chain.dayNumber + offset;
let target = grouped.get(number);
if (!target) {
const stored = days.find((day) => day.dayNumber === number);
let date = stored?.date ?? null;
if (!date && chain.date) {
const shifted = new Date(chain.date + 'T12:00:00Z');
shifted.setUTCDate(shifted.getUTCDate() + offset);
date = shifted.toISOString().slice(0, 10);
}
target = {
dayId: stored?.dayId ?? -1000000000 - number,
dayNumber: number,
date,
title: stored?.title ?? null,
stops: [],
schedule: { entries: [], warnings: [] },
spills: [],
};
grouped.set(number, target);
}
const index = target.stops.length;
target.stops.push(stop);
target.schedule.entries.push({ ...entry, dayOffset: 0 });
target.schedule.warnings.push(
...schedule.warnings
.filter((warning) => warning.index === i && !(offset && warning.code === 'overnight'))
.map((warning) => ({ ...warning, index })),
);
const inherited = chain.spills.find((spill) => i >= spill.at && i < spill.at + spill.count);
const fromDayNumber = offset ? chain.dayNumber : inherited?.fromDayNumber;
if (fromDayNumber !== undefined) {
const last = target.spills[target.spills.length - 1];
if (last && last.fromDayNumber === fromDayNumber && last.at + last.count === index) last.count += 1;
else {
const from = i > 0 ? chain.stops[i - 1] : inherited?.fromStop;
const leg = from ? legFor(from, stop) : undefined;
const mark: SpillMark = offset
? {
at: index,
count: 1,
fromDayNumber,
departure: schedule.entries[i - 1]?.departure ?? inherited?.departure ?? null,
fromStop: from,
leg: leg?.seg,
line: leg?.line ?? [],
}
: { ...inherited!, at: index, count: 1 };
target.spills.push(mark);
}
}
});
}
return [...grouped.values()].sort((a, b) => a.dayNumber - b.dayNumber);
}