fix(tours): a tour another member creates is a tour on the phone too

The list read marked tour places with tour_place_id, but the single-place
read behind place:created and place:updated did not, and the phone's
places browser kept a second tour list of its own that no realtime event
updated. A tour another member made, or one imported from GPX, showed as
an ordinary place on the phone until the screen remounted, and every
tour did offline. The single read carries the mark now, the browser asks
the planner, and the tour id set is memoised instead of rebuilt on every
render.
This commit is contained in:
Maurice
2026-10-07 16:52:05 +02:00
parent 72fbbd55d4
commit c60277c4d2
5 changed files with 38 additions and 15 deletions
+7 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useCallback, useRef } from 'react'
import { useEffect, useState, useCallback, useMemo, useRef } from 'react'
import type { TourListItem } from '@trek/shared'
import { toursApi } from '../api/client'
@@ -95,13 +95,18 @@ export function useTourPlaceIds(tripId: number, enabled: boolean) {
const visibleTours = enabled && tourData?.tripId === tripId ? tourData.tours : []
const pendingIds = enabled && pendingPlaceIds?.tripId === tripId ? pendingPlaceIds.ids : []
const currentRequest = requestState?.tripId === tripId ? requestState : null
// One Set per change, not per render: consumers memoise on it.
const tourPlaceIds = useMemo(
() => new Set([...visibleTours.map(tour => tour.place_id), ...pendingIds]),
[visibleTours, pendingIds],
)
return {
tours: visibleTours,
toursLoading: enabled && (currentRequest?.loading ?? false),
tourLoadError: enabled && (currentRequest?.error ?? false),
tourDataReady,
tourPlaceIds: new Set([...visibleTours.map(tour => tour.place_id), ...pendingIds]),
tourPlaceIds,
reloadTourPlaceIds: reload,
invalidateTourPlaceIds,
upsertTour,
@@ -24,7 +24,6 @@ import MPlacesSaveToCollectionSheet from './MPlacesSaveToCollectionSheet'
import MPlacesToursModeSwitch from './MPlacesToursModeSwitch'
import MToursSelectionList from './MToursSelectionList'
import { filterPool, firstPlannedDayNumbers, plannedPlaceIds } from './placesBrowserModel'
import { useTourPlaceIds } from '../../../../hooks/useTourPlaceIds'
import { MCategoryFilterList, MRatingFloorChips, SquareCheck } from './MPlacesFilterControls'
import { countActivePlacesFilters } from '../../../../utils/placesFilter'
@@ -46,9 +45,6 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
const canEditPlaces = planner.can('place_edit', trip)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
// Places that are tours (a `tours` facet row exists) — kept out of the
// Places pool entirely while the addon is on.
const { tourPlaceIds } = useTourPlaceIds(tripId, toursEnabled)
// Top level of the places browser, mirroring the desktop right add-panel's
// Places <-> Tours switch placement.
const [toursMode, setToursMode] = useState(false)
@@ -84,8 +80,11 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
)
const dayNumberByPlace = useMemo(() => firstPlannedDayNumbers(assignments, days), [assignments, days])
const poolPlaces = useMemo(
() => toursEnabled ? places.filter(place => !tourPlaceIds.has(place.id)) : places,
[places, toursEnabled, tourPlaceIds],
// Places that are tours stay out of the Places pool while the addon is on.
// The planner's answer, not a second list of its own: that one is kept up
// to date by the trip's realtime events and knows the mark on each place.
() => toursEnabled ? places.filter(place => !planner.isTourPlace(place.id)) : places,
[places, toursEnabled, planner.isTourPlace],
)
const filtered = useMemo(() => {
return filterPool(poolPlaces, { filter, categoryFilters, ratingFilter, search, plannedIds })
@@ -369,7 +369,7 @@ describe('MPlacesBrowser', () => {
tour_group_id: null, max_hiking_difficulty: 2, planned: false, caution: false,
}
seedStore(useAddonStore, { addons: [{ id: 'collections', enabled: true }, { id: 'tours', enabled: true }] })
vi.spyOn(toursApi, 'list').mockResolvedValue({ tours: [ridge] })
const list = vi.spyOn(toursApi, 'list').mockResolvedValue({ tours: [ridge] })
const planner = makePlanner({
places: [...PLACES, TOUR],
tours: [ridge],
@@ -379,7 +379,8 @@ describe('MPlacesBrowser', () => {
await waitFor(() => expect(screen.getByText('places.count:3')).toBeInTheDocument())
expect(screen.queryByText('Ridge walk')).not.toBeInTheDocument()
expect(toursApi.list).toHaveBeenCalledWith(planner.tripId)
// The planner owns the tour list; the browser does not fetch a second one.
expect(list).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('tab', { name: /^Tours$/i }))
expect(screen.getByRole('option', { name: /Ridge walk/ })).toBeInTheDocument()
@@ -53,14 +53,14 @@ export interface PlaceWithCategoryRow extends PlaceRow {
category_name: string | null;
category_color: string | null;
category_icon: string | null;
/** The place's own id when it is a Tour (it has a `tours` facet row), else null. */
tour_place_id: number | null;
}
/** {@link PlacesRepository.listForTrip}'s row: the category join plus the atlas' cached region (#2537), null when none resolved yet. */
export interface PlaceListRow extends PlaceWithCategoryRow {
country_code: string | null;
region_name: string | null;
/** The place's own id when it is a Tour (it has a `tours` facet row), else null. */
tour_place_id: number | null;
}
/** {@link PlacesRepository.findActiveTripFile}'s narrow `trip_files` shape. */
@@ -140,9 +140,17 @@ export class PlacesRepository extends TrekRepository<Places> {
// raw-bind seam (`legacy getPlaceWithTags(placeId: number | string)`
// bound the raw value with no `Number()` conversion). `p.id` is the
// physical column name.
const platform = this.getEntityManager().getPlatform();
// The tour mark rides along like it does on the list read: this row is
// what place:created and place:updated carry, and a client that only knew
// the list's mark showed a tour another member made as a plain place.
const place = await this.qb('p')
.leftJoin('p.category', 'c')
.select(['p.*', 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon'])
.leftJoin('p.tours', 't')
.select([
'p.*', 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
columnRef(platform, 't.place_id').as('tour_place_id'),
])
.where('p.id = ?', [place_id])
.execute<PlaceWithCategoryRow | undefined>('get', false);
if (!place) return null;
@@ -165,7 +173,6 @@ export class PlacesRepository extends TrekRepository<Places> {
// column, `'pr.user as user_id'` was tried and is still `u__id` — both
// verified directly, not assumed (same finding independently reproduced
// in `PlaceRatingsRepository.listForPlaces`'s docstring, Plan 3c Task 1).
const platform = this.getEntityManager().getPlatform();
const ratings = await this.qb('p')
.join('p.place_ratings_collection', 'pr')
.join('pr.user', 'u')
@@ -36,7 +36,7 @@ afterAll(async () => { await t.close(); testDb.close(); });
*/
function legacyGetPlaceWithTags(placeId: number): unknown {
const place = testDb
.prepare('SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?')
.prepare('SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon, t.place_id as tour_place_id FROM places p LEFT JOIN categories c ON p.category_id = c.id LEFT JOIN tours t ON t.place_id = p.id WHERE p.id = ?')
.get(placeId) as (Record<string, unknown> & { category_id: number | null; category_name: string | null; category_color: string | null; category_icon: string | null }) | undefined;
if (!place) return null;
const tags = testDb.prepare('SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?').all(placeId);
@@ -56,6 +56,17 @@ function legacyGetPlaceWithTags(placeId: number): unknown {
}
describe('PlacesRepository.findWithTagsAndRatings — parity with the legacy getPlaceWithTags', () => {
it('PLACEREPO-011b: the single-place read carries the tour mark, as the list does', async () => {
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const plain = createPlace(testDb, trip.id, { name: 'Plain' });
const tour = createPlace(testDb, trip.id, { name: 'Ridge walk' });
testDb.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tour.id);
expect((await places.findWithTagsAndRatings(tour.id))?.tour_place_id).toBe(tour.id);
expect((await places.findWithTagsAndRatings(plain.id))?.tour_place_id).toBeNull();
});
it('PLACEREPO-011 (0b security review F-B6): full key-for-key parity with the legacy statement, on a place with a category, two tags and two ratings', async () => {
const { user: owner } = createUser(testDb);
const { user: voterA } = createUser(testDb, { username: 'parity_voter_a' });