feat(tours): add non-motorized day tour planning

This commit is contained in:
elmocito
2026-10-04 12:59:55 +02:00
parent c93cf2bce9
commit 9e475f447a
202 changed files with 16129 additions and 383 deletions
@@ -2857,6 +2857,76 @@ describe('DayPlanSidebar', () => {
expect(pairs).toContainEqual([{ lat: 43.66, lng: 7.21 }, { lat: 43.70, lng: 7.26 }])
})
it.each([
{ enabled: true, excluded: false, pairs: [[48.85, 48.86], [48.88, 48.89]] },
{ enabled: true, excluded: true, pairs: [[48.85, 48.89]] },
{ enabled: false, excluded: false, pairs: [[48.85, 48.86], [48.86, 48.89]] },
])('B5 sidebar Tour connector parity enabled=$enabled excluded=$excluded', async ({ enabled, excluded, pairs }) => {
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', icon: 'Route', type: 'feature', enabled }] })
const day = buildDay({ id: 10, date: '2025-06-01' })
const places = [
buildPlace({ id: 1, name: 'Before Tour', lat: 48.85, lng: 2.35 }),
buildPlace({ id: 2, name: 'Assigned Tour', lat: 48.86, lng: 2.35, route_geometry: '[[48.86,2.35],[48.88,2.35]]' }),
buildPlace({ id: 3, name: 'After Tour', lat: 48.89, lng: 2.35 }),
]
const assignments = { '10': places.map((place, order) => buildAssignment({
id: order + 1, day_id: 10, order_index: order, place,
...(order === 1 ? { tour_place_id: 2, tour_route_geometry: places[1].route_geometry, route_excluded: excluded } : {}),
})) }
render(<DayPlanSidebar {...makeDefaultProps({ days: [day], places, assignments, selectedDayId: 10, routeShown: true })} />)
await waitFor(() => expect(vi.mocked(calculateRouteWithLegs)).toHaveBeenCalledTimes(pairs.length))
expect(vi.mocked(calculateRouteWithLegs).mock.calls.map(call => call[0].map(point => point.lat))).toEqual(pairs)
expect(screen.getByText('Assigned Tour')).toBeInTheDocument()
})
it('uses Tour boundary overrides for hotel connectors with a driving day default', async () => {
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', icon: 'Route', type: 'feature', enabled: true }] })
const days = [
buildDay({ id: 1, day_number: 1 }),
buildDay({ id: 2, day_number: 2, default_transport_mode: 'driving' }),
buildDay({ id: 3, day_number: 3 }),
]
const hotel = { id: 90, trip_id: 1, start_day_id: 1, end_day_id: 3, place_lat: 61.001, place_lng: 10.001 } as unknown as Accommodation
const place = buildPlace({ id: 91, name: 'Mode test Tour', lat: 61.01, lng: 10.01, route_geometry: '[[61.01,10.01],[61.02,10.02]]' })
const assignment = buildAssignment({
id: 92, day_id: 2, order_index: 0, place,
tour_place_id: place.id, tour_route_geometry: place.route_geometry,
incoming_leg_transport_mode: 'walking', leg_transport_mode: 'cycling',
})
render(<DayPlanSidebar {...makeDefaultProps({
days, places: [place], assignments: { '2': [assignment] }, accommodations: [hotel],
selectedDayId: 2, routeShown: true, routeProfile: 'driving', optimizeFromAccommodation: true,
})} />)
await waitFor(() => expect(vi.mocked(calculateRouteWithLegs)).toHaveBeenCalledTimes(2))
const calls = vi.mocked(calculateRouteWithLegs).mock.calls
expect(calls.map(call => call[1]?.profile)).toEqual(['walking', 'cycling'])
expect(calls.map(call => call[0].map(point => [point.lat, point.lng]))).toEqual([
[[hotel.place_lat, hotel.place_lng], [61.01, 10.01]],
[[61.02, 10.02], [hotel.place_lat, hotel.place_lng]],
])
})
it('does not connect an invalid Tour start to the evening hotel through an unlocated transport', async () => {
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', icon: 'Route', type: 'feature', enabled: true }] })
const days = [buildDay({ id: 1, day_number: 1 }), buildDay({ id: 2, day_number: 2 }), buildDay({ id: 3, day_number: 3 })]
const hotel = { id: 93, trip_id: 1, start_day_id: 1, end_day_id: 3, place_lat: 61.101, place_lng: 10.101 } as unknown as Accommodation
const place = buildPlace({ id: 94, name: 'Invalid Tour', lat: 61.11, lng: 10.11, route_geometry: '{bad' })
const assignment = buildAssignment({ id: 95, day_id: 2, order_index: 0, place,
tour_place_id: place.id, tour_route_geometry: place.route_geometry })
const unlocatedTrain = buildReservation({ id: 96, type: 'train', day_id: 2, day_plan_position: 1, endpoints: [] })
render(<DayPlanSidebar {...makeDefaultProps({
days, places: [place], assignments: { '2': [assignment] }, reservations: [unlocatedTrain],
accommodations: [hotel], selectedDayId: 2, routeShown: true, optimizeFromAccommodation: true,
})} />)
await waitFor(() => expect(vi.mocked(calculateRouteWithLegs)).toHaveBeenCalledTimes(1))
expect(vi.mocked(calculateRouteWithLegs).mock.calls[0][0].map(point => [point.lat, point.lng]))
.toEqual([[hotel.place_lat, hotel.place_lng], [place.lat, place.lng]])
})
it('FE-PLANNER-DAYPLAN-122: a failing route lookup leaves the day without connectors', async () => {
const { calculateRouteWithLegs } = await import('../Map/RouteCalculator')
vi.mocked(calculateRouteWithLegs).mockRejectedValue(new Error('router down'))
@@ -60,6 +60,7 @@ import { findTodayDayId } from './today'
import { markdownLinkComponents } from '../shared/markdownLink'
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
import { resolveLegMode } from './legMode'
import { projectDayItinerary } from '../Map/dayTourProjection'
import { usePluginDaySchedule, usePluginDayTints, dayTintBackground, dayTinted, PluginDayScheduleRow, formatScheduleMinutes } from '../Plugins/PluginDaySchedule'
import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton'
import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar'
@@ -130,7 +131,7 @@ interface DayPlanSidebarProps {
onCreatePlaceForDay?: (dayId: number) => void
onExpandedDaysChange?: (expandedDayIds: Set<number>) => void
/** `dayIds`: the days the step acts on, so deleting one of them drops it. */
pushUndo?: (label: string, undoFn: () => Promise<void> | void, dayIds?: number[]) => void
pushUndo?: (label: string, undoFn: () => Promise<void> | void, dayIds?: number[], placeIds?: number[]) => void
canUndo?: boolean
lastActionLabel?: string | null
onUndo?: () => void
@@ -233,6 +234,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const ctxMenu = useContextMenu()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const tripActions = useRef(useTripStore.getState()).current
const can = useCanDo()
const canEditDays = can('day_edit', trip)
@@ -643,6 +645,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// legs to draw. Side-effect free, so the async loop below only does OSRM I/O.
const planDay = (dayId: number) => {
const merged = mergedItemsMap[dayId] || []
const projected = new Map(projectDayItinerary(assignments[String(dayId)] || [], toursEnabled, places).map(item => [item.assignment.id, item]))
// Each run point carries the ORIGIN assignment's per-segment travel mode
// (#1281): the leg from this point to the next is routed with `mode` (null =
// inherit the day default). Transport endpoints carry no mode → day default.
@@ -654,8 +657,24 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// flight, not a drive — and surface it as a bogus connector distance (#1394).
let curHasPlace = false
for (const it of merged) {
// A stop out of the route (#2532) is passed by, like a note.
if (it.type === 'place' && it.data.route_excluded) continue
const tour = it.type === 'place' ? projected.get(it.data.id) : undefined
if (tour?.kind === 'tour') {
if (tour.start) {
const prev = cur[cur.length - 1]
if (prev && !prev.isPlace && !withinDriveRange(prev, tour.start)) {
if (cur.length >= 2 && curHasPlace) runs.push(cur)
cur = []
curHasPlace = false
}
cur.push({ id: it.data.id, ...tour.start, isPlace: true, incoming_leg_transport_mode: it.data.incoming_leg_transport_mode ?? null })
curHasPlace = true
}
if (cur.length >= 2 && curHasPlace) runs.push(cur)
cur = tour.end ? [{ id: it.data.id, ...tour.end, isPlace: true, leg_transport_mode: it.data.leg_transport_mode ?? null }] : []
curHasPlace = !!tour.end
continue
}
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) {
// Mirror of the guard below: the open run may hold nothing but a far-away
// arrival endpoint, which is no more drivable in this direction (#2133).
@@ -714,7 +733,14 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// is one you flew out of or landed at rather than drove between (#2133).
const wayPts: { lat: number; lng: number; isPlace: boolean; time: string | null; carrierEdge?: CarrierEdge; leg_transport_mode?: string | null; incoming_leg_transport_mode?: string | null; id?: number }[] = []
for (const it of merged) {
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng && !it.data.route_excluded) {
if (it.type === 'place' && it.data.route_excluded) continue
const tour = it.type === 'place' ? projected.get(it.data.id) : undefined
if (tour?.kind === 'tour') {
if (tour.start) wayPts.push({ ...tour.start, isPlace: true, time: it.data.place?.place_time ?? null, id: it.data.id, incoming_leg_transport_mode: it.data.incoming_leg_transport_mode ?? null })
if (tour.end) wayPts.push({ ...tour.end, isPlace: true, time: it.data.place?.place_time ?? null, id: it.data.id, leg_transport_mode: it.data.leg_transport_mode ?? null })
continue
}
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) {
wayPts.push({ lat: it.data.place.lat, lng: it.data.place.lng, isPlace: true, time: it.data.place?.place_time ?? null, leg_transport_mode: it.data.leg_transport_mode ?? null, incoming_leg_transport_mode: it.data.incoming_leg_transport_mode ?? null, id: it.data.id })
} else if (it.type === 'transport') {
const { from, to } = getTransportRouteEndpoints(it.data, dayId)
@@ -725,14 +751,31 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
}
const firstWay = wayPts[0]
const lastWay = wayPts[wayPts.length - 1]
const hasRouteWaypoint = (item: typeof merged[number]) => {
if (item.type === 'place') {
if (item.data.route_excluded) return false
const tour = projected.get(item.data.id)
if (tour?.kind === 'tour') return !!tour.start || !!tour.end
return !!item.data.place?.lat && !!item.data.place?.lng
}
if (item.type === 'transport') {
const { from, to } = getTransportRouteEndpoints(item.data, dayId)
return !!from || !!to
}
return false
}
const reachable = (h: { place_lat?: number | null; place_lng?: number | null } | undefined, w: typeof firstWay) =>
!h || !w || w.isPlace || h.place_lat == null || h.place_lng == null
|| withinDriveRange({ lat: h.place_lat, lng: h.place_lng }, w)
// Same carrier evidence the map route uses (#2157): with a located carrier
// endpoint on the day, the no-time default must not open a hotel leg.
const dayHasCarrier = wayPts.some(w => w.carrierEdge != null)
const wantTop = !!(startHotel && firstWay && bookends && day && shouldDrawMorningLeg(bookends, day, firstWay, dayHasCarrier)) && reachable(startHotel, firstWay)
const wantBottom = !!(endHotel && lastWay && bookends && day && shouldDrawEveningLeg(bookends, day, lastWay, dayHasCarrier)) && reachable(endHotel, lastWay)
const firstItem = merged.find(hasRouteWaypoint)
const firstTour = firstItem?.type === 'place' ? projected.get(firstItem.data.id) : undefined
const wantTop = !(firstTour?.kind === 'tour' && !firstTour.start) && !!(startHotel && firstWay && bookends && day && shouldDrawMorningLeg(bookends, day, firstWay, dayHasCarrier)) && reachable(startHotel, firstWay)
const lastItem = [...merged].reverse().find(hasRouteWaypoint)
const lastTour = lastItem?.type === 'place' ? projected.get(lastItem.data.id) : undefined
const wantBottom = !(lastTour?.kind === 'tour' && !lastTour.end) && !!(endHotel && lastWay && bookends && day && shouldDrawEveningLeg(bookends, day, lastWay, dayHasCarrier)) && reachable(endHotel, lastWay)
return { runs, startHotel, endHotel, firstWay, lastWay, wantTop, wantBottom }
}
@@ -822,7 +865,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// routeDayIds is memoized from the same inputs as routeDayKey below, so keying the
// effect on the string is equivalent while staying stable across unrelated renders.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [routeDayKey, routeProfile, mergedItemsMap, accommodations, days, optimizeFromAccommodation, distanceUnit])
}, [routeDayKey, routeProfile, mergedItemsMap, accommodations, days, optimizeFromAccommodation, distanceUnit, toursEnabled, places])
const openAddNote = (dayId, e) => {
e?.stopPropagation()
@@ -842,7 +885,9 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// Unified reorder: assigns positions to ALL item types based on new visual order
const applyMergedOrder = async (dayId: number, newOrder: { type: string; data: any }[]) => {
// Capture previous place order for undo
const prevAssignmentIds = (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
const previousAssignments = assignments[String(dayId)] || []
const prevAssignmentIds = previousAssignments.slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
const prevPlaceIds = [...new Set(previousAssignments.map(a => a.place?.id).filter((id): id is number => id != null))]
// …and, per booking, the fields this call is about to overwrite, so a failed write
// can put the visible order back instead of leaving a phantom one behind the error
// toast. Restoring the whole array instead would also drop what a collaborator's
@@ -958,7 +1003,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const capturedPrevIds = prevAssignmentIds
pushUndo?.(t('undo.reorder'), async () => {
await tripActions.reorderAssignments(tripId, capturedDayId, capturedPrevIds)
}, [capturedDayId])
}, [capturedDayId], prevPlaceIds)
}
} catch (err: unknown) {
rollBackReservations()
@@ -1090,6 +1135,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
if (da.length < 3) return
const prevIds = (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index).map(a => a.id)
const placeIds = [...new Set((assignments[String(dayId)] || []).map(a => a.place?.id).filter((id): id is number => id != null))]
// Separate fixed (stay at their index) and movable assignments. A place is
// fixed if it's locked OR has a set time — timed places are anchored by their
@@ -1133,7 +1179,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const capturedDayId = dayId
pushUndo?.(t('undo.optimize'), async () => {
await tripActions.reorderAssignments(tripId, capturedDayId, prevIds)
}, [capturedDayId])
}, [capturedDayId], placeIds)
}
@@ -1364,6 +1410,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
// Plugin time contributions in the day plan (dayScheduleProvider hook).
const daySchedule = usePluginDaySchedule(S.tripId)
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
@@ -1625,6 +1672,11 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
// Where nothing sits above it (the mobile shell), the height still fills the panel.
<div ref={setPanel} data-touch-drag={dragDisabled ? undefined : ''} style={{ display: 'flex', flexDirection: 'column', flex: '1 1 0%', minHeight: 0, height: '100%', position: 'relative', fontFamily: "var(--font-system)" }}>
{/* Toolbar */}
{toursEnabled && selectedDayId != null && projectDayItinerary(assignments[String(selectedDayId)] || [], true, places).some(item => item.kind === 'tour' && !item.valid) && (
<div role="status" style={{ color: 'var(--warning)', padding: '8px 12px' }}>
<span aria-hidden="true">!</span> {t('tours.dayRoute.endpointUnknown')}
</div>
)}
<DayPlanSidebarToolbar
tripId={tripId}
trip={trip}
@@ -0,0 +1,169 @@
import { act, fireEvent, render, screen } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import { buildAssignment, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories'
import { useAuthStore } from '../../store/authStore'
import { useTripStore } from '../../store/tripStore'
import { usePermissionsStore } from '../../store/permissionsStore'
import { PlacesHeader } from './PlacesSidebarHeader'
import { usePlacesSidebar, type PlacesSidebarProps, type SidebarState } from './usePlacesSidebar'
let sidebar: SidebarState
function Host(props: PlacesSidebarProps) {
sidebar = usePlacesSidebar(props)
return (
<div data-testid="pool" onDragEnter={sidebar.handleSidebarDragEnter}
onDragOver={sidebar.handleSidebarDragOver} onDragLeave={sidebar.handleSidebarDragLeave}
onDrop={sidebar.handleSidebarDrop}>
<PlacesHeader {...sidebar} />
{sidebar.filtered.map(place => <span key={place.id} data-testid={`place-${place.id}`}>{place.name}</span>)}
</div>
)
}
function makeProps(overrides: Partial<PlacesSidebarProps> = {}): PlacesSidebarProps {
return {
tripId: 1,
places: [],
categories: [],
assignments: {},
selectedDayId: null,
selectedPlaceId: null,
onPlaceClick: vi.fn(),
onAddPlace: vi.fn(),
onAssignToDay: vi.fn(),
onEditPlace: vi.fn(),
onDeletePlace: vi.fn(),
days: [],
isMobile: false,
...overrides,
}
}
beforeEach(() => {
resetAllStores()
localStorage.removeItem('trek:places-sort')
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true })
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) })
})
afterEach(() => {
localStorage.removeItem('trek:places-sort')
})
describe('B4A Places pool', () => {
it('excludes only parent-identified Tours from rows and every Show count base', () => {
const tour = buildPlace({ id: 1, name: 'Tour', route_geometry: 'track', rating_avg: 5 })
const legacyTrack = buildPlace({ id: 2, name: 'Zebra track', route_geometry: 'track', rating_avg: 2 })
const planned = buildPlace({ id: 3, name: 'Alpha planned', rating_avg: 5 })
const loose = buildPlace({ id: 4, name: 'Beta loose', rating_avg: 2 })
render(<Host {...makeProps({
places: [tour, legacyTrack, planned, loose],
selectedDayId: 7,
assignments: {
'7': [buildAssignment({ day_id: 7, place: tour }), buildAssignment({ day_id: 7, place: planned })],
'8': [buildAssignment({ day_id: 8, place: legacyTrack })],
},
toursEnabled: true,
excludePlaceIds: new Set([1]),
})} />)
expect(sidebar.filtered.map(place => place.id)).toEqual([2, 3, 4])
expect(sidebar.filterCounts).toEqual({ all: 3, unplanned: 1, planned: 1, tracks: 1 })
expect(sidebar.hasTracks).toBe(false)
act(() => sidebar.setPlacesSort('name'))
expect(sidebar.filtered.map(place => place.id)).toEqual([3, 4, 2])
act(() => sidebar.setLocalityFilter({ country: 'No matching country', region: null }))
expect(sidebar.filtered).toEqual([])
act(() => { sidebar.setLocalityFilter(null); sidebar.setRatingFilter(5) })
expect(sidebar.filtered.map(place => place.id)).toEqual([3])
expect(sidebar.filterCounts.all).toBe(3)
act(() => { sidebar.setRatingFilter('all'); sidebar.pickFilter('planned') })
expect(sidebar.filtered.map(place => place.id)).toEqual([3])
act(() => sidebar.pickFilter('unplanned'))
expect(sidebar.filtered.map(place => place.id)).toEqual([4])
})
it('applies category and search to the excluded count base and reacts to a replacement exclusion set', () => {
const props = makeProps({
toursEnabled: true,
excludePlaceIds: new Set([1]),
places: [
buildPlace({ id: 1, name: 'Matching tour', category_id: 7 }),
buildPlace({ id: 2, name: 'Matching place', category_id: 7 }),
buildPlace({ id: 3, name: 'Matching other category', category_id: 8 }),
buildPlace({ id: 4, name: 'Other place', category_id: 7 }),
],
})
const { rerender } = render(<Host {...props} />)
act(() => { sidebar.setCategoryFilters(new Set(['7'])); sidebar.setSearch('matching') })
expect(sidebar.filtered.map(place => place.id)).toEqual([2])
expect(sidebar.filterCounts).toEqual({ all: 1, unplanned: 1, planned: 0, tracks: 0 })
rerender(<Host {...props} excludePlaceIds={new Set([1, 2])} />)
expect(sidebar.filtered).toEqual([])
expect(sidebar.filterCounts.all).toBe(0)
})
it('restores legacy rows and Tracks while off, even when the parent retains the exclusion set', () => {
const props = makeProps({
places: [buildPlace({ id: 1, name: 'Tour', route_geometry: 'track' }), buildPlace({ id: 2, name: 'Place' })],
toursEnabled: true,
excludePlaceIds: new Set([1]),
})
const { rerender } = render(<Host {...props} />)
expect(sidebar.filtered.map(place => place.id)).toEqual([2])
rerender(<Host {...props} toursEnabled={false} />)
expect(sidebar.filtered.map(place => place.id)).toEqual([1, 2])
expect(sidebar.filterCounts.all).toBe(2)
expect(sidebar.hasTracks).toBe(true)
act(() => sidebar.pickFilter('tracks'))
expect(sidebar.filtered.map(place => place.id)).toEqual([1])
rerender(<Host {...props} />)
expect(sidebar.filter).toBe('all')
expect(sidebar.filtered.map(place => place.id)).toEqual([2])
})
it('blocks Places file drops while Tours is on and restores them while off', () => {
const props = makeProps({ toursEnabled: true })
const { rerender } = render(<Host {...props} />)
const file = new File(['track'], 'route.gpx', { type: 'application/gpx+xml' })
fireEvent.dragEnter(screen.getByTestId('pool'))
expect(sidebar.sidebarDragOver).toBe(false)
fireEvent.drop(screen.getByTestId('pool'), { dataTransfer: { files: [file] } })
expect(sidebar.fileImportOpen).toBe(false)
expect(sidebar.sidebarDropFile).toBeNull()
rerender(<Host {...props} toursEnabled={false} />)
fireEvent.dragEnter(screen.getByTestId('pool'))
expect(sidebar.sidebarDragOver).toBe(true)
fireEvent.drop(screen.getByTestId('pool'), { dataTransfer: { files: [file] } })
expect(sidebar.fileImportOpen).toBe(true)
expect(sidebar.sidebarDropFile).toBe(file)
})
it('keeps list import in Places while Tours is on and restores the file menu while off', async () => {
const user = userEvent.setup()
const props = makeProps({ toursEnabled: true })
const { rerender } = render(<Host {...props} />)
await user.click(screen.getByRole('button', { name: 'Import Places' }))
expect(screen.queryByRole('button', { name: sidebar.t('places.importFile') })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: sidebar.t('places.importList') }))
expect(sidebar.listImportOpen).toBe(true)
expect(sidebar.fileImportOpen).toBe(false)
rerender(<Host {...props} toursEnabled={false} />)
await user.click(screen.getByRole('button', { name: 'Import Places' }))
await user.click(screen.getByRole('button', { name: sidebar.t('places.importFile') }))
expect(sidebar.fileImportOpen).toBe(true)
})
it.each([true, false])('exposes no AddRow actions without place-edit permission (Tours=%s)', async toursEnabled => {
seedStore(usePermissionsStore, { permissions: { place_edit: 'admin' } })
const props = makeProps({ toursEnabled, selectedDayId: 7, onAddPlaceToSelectedDay: vi.fn() })
render(<Host {...props} />)
expect(sidebar.canEditPlaces).toBe(false)
expect(screen.queryByRole('button', { name: 'Import Places' })).not.toBeInTheDocument()
expect(screen.queryByTestId('add-place-to-day')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Add Place|New place/i })).not.toBeInTheDocument()
expect(props.onAddPlace).not.toHaveBeenCalled()
expect(props.onAddPlaceToSelectedDay).not.toHaveBeenCalled()
})
})
@@ -409,7 +409,7 @@ function LocalityFilterDropdown(S: SidebarState) {
}
function AddRow(S: SidebarState) {
const { onAddPlace, onAddPlaceToSelectedDay, selectedDayId, t, setFileImportOpen, setListImportOpen, hasMultipleListImportProviders } = S
const { onAddPlace, onAddPlaceToSelectedDay, selectedDayId, t, setFileImportOpen, setListImportOpen, hasMultipleListImportProviders, toursEnabled } = S
const dayOpen = selectedDayId != null
const split = dayOpen && !!onAddPlaceToSelectedDay
const { ref: rowRef, width: rowWidth } = useElementSize<HTMLDivElement>()
@@ -419,7 +419,7 @@ function AddRow(S: SidebarState) {
const addLabel = t(dayOpen ? 'places.addPlaceShort' : 'places.addPlace')
const importMenu = useContextMenu()
const importItems = [
{ label: t('places.importFile'), icon: FileDown, onClick: () => setFileImportOpen(true) },
...(!toursEnabled ? [{ label: t('places.importFile'), icon: FileDown, onClick: () => setFileImportOpen(true) }] : []),
{ label: t(hasMultipleListImportProviders ? 'places.importList' : 'places.importGoogleList'), icon: ListPlus, onClick: () => setListImportOpen(true) },
]
return (
@@ -65,6 +65,13 @@ export interface PlacesSidebarProps {
pushUndo?: (label: string, undoFn: () => Promise<void> | void) => void
initialScrollTop?: number
onScrollTopChange?: (top: number) => void
/**
* With the Tours addon on, file import belongs to Tours mode, list import
* stays here, and the "Tracks" chip is hidden because tracks are tours.
*/
toursEnabled?: boolean
/** Places that are tours (a `tours` facet row exists) — hidden from the pool entirely while tours is on. */
excludePlaceIds?: Set<number>
}
/**
@@ -77,6 +84,10 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
tripId, places, assignments, selectedDayId, days, accommodations = NO_ACCOMMODATIONS,
pushUndo, initialScrollTop, onScrollTopChange, onEditPlace, onAssignToDay, onDeletePlace,
} = props
const poolPlaces = useMemo(
() => props.toursEnabled && props.excludePlaceIds ? places.filter(p => !props.excludePlaceIds!.has(p.id)) : places,
[places, props.toursEnabled, props.excludePlaceIds],
)
const { t, language } = useTranslation()
const toast = useToast()
const ctxMenu = useContextMenu()
@@ -107,14 +118,14 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
}, [])
const handleSidebarDragEnter = (e: React.DragEvent) => {
if (!canEditPlaces) return
if (!canEditPlaces || props.toursEnabled) return
e.preventDefault()
sidebarDragCounter.current++
setSidebarDragOver(true)
}
const handleSidebarDragOver = (e: React.DragEvent) => {
if (!canEditPlaces) return
if (!canEditPlaces || props.toursEnabled) return
e.preventDefault()
}
@@ -127,7 +138,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
e.preventDefault()
sidebarDragCounter.current = 0
setSidebarDragOver(false)
if (!canEditPlaces) return
if (!canEditPlaces || props.toursEnabled) return
const f = e.dataTransfer.files[0]
if (!f) return
setSidebarDropFile(f)
@@ -195,7 +206,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
// like the rating floor.
const [localityFilter, setLocalityFilter] = useState<LocalityFilter | null>(null)
const localityOf = useMemo(() => new Map(places.map(p => [p.id, placeLocality(p, language)])), [places, language])
const localities = useMemo(() => localityGroups(places.map(p => localityOf.get(p.id)!)), [places, localityOf])
const localities = useMemo(() => localityGroups(poolPlaces.map(p => localityOf.get(p.id)!)), [poolPlaces, localityOf])
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
const [pendingDeleteIds, setPendingDeleteIds] = useState<number[] | null>(null)
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
@@ -257,7 +268,10 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
const pickFilter = (next: PlacesFilter) => { setFilter(next); setSelectedIds(new Set()) }
// Alle geplanten Ort-IDs abrufen (einem Tag zugewiesen)
const hasTracks = useMemo(() => places.some(p => p.route_geometry), [places])
const hasTracks = useMemo(
() => !props.toursEnabled && poolPlaces.some(p => p.route_geometry),
[poolPlaces, props.toursEnabled],
)
useEffect(() => { if (filter === 'tracks' && !hasTracks) setFilter('all') }, [hasTracks, filter])
const plannedIds = useMemo(
@@ -286,7 +300,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
const dayScoped = filter === 'planned' && plannedInDayIds !== null
const filtered = useMemo(() => {
const list = places.filter(p => {
const list = poolPlaces.filter(p => {
if (filter === 'unplanned' && plannedIds.has(p.id)) return false
if (filter === 'planned' && !plannedFilterIds.has(p.id)) return false
if (filter === 'tracks' && !p.route_geometry) return false
@@ -301,7 +315,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
return true
})
return sortPlaces(list, placesSort, language)
}, [places, filter, categoryFilters, search, plannedIds, plannedFilterIds, ratingFilter, localityFilter, localityOf, placesSort, language])
}, [poolPlaces, filter, categoryFilters, search, plannedIds, plannedFilterIds, ratingFilter, localityFilter, localityOf, placesSort, language])
/**
* How many places each "show" choice would leave, under the category and search
@@ -311,7 +325,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
* different questions.
*/
const filterCounts = useMemo(() => {
const base = places.filter(p => {
const base = poolPlaces.filter(p => {
if (categoryFilters.size > 0) {
if (p.category_id == null) {
if (!categoryFilters.has('uncategorized')) return false
@@ -325,7 +339,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
planned: base.filter(p => plannedFilterIds.has(p.id)).length,
tracks: base.filter(p => p.route_geometry).length,
} satisfies Record<PlacesFilter, number>
}, [places, categoryFilters, search, plannedIds, plannedFilterIds])
}, [poolPlaces, categoryFilters, search, plannedIds, plannedFilterIds])
/** The filters narrowing the list besides the search box, for the badge on the filter button. */