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.

fix(roadtrip): the stop a booking put on its check-in day keeps the night over a rest later that day

Maurice92af437ff6c9
diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.test.ts b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
index 8896a47de..99121f09c 100644
--- a/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
+++ b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
@@ -1433,6 +1433,35 @@ describe('a booked night at both ends of its days', () => {
expect(result.current.days.map(d => d.dayId)).toEqual([1])
})
+ it('FE-ROADTRIP-ROUTES-066: the stop the booking put first keeps the night over a rest later in the day (#2636)', async () => {
+ switchTo(false)
+ const days = [day(1, 1), day(2, 2)]
+ // A day without hours: the booking seats its stop first, Days does not show it, and the
+ // rest the traveller put mid-day is the last visit of the hotel.
+ const assignments = map(1, [
+ { id: 1, at: HOTEL },
+ { id: 2, at: P[0], dwell: 30 },
+ { id: 3, at: HOTEL, dwell: 60 },
+ { id: 4, at: P[1], dwell: 30 },
+ ]) as AssignmentsMap
+ Object.assign(assignments['1'][0], { place_id: 20, accommodation_id: 5 })
+ Object.assign(assignments['1'][2], { place_id: 20 })
+ const stays = [stayOf(5, 2, 1, 2, HOTEL, { check_in: '15:00' })]
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, assignments, 'driving', {}, [], stays))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ const [card] = result.current.days
+ expect(card.stops.map(s => [s.name, s.night, s.checkInTime])).toEqual([
+ ['Stop 1', true, '15:00'],
+ ['Stop 2', false, null],
+ ['Stop 3', false, null],
+ ['Stop 4', false, null],
+ ])
+ expect(card.schedule.entries.map(e => e.anchored ?? false)).toEqual([true, false, false, false])
+ expect(card.schedule.warnings).toEqual([])
+ expect(result.current.days.map(d => d.dayId)).toEqual([1])
+ })
+
it('FE-ROADTRIP-ROUTES-064: the stop tonight’s booking put first on its day gives way to the evening at the stay (#2546)', async () => {
const { days } = cam()
const stays = [stayOf(1, 1, 1, 2, GETAWAY), stayOf(2, 4, 2, 3, WALLINGA)]
diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.ts b/client/src/components/Roadtrip/useRoadtripRoutes.ts
index a4c0ffd41..bcc43bce8 100644
--- a/client/src/components/Roadtrip/useRoadtripRoutes.ts
+++ b/client/src/components/Roadtrip/useRoadtripRoutes.ts
@@ -321,7 +321,7 @@ export function useRoadtripRoutes(
// The index is filled in after the drop, because it is the index into THIS
// list: an assignment whose place has no coordinates never becomes a stop, and
// counting before the filter would name a row the rail does not draw. A hotel
- // visited twice on its check-in day is the night at its last visit only.
+ // visited twice on its check-in day is the night at one visit only.
const stops = oneNightPerStay(located.map((x, i) => ({ ...x.stop, ownerIndex: i })))
return {
dayId: d.id,
diff --git a/client/src/pages/tripPlanner/usePlaceFormOpeners.test.ts b/client/src/pages/tripPlanner/usePlaceFormOpeners.test.ts
index d306cbf89..a5c494547 100644
--- a/client/src/pages/tripPlanner/usePlaceFormOpeners.test.ts
+++ b/client/src/pages/tripPlanner/usePlaceFormOpeners.test.ts
@@ -378,6 +378,27 @@ describe('usePlaceFormOpeners', () => {
expect(result.current.stopDraft).toMatchObject({ dayId: 14, position: 2, editing: { accommodationId: 70, checkIn: '15:00' }, overnight: { defaultEndDayId: 12 } })
})
+ it("FE-TP-OPENERS-014c: the booking's stop stays the night over a rest the traveller put after it (#2636)", () => {
+ const tripAccommodations = [stay({ id: 70, place_id: 3, start_day_id: 14, end_day_id: 12, check_in: '15:00', check_out: '10:00' })]
+ const twice: AssignmentsMap = {
+ ...assignments,
+ 14: [
+ buildAssignment({ id: 140, place: hotel, order_index: 0, accommodation_id: 70 }),
+ buildAssignment({ id: 141, place: lake, order_index: 1 }),
+ buildAssignment({ id: 142, place: hotel, order_index: 2 }),
+ buildAssignment({ id: 143, place: pump, order_index: 3 }),
+ ],
+ }
+ const { result } = renderOpeners({ roadtripActive: true, tripAccommodations, assignments: twice })
+
+ act(() => { result.current.openPlaceEditor(hotel, 142) })
+ expect(result.current.stopDraft).toMatchObject({ dayId: 14, position: 2, editing: { accommodationId: undefined, checkIn: '' } })
+ expect(result.current.stopDraft?.overnight).toBeUndefined()
+
+ act(() => { result.current.openPlaceEditor(hotel, 140) })
+ expect(result.current.stopDraft).toMatchObject({ dayId: 14, position: 0, editing: { accommodationId: 70, checkIn: '15:00' } })
+ })
+
it('FE-TP-OPENERS-015: an ordinary place opens the form on its one visit, a tour on the phone selects it instead', () => {
const { result } = renderOpeners()
diff --git a/client/src/pages/tripPlanner/usePlaceFormOpeners.ts b/client/src/pages/tripPlanner/usePlaceFormOpeners.ts
index 991b17f4a..6cc58849f 100644
--- a/client/src/pages/tripPlanner/usePlaceFormOpeners.ts
+++ b/client/src/pages/tripPlanner/usePlaceFormOpeners.ts
@@ -10,6 +10,7 @@ import type { CorridorPoi } from '../../components/Roadtrip/useCorridorPois'
import type { usePlaceLanguage } from '../../hooks/usePlaceLanguage'
import type { TripStoreState } from '../../store/tripStore'
import type { Accommodation, Place } from '../../types'
+import { nightRowsOf } from '../../utils/dayMerge'
import { getDayOrder } from '../../utils/dayOrder'
import type { PlannerBase } from './plannerTypes'
import { resolvePoolAssignmentId } from './tripPlannerModel'
@@ -295,9 +296,9 @@ export function usePlaceFormOpeners(options: PlaceFormOpenersOptions) {
if (entry) {
const dayId = Number(entry[0])
const visit = entry[1].find(visit => visit.id === visitId)!
- // The night is the hotel's last visit of the day; an earlier one opens as a stop.
- const lastVisit = entry[1].filter(other => other.place_id === place.id).every(other => (other.order_index ?? 0) <= (visit.order_index ?? 0))
- const stay = lastVisit ? tripAccommodations.find(stay => stay.place_id === place.id && stay.start_day_id === dayId) : undefined
+ // One visit of the hotel is the night; another one that day opens as a stop.
+ const night = nightRowsOf(entry[1].map(other => ({ ...other, order_index: other.order_index ?? 0 })), tripAccommodations, dayId).has(visit.order_index ?? 0)
+ const stay = night ? tripAccommodations.find(stay => stay.place_id === place.id && stay.start_day_id === dayId) : undefined
const category = place.stop_type ?? (stay ? 'hotel' : '')
const routedDay = roadtripRoutes.days.find(day => day.stops.some(stop => stop.assignmentId === visitId))
const arrivalTime = routedDay?.schedule.entries[routedDay.stops.findIndex(stop => stop.assignmentId === visitId)]?.arrival ?? null
diff --git a/client/src/utils/dayMerge.test.ts b/client/src/utils/dayMerge.test.ts
index 131a10320..e832594a6 100644
--- a/client/src/utils/dayMerge.test.ts
+++ b/client/src/utils/dayMerge.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, getPlaceBookings, getMergedItems, rideSeatKey, seatTimedDrop, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge'
+import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, getPlaceBookings, getMergedItems, nightRowsOf, rideSeatKey, seatTimedDrop, stayStartingOn, storedRideSlot, timedSlot, type MergedItem } from './dayMerge'
import { planMergedOrder, withTransportPositions } from './mergedOrder'
describe('parseTimeToMinutes', () => {
@@ -423,6 +423,18 @@ describe('storedRideSlot', () => {
expect(storedRideSlot(ferry(), [amsterdam, hotel, night], checkIn, 5)).toBe(0.5)
})
+ it("reads the booking's stop as the night over a rest after it, and a visit that ends the day over both (#2636)", () => {
+ const stays = [{ place_id: 30, start_day_id: 5, check_in: '18:00' }]
+ // The booking seats its stop first on a day without hours, and Days does not show it.
+ const booked = { ...hotel, order_index: 0, accommodation_id: 7 }
+ const rest = { ...hotel, id: 4, order_index: 2 }
+ const after = row(5, 3, 54.9783, -1.6178)
+ expect([...nightRowsOf([booked, { ...amsterdam, order_index: 1 }, rest, after], stays, 5)]).toEqual([0])
+ expect([...nightRowsOf([booked, { ...amsterdam, order_index: 1 }, rest], stays, 5)]).toEqual([2])
+ // Without a stay starting there that day nothing is a night.
+ expect([...nightRowsOf([booked, rest], stays, 6)]).toEqual([])
+ })
+
it('opens the day, closes it, or sits behind a timed row, measured on order indexes', () => {
expect(storedRideSlot(ferry(), [row(2, 3, 54.9783, -1.6178)], [], 5)).toBe(2.5)
expect(storedRideSlot(ferry(), [amsterdam], [], 5)).toBe(0.5)
diff --git a/client/src/utils/dayMerge.ts b/client/src/utils/dayMerge.ts
index bb0462fdf..25e4dce3d 100644
--- a/client/src/utils/dayMerge.ts
+++ b/client/src/utils/dayMerge.ts
@@ -1,5 +1,5 @@
import { chronoOrder } from '@trek/shared'
-import { rideSeatAfter, sameDayRide, type CarrierBooking, type SeatItem } from '@trek/shared/roadtrip'
+import { nightVisits, rideSeatAfter, sameDayRide, type CarrierBooking, type SeatItem } from '@trek/shared/roadtrip'
// `orderedEndpoints` is the geometry order's single source of truth, in the module
// that documents the multi-leg model. Sorting endpoints a second time here is how
// the two drift.
@@ -398,9 +398,33 @@ export function stayStartingOn<T extends StayStart>(stays: readonly T[], placeId
interface StoredStop {
order_index: number
place_id?: number | null
+ accommodation_id?: number | null
place?: { lat?: number | null; lng?: number | null; place_time?: string | null } | null
}
+/** Where the row stands, or null for a row without coordinates, which is no stop of the drive. */
+function pointOf(row: StoredStop): { lat: number; lng: number } | null {
+ const lat = row.place?.lat
+ const lng = row.place?.lng
+ return typeof lat === 'number' && typeof lng === 'number' && Number.isFinite(lat) && Number.isFinite(lng) ? { lat, lng } : null
+}
+
+/**
+ * The order indexes of the day's rows the road trip reads as a night, timed by the check-in
+ * of the stay that begins there (`stayStartingOn`): one per hotel, picked the way
+ * `oneNightPerStay` picks it over the rows the drive stops at (#2636). Another visit of
+ * the same hotel that day is a stop like any other.
+ */
+export function nightRowsOf(day: readonly StoredStop[], stays: readonly StayStart[], dayId: number): Set<number> {
+ const rows = day.filter(row => pointOf(row) !== null).sort((a, b) => a.order_index - b.order_index)
+ const nights = nightVisits(rows.map(row => ({
+ placeId: row.place_id ?? 0,
+ night: row.place_id != null && stayStartingOn(stays, row.place_id, dayId) !== undefined,
+ bookedNightId: row.accommodation_id ?? null,
+ })))
+ return new Set(rows.filter((_, i) => nights.has(i)).map(row => row.order_index))
+}
+
/**
* The slot to store for a ride that lands on the day it left (`sameDayRide`) and has none
* yet: worked out over the day's rows the way the road trip seats its terminals among
@@ -412,11 +436,10 @@ interface StoredStop {
* number among their order indexes all the same, and worked out over the rows the list
* shows it could land behind a hidden stop on the far shore, which the drive then went to
* overland before the crossing (#2461). Each row counts with its start, else the check-in
- * of the stay that begins there that day (`stayStartingOn`) on the place's last row of the
- * day, and with its coordinates; a row without them is no stop of the drive. Where the
- * rule keeps the clock's seat, the
- * clock is read over the same rows: behind the last one timed at or before the departure,
- * else at the end of the day.
+ * of the stay that begins there that day on the row that is its night (`nightRowsOf`), and
+ * with its coordinates; a row without them is no stop of the drive. Where the rule keeps
+ * the clock's seat, the clock is read over the same rows: behind the last one timed at or
+ * before the departure, else at the end of the day.
*/
export function storedRideSlot(
r: CarrierBooking,
@@ -426,17 +449,12 @@ export function storedRideSlot(
): number | null {
const ride = sameDayRide(r)
if (!ride || !day.length) return null
- // The night is the last visit of its hotel on the day (`oneNightPerStay`), so only that
- // row is timed by the check-in; an earlier visit of the same place is a stop like any other.
- const lastOfPlace = new Map<number | null | undefined, number>()
- for (const row of day) lastOfPlace.set(row.place_id, Math.max(lastOfPlace.get(row.place_id) ?? -Infinity, row.order_index))
+ const nights = nightRowsOf(day, stays, dayId)
const items: SeatItem[] = day.flatMap(row => {
- const lat = row.place?.lat
- const lng = row.place?.lng
- if (typeof lat !== 'number' || typeof lng !== 'number' || !Number.isFinite(lat) || !Number.isFinite(lng)) return []
- const night = lastOfPlace.get(row.place_id) === row.order_index
- const start = row.place?.place_time ?? (night ? stayStartingOn(stays, row.place_id, dayId)?.check_in : null)
- return [{ key: row.order_index, minutes: parseTimeToMinutes(start), point: { lat, lng } }]
+ const point = pointOf(row)
+ if (!point) return []
+ const start = row.place?.place_time ?? (nights.has(row.order_index) ? stayStartingOn(stays, row.place_id, dayId)?.check_in : null)
+ return [{ key: row.order_index, minutes: parseTimeToMinutes(start), point }]
})
const keys = day.map(row => row.order_index)
const seat = rideSeatAfter(items, ride)
diff --git a/server/src/nest/roadtrip/roadtrip-plan.service.ts b/server/src/nest/roadtrip/roadtrip-plan.service.ts
index d56c6b57b..23728ab3a 100644
--- a/server/src/nest/roadtrip/roadtrip-plan.service.ts
+++ b/server/src/nest/roadtrip/roadtrip-plan.service.ts
@@ -148,7 +148,7 @@ export class RoadtripPlanService {
const dayNumberOf = (dayId: number): number => context.days.find((d) => d.id === dayId)?.day_number ?? 0;
const stored: PlanDay[] = context.days.map((day) => {
const visits = context.visits.filter((v) => v.day_id === day.id && v.lat !== null && v.lng !== null);
- // One night per hotel, the last visit of it, the way the browser reads the day.
+ // One night per hotel (oneNightPerStay), the way the browser reads the day.
const stops = oneNightPerStay(
visits.map((v, index): RoadtripStop => ({
assignmentId: v.id,
diff --git a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts b/server/src/nest/roadtrip/roadtrip-planning.mcp.ts
index 2efc9a140..e4d71edef 100644
--- a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts
+++ b/server/src/nest/roadtrip/roadtrip-planning.mcp.ts
@@ -48,7 +48,7 @@ export class RoadtripPlanningMcp {
@Tool({
name: 'calculate_roadtrip',
description:
- 'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts that desk on the road as a stop carrying `carrier` with role pickup, and its return desk with role return when the booking names a return day and place; the road runs through both. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) only at its last visit; the earlier visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.',
+ 'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts that desk on the road as a stop carrying `carrier` with role pickup, and its return desk with role return when the booking names a return day and place; the road runs through both. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) at one visit only: the visit that ends the day, else the stop the booking put on the day, else the last visit; the other visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.',
inputSchema: roadtripPlanRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'trips', mode: 'read' },
diff --git a/server/tests/unit/nest/roadtrip-plan.service.test.ts b/server/tests/unit/nest/roadtrip-plan.service.test.ts
index 0e075e362..2f298436e 100644
--- a/server/tests/unit/nest/roadtrip-plan.service.test.ts
+++ b/server/tests/unit/nest/roadtrip-plan.service.test.ts
@@ -276,6 +276,39 @@ describe('a booked night on the road trip (#2410)', () => {
expect(day.schedule.warnings).toEqual([]);
});
+ it('keeps the night on the stop the booking put first over a rest later in the day (#2636)', async () => {
+ const { user, trip, plans } = await setup();
+ const arrival = createDay(db, trip.id);
+ const hotel = createPlace(db, trip.id, { name: 'Rostock', lat: 54.09, lng: 12.1 });
+ const beach = createPlace(db, trip.id, { name: 'Warnemuende', lat: 54.17, lng: 12.08 });
+ const port = createPlace(db, trip.id, { name: 'Wismar', lat: 53.9, lng: 11.46 });
+ await setPlace(hotel.id, { duration_minutes: 30 });
+ await setPlace(beach.id, { duration_minutes: 30 });
+ await setPlace(port.id, { duration_minutes: 30 });
+ // A day without hours: the booking seats its stop first, Days does not show it, and the
+ // rest the traveller put mid-day is the last visit of the hotel.
+ const booked = createDayAssignment(db, arrival.id, hotel.id);
+ createDayAssignment(db, arrival.id, beach.id);
+ createDayAssignment(db, arrival.id, hotel.id);
+ createDayAssignment(db, arrival.id, port.id);
+ const departure = createDay(db, trip.id);
+ const stay = createDayAccommodation(db, trip.id, hotel.id, arrival.id, departure.id, { check_in: '15:00' });
+ await setVisit(booked.id, { accommodation_id: stay.id });
+
+ const { calculated } = await plans.calculate(trip.id, user.id);
+
+ const [day] = calculated.days.filter((d) => d.dayId === arrival.id);
+ expect(day.stops.map((s) => [s.name, s.night, s.checkInTime])).toEqual([
+ ['Rostock', true, '15:00'],
+ ['Warnemuende', false, null],
+ ['Rostock', false, null],
+ ['Wismar', false, null],
+ ]);
+ expect(day.schedule.entries.map((e) => e.anchored ?? false)).toEqual([true, false, false, false]);
+ expect(day.schedule.warnings).toEqual([]);
+ expect(calculated.days.filter((d) => d.stops.some((s) => s.ownerDayId === arrival.id))).toHaveLength(1);
+ });
+
it('files a lone stop that is no night under the quiet days', async () => {
const { user, trip, plans } = await setup();
const quiet = createDay(db, trip.id);
diff --git a/shared/src/roadtrip/assemble.spec.ts b/shared/src/roadtrip/assemble.spec.ts
index 959ede18a..112301969 100644
--- a/shared/src/roadtrip/assemble.spec.ts
+++ b/shared/src/roadtrip/assemble.spec.ts
@@ -1,5 +1,5 @@
/**
- * ROADTRIP-ASSEMBLE-001..023: what the assembler does with the model's warnings, and
+ * ROADTRIP-ASSEMBLE-001..024: what the assembler does with the model's warnings, and
* what it tells a surface about the drive between connected days. From 017 on: a booked
* night seated at both ends of its days (`seatNightBookends`) is one spot overnight,
* driven to and from like any stop and never between.
@@ -416,6 +416,35 @@ describe('assembleRoadtrip a hotel visited twice on its check-in day (#2636)', (
expect(day.schedule.entries[3]!.anchored).toBe(true);
expect(day.schedule.warnings).toEqual([]);
});
+
+ it('ROADTRIP-ASSEMBLE-024: the booking leads a day without hours, and a rest later on is a stop', () => {
+ // The booking seats its stop first on a day nobody put an hour on, and Days does not
+ // show it. The rest the traveller put mid-day is then the hotel's last visit, and read
+ // as the night it was held to the check-in a second time.
+ const day = (rest: Partial<RoadtripStop>) =>
+ oneNightPerStay([
+ stop({ ownerIndex: 0, ...hotel, checkInTime: '15:00', bookedNightId: 7 }),
+ stop({ ownerIndex: 1, dwellMinutes: 30 }),
+ stop({ ownerIndex: 2, ...rest, dwellMinutes: 60 }),
+ stop({ ownerIndex: 3, dwellMinutes: 30 }),
+ ]);
+
+ const routes = assemble(day({ ...hotel, checkInTime: '15:00' }), [hour, hour, hour]);
+
+ expect(routes.days).toHaveLength(1);
+ const [only] = routes.days;
+ expect(only!.stops.map((s) => [s.ownerIndex, s.night, s.checkInTime])).toEqual([
+ [0, true, '15:00'],
+ [1, undefined, undefined],
+ [2, false, null],
+ [3, undefined, undefined],
+ ]);
+ // The day runs as it did before the rest was put on it.
+ const without = assemble(day({ placeId: 900, lat: 45, lng: 7 }), [hour, hour, hour]);
+ expect(only!.schedule.entries).toEqual(without.days[0]!.schedule.entries);
+ expect(only!.schedule.entries.map((e) => e.arrival)).toEqual(['15:00', '16:00', '17:30', '19:30']);
+ expect(only!.schedule.warnings).toEqual([]);
+ });
});
describe('assembleRoadtrip nights at a booked hotel', () => {
diff --git a/shared/src/roadtrip/nightBookends.spec.ts b/shared/src/roadtrip/nightBookends.spec.ts
index 4a4c8eb9a..908811707 100644
--- a/shared/src/roadtrip/nightBookends.spec.ts
+++ b/shared/src/roadtrip/nightBookends.spec.ts
@@ -9,7 +9,7 @@
* ride the road does not see, a terminal out of a drive's reach, and the flight day of
* the report read from the stored day to its nights. From 033 on: the stop a booking put
* on its check-in day gives way to the evening at that stay. From 036 on: a hotel visited
- * twice on its check-in day is the night at its last visit only (#2636).
+ * twice on its check-in day is the night at one visit only (#2636).
*/
import { assembleRoadtrip } from './assemble';
import { carrierLegsFor, carrierSeam, seatCarrierStops, terminalAssignmentId, type CarrierBooking } from './carriers';
@@ -839,6 +839,26 @@ describe('a hotel visited twice on its check-in day (#2636)', () => {
for (const stops of [[place, night], [night, other], [place]]) expect(oneNightPerStay(stops)).toBe(stops);
});
+ it('ROADTRIP-BOOKENDS-038: the booking keeps the night over a later rest, and a visit that ends the day takes it', () => {
+ const booked = stayStop(D2, 0, WALLINGA, { name: 'Booked', placeId: 502, checkInTime: '15:00', bookedNightId: 2 });
+ const rest = stayStop(D2, 2, WALLINGA, { name: 'Rest', placeId: 502, checkInTime: '15:00' });
+ const place = visit(D2, 1, { name: 'P' });
+ const after = visit(D2, 3, { name: 'Q' });
+ // The booking's stop first, the traveller's rest mid-day: the rest is a stop.
+ expect(nights(planDay(D2, oneNightPerStay([booked, place, rest, after])))).toEqual([
+ ['Booked', true, '15:00'],
+ ['P', false, null],
+ ['Rest', false, null],
+ ['Q', false, null],
+ ]);
+ // The traveller's own visit ends the day: that is the night, the booking's stop a stop.
+ expect(nights(planDay(D2, oneNightPerStay([booked, place, rest])))).toEqual([
+ ['Booked', false, null],
+ ['P', false, null],
+ ['Rest', true, '15:00'],
+ ]);
+ });
+
it('ROADTRIP-BOOKENDS-037: with the days at the stay, the rest stays a stop and the booked night ends the day', () => {
const stops = oneNightPerStay([
stayStop(D2, 0, WALLINGA, { name: 'Rest', placeId: 502, checkInTime: '15:00' }),
diff --git a/shared/src/roadtrip/nightBookends.ts b/shared/src/roadtrip/nightBookends.ts
index f5ee13b53..5715751b1 100644
--- a/shared/src/roadtrip/nightBookends.ts
+++ b/shared/src/roadtrip/nightBookends.ts
@@ -113,30 +113,52 @@ export function bookendStaysOf<S extends Omit<BookendStay, 'reservation_id'>>(
}
/**
- * The stored day's stops with one night per hotel: the last visit of a place a stay begins
- * at on this day (#2636).
+ * The stored day's stops with one night per hotel (#2636).
*
* A stop is a night when a stay begins at its place on its day, and a hotel can be on its
* check-in day twice: the stop the booking put there and the traveller's own visit, back
* for a rest at noon. Both were read as the night and both held to the check-in, so the
* rest waited for the room or was set back to it, and a check-in twelve hours off its
- * arrival moved it and every stop behind it onto the next day's card. The night ends the
- * day, so the last visit is the night; the ones before it are stops like any other, a
- * hotel all the same, without the check-in.
+ * arrival moved it and every stop behind it onto the next day's card.
+ *
+ * One of the visits keeps the night and its check-in, the others are stops like any
+ * other, a hotel all the same. A visit that ends the day is the night. Else the booking's
+ * stop is: it is seated by its check-in (night-seat.ts), first on a day without hours,
+ * and Days does not show it, so a rest the traveller put after it is the last visit they
+ * see and still not the night. Else the last visit is.
*
* Read over the stops in their stored order, before a terminal or a bookend is seated
* among them, the same in the browser and on the server. A day with one visit per hotel
* comes back as it was.
*/
export function oneNightPerStay(stops: RoadtripStop[]): RoadtripStop[] {
- const last = new Map<number, number>();
- stops.forEach((stop, i) => {
- if (stop.night) last.set(stop.placeId, i);
+ const nights = nightVisits(stops);
+ if (nights.size === stops.filter((stop) => stop.night).length) return stops;
+ return stops.map((stop, i) => (stop.night && !nights.has(i) ? { ...stop, night: false, checkInTime: null } : stop));
+}
+
+/**
+ * The indexes of the visits `oneNightPerStay` keeps as the night, one per place, over a
+ * day's visits in their stored order. A row is a candidate when a stay begins at its
+ * place that day (`night`); `bookedNightId` marks the stop the booking put there. For a
+ * caller that reads the stored rows rather than the stops (the ride slot, the editor).
+ */
+export function nightVisits(visits: readonly Pick<RoadtripStop, 'placeId' | 'night' | 'bookedNightId'>[]): Set<number> {
+ const byPlace = new Map<number, number[]>();
+ visits.forEach((visit, i) => {
+ if (visit.night) byPlace.set(visit.placeId, [...(byPlace.get(visit.placeId) ?? []), i]);
});
- if (last.size === stops.filter((stop) => stop.night).length) return stops;
- return stops.map((stop, i) =>
- stop.night && last.get(stop.placeId) !== i ? { ...stop, night: false, checkInTime: null } : stop,
- );
+ const nights = new Set<number>();
+ for (const at of byPlace.values()) {
+ let last = -1;
+ let booked = -1;
+ for (const i of at) {
+ last = i;
+ if (visits[i]?.bookedNightId != null) booked = i;
+ }
+ nights.add(last === visits.length - 1 || booked < 0 ? last : booked);
+ }
+ return nights;
}
/**