diff --git a/client/src/api/placeActivities.test.ts b/client/src/api/placeActivities.test.ts new file mode 100644 index 000000000..1cd3406b0 --- /dev/null +++ b/client/src/api/placeActivities.test.ts @@ -0,0 +1,63 @@ +// FE-API-PLACE-ACTIVITIES-001 +// +// PLC-18: each method pins its verb, its path and its body. +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { server } from '../../tests/helpers/msw/server'; +import { placeActivitiesApi } from './placeActivities'; + +const activities = { activities: [], can_link: true }; +const candidates = { candidates: [] }; +const entry = { activities: [], sources: [] }; +let calls: Array<[string, string, unknown]> = []; + +beforeEach(() => { + calls = []; +}); + +function record(data: object) { + return async ({ request }: { request: Request }) => { + const text = request.method === 'POST' ? await request.text() : ''; + calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]); + return HttpResponse.json(data); + }; +} + +describe('placeActivitiesApi', () => { + it('FE-API-PLACE-ACTIVITIES-001: reads, links and unlinks the activities of trip places, saved places and entries', async () => { + server.use( + http.get('/api/trips/4/places/7/activities', record(activities)), + http.get('/api/trips/4/places/7/activities/candidates', record(candidates)), + http.post('/api/trips/4/places/7/activities', record(activities)), + http.delete('/api/trips/4/places/7/activities/reservations/9', record(activities)), + http.delete('/api/trips/4/places/7/activities/tours/11', record(activities)), + http.get('/api/addons/collections/places/8/activities', record(activities)), + http.get('/api/addons/collections/places/8/activities/candidates', record(candidates)), + http.post('/api/addons/collections/places/8/activities', record(activities)), + http.delete('/api/addons/collections/places/8/activities/tours/5', record(activities)), + http.get('/api/addons/collections/library/places/list/8/activities', record(entry)) + ); + expect(await placeActivitiesApi.tripPlace(4, 7)).toEqual(activities); + expect(await placeActivitiesApi.tripCandidates(4, 7)).toEqual(candidates); + expect(await placeActivitiesApi.linkTrip(4, 7, { reservation_id: 9 })).toEqual(activities); + expect(await placeActivitiesApi.unlinkTripBooking(4, 7, 9)).toEqual(activities); + expect(await placeActivitiesApi.unlinkTripTour(4, 7, 11)).toEqual(activities); + expect(await placeActivitiesApi.savedPlace(8)).toEqual(activities); + expect(await placeActivitiesApi.savedCandidates(8)).toEqual(candidates); + expect(await placeActivitiesApi.linkSaved(8, 5)).toEqual(activities); + expect(await placeActivitiesApi.unlinkSaved(8, 5)).toEqual(activities); + expect(await placeActivitiesApi.libraryEntry('list', 8)).toEqual(entry); + expect(calls).toEqual([ + ['GET', '/api/trips/4/places/7/activities', null], + ['GET', '/api/trips/4/places/7/activities/candidates', null], + ['POST', '/api/trips/4/places/7/activities', { reservation_id: 9 }], + ['DELETE', '/api/trips/4/places/7/activities/reservations/9', null], + ['DELETE', '/api/trips/4/places/7/activities/tours/11', null], + ['GET', '/api/addons/collections/places/8/activities', null], + ['GET', '/api/addons/collections/places/8/activities/candidates', null], + ['POST', '/api/addons/collections/places/8/activities', { collection_tour_id: 5 }], + ['DELETE', '/api/addons/collections/places/8/activities/tours/5', null], + ['GET', '/api/addons/collections/library/places/list/8/activities', null], + ]); + }); +}); diff --git a/client/src/api/placeHistory.test.ts b/client/src/api/placeHistory.test.ts new file mode 100644 index 000000000..7e7639f5c --- /dev/null +++ b/client/src/api/placeHistory.test.ts @@ -0,0 +1,29 @@ +// FE-API-PLACE-HISTORY-001 +// +// PLC-14: the history pins its verb, its path and its query, and hands back +// what the server answered. +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; +import { server } from '../../tests/helpers/msw/server'; +import { placeHistoryApi } from './placeHistory'; + +const BASE = '/api/addons/collections/library/places'; + +describe('placeHistoryApi', () => { + it('FE-API-PLACE-HISTORY-001: reads the history of the trip place or saved place it names, page by page', async () => { + const calls: Array<{ path: string; query: Record }> = []; + const page = { entries: [], next_cursor: null }; + const record = ({ request }: { request: Request }) => { + const url = new URL(request.url); + calls.push({ path: url.pathname, query: Object.fromEntries(url.searchParams) }); + return HttpResponse.json(page); + }; + server.use(http.get(`${BASE}/trip/4/history`, record), http.get(`${BASE}/list/9/history`, record)); + expect(await placeHistoryApi.history('trip', 4)).toEqual(page); + expect(await placeHistoryApi.history('list', 9, { cursor: '12', limit: 20 })).toEqual(page); + expect(calls).toEqual([ + { path: `${BASE}/trip/4/history`, query: {} }, + { path: `${BASE}/list/9/history`, query: { cursor: '12', limit: '20' } }, + ]); + }); +}); diff --git a/client/src/api/placeTags.test.ts b/client/src/api/placeTags.test.ts new file mode 100644 index 000000000..ef24c74f2 --- /dev/null +++ b/client/src/api/placeTags.test.ts @@ -0,0 +1,72 @@ +// FE-API-PLACE-TAGS-001 to FE-API-PLACE-TAGS-003 +// +// PLC-21: each method pins its verb, its path and its body, and hands back +// what the server answered; the All places list sends a tag filter joined by commas. +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { server } from '../../tests/helpers/msw/server'; +import { placeTagsApi } from './placeTags'; +import { placesLibraryApi } from './placesLibrary'; + +const TAGS = '/api/addons/collections/library/places/tags'; +const tag = { id: 3, user_id: 1, trip_id: null, name: 'Wine', color: '#aa0000' }; + +let calls: Array<{ method: string; path: string; body: unknown; query: Record }> = []; + +beforeEach(() => { + calls = []; +}); + +function record(data: object) { + return async ({ request }: { request: Request }) => { + const url = new URL(request.url); + const text = request.method === 'GET' || request.method === 'DELETE' ? '' : await request.text(); + calls.push({ + method: request.method, + path: url.pathname, + body: text ? JSON.parse(text) : null, + query: Object.fromEntries(url.searchParams), + }); + return HttpResponse.json(data); + }; +} + +describe('placeTagsApi', () => { + it('FE-API-PLACE-TAGS-001: lists, creates, renames and deletes personal tags under /tags', async () => { + server.use( + http.get('/api/tags', record({ tags: [tag] })), + http.post('/api/tags', record({ tag })), + http.put('/api/tags/3', record({ tag })), + http.delete('/api/tags/3', record({ success: true })) + ); + expect(await placeTagsApi.list()).toEqual({ tags: [tag] }); + expect(await placeTagsApi.create({ name: 'Wine' })).toEqual({ tag }); + expect(await placeTagsApi.update(3, { color: '#000000' })).toEqual({ tag }); + expect(await placeTagsApi.remove(3)).toEqual({ success: true }); + expect(calls.map(({ method, path, body }) => ({ method, path, body }))).toEqual([ + { method: 'GET', path: '/api/tags', body: null }, + { method: 'POST', path: '/api/tags', body: { name: 'Wine' } }, + { method: 'PUT', path: '/api/tags/3', body: { color: '#000000' } }, + { method: 'DELETE', path: '/api/tags/3', body: null }, + ]); + }); + + it('FE-API-PLACE-TAGS-002: sets the tags of one entry and changes several', async () => { + server.use(http.put(TAGS, record({ entry: null })), http.post(`${TAGS}/bulk`, record({ entries: [] }))); + expect(await placeTagsApi.setForEntry({ key: 'trip:4', tag_ids: [3] })).toEqual({ entry: null }); + expect(await placeTagsApi.bulk({ keys: ['list:9'], add: [3], remove: [5] })).toEqual({ entries: [] }); + expect(calls.map(({ method, path, body }) => ({ method, path, body }))).toEqual([ + { method: 'PUT', path: TAGS, body: { key: 'trip:4', tag_ids: [3] } }, + { method: 'POST', path: `${TAGS}/bulk`, body: { keys: ['list:9'], add: [3], remove: [5] } }, + ]); + }); + + it('FE-API-PLACE-TAGS-003: All places sends the tag filter as ids joined by commas', async () => { + const page = { entries: [], total: 0, counts: { all: 0, trip: 0, list: 0 }, next_cursor: null }; + server.use(http.get('/api/addons/collections/library/places', record(page))); + await placesLibraryApi.list({ tag_ids: [3, 7], q: 'x' }); + await placesLibraryApi.list({ tag_ids: '5' }); + await placesLibraryApi.list({ tag_ids: [] }); + expect(calls.map((call) => call.query)).toEqual([{ q: 'x', tag_ids: '3,7' }, { tag_ids: '5' }, {}]); + }); +}); diff --git a/client/src/api/placeVisits.test.ts b/client/src/api/placeVisits.test.ts new file mode 100644 index 000000000..1a8ea4bb9 --- /dev/null +++ b/client/src/api/placeVisits.test.ts @@ -0,0 +1,48 @@ +// FE-API-PLACE-VISITS-001 +// +// D7/PLC-10 to PLC-23: each read pins its verb, its path and its query; there is nothing to write. +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { server } from '../../tests/helpers/msw/server'; +import { placeVisitsApi } from './placeVisits'; + +let calls: Array<[string, string]> = []; + +beforeEach(() => { + calls = []; +}); + +function record(data: object) { + return ({ request }: { request: Request }) => { + const url = new URL(request.url); + calls.push([request.method, `${url.pathname}${url.search}`]); + return HttpResponse.json(data); + }; +} + +describe('placeVisitsApi', () => { + it('FE-API-PLACE-VISITS-001: reads the visits and the media at the routes the server serves', async () => { + server.use( + http.get('/api/place-visits', record({ visits: [], total: 0 })), + http.get('/api/place-visits/place', record({ visits: [], visit_count: 0, last_visit: null })), + http.get('/api/trips/4/place-visits/mine', record({ place_ids: [], places: [] })), + http.get( + '/api/addons/collections/library/places/trip/3/media', + record({ images: [], journey_photos: [], files: [] }) + ) + ); + + expect(await placeVisitsApi.list({ trip_id: 4 })).toEqual({ visits: [], total: 0 }); + expect(await placeVisitsApi.forPlace('trip', 3)).toEqual({ visits: [], visit_count: 0, last_visit: null }); + expect(await placeVisitsApi.tripVisited(4)).toEqual({ place_ids: [], places: [] }); + expect(await placeVisitsApi.media('trip', 3)).toEqual({ images: [], journey_photos: [], files: [] }); + expect(Object.keys(placeVisitsApi).sort()).toEqual(['forPlace', 'list', 'media', 'tripVisited']); + + expect(calls).toEqual([ + ['GET', '/api/place-visits?trip_id=4'], + ['GET', '/api/place-visits/place?kind=trip&id=3'], + ['GET', '/api/trips/4/place-visits/mine'], + ['GET', '/api/addons/collections/library/places/trip/3/media'], + ]); + }); +}); diff --git a/client/src/components/Collections/CategoryTileMenu.test.tsx b/client/src/components/Collections/CategoryTileMenu.test.tsx index 7c7010096..3109e4697 100644 --- a/client/src/components/Collections/CategoryTileMenu.test.tsx +++ b/client/src/components/Collections/CategoryTileMenu.test.tsx @@ -30,7 +30,6 @@ describe('CategoryTileMenu', () => { setup(); const tile = screen.getByRole('button', { name: 'Category: No category' }); expect(tile).toHaveAttribute('aria-expanded', 'false'); - expect(tile).toHaveAttribute('title', 'Category: No category'); expect(tile).toHaveStyle({ width: '46px', height: '46px' }); expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); }); diff --git a/client/src/components/Collections/CopyCarryPanel.test.tsx b/client/src/components/Collections/CopyCarryPanel.test.tsx index 1bdcd1eee..0b7fbcf78 100644 --- a/client/src/components/Collections/CopyCarryPanel.test.tsx +++ b/client/src/components/Collections/CopyCarryPanel.test.tsx @@ -1,5 +1,5 @@ -// FE-COMP-COPYCARRY-001 to FE-COMP-COPYCARRY-002 -import { fireEvent, render, screen } from '../../../tests/helpers/render'; +// FE-COMP-COPYCARRY-001 to FE-COMP-COPYCARRY-004 +import { fireEvent, render, screen, within } from '../../../tests/helpers/render'; import CopyCarryPanel from './CopyCarryPanel'; const t = (k: string) => k; @@ -47,4 +47,79 @@ describe.each(['dialog', 'sheet'] as const)('CopyCarryPanel (%s)', (variant) => expect(screen.queryByText('collections.copyCarry.notes')).toBeNull(); expect(screen.getByRole('button', { name: 'Coffee' })).toHaveAttribute('aria-pressed', 'false'); }); + + it('FE-COMP-COPYCARRY-003: offers the own tags as their own group and toggles them apart from the labels', () => { + const onToggleTag = vi.fn(); + const onTogglePersonalTag = vi.fn(); + render( + + ); + const own = screen.getByRole('group', { name: 'collections.copyCarry.personalTags' }); + expect(screen.getByText('collections.copyCarry.personalTagsHint')).toBeInTheDocument(); + expect(within(own).getByRole('button', { name: 'Beach' })).toHaveAttribute('aria-pressed', 'true'); + expect(within(own).getByRole('button', { name: 'Wine' })).toHaveAttribute('aria-pressed', 'false'); + expect(within(own).queryByRole('button', { name: 'Coffee' })).toBeNull(); + fireEvent.click(within(own).getByRole('button', { name: 'Wine' })); + expect(onTogglePersonalTag).toHaveBeenCalledWith(3); + expect(onToggleTag).not.toHaveBeenCalled(); + }); + + it('FE-COMP-COPYCARRY-004: no own tags group without tags or without a handler, and nothing picked by default', () => { + const personalTags = [{ id: 3, name: 'Wine' }]; + const { rerender } = render( + + ); + expect(screen.queryByText('collections.copyCarry.personalTags')).toBeNull(); + rerender( + + ); + expect(screen.queryByText('collections.copyCarry.personalTags')).toBeNull(); + rerender( + + ); + expect(screen.getByRole('button', { name: 'Wine' })).toHaveAttribute('aria-pressed', 'false'); + }); }); diff --git a/client/src/components/Collections/EntryTagDots.test.tsx b/client/src/components/Collections/EntryTagDots.test.tsx new file mode 100644 index 000000000..ad72f3844 --- /dev/null +++ b/client/src/components/Collections/EntryTagDots.test.tsx @@ -0,0 +1,28 @@ +// FE-COMP-ENTRYTAGDOTS-001 to FE-COMP-ENTRYTAGDOTS-002 +import { render, screen } from '../../../tests/helpers/render'; +import EntryTagDots from './EntryTagDots'; + +describe('EntryTagDots', () => { + it('FE-COMP-ENTRYTAGDOTS-001: draws nothing for a row without tags', () => { + const { container, rerender } = render(); + expect(container).toBeEmptyDOMElement(); + rerender(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-ENTRYTAGDOTS-002: one dot per tag up to four, named by all of them, in their colour or the accent', () => { + const tags = [ + { id: 1, name: 'Beach', color: '#ff0000' }, + { id: 2, name: 'Coffee', color: null }, + { id: 3, name: 'Late', color: '#00ff00' }, + { id: 4, name: 'Wine', color: '#0000ff' }, + { id: 5, name: 'Zoo', color: '#ffff00' }, + ]; + render(); + const dots = screen.getByRole('img', { name: 'Beach, Coffee, Late, Wine, Zoo' }); + const spans = Array.from(dots.children) as HTMLElement[]; + expect(spans).toHaveLength(4); + expect(spans[0].style.background).toBe('rgb(255, 0, 0)'); + expect(spans[1].style.background).toBe('var(--accent)'); + }); +}); diff --git a/client/src/components/Collections/EntryTagsSection.test.tsx b/client/src/components/Collections/EntryTagsSection.test.tsx new file mode 100644 index 000000000..380b309ab --- /dev/null +++ b/client/src/components/Collections/EntryTagsSection.test.tsx @@ -0,0 +1,163 @@ +// FE-COMP-ENTRYTAGSSEC-001 to FE-COMP-ENTRYTAGSSEC-009: the reader's own tags in the +// desktop sheet of All places (PLC-21), rendered against a mocked useEntryTags. +import type { PlacesLibraryDetailResponse, Tag } from '@trek/shared'; + +import { bothOrigins } from '../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import EntryTagsSection from './EntryTagsSection'; +import type { useEntryTags } from './useEntryTags'; + +type EntryTags = ReturnType; + +const hook = vi.hoisted(() => ({ state: null as unknown as EntryTags, args: [] as unknown[] })); +vi.mock('./useEntryTags', () => ({ + useEntryTags: (args: unknown) => { + hook.args.push(args); + return hook.state; + }, +})); + +vi.mock('../shared/ConfirmDialog', () => ({ + default: ({ isOpen, onConfirm, title }: { isOpen: boolean; onConfirm: () => void; title: string }) => + isOpen ? ( +
+ +
+ ) : null, +})); + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +const tag = (id: number, name: string, color = '#aa0000'): Tag => ({ id, user_id: 1, trip_id: null, name, color }); +const BEACH = tag(1, 'Beach'); +const WINE = tag(3, 'Wine', ''); + +function state(over: Partial = {}): EntryTags { + return { + all: [BEACH, WINE], + assigned: [], + assignedIds: [], + query: '', + setQuery: vi.fn(), + matches: [BEACH, WINE], + canCreate: false, + toggle: vi.fn(() => Promise.resolve()), + createAndAdd: vi.fn(() => Promise.resolve()), + rename: vi.fn(() => Promise.resolve()), + destroy: vi.fn(() => Promise.resolve()), + busy: false, + ...over, + }; +} + +function mount(over: Partial = {}, data: PlacesLibraryDetailResponse | null = bothOrigins()) { + hook.state = state(over); + const onChanged = vi.fn(); + render(); + return { tags: hook.state, onChanged }; +} + +const openPicker = () => fireEvent.click(screen.getByRole('button', { name: 'placeTags.add' })); + +beforeEach(() => { + hook.args.length = 0; +}); + +describe('EntryTagsSection', () => { + it('FE-COMP-ENTRYTAGSSEC-001: without tags on the place it says they are private, and hands the entry to the hook', () => { + const data = bothOrigins(); + const { onChanged } = mount({}, data); + expect(screen.getByText('placeTags.private')).toBeInTheDocument(); + expect(screen.queryByRole('menu')).toBeNull(); + expect(hook.args[0]).toEqual({ entry: data.entry, onChanged, t }); + + mount({}, null); + expect(hook.args.at(-1)).toMatchObject({ entry: null }); + }); + + it('FE-COMP-ENTRYTAGSSEC-002: shows the carried tags as chips that take a tag off', () => { + const { tags } = mount({ assigned: [{ id: 1, name: 'Beach', color: null }], assignedIds: [1] }); + expect(screen.queryByText('placeTags.private')).toBeNull(); + expect(screen.getByText('Beach')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'placeTags.removeFrom:{"name":"Beach"}' })); + expect(tags.toggle).toHaveBeenCalledWith(1); + }); + + it('FE-COMP-ENTRYTAGSSEC-003: the picker ticks the carried tags and toggles one on a click', () => { + const { tags } = mount({ assignedIds: [3] }); + openPicker(); + expect(screen.getByRole('button', { name: 'placeTags.add' })).toHaveAttribute('aria-expanded', 'true'); + expect(screen.getByRole('menuitemcheckbox', { name: 'Wine' })).toHaveAttribute('aria-checked', 'true'); + expect(screen.getByRole('menuitemcheckbox', { name: 'Beach' })).toHaveAttribute('aria-checked', 'false'); + fireEvent.click(screen.getByRole('menuitemcheckbox', { name: 'Beach' })); + expect(tags.toggle).toHaveBeenCalledWith(1); + }); + + it('FE-COMP-ENTRYTAGSSEC-004: typing goes to the search, and a new name is made from it by click or Enter', () => { + const { tags } = mount({ query: ' Rooftop ', matches: [], canCreate: true }); + openPicker(); + fireEvent.change(screen.getByRole('textbox', { name: 'placeTags.search' }), { target: { value: 'Roof' } }); + expect(tags.setQuery).toHaveBeenCalledWith('Roof'); + expect(screen.queryByText('placeTags.none')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'placeTags.create:{"name":"Rooftop"}' })); + expect(tags.createAndAdd).toHaveBeenCalledTimes(1); + fireEvent.submit(screen.getByRole('textbox', { name: 'placeTags.search' })); + expect(tags.createAndAdd).toHaveBeenCalledTimes(2); + }); + + it('FE-COMP-ENTRYTAGSSEC-005: Enter makes nothing when the name exists, and no match says so', () => { + const { tags } = mount({ query: 'zz', matches: [], canCreate: false }); + openPicker(); + expect(screen.getByText('placeTags.none')).toBeInTheDocument(); + fireEvent.submit(screen.getByRole('textbox', { name: 'placeTags.search' })); + expect(tags.createAndAdd).not.toHaveBeenCalled(); + }); + + it('FE-COMP-ENTRYTAGSSEC-006: the create row is disabled while a change runs', () => { + mount({ query: 'New', matches: [], canCreate: true, busy: true }); + openPicker(); + expect(screen.getByRole('button', { name: 'placeTags.create:{"name":"New"}' })).toBeDisabled(); + }); + + it('FE-COMP-ENTRYTAGSSEC-007: renames a tag in place, or cancels without asking', () => { + const { tags } = mount(); + openPicker(); + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[0]); + const input = screen.getByRole('textbox', { name: 'placeTags.rename' }); + expect(input).toHaveValue('Beach'); + fireEvent.change(input, { target: { value: 'Seaside' } }); + fireEvent.click(screen.getByRole('button', { name: 'common.save' })); + expect(tags.rename).toHaveBeenCalledWith(1, 'Seaside'); + expect(screen.getByRole('menuitemcheckbox', { name: 'Beach' })).toBeInTheDocument(); + + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[1]); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + expect(tags.rename).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('textbox', { name: 'placeTags.rename' })).toBeNull(); + }); + + it('FE-COMP-ENTRYTAGSSEC-008: deleting asks first, and a click in the dialog keeps the picker open', () => { + const { tags } = mount(); + openPicker(); + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.delete' })[1]); + const dialog = screen.getByRole('dialog', { name: 'placeTags.deleteTitle:{"name":"Wine"}' }); + fireEvent.pointerDown(dialog); + expect(screen.getByRole('menu')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'confirm' })); + expect(tags.destroy).toHaveBeenCalledWith(3); + }); + + it('FE-COMP-ENTRYTAGSSEC-009: a press outside closes the picker, one inside keeps it, and the button toggles it', () => { + mount(); + openPicker(); + fireEvent.pointerDown(screen.getByRole('menu')); + expect(screen.getByRole('menu')).toBeInTheDocument(); + fireEvent.pointerDown(document.body); + expect(screen.queryByRole('menu')).toBeNull(); + openPicker(); + openPicker(); + expect(screen.queryByRole('menu')).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/FilterDropdown.test.tsx b/client/src/components/Collections/FilterDropdown.test.tsx index e3a86fe80..6640b9e28 100644 --- a/client/src/components/Collections/FilterDropdown.test.tsx +++ b/client/src/components/Collections/FilterDropdown.test.tsx @@ -24,7 +24,6 @@ describe('FilterDropdown', () => { it('FE-COMP-FILTERDROPDOWN-001: the trigger names the current option and marks the default one', () => { const { trigger } = setup(); expect(trigger).toHaveTextContent('Everything'); - expect(trigger).toHaveAttribute('title', 'Everything'); expect(trigger).toHaveAttribute('aria-haspopup', 'listbox'); expect(trigger).toHaveAttribute('aria-expanded', 'false'); expect(trigger).toHaveClass('is-default'); diff --git a/client/src/components/Collections/LibraryOrigins.test.tsx b/client/src/components/Collections/LibraryOrigins.test.tsx index 69f86f70f..bdb841b32 100644 --- a/client/src/components/Collections/LibraryOrigins.test.tsx +++ b/client/src/components/Collections/LibraryOrigins.test.tsx @@ -23,13 +23,11 @@ describe('LibraryOrigins', () => { expect(originName(tripOrigin({ trip_title: 'Japan 2027' }))).toBe('Japan 2027'); }); - it('FE-COMP-LIBORIGINS-002: trips come before lists, each with a title saying where the place is', () => { + it('FE-COMP-LIBORIGINS-002: trips come before lists', () => { const { container } = render( ); expect(pillTexts(container)).toEqual(['Rome 2026', 'Favourites']); - expect(screen.getByTitle('In the trip Rome 2026')).toBeInTheDocument(); - expect(screen.getByTitle('In the list Favourites')).toBeInTheDocument(); }); it('FE-COMP-LIBORIGINS-003: past two origins the rest is counted', () => { diff --git a/client/src/components/Collections/LibraryPlaceDetail.test.tsx b/client/src/components/Collections/LibraryPlaceDetail.test.tsx index c561658eb..0e9825726 100644 --- a/client/src/components/Collections/LibraryPlaceDetail.test.tsx +++ b/client/src/components/Collections/LibraryPlaceDetail.test.tsx @@ -1,4 +1,4 @@ -// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-013 +// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-017 import userEvent from '@testing-library/user-event'; import type { PlacesLibraryDetailResponse } from '@trek/shared'; import React from 'react'; @@ -19,6 +19,22 @@ import { type NavigationTarget, openNavigationTarget } from '../Planner/placeNav import LibraryPlaceDetail from './LibraryPlaceDetail'; const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] })); +/** The props each section below the origins was last handed; they read their own stores. */ +const sections = vi.hoisted(() => ({}) as Record>); +const section = vi.hoisted( + () => (name: string) => + function Section(props: Record) { + sections[name] = props; + return
; + } +); + +vi.mock('./EntryTagsSection', () => ({ default: section('tags') })); +vi.mock('./OriginNotesSection', () => ({ default: section('notes') })); +vi.mock('./PlaceMediaSection', () => ({ default: section('media') })); +vi.mock('./VisitsSection', () => ({ default: section('visits') })); +vi.mock('./PlaceActivitiesSection', () => ({ default: section('activities') })); +vi.mock('./PlaceHistorySection', () => ({ default: section('history') })); vi.mock('../Planner/placeNavigation', () => ({ getNavigationTargets: () => nav.targets, @@ -82,6 +98,7 @@ function setup(over: Partial = {}) { onOpenTrip: vi.fn(), onSaveToList: vi.fn(), onCopyToTrip: vi.fn(), + onNotesSaved: vi.fn(), ...over, }; const view = render(); @@ -91,6 +108,7 @@ function setup(over: Partial = {}) { beforeEach(() => { nav.targets = []; vi.mocked(openNavigationTarget).mockClear(); + for (const key of Object.keys(sections)) delete sections[key]; }); describe('LibraryPlaceDetail: the sheet', () => { @@ -142,7 +160,7 @@ describe('LibraryPlaceDetail: the sheet', () => { }); describe('LibraryPlaceDetail: where the place sits', () => { - it('FE-COMP-LIBPLACEDETAIL-006: a trip shows its planned day, its name there, a stay, a booking and its notes', async () => { + it('FE-COMP-LIBPLACEDETAIL-006: a trip shows its planned day, its name there, a stay and a booking, its notes go below', async () => { const user = userEvent.setup(); const { props } = setup(); expect(screen.getByText('In your trips')).toBeInTheDocument(); @@ -152,18 +170,19 @@ describe('LibraryPlaceDetail: where the place sits', () => { expect(within(card).getByText('Called Colosseo here')).toBeInTheDocument(); expect(within(card).getByText('Stay')).toBeInTheDocument(); expect(within(card).getByText('Booking')).toBeInTheDocument(); - expect(within(card).getByText('Book the underground tour')).toBeInTheDocument(); + // The notes moved out of the card into the notes section under the origins. + expect(within(card).queryByText('Book the underground tour')).not.toBeInTheDocument(); await user.click(card); expect(props.onOpenTrip).toHaveBeenCalledWith(5, 42); }); - it('FE-COMP-LIBPLACEDETAIL-007: a list shows its status, labels and votes, and no notes when they are blank', async () => { + it('FE-COMP-LIBPLACEDETAIL-007: a list beside a trip shows its status under its name, its labels and votes', async () => { const user = userEvent.setup(); const { props } = setup(); expect(screen.getByText('In your lists')).toBeInTheDocument(); const card = screen.getByRole('button', { name: 'Open in the list: Favourites' }); - expect(within(card).getByText('Want to go')).toBeInTheDocument(); + expect(card.querySelector('.col-origin-title .sub')?.textContent).toBe('Want to go'); expect(within(card).getByText('Must see')).toBeInTheDocument(); expect(within(card).getByText('4.5 from 2 votes')).toBeInTheDocument(); expect(within(card).queryByText('Notes')).not.toBeInTheDocument(); @@ -243,3 +262,49 @@ describe('LibraryPlaceDetail: what to do with it', () => { expect(screen.queryByRole('menu')).not.toBeInTheDocument(); }); }); + +describe('LibraryPlaceDetail: the look of its origins and the sections below', () => { + it('FE-COMP-LIBPLACEDETAIL-014: a trip with a cover shows it, a list wears its own symbol and colour', () => { + const entry = libraryEntry({ + origins: [ + tripOrigin({ trip_cover: '/uploads/covers/rome.jpg' }), + listOrigin({ collection_color: '#ff0000', collection_icon: 'star' }), + ], + }); + const { container } = setup({ data: libraryDetail(entry, [tripDetail(), listDetail()]) }); + expect(container.querySelector('.col-origin-cover')).toHaveAttribute('src', '/uploads/covers/rome.jpg'); + const ico = container.querySelector('.col-origin-ico-list'); + expect(ico?.style.getPropertyValue('--list')).toBe('#ff0000'); + expect(container.querySelector('.col-origin-pair')).not.toBeNull(); + }); + + it('FE-COMP-LIBPLACEDETAIL-015: a list on its own keeps its status badge and the accent colour', () => { + const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] }); + const { container } = setup({ data: libraryDetail(entry, [listDetail()]) }); + const card = screen.getByRole('button', { name: 'Open in the list: Favourites' }); + expect(within(card).getByText('Want to go')).toBeInTheDocument(); + expect(card.querySelector('.col-origin-title .sub')).toBeNull(); + expect(container.querySelector('.col-origin-ico-list')?.style.getPropertyValue('--list')).toBe( + 'var(--accent)' + ); + expect(container.querySelector('.col-origin-pair')).toBeNull(); + }); + + it('FE-COMP-LIBPLACEDETAIL-016: tags, notes, media, visits, activities and history follow, wired to the place', () => { + const { props } = setup(); + for (const name of ['tags', 'notes', 'media', 'visits', 'activities', 'history']) { + expect(screen.getByTestId(`section-${name}`)).toBeInTheDocument(); + } + expect(sections.tags).toMatchObject({ data: props.data, onChanged: props.onNotesSaved }); + expect(sections.notes).toMatchObject({ data: props.data, onSaved: props.onNotesSaved }); + expect(sections.media).toMatchObject({ entry: props.data?.entry }); + expect(sections.visits).toMatchObject({ entry: props.data?.entry, language: 'en' }); + expect(sections.activities).toMatchObject({ entry: props.data?.entry, language: 'en' }); + expect(sections.history).toMatchObject({ entry: props.data?.entry, language: 'en' }); + }); + + it('FE-COMP-LIBPLACEDETAIL-017: while it loads no section is drawn', () => { + setup({ data: null, loading: true }); + expect(screen.queryByTestId('section-notes')).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/OriginNotesSection.test.tsx b/client/src/components/Collections/OriginNotesSection.test.tsx new file mode 100644 index 000000000..474639442 --- /dev/null +++ b/client/src/components/Collections/OriginNotesSection.test.tsx @@ -0,0 +1,91 @@ +// FE-COMP-ORIGINNOTESSEC-001 to FE-COMP-ORIGINNOTESSEC-005: the notes section of the desktop place sheet. +import type { PlacesLibraryDetailResponse } from '@trek/shared'; +import type { MockInstance } from 'vitest'; + +import { + libraryDetail, + libraryEntry, + listDetail, + listOrigin, + tripDetail, + tripOrigin, +} from '../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'; +import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; +import OriginNotesSection from './OriginNotesSection'; + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('../shared/Toast', () => { + const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() }; + return { useToast: () => toast }; +}); + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +function data(tripNotes: string | null, canEdit = true): PlacesLibraryDetailResponse { + const entry = libraryEntry({ + origins: [tripOrigin({ can_edit: canEdit }), listOrigin({ can_edit: canEdit })], + }); + return libraryDetail(entry, [tripDetail({ notes: tripNotes }), listDetail()]); +} + +let saveNotes: MockInstance; + +beforeEach(() => { + toastError.mockReset(); + saveNotes = vi.spyOn(placesLibraryRepo, 'saveNotes').mockResolvedValue(undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('OriginNotesSection', () => { + it('FE-COMP-ORIGINNOTESSEC-001: nothing to read and nowhere to write leaves the section out', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-ORIGINNOTESSEC-002: a read-only note shows with its source and no pencil or add', () => { + render(); + expect(screen.getByText('collections.notes')).toBeInTheDocument(); + expect(screen.getByText('Rome 2026')).toBeInTheDocument(); + expect(screen.getByText('Buy tickets online')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'placeNotes.edit' })).toBeNull(); + expect(screen.queryByRole('button', { name: /placeNotes\.add/ })).toBeNull(); + }); + + it('FE-COMP-ORIGINNOTESSEC-003: edits a note in place and saves it', async () => { + const onSaved = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'placeNotes.edit' })); + const field = screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Rome 2026"}' }); + expect(field).toHaveValue('Buy tickets online'); + // The pencil hides while its note is open. + expect(screen.queryByRole('button', { name: 'placeNotes.edit' })).toBeNull(); + fireEvent.change(field, { target: { value: 'Tickets at the gate' } }); + fireEvent.click(screen.getByRole('button', { name: 'common.save' })); + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(saveNotes).toHaveBeenCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, 'Tickets at the gate'); + expect(screen.queryByRole('textbox')).toBeNull(); + }); + + it('FE-COMP-ORIGINNOTESSEC-004: "+ Note" goes straight to the one empty place, and cancel closes it', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: /placeNotes\.add/ })); + expect(screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Favourites"}' })).toHaveValue(''); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + expect(screen.queryByRole('textbox')).toBeNull(); + expect(saveNotes).not.toHaveBeenCalled(); + }); + + it('FE-COMP-ORIGINNOTESSEC-005: with several empty places "+ Note" asks which one, then opens it', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: /placeNotes\.add/ })); + expect(screen.queryByRole('textbox')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: /Favourites/ })); + expect(screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Favourites"}' })).toBeInTheDocument(); + // The chooser closes and the other trip stays a target. + expect(screen.queryByRole('button', { name: /Rome 2026/ })).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/PlaceActivitiesSection.test.tsx b/client/src/components/Collections/PlaceActivitiesSection.test.tsx new file mode 100644 index 000000000..87b75135c --- /dev/null +++ b/client/src/components/Collections/PlaceActivitiesSection.test.tsx @@ -0,0 +1,115 @@ +// FE-COMP-PLACEACTSECTION-001 to FE-COMP-PLACEACTSECTION-006: the tours and bookings of a +// place in the desktop sheet of All places (PLC-18), against a mocked hook. +import { + activitiesState, + activityCandidate, + listSource, + placeActivity, + tripSource, +} from '../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import PlaceActivitiesSection from './PlaceActivitiesSection'; +import { usePlaceActivities } from './usePlaceActivities'; + +const mockNavigate = vi.fn(); +vi.mock('react-router', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, useNavigate: () => mockNavigate }; +}); + +vi.mock('./usePlaceActivities', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, usePlaceActivities: vi.fn() }; +}); + +const hook = vi.mocked(usePlaceActivities); +const t = (k: string) => k; + +function show(state = activitiesState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + mockNavigate.mockClear(); + hook.mockReset(); +}); + +describe('PlaceActivitiesSection', () => { + it('FE-COMP-PLACEACTSECTION-001: is not there with nothing linked and nothing to link', () => { + show(); + expect(screen.queryByText('placeActivities.title')).toBeNull(); + }); + + it('FE-COMP-PLACEACTSECTION-002: an activity opens where it lives, a said link comes off again', () => { + const linked = placeActivity(); + const implicit = placeActivity({ + key: 'tour:8', + type: 'tour', + title: 'Forum walk', + target: { kind: 'tour', trip_id: 5, tour_id: 8 }, + can_unlink: false, + }); + const state = show(activitiesState({ activities: [linked, implicit] })); + fireEvent.click(screen.getByRole('button', { name: /Colosseum tickets/ })); + expect(mockNavigate).toHaveBeenCalledWith('/trips/5?booking=7'); + fireEvent.click(screen.getByRole('button', { name: /Forum walk/ })); + expect(mockNavigate).toHaveBeenLastCalledWith('/trips/5?tour=8'); + const unlink = screen.getAllByRole('button', { name: 'placeActivities.unlink' }); + expect(unlink).toHaveLength(1); + fireEvent.click(unlink[0]); + expect(state.unlink).toHaveBeenCalledWith(linked); + expect(screen.getByText('placeActivities.atThisPlace')).toBeInTheDocument(); + // Nothing more to link: no "+ Link". + expect(screen.queryByRole('button', { name: /placeActivities\.link/ })).toBeNull(); + }); + + it('FE-COMP-PLACEACTSECTION-003: with nothing linked yet but rights to link, it says so and offers the picker', () => { + const state = show(activitiesState({ canLink: true })); + expect(screen.getByText('placeActivities.none')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /placeActivities\.link/ })); + expect(state.openPicker).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEACTSECTION-004: the picker lists the candidates of every source and links the picked one', () => { + const booking = activityCandidate(); + const tour = activityCandidate({ key: 'collection_tour:3', type: 'tour', title: 'Old town walk' }); + const state = show( + activitiesState({ + canLink: true, + picking: [ + { source: tripSource(), candidates: [booking] }, + { source: listSource(), candidates: [tour] }, + ], + }) + ); + expect(screen.getByText('placeActivities.pickTitle')).toBeInTheDocument(); + expect(screen.queryByText('placeActivities.none')).toBeNull(); + expect(screen.queryByText('placeActivities.nothingToLink')).toBeNull(); + // The "+ Link" button gives way to the open picker. + expect(screen.queryByRole('button', { name: /placeActivities\.link/ })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: /Old town walk/ })); + expect(state.link).toHaveBeenCalledWith(listSource(), tour); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(state.closePicker).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEACTSECTION-005: a picker without candidates says there is nothing to link', () => { + show(activitiesState({ canLink: true, picking: [{ source: tripSource(), candidates: [] }] })); + expect(screen.getByText('placeActivities.nothingToLink')).toBeInTheDocument(); + }); + + it('FE-COMP-PLACEACTSECTION-006: while a write runs the buttons wait', () => { + show( + activitiesState({ + activities: [placeActivity()], + canLink: true, + busy: true, + }) + ); + expect(screen.getByRole('button', { name: /placeActivities\.link/ })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'placeActivities.unlink' })).toBeDisabled(); + }); +}); diff --git a/client/src/components/Collections/PlaceHistorySection.test.tsx b/client/src/components/Collections/PlaceHistorySection.test.tsx new file mode 100644 index 000000000..d0baf95ce --- /dev/null +++ b/client/src/components/Collections/PlaceHistorySection.test.tsx @@ -0,0 +1,72 @@ +// FE-COMP-PLACEHISTSECTION-001 to FE-COMP-PLACEHISTSECTION-005: the change history of a +// place in the desktop sheet of All places (PLC-14), against a mocked hook. +import { historyEntries, historyEntry, historyState } from '../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import PlaceHistorySection from './PlaceHistorySection'; +import { usePlaceHistory } from './usePlaceHistory'; + +vi.mock('./usePlaceHistory', () => ({ usePlaceHistory: vi.fn() })); + +const hook = vi.mocked(usePlaceHistory); +const t = (k: string) => k; + +function show(state = historyState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + hook.mockReset(); +}); + +describe('PlaceHistorySection', () => { + it('FE-COMP-PLACEHISTSECTION-001: is not there before the first change', () => { + show(); + expect(screen.queryByText('placeHistory.title')).toBeNull(); + }); + + it('FE-COMP-PLACEHISTSECTION-002: a change shows the detail, from and to, the trip, who and when', () => { + show(historyState({ entries: [historyEntry()] })); + expect(screen.getByText('placeHistory.field.name')).toBeInTheDocument(); + expect(screen.getByText('Colosseo')).toHaveClass('line-through'); + expect(screen.getByText('Colosseum')).toBeInTheDocument(); + expect(screen.getByText(/Rome 2026/)).toHaveTextContent(/anna/); + expect(screen.queryByRole('button')).toBeNull(); + }); + + it('FE-COMP-PLACEHISTSECTION-003: a list change names the list, a picture change only its detail', () => { + show( + historyState({ + entries: [ + historyEntry({ + field: 'image', + old_value: '/a.jpg', + new_value: '/b.jpg', + origin: { kind: 'list', collection_id: 9, collection_name: 'Favourites', collection_place_id: 900 }, + }), + ], + }) + ); + expect(screen.getByText(/Favourites/)).toBeInTheDocument(); + expect(screen.queryByText('/b.jpg')).toBeNull(); + }); + + it('FE-COMP-PLACEHISTSECTION-004: shows three at first, then all, then reads more', () => { + const state = show(historyState({ entries: historyEntries(5), hasMore: true })); + expect(screen.getAllByRole('listitem')).toHaveLength(3); + fireEvent.click(screen.getByRole('button', { name: 'placeHistory.showAll' })); + expect(screen.getAllByRole('listitem')).toHaveLength(5); + expect(state.more).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'placeHistory.more' })); + expect(state.more).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEHISTSECTION-005: once all are open and none are left, the button goes', () => { + show(historyState({ entries: historyEntries(4) })); + fireEvent.click(screen.getByRole('button', { name: 'placeHistory.showAll' })); + expect(screen.getAllByRole('listitem')).toHaveLength(4); + expect(screen.queryByRole('button')).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/PlaceLocationBadge.test.tsx b/client/src/components/Collections/PlaceLocationBadge.test.tsx new file mode 100644 index 000000000..9ba0ceb01 --- /dev/null +++ b/client/src/components/Collections/PlaceLocationBadge.test.tsx @@ -0,0 +1,34 @@ +// FE-COMP-PLACELOCBADGE-001 to FE-COMP-PLACELOCBADGE-004: where a place is, under its name +// on the cover of a place sheet. +import { render, screen } from '../../../tests/helpers/render'; +import PlaceLocationBadge, { coordsText } from './PlaceLocationBadge'; + +const t = (k: string) => k; + +describe('PlaceLocationBadge', () => { + it('FE-COMP-PLACELOCBADGE-001: coordinates read with five decimals', () => { + expect(coordsText(41.890251, 12.4922309)).toBe('41.89025, 12.49223'); + expect(coordsText(-3, 0)).toBe('-3.00000, 0.00000'); + }); + + it('FE-COMP-PLACELOCBADGE-002: a placed place shows its address', () => { + render(); + const badge = screen.getByText('Piazza del Colosseo').parentElement; + expect(badge).toHaveClass('place-loc-badge'); + expect(badge).not.toHaveClass('unplaced'); + }); + + it('FE-COMP-PLACELOCBADGE-003: without an address the coordinates stand in', () => { + render(); + expect(screen.getByText('41.89000, 12.49000')).toBeInTheDocument(); + }); + + it('FE-COMP-PLACELOCBADGE-004: a place without a position says so and wears the warning pin', () => { + const { rerender } = render(); + expect(screen.getByText('places.noCoordinates').parentElement).toHaveClass('place-loc-badge', 'unplaced'); + expect(screen.getByLabelText('places.noCoordinates')).toBeInTheDocument(); + // An address still shows, but the pin keeps warning. + rerender(); + expect(screen.getByText('Somewhere').parentElement).toHaveClass('unplaced'); + }); +}); diff --git a/client/src/components/Collections/PlaceMediaSection.test.tsx b/client/src/components/Collections/PlaceMediaSection.test.tsx new file mode 100644 index 000000000..6f43b1a5a --- /dev/null +++ b/client/src/components/Collections/PlaceMediaSection.test.tsx @@ -0,0 +1,65 @@ +// FE-COMP-PLACEMEDIASECTION-001 to FE-COMP-PLACEMEDIASECTION-004: the pictures and trip files +// of a place in the desktop sheet of All places (PLC-19, PLC-20), against a mocked hook. +import { mediaFile, mediaState, photos } from '../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import PlaceMediaSection from './PlaceMediaSection'; +import { usePlaceMedia } from './usePlaceMedia'; + +vi.mock('./usePlaceMedia', () => ({ usePlaceMedia: vi.fn() })); +vi.mock('../Journey/PhotoLightbox', () => ({ + default: (p: { photos: { id: string }[]; startIndex: number; label?: string; onClose: () => void }) => ( +
+ {`${p.photos.length} from ${p.startIndex}`} + +
+ ), +})); + +const hook = vi.mocked(usePlaceMedia); +const t = (k: string) => k; + +function show(state = mediaState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + hook.mockReset(); +}); + +describe('PlaceMediaSection', () => { + it('FE-COMP-PLACEMEDIASECTION-001: is not there without pictures or files', () => { + show(); + expect(screen.queryByText('places.media.photos')).toBeNull(); + expect(screen.queryByText('places.media.files')).toBeNull(); + }); + + it('FE-COMP-PLACEMEDIASECTION-002: a picture opens the lightbox at its place', () => { + const state = show(mediaState({ photos: photos(2) })); + expect(screen.queryByText('places.media.files')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Photo 1' })); + expect(state.setOpen).toHaveBeenCalledWith(1); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-COMP-PLACEMEDIASECTION-003: shows eight and counts the rest on the last', () => { + show(mediaState({ photos: photos(11) })); + expect(screen.getAllByRole('button')).toHaveLength(8); + expect(screen.getByText('+3')).toBeInTheDocument(); + }); + + it('FE-COMP-PLACEMEDIASECTION-004: the open picture shows in the lightbox, and files link to their trip', () => { + const state = show(mediaState({ photos: photos(3), files: [mediaFile()], open: 2 })); + expect(screen.getByRole('dialog', { name: 'Colosseum' })).toHaveTextContent('3 from 2'); + fireEvent.click(screen.getByRole('button', { name: 'close lightbox' })); + expect(state.close).toHaveBeenCalledTimes(1); + const file = screen.getByRole('link', { name: /tickets\.pdf/ }); + expect(file).toHaveAttribute('href', '/trips/5/files?file=31'); + expect(file).toHaveAttribute('target', '_blank'); + expect(file).toHaveTextContent('Rome 2026'); + }); +}); diff --git a/client/src/components/Collections/PlacesLibraryView.test.tsx b/client/src/components/Collections/PlacesLibraryView.test.tsx index c8882ee6b..70ffd2bb3 100644 --- a/client/src/components/Collections/PlacesLibraryView.test.tsx +++ b/client/src/components/Collections/PlacesLibraryView.test.tsx @@ -368,6 +368,9 @@ describe('PlacesLibraryView: the place sheet', () => { await modal.onCopy(7, carry); }); expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry); + // The copy adds an origin, so the place is read again; a saved note does the same. + expect(captured(seen.lib).reload).toHaveBeenCalledTimes(1); + expect(captured(seen.detail).onNotesSaved).toBe(captured(seen.lib).reload); act(() => modal.onClose()); expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument(); diff --git a/client/src/components/Collections/SaveToCollectionModal.test.tsx b/client/src/components/Collections/SaveToCollectionModal.test.tsx index 75372b693..3fc92e456 100644 --- a/client/src/components/Collections/SaveToCollectionModal.test.tsx +++ b/client/src/components/Collections/SaveToCollectionModal.test.tsx @@ -316,7 +316,7 @@ describe('SaveToCollectionModal', () => { await screen.findByText('Favorites'); expect(screen.queryByRole('button', { name: 'Want to go' })).not.toBeInTheDocument(); - expect(screen.getByTitle('Want to go')).toBeInTheDocument(); + expect(screen.getByRole('img', { name: 'Want to go' })).toBeInTheDocument(); // Nothing to offer: the only list holding it is one the viewer cannot edit. expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument(); }); diff --git a/client/src/components/Collections/StatusBadge.test.tsx b/client/src/components/Collections/StatusBadge.test.tsx index 7ffedf165..33ea7d454 100644 --- a/client/src/components/Collections/StatusBadge.test.tsx +++ b/client/src/components/Collections/StatusBadge.test.tsx @@ -99,13 +99,10 @@ describe('StatusBadge', () => { expect(onChange).toHaveBeenCalledWith('want'); }); - it('FE-COMP-STATUSBADGE-010: interactive badge advertises the cycle hint in its title', () => { + it('FE-COMP-STATUSBADGE-010: interactive badge is named by its status, the cycle hint lives in the tooltip', () => { render(); - // English: 'collections.status.cycleHint' = 'tap to change' - expect(screen.getByRole('button', { name: 'Idea' })).toHaveAttribute( - 'title', - 'Idea — tap to change', - ); + const badge = screen.getByRole('button', { name: 'Idea' }); + expect(badge).not.toHaveAttribute('title'); }); // ── Read-only (onChange omitted) ───────────────────────────────────────────── @@ -116,12 +113,11 @@ describe('StatusBadge', () => { expect(screen.queryByRole('button')).not.toBeInTheDocument(); }); - it('FE-COMP-STATUSBADGE-012: read-only badge uses the plain label as its title (no cycle hint)', () => { + it('FE-COMP-STATUSBADGE-012: read-only badge shows its word and needs no tooltip', () => { render(); const label = screen.getByText('Visited'); const pill = label.parentElement as HTMLElement; - expect(pill).toHaveAttribute('title', 'Visited'); - expect(pill.getAttribute('title')).not.toMatch(/tap to change/i); + expect(pill).not.toHaveAttribute('title'); }); it('FE-COMP-STATUSBADGE-013: clicking a read-only badge does not throw', async () => { diff --git a/client/src/components/Collections/TagFilterDropdown.test.tsx b/client/src/components/Collections/TagFilterDropdown.test.tsx new file mode 100644 index 000000000..3a8d9498d --- /dev/null +++ b/client/src/components/Collections/TagFilterDropdown.test.tsx @@ -0,0 +1,78 @@ +// FE-COMP-TAGFILTER-001 to FE-COMP-TAGFILTER-005 +import type { Tag } from '@trek/shared'; + +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import TagFilterDropdown from './TagFilterDropdown'; + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +const tag = (id: number, name: string, color = '#aa0000'): Tag => ({ id, user_id: 1, trip_id: null, name, color }); +const TAGS = [tag(1, 'Beach'), tag(2, 'Coffee', '')]; + +function mount(picked: number[], onToggle = vi.fn()) { + render(); + return onToggle; +} + +describe('TagFilterDropdown', () => { + it('FE-COMP-TAGFILTER-001: is not drawn while the reader has no tags', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-TAGFILTER-002: the button names all tags, the one picked tag, or the count of picks', () => { + const { rerender } = render(); + const all = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' }); + expect(all).toHaveClass('is-default'); + expect(all).toHaveAttribute('aria-expanded', 'false'); + + rerender(); + expect(screen.getByRole('button', { name: 'placeTags.title: Coffee' })).not.toHaveClass('is-default'); + + rerender(); + expect( + screen.getByRole('button', { name: 'placeTags.title: placeTags.filterCount:{"count":2}' }) + ).toBeInTheDocument(); + + // A pick whose tag is gone names nothing rather than failing. + rerender(); + expect(screen.getByRole('button', { name: 'placeTags.title:' })).toBeInTheDocument(); + }); + + it('FE-COMP-TAGFILTER-003: opens a list with the picks marked and toggles a tag on a click', () => { + const onToggle = mount([1]); + fireEvent.click(screen.getByRole('button', { name: 'placeTags.title: Beach' })); + expect(screen.getByRole('listbox')).toHaveAttribute('aria-multiselectable', 'true'); + expect(screen.getByRole('option', { name: 'Beach' })).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('option', { name: 'Coffee' })).toHaveAttribute('aria-selected', 'false'); + fireEvent.click(screen.getByRole('option', { name: 'Coffee' })); + expect(onToggle).toHaveBeenCalledWith(2); + // Several picks at once: the list stays open after a pick. + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); + + it('FE-COMP-TAGFILTER-004: Escape and a press outside close the list, a press inside keeps it', () => { + mount([]); + const button = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' }); + fireEvent.click(button); + fireEvent.keyDown(document, { key: 'Enter' }); + expect(screen.getByRole('listbox')).toBeInTheDocument(); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('listbox')).toBeNull(); + + fireEvent.click(button); + fireEvent.mouseDown(screen.getByRole('listbox')); + expect(screen.getByRole('listbox')).toBeInTheDocument(); + fireEvent.mouseDown(document.body); + expect(screen.queryByRole('listbox')).toBeNull(); + }); + + it('FE-COMP-TAGFILTER-005: the button closes the list it opened', () => { + mount([]); + const button = screen.getByRole('button', { name: 'placeTags.title: placeTags.filterAll' }); + fireEvent.click(button); + expect(button).toHaveAttribute('aria-expanded', 'true'); + fireEvent.click(button); + expect(screen.queryByRole('listbox')).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/TripListsPill.test.tsx b/client/src/components/Collections/TripListsPill.test.tsx new file mode 100644 index 000000000..e9f411d67 --- /dev/null +++ b/client/src/components/Collections/TripListsPill.test.tsx @@ -0,0 +1,143 @@ +// FE-COMP-TRIPLISTSPILL-001 to FE-COMP-TRIPLISTSPILL-008: the trip map's control for the +// lists a trip draws on, rendered against a stubbed useTripLists result. +import type { Collection, TripCollectionLink } from '@trek/shared'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import { TripListsPill } from './TripListsPill'; +import type { useTripLists } from './useTripLists'; + +const navigate = vi.hoisted(() => vi.fn()); +vi.mock('react-router', async (importOriginal) => ({ + ...(await importOriginal()), + useNavigate: () => navigate, +})); + +type TripLists = ReturnType; + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +function link(collectionId: number, over: Partial = {}): TripCollectionLink { + return { + collection_id: collectionId, + name: `List ${collectionId}`, + color: null, + role: 'owner', + place_count: 3, + linked_by: 1, + created_at: null, + ...over, + }; +} + +function lists(over: Partial = {}): TripLists { + return { + links: [], + canLink: true, + visible: [], + pois: [], + toggle: vi.fn(), + claim: vi.fn(), + pending: null, + cancelPending: vi.fn(), + addPending: vi.fn().mockResolvedValue(undefined), + busy: false, + linkable: [], + loadLinkable: vi.fn(), + link: vi.fn().mockResolvedValue(undefined), + unlink: vi.fn().mockResolvedValue(undefined), + lookOf: new Map(), + ...over, + } as TripLists; +} + +const openCard = () => fireEvent.click(screen.getByTestId('trip-lists-pill')); + +beforeEach(() => navigate.mockReset()); + +describe('TripListsPill', () => { + it('FE-COMP-TRIPLISTSPILL-001: draws nothing without a linked list or the right to link one', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-TRIPLISTSPILL-002: opens a card that says nothing is linked yet', () => { + render(); + expect(screen.queryByRole('dialog')).toBeNull(); + openCard(); + expect(screen.getByRole('dialog', { name: 'tripLists.title' })).toBeInTheDocument(); + expect(screen.getByText('tripLists.none')).toBeInTheDocument(); + }); + + it('FE-COMP-TRIPLISTSPILL-003: each linked list is shown or hidden, opened in Places and unlinked', () => { + const value = lists({ links: [link(9, { name: 'Food' }), link(10, { name: 'Bars' })], visible: [9] }); + render(); + openCard(); + expect(screen.getByText('Food')).toBeInTheDocument(); + expect(screen.getAllByText('tripLists.places:{"count":3}')).toHaveLength(2); + + const hide = screen.getByRole('button', { name: 'tripLists.hide' }); + expect(hide).toHaveAttribute('aria-pressed', 'true'); + const show = screen.getByRole('button', { name: 'tripLists.show' }); + expect(show).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(show); + expect(value.toggle).toHaveBeenCalledWith(10); + + fireEvent.click(screen.getAllByRole('button', { name: 'tripLists.open' })[0]); + expect(navigate).toHaveBeenCalledWith(expect.stringMatching(/\/9$/)); + + fireEvent.click(screen.getAllByRole('button', { name: 'tripLists.unlink' })[1]); + expect(value.unlink).toHaveBeenCalledWith(10); + }); + + it('FE-COMP-TRIPLISTSPILL-004: a reader who may not link sees the lists without unlink or link', () => { + render(); + openCard(); + expect(screen.queryByRole('button', { name: 'tripLists.unlink' })).toBeNull(); + expect(screen.queryByText('tripLists.link')).toBeNull(); + }); + + it('FE-COMP-TRIPLISTSPILL-005: linking reads the reader lists, offers the unlinked ones and links the pick', () => { + const value = lists({ + linkable: [{ id: 12, name: 'Museums', color: '#0a0', icon: 'star' } as Collection], + }); + render(); + openCard(); + fireEvent.click(screen.getByRole('button', { name: /tripLists\.link/ })); + expect(value.loadLinkable).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole('button', { name: 'Museums' })); + expect(value.link).toHaveBeenCalledWith(12); + // The picker closes again, the way in comes back. + expect(screen.queryByRole('button', { name: 'Museums' })).toBeNull(); + expect(screen.getByRole('button', { name: /tripLists\.link/ })).toBeInTheDocument(); + }); + + it('FE-COMP-TRIPLISTSPILL-006: with everything linked the picker says so', () => { + render(); + openCard(); + fireEvent.click(screen.getByRole('button', { name: /tripLists\.link/ })); + expect(screen.getByText('tripLists.nothingToLink')).toBeInTheDocument(); + }); + + it('FE-COMP-TRIPLISTSPILL-007: Escape and a press outside close the card', () => { + render(); + openCard(); + fireEvent.keyDown(document, { key: 'Enter' }); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('dialog')).toBeNull(); + + openCard(); + fireEvent.pointerDown(screen.getByRole('dialog')); + expect(screen.getByRole('dialog')).toBeInTheDocument(); + fireEvent.pointerDown(document.body); + expect(screen.queryByRole('dialog')).toBeNull(); + }); + + it('FE-COMP-TRIPLISTSPILL-008: a pending saved place asks before it joins the trip', () => { + const value = lists({ pending: { id: 5, name: 'Bakery' } }); + render(); + expect(screen.getByText('tripLists.addMessage:{"name":"Bakery"}')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'tripLists.add' })); + expect(value.addPending).toHaveBeenCalledTimes(1); + expect(value.cancelPending).toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Collections/VisitsSection.test.tsx b/client/src/components/Collections/VisitsSection.test.tsx new file mode 100644 index 000000000..c2af8e24f --- /dev/null +++ b/client/src/components/Collections/VisitsSection.test.tsx @@ -0,0 +1,127 @@ +// FE-COMP-VISITS-001 to FE-COMP-VISITS-009: the visits of a place in All places and the planner, and the visited tick. +import type { PlaceVisit } from '@trek/shared'; + +import { libraryEntry } from '../../../tests/helpers/placesLibrary'; +import { render, screen } from '../../../tests/helpers/render'; +import { visitDate } from './libraryDates'; +import TripPlaceVisits from './TripPlaceVisits'; +import { usePlaceVisits } from './usePlaceVisits'; +import VisitedMark from './VisitedMark'; +import VisitsSection from './VisitsSection'; + +vi.mock('./usePlaceVisits', async (importOriginal) => ({ + ...(await importOriginal()), + usePlaceVisits: vi.fn(), +})); + +const hook = vi.mocked(usePlaceVisits); +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +function visit(over: Partial = {}): PlaceVisit { + return { + visited_on: '2026-07-02', + visited_time: null, + trip: { id: 5, title: 'Rome 2026' }, + place_id: 42, + day_id: 3, + day_number: 2, + name: 'Colosseum', + participants: [], + ...over, + }; +} + +function visits(list: PlaceVisit[], lastVisit: string | null = '2026-07-02') { + hook.mockReturnValue({ visits: list, count: list.length, lastVisit, loading: false }); +} + +const PEOPLE = [ + { id: 1, username: 'anna', avatar_url: null }, + { id: 2, username: 'ben', avatar_url: '/uploads/ben.png' }, +]; + +beforeEach(() => { + hook.mockReset(); +}); + +describe('VisitsSection', () => { + it('FE-COMP-VISITS-001: without visits the section is not there', () => { + visits([]); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-VISITS-002: a count without a readable last date shows nothing either', () => { + hook.mockReturnValue({ visits: [visit()], count: 1, lastVisit: 'garbage', loading: false }); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-VISITS-003: lists every visit with its day and trip under the summary', () => { + visits([ + visit({ visited_time: '10:00' }), + visit({ visited_on: '2025-05-01', trip: { id: 6, title: 'Rome 2025' }, day_id: 9 }), + ]); + render(); + expect(screen.getByText('visits.title')).toBeInTheDocument(); + const last = visitDate('2026-07-02', null, 'en-GB'); + expect(screen.getByText(`visits.summary:${JSON.stringify({ count: 2, date: last })}`)).toBeInTheDocument(); + expect(screen.getByText(visitDate('2026-07-02', '10:00', 'en-GB') as string)).toBeInTheDocument(); + expect(screen.getByText(visitDate('2025-05-01', null, 'en-GB') as string)).toBeInTheDocument(); + expect(screen.getByText('Rome 2026')).toBeInTheDocument(); + expect(screen.getByText('Rome 2025')).toBeInTheDocument(); + expect(hook).toHaveBeenCalledWith({ entry: expect.objectContaining({ key: 'trip:42' }) }); + }); + + it('FE-COMP-VISITS-004: shows who was there only when more than one person was', () => { + visits([visit({ participants: [PEOPLE[0]] }), visit({ day_id: 4, participants: PEOPLE })]); + const { container } = render(); + // One avatar letter for anna and one picture for ben, from the second visit only. + expect(screen.getAllByText('A')).toHaveLength(1); + expect(container.querySelectorAll('img[src="/uploads/ben.png"]')).toHaveLength(1); + }); +}); + +describe('TripPlaceVisits', () => { + const trip = { id: 5, title: 'Rome 2026', start_date: '2026-07-01', end_date: '2026-07-05' }; + const place = { id: 42, name: 'Colosseum' }; + + it('FE-COMP-VISITS-005: reads the visits through the trip place and sums them up', () => { + visits([visit(), visit({ day_id: 4 })]); + render(); + const last = visitDate('2026-07-02', null, 'en-GB'); + expect(screen.getByText(`visits.summary:${JSON.stringify({ count: 2, date: last })}`)).toBeInTheDocument(); + expect(hook).toHaveBeenCalledWith({ + entry: expect.objectContaining({ + key: 'trip:42', + origins: [expect.objectContaining({ kind: 'trip', trip_id: 5, place_id: 42 })], + }), + }); + }); + + it('FE-COMP-VISITS-006: not shown before the first visit', () => { + visits([], null); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); +}); + +describe('VisitedMark', () => { + it('FE-COMP-VISITS-007: no tick for a place never visited', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + const zero = render(); + expect(zero.container).toBeEmptyDOMElement(); + }); + + it('FE-COMP-VISITS-008: one visit is a plain tick named by the count', () => { + render(); + const mark = screen.getByRole('img', { name: 'visits.visitedTimes:{"count":1}' }); + expect(mark).not.toHaveTextContent('1'); + }); + + it('FE-COMP-VISITS-009: several visits show their number beside the tick', () => { + render(); + expect(screen.getByRole('img', { name: 'visits.visitedTimes:{"count":3}' })).toHaveTextContent('3'); + }); +}); diff --git a/client/src/components/Collections/libraryDates.test.ts b/client/src/components/Collections/libraryDates.test.ts index 35efff795..04282a271 100644 --- a/client/src/components/Collections/libraryDates.test.ts +++ b/client/src/components/Collections/libraryDates.test.ts @@ -1,7 +1,7 @@ -// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-003 +// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-004 import { describe, expect, it } from 'vitest'; -import { dayDate, tripLine, tripRange } from './libraryDates'; +import { dayDate, tripLine, tripRange, visitDate } from './libraryDates'; describe('libraryDates', () => { it('FE-COMP-LIBDATES-001: a trip reads as one short range, or one date when only one end is known', () => { @@ -39,4 +39,11 @@ describe('libraryDates', () => { 'collections.library.day{"day":4}' ); }); + it('FE-COMP-LIBDATES-004: a visit names its weekday and year, with the time when there is one', () => { + expect(visitDate('2026-12-02', null, 'en-GB')).toMatch(/^Wed,? 2 Dec 2026$/); + expect(visitDate('2026-12-02', '14:30', 'en-GB')).toMatch(/^Wed,? 2 Dec 2026, 14:30$/); + expect(visitDate(null, '14:30', 'en-GB')).toBeNull(); + expect(visitDate(undefined, null, 'en-GB')).toBeNull(); + expect(visitDate('not a date', null, 'en-GB')).toBeNull(); + }); }); diff --git a/client/src/components/Collections/libraryPairs.test.ts b/client/src/components/Collections/libraryPairs.test.ts index 7359618fb..3aaf6990c 100644 --- a/client/src/components/Collections/libraryPairs.test.ts +++ b/client/src/components/Collections/libraryPairs.test.ts @@ -1,4 +1,4 @@ -// FE-COMP-LIBPAIRS-001 to FE-COMP-LIBPAIRS-009 +// FE-COMP-LIBPAIRS-001 to FE-COMP-LIBPAIRS-012 import type { PlacesLibraryDetailResponse } from '@trek/shared'; import { @@ -11,7 +11,7 @@ import { tripDetail, tripOrigin, } from '../../../tests/helpers/placesLibrary'; -import { originPairs, saveDraftOf } from './libraryPairs'; +import { libraryCarryOptions, originPairs, saveDraftOf } from './libraryPairs'; describe('originPairs', () => { it('FE-COMP-LIBPAIRS-001: nothing open gives nothing', () => { @@ -86,3 +86,39 @@ describe('originPairs', () => { expect(saveDraftOf(origin, detail, undefined).category_id).toBeNull(); }); }); + +describe('libraryCarryOptions', () => { + it('FE-COMP-LIBPAIRS-010: nothing to carry without an open entry or a picked saved place', () => { + expect(libraryCarryOptions(null, 900)).toBeUndefined(); + expect(libraryCarryOptions(bothOrigins(), null)).toBeUndefined(); + }); + + it("FE-COMP-LIBPAIRS-011: offers the saved place's notes and labels and the reader's own tags", () => { + const entry = libraryEntry({ + origins: [tripOrigin(), listOrigin()], + tags: [{ id: 3, name: 'Coffee', color: '#f97316' }], + }); + const data = libraryDetail(entry, [ + tripDetail(), + listDetail({ notes: ' Go early ', labels: [{ id: 7, name: 'Late', color: null }] }), + ]); + expect(libraryCarryOptions(data, 900)).toEqual({ + hasNotes: true, + tags: [{ id: 7, name: 'Late', color: null }], + personalTags: [{ id: 3, name: 'Coffee', color: '#f97316' }], + }); + }); + + it('FE-COMP-LIBPAIRS-012: blank notes, an unknown saved place and an entry without tags offer nothing', () => { + const entry = libraryEntry({ origins: [listOrigin()] }); + const data = libraryDetail(entry, [ + listDetail({ notes: ' ', labels: [{ id: 7, name: 'Late', color: '#123456' }] }), + ]); + expect(libraryCarryOptions(data, 900)).toEqual({ + hasNotes: false, + tags: [{ id: 7, name: 'Late', color: '#123456' }], + personalTags: [], + }); + expect(libraryCarryOptions(data, 12345)).toEqual({ hasNotes: false, tags: [], personalTags: [] }); + }); +}); diff --git a/client/src/components/Collections/placeExtrasText.test.ts b/client/src/components/Collections/placeExtrasText.test.ts new file mode 100644 index 000000000..6a2f1c290 --- /dev/null +++ b/client/src/components/Collections/placeExtrasText.test.ts @@ -0,0 +1,97 @@ +// FE-COMP-PLACEEXTRAS-001 to FE-COMP-PLACEEXTRAS-009: the words of the history and +// activities sections of All places (PLC-14, PLC-18). +import { describe, expect, it } from 'vitest'; + +import { activityCandidate, historyEntry, listTour, placeActivity } from '../../../tests/helpers/placeExtras'; +import type { TranslationFn } from '../../types'; +import { activityLine, historyEditor, historyLine, historyMeta, historyWhen } from './placeExtrasText'; + +const t: TranslationFn = (k, p) => (p ? `${k}${JSON.stringify(p)}` : k); + +describe('historyLine', () => { + it('FE-COMP-PLACEEXTRAS-001: a text detail shows its old and new value as they were', () => { + expect(historyLine(historyEntry({ field: 'address', old_value: 'Via A', new_value: 'Via B' }), t)).toEqual({ + field: 'placeHistory.field.address', + from: 'Via A', + to: 'Via B', + }); + expect(historyLine(historyEntry({ old_value: null, new_value: 'Colosseum' }), t)).toEqual({ + field: 'placeHistory.field.name', + from: null, + to: 'Colosseum', + }); + }); + + it('FE-COMP-PLACEEXTRAS-002: a picture or opening hours only say that they changed', () => { + for (const field of ['image', 'opening_hours'] as const) { + expect(historyLine(historyEntry({ field, old_value: '/a.jpg', new_value: '/b.jpg' }), t)).toEqual({ + field: `placeHistory.field.${field}`, + from: null, + to: null, + }); + } + }); + + it('FE-COMP-PLACEEXTRAS-003: a status reads as the status words, an empty side stays empty', () => { + expect(historyLine(historyEntry({ field: 'status', old_value: 'want', new_value: 'visited' }), t)).toEqual({ + field: 'placeHistory.field.status', + from: 'collections.status.want', + to: 'collections.status.visited', + }); + expect(historyLine(historyEntry({ field: 'status', old_value: null, new_value: 'idea' }), t).from).toBeNull(); + }); +}); + +describe('historyEditor', () => { + it('FE-COMP-PLACEEXTRAS-004: names the person, TREK itself, or a former member', () => { + expect(historyEditor(historyEntry(), t)).toBe('anna'); + expect(historyEditor(historyEntry({ automatic: true }), t)).toBe('placeHistory.automatic'); + expect(historyEditor(historyEntry({ editor: null }), t)).toBe('placeHistory.formerMember'); + }); +}); + +describe('historyWhen', () => { + it('FE-COMP-PLACEEXTRAS-005: a stored UTC time reads as a short date with the year', () => { + const when = historyWhen(historyEntry({ changed_at: '2026-12-02 14:30:00' }), 'en-GB'); + expect(when).toMatch(/Dec/); + expect(when).toMatch(/2026/); + // An ISO stamp that already names its zone reads the same way. + expect(historyWhen(historyEntry({ changed_at: '2026-12-02T14:30:00Z' }), 'en-GB')).toBe(when); + }); + + it('FE-COMP-PLACEEXTRAS-006: no time or an unreadable one says nothing', () => { + expect(historyWhen(historyEntry({ changed_at: null }), 'en-GB')).toBe(''); + expect(historyWhen(historyEntry({ changed_at: 'yesterday' }), 'en-GB')).toBe(''); + }); +}); + +describe('activityLine', () => { + it('FE-COMP-PLACEEXTRAS-007: a booking names its kind, its trip and its day', () => { + expect(activityLine(placeActivity({ date: '2026-12-02' }), 'en-GB', t)).toMatch( + /^placeActivities\.booking, Rome 2026, Wed,? 2 Dec$/ + ); + }); + + it('FE-COMP-PLACEEXTRAS-008: without a date the day number stands in, and a list tour names its list', () => { + expect(activityLine(activityCandidate({ day_number: 3 }), 'en-GB', t)).toBe( + 'placeActivities.booking, Rome 2026, collections.library.day{"day":3}' + ); + expect(activityLine(listTour(), 'en-GB', t)).toBe('placeActivities.tour, Favourites'); + }); + + it('FE-COMP-PLACEEXTRAS-009: an unreadable date falls back to the day number', () => { + expect(activityLine(placeActivity({ date: 'soon', day_number: 1 }), 'en-GB', t)).toBe( + 'placeActivities.booking, Rome 2026, collections.library.day{"day":1}' + ); + }); +}); + +describe('historyMeta', () => { + it('joins where, who and when, and leaves out an unknown time', () => { + const when = historyWhen(historyEntry({ changed_at: '2026-12-02 14:30:00' }), 'en-GB'); + expect(historyMeta(historyEntry({ changed_at: '2026-12-02 14:30:00' }), t, 'en-GB')).toBe( + `Rome 2026, anna, ${when}` + ); + expect(historyMeta(historyEntry({ changed_at: null }), t, 'en-GB')).toBe('Rome 2026, anna'); + }); +}); diff --git a/client/src/components/Collections/useEntryTags.test.ts b/client/src/components/Collections/useEntryTags.test.ts new file mode 100644 index 000000000..69a1c0f38 --- /dev/null +++ b/client/src/components/Collections/useEntryTags.test.ts @@ -0,0 +1,203 @@ +// FE-COMP-ENTRYTAGS-001 to FE-COMP-ENTRYTAGS-011: the reader's own tags on a place of +// All places (PLC-21), behind the desktop sheet, the phone sheet and the tag filter. +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { PlacesLibraryEntry, Tag } from '@trek/shared'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { libraryEntry } from '../../../tests/helpers/placesLibrary'; +import { placeTagsRepo } from '../../repo/placeTagsRepo'; +import { usePlaceTagsStore } from '../../store/placeTagsStore'; +import type { TranslationFn } from '../../types'; +import { matchTags, useEntryTags, usePersonalTags } from './useEntryTags'; + +const ws = vi.hoisted(() => ({ listeners: new Set<(event: Record) => void>() })); +vi.mock('../../api/websocket', () => ({ + addListener: (fn: (event: Record) => void) => ws.listeners.add(fn), + removeListener: (fn: (event: Record) => void) => ws.listeners.delete(fn), +})); + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('../shared/Toast', () => { + const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() }; + return { useToast: () => toast }; +}); + +const t: TranslationFn = (key) => key; + +const tag = (id: number, name: string): Tag => ({ id, user_id: 1, trip_id: null, name, color: '#aa0000' }); +const BEACH = tag(1, 'Beach'); +const COFFEE = tag(2, 'Coffee'); +const WINE = tag(3, 'Wine'); + +function entryWith(tags: Tag[]): PlacesLibraryEntry { + return libraryEntry({ key: 'trip:42', tags: tags.map(({ id, name, color }) => ({ id, name, color })) }); +} + +function mount(entry: PlacesLibraryEntry | null, onChanged = vi.fn()) { + const hook = renderHook(() => useEntryTags({ entry, onChanged, t })); + return { ...hook, onChanged }; +} + +beforeEach(() => { + usePlaceTagsStore.setState({ tags: [BEACH, COFFEE, WINE], loaded: true }); + toastError.mockReset(); +}); + +afterEach(() => { + vi.restoreAllMocks(); + ws.listeners.clear(); +}); + +describe('matchTags', () => { + it('FE-COMP-ENTRYTAGS-001: matches the trimmed, case folded query, and all tags for an empty one', () => { + const all = [BEACH, COFFEE, WINE]; + expect(matchTags(all, ' ')).toEqual(all); + expect(matchTags(all, ' ')).not.toBe(all); + expect(matchTags(all, ' fF ')).toEqual([COFFEE]); + expect(matchTags(all, 'zzz')).toEqual([]); + }); +}); + +describe('usePersonalTags', () => { + it('FE-COMP-ENTRYTAGS-002: reads the tags once when they were not loaded yet', async () => { + usePlaceTagsStore.setState({ tags: [], loaded: false }); + const list = vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([WINE, BEACH]); + const { result } = renderHook(() => usePersonalTags()); + await waitFor(() => expect(result.current).toEqual([BEACH, WINE])); + expect(list).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-ENTRYTAGS-003: loaded tags are not read again, and offline leaves the list empty', async () => { + const list = vi.spyOn(placeTagsRepo, 'list'); + const { result } = renderHook(() => usePersonalTags()); + expect(result.current).toEqual([BEACH, COFFEE, WINE]); + expect(list).not.toHaveBeenCalled(); + + usePlaceTagsStore.setState({ tags: [], loaded: false }); + list.mockRejectedValue(new Error('offline')); + const offline = renderHook(() => usePersonalTags()); + await waitFor(() => expect(list).toHaveBeenCalled()); + expect(offline.result.current).toEqual([]); + }); + + it('FE-COMP-ENTRYTAGS-004: listens for tag changes from elsewhere while mounted', async () => { + const list = vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([COFFEE]); + const { result, unmount } = renderHook(() => usePersonalTags()); + expect(ws.listeners.size).toBe(1); + act(() => ws.listeners.forEach((fn) => fn({ type: 'tags:changed' }))); + await waitFor(() => expect(result.current).toEqual([COFFEE])); + expect(list).toHaveBeenCalledTimes(1); + unmount(); + expect(ws.listeners.size).toBe(0); + }); +}); + +describe('useEntryTags', () => { + it('FE-COMP-ENTRYTAGS-005: offers what the place carries and the tags matching the search', () => { + const { result } = mount(entryWith([COFFEE])); + expect(result.current.all).toEqual([BEACH, COFFEE, WINE]); + expect(result.current.assignedIds).toEqual([2]); + expect(result.current.matches).toEqual([BEACH, COFFEE, WINE]); + expect(result.current.canCreate).toBe(false); + + act(() => result.current.setQuery(' wi')); + expect(result.current.matches).toEqual([WINE]); + expect(result.current.canCreate).toBe(true); + + act(() => result.current.setQuery(' wINe ')); + expect(result.current.canCreate).toBe(false); + }); + + it('FE-COMP-ENTRYTAGS-006: an entry without tags, or none at all, carries nothing', () => { + expect(mount(libraryEntry()).result.current.assigned).toEqual([]); + expect(mount(null).result.current.assignedIds).toEqual([]); + }); + + it('FE-COMP-ENTRYTAGS-007: toggling puts a tag on or takes it off, then reports the change', async () => { + const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null); + const { result, onChanged } = mount(entryWith([COFFEE])); + await act(() => result.current.toggle(3)); + expect(setForEntry).toHaveBeenLastCalledWith('trip:42', [2, 3]); + await act(() => result.current.toggle(2)); + expect(setForEntry).toHaveBeenLastCalledWith('trip:42', []); + expect(onChanged).toHaveBeenCalledTimes(2); + expect(result.current.busy).toBe(false); + }); + + it('FE-COMP-ENTRYTAGS-008: the typed name becomes a new tag on the place, and clears the search', async () => { + const created = tag(9, 'Rooftop'); + const create = vi.spyOn(placeTagsRepo, 'create').mockResolvedValue(created); + const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null); + const { result, onChanged } = mount(entryWith([COFFEE])); + act(() => result.current.setQuery(' Rooftop ')); + await act(() => result.current.createAndAdd()); + expect(create).toHaveBeenCalledWith('Rooftop', undefined); + expect(setForEntry).toHaveBeenCalledWith('trip:42', [2, 9]); + expect(result.current.query).toBe(''); + expect(onChanged).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-ENTRYTAGS-009: a tag the place already carries is not put on twice, and an empty name or no entry makes none', async () => { + const create = vi.spyOn(placeTagsRepo, 'create').mockResolvedValue(COFFEE); + const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(null); + const { result } = mount(entryWith([COFFEE])); + act(() => result.current.setQuery('coffee bar')); + await act(() => result.current.createAndAdd()); + expect(create).toHaveBeenCalledTimes(1); + expect(setForEntry).not.toHaveBeenCalled(); + + act(() => result.current.setQuery(' ')); + await act(() => result.current.createAndAdd()); + expect(create).toHaveBeenCalledTimes(1); + + const none = mount(null); + act(() => none.result.current.setQuery('New')); + await act(() => none.result.current.createAndAdd()); + await act(() => none.result.current.toggle(1)); + expect(create).toHaveBeenCalledTimes(1); + expect(setForEntry).not.toHaveBeenCalled(); + }); + + it('FE-COMP-ENTRYTAGS-010: renames with the trimmed name, skips a blank one, and deletes a tag everywhere', async () => { + const update = vi.spyOn(placeTagsRepo, 'update').mockResolvedValue(tag(3, 'Natural wine')); + const remove = vi.spyOn(placeTagsRepo, 'remove').mockResolvedValue(undefined); + const { result, onChanged } = mount(entryWith([])); + await act(() => result.current.rename(3, ' Natural wine ')); + expect(update).toHaveBeenCalledWith(3, { name: 'Natural wine' }); + await act(() => result.current.rename(3, ' ')); + expect(update).toHaveBeenCalledTimes(1); + await act(() => result.current.destroy(1)); + expect(remove).toHaveBeenCalledWith(1); + expect(usePlaceTagsStore.getState().tags.map((x) => x.name)).toEqual(['Coffee', 'Natural wine']); + expect(onChanged).toHaveBeenCalledTimes(2); + }); + + it('FE-COMP-ENTRYTAGS-011: a refused change toasts the reason, reports nothing, and one change runs at a time', async () => { + vi.spyOn(placeTagsRepo, 'setForEntry').mockRejectedValueOnce({ response: { data: { error: 'Nope' } } }); + const { result, onChanged } = mount(entryWith([])); + await act(() => result.current.toggle(1)); + expect(toastError).toHaveBeenCalledWith('Nope'); + expect(onChanged).not.toHaveBeenCalled(); + + vi.spyOn(placeTagsRepo, 'remove').mockRejectedValueOnce(new Error('down')); + await act(() => result.current.destroy(1)); + expect(toastError).toHaveBeenLastCalledWith('common.error'); + + let finish: () => void = () => undefined; + const setForEntry = vi.spyOn(placeTagsRepo, 'setForEntry').mockReturnValue( + new Promise((resolve) => { + finish = () => resolve(null); + }) + ); + setForEntry.mockClear(); + act(() => { + void result.current.toggle(1); + }); + expect(result.current.busy).toBe(true); + await act(() => result.current.toggle(2)); + expect(setForEntry).toHaveBeenCalledTimes(1); + await act(async () => finish()); + await waitFor(() => expect(result.current.busy).toBe(false)); + expect(onChanged).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/components/Collections/useOriginNotes.test.ts b/client/src/components/Collections/useOriginNotes.test.ts new file mode 100644 index 000000000..1007906b3 --- /dev/null +++ b/client/src/components/Collections/useOriginNotes.test.ts @@ -0,0 +1,171 @@ +// FE-COMP-ORIGINNOTES-001 to FE-COMP-ORIGINNOTES-011: each trip's and list's own notes on a place of All places. +import { act, renderHook } from '@testing-library/react'; +import type { PlacesLibraryDetailResponse } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'; + +import { + libraryDetail, + libraryEntry, + listDetail, + listOrigin, + tripDetail, + tripOrigin, +} from '../../../tests/helpers/placesLibrary'; +import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; +import { notesOf, useOriginNotes } from './useOriginNotes'; + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('../shared/Toast', () => { + const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() }; + return { useToast: () => toast }; +}); + +const t = (key: string) => key; + +/** A trip place with a note, a trip place without one and a saved place without one, all writable. */ +function threeOrigins(over: { tripNotes?: string | null; canEditSecond?: boolean } = {}): PlacesLibraryDetailResponse { + const entry = libraryEntry({ + origins: [ + tripOrigin(), + tripOrigin({ trip_id: 6, trip_title: 'Lazio', place_id: 43, can_edit: over.canEditSecond ?? true }), + listOrigin(), + ], + }); + return libraryDetail(entry, [ + tripDetail({ notes: over.tripNotes === undefined ? 'Buy tickets online' : over.tripNotes }), + tripDetail({ place_id: 43 }), + listDetail(), + ]); +} + +let saveNotes: MockInstance; + +beforeEach(() => { + toastError.mockReset(); + vi.restoreAllMocks(); + saveNotes = vi.spyOn(placesLibraryRepo, 'saveNotes').mockResolvedValue(undefined); +}); + +function setup(data: PlacesLibraryDetailResponse | null = threeOrigins()) { + const onSaved = vi.fn(); + const hook = renderHook(() => useOriginNotes({ data, onSaved, t })); + return { ...hook, onSaved }; +} + +describe('notesOf', () => { + it('FE-COMP-ORIGINNOTES-001: nothing open gives no notes', () => { + expect(notesOf(null)).toEqual([]); + }); + + it('FE-COMP-ORIGINNOTES-002: the trips come first, then the lists, each named by where it lives', () => { + const notes = notesOf(threeOrigins()); + expect(notes.map((n) => [n.key, n.kind, n.source, n.text, n.canEdit])).toEqual([ + ['trip:42', 'trip', 'Rome 2026', 'Buy tickets online', true], + ['trip:43', 'trip', 'Lazio', '', true], + ['list:900', 'list', 'Favourites', '', true], + ]); + }); + + it('FE-COMP-ORIGINNOTES-003: an empty note stays out where the reader could not write one, a written one stays', () => { + const entry = libraryEntry({ origins: [tripOrigin({ can_edit: false }), listOrigin({ can_edit: false })] }); + const data = libraryDetail(entry, [tripDetail({ notes: ' ' }), listDetail({ notes: 'Ask for Marco' })]); + expect(notesOf(data).map((n) => [n.key, n.canEdit])).toEqual([['list:900', false]]); + }); + + it('FE-COMP-ORIGINNOTES-004: each note saves where it lives', async () => { + const [trip, , list] = notesOf(threeOrigins()); + await trip.save('New'); + expect(saveNotes).toHaveBeenLastCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, 'New'); + await list.save(null); + expect(saveNotes).toHaveBeenLastCalledWith({ kind: 'list', collection_place_id: 900 }, null); + }); +}); + +describe('useOriginNotes', () => { + it('FE-COMP-ORIGINNOTES-005: shows the written notes and offers the empty writable ones as targets', () => { + const { result } = setup(); + expect(result.current.notes.map((n) => n.key)).toEqual(['trip:42']); + expect(result.current.targets.map((n) => n.key)).toEqual(['trip:43', 'list:900']); + expect(result.current.editing).toBeNull(); + expect(result.current.choosing).toBe(false); + }); + + it('FE-COMP-ORIGINNOTES-006: "+ Note" with several targets asks where, and toggles the choice', () => { + const { result } = setup(); + act(() => result.current.add()); + expect(result.current.choosing).toBe(true); + act(() => result.current.add()); + expect(result.current.choosing).toBe(false); + }); + + it('FE-COMP-ORIGINNOTES-007: "+ Note" with one target opens it straight away', () => { + const { result } = setup(threeOrigins({ canEditSecond: false })); + // The second trip is read only, and the list is the one place left. + expect(result.current.targets.map((n) => n.key)).toEqual(['list:900']); + act(() => result.current.add()); + expect(result.current.editing).toBe('list:900'); + expect(result.current.choosing).toBe(false); + // The note being written shows and is no target any more. + expect(result.current.notes.map((n) => n.key)).toEqual(['trip:42', 'list:900']); + expect(result.current.targets).toEqual([]); + }); + + it('FE-COMP-ORIGINNOTES-008: editing starts from the stored text, cancel leaves it', () => { + const { result } = setup(); + act(() => result.current.add()); + act(() => result.current.edit(result.current.notes[0])); + expect(result.current.choosing).toBe(false); + expect(result.current.editing).toBe('trip:42'); + expect(result.current.draft).toBe('Buy tickets online'); + act(() => result.current.setDraft('Changed')); + act(() => result.current.cancel()); + expect(result.current.editing).toBeNull(); + expect(saveNotes).not.toHaveBeenCalled(); + }); + + it('FE-COMP-ORIGINNOTES-009: saving stores the draft, closes the editor and reads the place again', async () => { + const { result, onSaved } = setup(); + act(() => result.current.edit(result.current.targets[1])); + act(() => result.current.setDraft('Bring water')); + await act(async () => { + await result.current.save(); + }); + expect(saveNotes).toHaveBeenCalledWith({ kind: 'list', collection_place_id: 900 }, 'Bring water'); + expect(result.current.editing).toBeNull(); + expect(result.current.busy).toBe(false); + expect(onSaved).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-ORIGINNOTES-010: a blank draft clears the note, and nothing saves without an open editor', async () => { + const { result, onSaved } = setup(); + await act(async () => { + await result.current.save(); + }); + expect(saveNotes).not.toHaveBeenCalled(); + act(() => result.current.edit(result.current.notes[0])); + act(() => result.current.setDraft(' ')); + await act(async () => { + await result.current.save(); + }); + expect(saveNotes).toHaveBeenCalledWith({ kind: 'trip', trip_id: 5, place_id: 42 }, null); + expect(onSaved).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-ORIGINNOTES-011: a refused save toasts the reason and keeps the editor open', async () => { + saveNotes.mockRejectedValueOnce({ response: { data: { error: 'No access' } } }); + saveNotes.mockRejectedValueOnce(new Error('offline')); + const { result, onSaved } = setup(); + act(() => result.current.edit(result.current.notes[0])); + await act(async () => { + await result.current.save(); + }); + expect(toastError).toHaveBeenLastCalledWith('No access'); + expect(result.current.editing).toBe('trip:42'); + expect(result.current.busy).toBe(false); + await act(async () => { + await result.current.save(); + }); + expect(toastError).toHaveBeenLastCalledWith('common.error'); + expect(onSaved).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Collections/usePlaceActivities.test.ts b/client/src/components/Collections/usePlaceActivities.test.ts new file mode 100644 index 000000000..8261c3b26 --- /dev/null +++ b/client/src/components/Collections/usePlaceActivities.test.ts @@ -0,0 +1,228 @@ +// FE-COMP-PLACEACTIVITIES-001 to FE-COMP-PLACEACTIVITIES-013: the tours and bookings of a +// place of All places (PLC-18), behind the desktop section and the phone section. +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { PlaceLibraryActivitiesResponse, PlacesLibraryEntry } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { activityCandidate, listSource, listTour, placeActivity, tripSource } from '../../../tests/helpers/placeExtras'; +import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary'; +import { placeActivitiesRepo } from '../../repo/placeActivitiesRepo'; +import type { TranslationFn } from '../../types'; +import { activityHref, usePlaceActivities } from './usePlaceActivities'; + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('../shared/Toast', () => { + const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() }; + return { useToast: () => toast }; +}); + +vi.mock('../../repo/placeActivitiesRepo', () => ({ + placeActivitiesRepo: { + libraryEntry: vi.fn(), + tripCandidates: vi.fn(), + savedCandidates: vi.fn(), + linkTrip: vi.fn(), + linkSaved: vi.fn(), + unlink: vi.fn(), + }, +})); + +const repo = vi.mocked(placeActivitiesRepo); +const t: TranslationFn = (k) => k; + +const EMPTY = { activities: [], can_link: true }; + +function mount(entry: PlacesLibraryEntry | null = libraryEntry()) { + return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceActivities({ entry: e, t }), { + initialProps: { e: entry }, + }); +} + +async function mountLoaded(res: PlaceLibraryActivitiesResponse, entry = libraryEntry()) { + repo.libraryEntry.mockResolvedValue(res); + const view = mount(entry); + await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalled()); + await waitFor(() => expect(view.result.current.activities).toEqual(res.activities)); + return view; +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe('activityHref', () => { + it('FE-COMP-PLACEACTIVITIES-001: a booking and a tour open in their trip, a kept tour in its list', () => { + expect(activityHref(placeActivity())).toBe('/trips/5?booking=7'); + expect(activityHref({ target: { kind: 'tour', trip_id: 5, tour_id: 8 } })).toBe('/trips/5?tour=8'); + expect(activityHref(listTour())).toMatch(/\/9$/); + }); +}); + +describe('usePlaceActivities', () => { + it('FE-COMP-PLACEACTIVITIES-002: reads the entry through its first origin and says whether it may link', async () => { + const view = await mountLoaded({ activities: [placeActivity()], sources: [tripSource()] }); + expect(repo.libraryEntry).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal)); + await waitFor(() => expect(view.result.current.canLink).toBe(true)); + expect(view.result.current.picking).toBeNull(); + expect(view.result.current.busy).toBe(false); + }); + + it('FE-COMP-PLACEACTIVITIES-003: a list origin reads through its saved place; no origin reads nothing', async () => { + await mountLoaded({ activities: [], sources: [] }, libraryEntry({ origins: [listOrigin()] })); + expect(repo.libraryEntry).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal)); + repo.libraryEntry.mockClear(); + const empty = mount(libraryEntry({ origins: [] })); + expect(repo.libraryEntry).not.toHaveBeenCalled(); + expect(empty.result.current.activities).toEqual([]); + expect(empty.result.current.canLink).toBe(false); + mount(null); + expect(repo.libraryEntry).not.toHaveBeenCalled(); + }); + + it('FE-COMP-PLACEACTIVITIES-004: a failed read shows nothing and offers no link', async () => { + repo.libraryEntry.mockRejectedValue(new Error('offline')); + const view = mount(); + await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalled()); + expect(view.result.current.activities).toEqual([]); + expect(view.result.current.canLink).toBe(false); + }); + + it('FE-COMP-PLACEACTIVITIES-005: an origin without the right to link does not count', async () => { + const view = await mountLoaded({ activities: [placeActivity()], sources: [tripSource({ can_link: false })] }); + expect(view.result.current.canLink).toBe(false); + }); + + it('FE-COMP-PLACEACTIVITIES-006: another entry hides the old answer until its own arrives', async () => { + const view = await mountLoaded({ activities: [placeActivity()], sources: [] }); + repo.libraryEntry.mockReturnValue(new Promise(() => undefined)); + view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) }); + expect(view.result.current.activities).toEqual([]); + }); + + it('FE-COMP-PLACEACTIVITIES-007: the picker reads the candidates of every origin that takes links', async () => { + const view = await mountLoaded({ + activities: [], + sources: [ + tripSource(), + listSource(), + tripSource({ source: { kind: 'trip', trip_id: 6, place_id: 43 }, can_link: false }), + ], + }); + const booking = activityCandidate(); + const tour = activityCandidate({ key: 'collection_tour:3' }); + repo.tripCandidates.mockResolvedValue({ candidates: [booking] }); + repo.savedCandidates.mockResolvedValue({ candidates: [tour] }); + await act(async () => { + await view.result.current.openPicker(); + }); + expect(repo.tripCandidates).toHaveBeenCalledTimes(1); + expect(repo.tripCandidates).toHaveBeenCalledWith(5, 42); + expect(repo.savedCandidates).toHaveBeenCalledWith(900); + expect(view.result.current.picking).toEqual([ + { source: tripSource(), candidates: [booking] }, + { source: listSource(), candidates: [tour] }, + ]); + // Opening reads the entry again. + await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalledTimes(2)); + act(() => view.result.current.closePicker()); + expect(view.result.current.picking).toBeNull(); + }); + + it('FE-COMP-PLACEACTIVITIES-008: a failed picker read toasts the server message and opens nothing', async () => { + const view = await mountLoaded({ activities: [], sources: [tripSource()] }); + repo.tripCandidates.mockRejectedValue({ response: { data: { error: 'No access' } } }); + await act(async () => { + await view.result.current.openPicker(); + }); + expect(toastError).toHaveBeenCalledWith('No access'); + expect(view.result.current.picking).toBeNull(); + expect(view.result.current.busy).toBe(false); + }); + + it('FE-COMP-PLACEACTIVITIES-009: linking a booking or a tour to a trip place sends its own id and closes the picker', async () => { + const view = await mountLoaded({ activities: [], sources: [tripSource()] }); + repo.tripCandidates.mockResolvedValue({ candidates: [activityCandidate()] }); + repo.linkTrip.mockResolvedValue(EMPTY); + await act(async () => { + await view.result.current.openPicker(); + }); + await act(async () => { + await view.result.current.link(tripSource(), activityCandidate()); + }); + expect(repo.linkTrip).toHaveBeenLastCalledWith(5, 42, { reservation_id: 7 }); + expect(view.result.current.picking).toBeNull(); + await act(async () => { + await view.result.current.link( + tripSource(), + activityCandidate({ type: 'tour', target: { kind: 'tour', trip_id: 5, tour_id: 8 } }) + ); + }); + expect(repo.linkTrip).toHaveBeenLastCalledWith(5, 42, { tour_id: 8 }); + }); + + it('FE-COMP-PLACEACTIVITIES-010: a kept tour links to the saved place, never to a trip place', async () => { + const view = await mountLoaded({ activities: [], sources: [tripSource(), listSource()] }); + repo.linkSaved.mockResolvedValue(EMPTY); + const keptTour = activityCandidate({ + target: { kind: 'collection_tour', collection_id: 9, collection_tour_id: 3 }, + }); + await act(async () => { + await view.result.current.link(listSource(), keptTour); + }); + expect(repo.linkSaved).toHaveBeenCalledWith(900, 3); + await act(async () => { + await view.result.current.link(tripSource(), keptTour); + }); + // A booking never reaches a saved place either. + await act(async () => { + await view.result.current.link(listSource(), activityCandidate()); + }); + expect(repo.linkTrip).not.toHaveBeenCalled(); + expect(repo.linkSaved).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEACTIVITIES-011: unlinking takes the link off and reads the entry again', async () => { + const act1 = placeActivity(); + const view = await mountLoaded({ activities: [act1], sources: [tripSource()] }); + repo.unlink.mockResolvedValue(EMPTY); + await act(async () => { + await view.result.current.unlink(act1); + }); + expect(repo.unlink).toHaveBeenCalledWith(act1); + await waitFor(() => expect(repo.libraryEntry).toHaveBeenCalledTimes(2)); + }); + + it('FE-COMP-PLACEACTIVITIES-012: a refused write without a message toasts the general error', async () => { + const view = await mountLoaded({ activities: [placeActivity()], sources: [] }); + repo.unlink.mockRejectedValue(new Error('boom')); + await act(async () => { + await view.result.current.unlink(placeActivity()); + }); + expect(toastError).toHaveBeenCalledWith('common.error'); + expect(repo.libraryEntry).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEACTIVITIES-013: a second write while one runs is ignored', async () => { + const view = await mountLoaded({ activities: [placeActivity()], sources: [] }); + let finish: (v: typeof EMPTY) => void = () => undefined; + repo.unlink.mockReturnValue( + new Promise((res) => { + finish = res; + }) + ); + let first: Promise | undefined; + act(() => { + first = view.result.current.unlink(placeActivity()); + }); + expect(view.result.current.busy).toBe(true); + await act(async () => { + await view.result.current.unlink(placeActivity()); + }); + expect(repo.unlink).toHaveBeenCalledTimes(1); + await act(async () => { + finish(EMPTY); + await first; + }); + expect(view.result.current.busy).toBe(false); + }); +}); diff --git a/client/src/components/Collections/usePlaceHistory.test.ts b/client/src/components/Collections/usePlaceHistory.test.ts new file mode 100644 index 000000000..38acbf523 --- /dev/null +++ b/client/src/components/Collections/usePlaceHistory.test.ts @@ -0,0 +1,98 @@ +// FE-COMP-PLACEHISTORY-001 to FE-COMP-PLACEHISTORY-007: the change history of a place of +// All places (PLC-14), behind the desktop section and the phone section. +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { PlaceHistoryPageResponse, PlacesLibraryEntry } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { historyEntries } from '../../../tests/helpers/placeExtras'; +import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary'; +import { placeHistoryRepo } from '../../repo/placeHistoryRepo'; +import { usePlaceHistory } from './usePlaceHistory'; + +vi.mock('../../repo/placeHistoryRepo', () => ({ placeHistoryRepo: { history: vi.fn() } })); + +const history = vi.mocked(placeHistoryRepo.history); + +function mount(entry: PlacesLibraryEntry | null = libraryEntry()) { + return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceHistory(e), { initialProps: { e: entry } }); +} + +function page(from: number, count: number, next: string | null): PlaceHistoryPageResponse { + return { entries: historyEntries(count, from), next_cursor: next }; +} + +beforeEach(() => { + history.mockReset(); +}); + +describe('usePlaceHistory', () => { + it('FE-COMP-PLACEHISTORY-001: reads the first page through the first origin', async () => { + history.mockResolvedValue(page(1, 2, null)); + const { result } = mount(); + await waitFor(() => expect(result.current.entries).toHaveLength(2)); + expect(history).toHaveBeenCalledWith('trip', 42, { limit: 20 }, expect.any(AbortSignal)); + expect(result.current.hasMore).toBe(false); + }); + + it('FE-COMP-PLACEHISTORY-002: a list origin reads through its saved place; no origin reads nothing', async () => { + history.mockResolvedValue(page(1, 1, null)); + mount(libraryEntry({ origins: [listOrigin()] })); + await waitFor(() => expect(history).toHaveBeenCalledWith('list', 900, { limit: 20 }, expect.any(AbortSignal))); + history.mockClear(); + const { result } = mount(null); + expect(history).not.toHaveBeenCalled(); + expect(result.current.entries).toEqual([]); + expect(result.current.hasMore).toBe(false); + }); + + it('FE-COMP-PLACEHISTORY-003: a failed read shows no history', async () => { + history.mockRejectedValue(new Error('offline')); + const { result } = mount(); + await waitFor(() => expect(history).toHaveBeenCalled()); + expect(result.current.entries).toEqual([]); + expect(result.current.hasMore).toBe(false); + }); + + it('FE-COMP-PLACEHISTORY-004: more appends the next page with the cursor', async () => { + history.mockResolvedValueOnce(page(1, 2, '10')).mockResolvedValueOnce(page(3, 1, null)); + const { result } = mount(); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + await act(async () => { + await result.current.more(); + }); + expect(history).toHaveBeenLastCalledWith('trip', 42, { limit: 20, cursor: '10' }); + expect(result.current.entries.map((e) => e.id)).toEqual([1, 2, 3]); + expect(result.current.hasMore).toBe(false); + expect(result.current.loadingMore).toBe(false); + }); + + it('FE-COMP-PLACEHISTORY-005: more does nothing on the last page', async () => { + history.mockResolvedValue(page(1, 1, null)); + const { result } = mount(); + await waitFor(() => expect(result.current.entries).toHaveLength(1)); + await act(async () => { + await result.current.more(); + }); + expect(history).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-PLACEHISTORY-006: a failed "more" keeps the list and lets another tap try again', async () => { + history.mockResolvedValueOnce(page(1, 2, '10')).mockRejectedValueOnce(new Error('offline')); + const { result } = mount(); + await waitFor(() => expect(result.current.hasMore).toBe(true)); + await act(async () => { + await result.current.more(); + }); + expect(result.current.entries).toHaveLength(2); + expect(result.current.hasMore).toBe(true); + expect(result.current.loadingMore).toBe(false); + }); + + it('FE-COMP-PLACEHISTORY-007: another entry hides the old history until its own arrives', async () => { + history.mockResolvedValueOnce(page(1, 2, null)).mockReturnValueOnce(new Promise(() => undefined)); + const view = mount(); + await waitFor(() => expect(view.result.current.entries).toHaveLength(2)); + view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) }); + expect(view.result.current.entries).toEqual([]); + }); +}); diff --git a/client/src/components/Collections/usePlaceMedia.test.ts b/client/src/components/Collections/usePlaceMedia.test.ts new file mode 100644 index 000000000..e76cf2978 --- /dev/null +++ b/client/src/components/Collections/usePlaceMedia.test.ts @@ -0,0 +1,96 @@ +// FE-COMP-PLACEMEDIA-001 to FE-COMP-PLACEMEDIA-006: the pictures and files of a place of +// All places (PLC-19, PLC-20), behind the desktop section and the phone section. +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { PlacesLibraryEntry } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { journeyPhoto, mediaFile, mediaImage } from '../../../tests/helpers/placeExtras'; +import { libraryEntry, listOrigin } from '../../../tests/helpers/placesLibrary'; +import { placeVisitsRepo } from '../../repo/placeVisitsRepo'; +import { photosOf, usePlaceMedia } from './usePlaceMedia'; + +vi.mock('../../repo/placeVisitsRepo', () => ({ placeVisitsRepo: { media: vi.fn() } })); + +const media = vi.mocked(placeVisitsRepo.media); + +function mount(entry: PlacesLibraryEntry | null = libraryEntry()) { + return renderHook(({ e }: { e: PlacesLibraryEntry | null }) => usePlaceMedia(e), { initialProps: { e: entry } }); +} + +beforeEach(() => { + media.mockReset(); +}); + +describe('photosOf', () => { + it('FE-COMP-PLACEMEDIA-001: the place pictures come first, each address once, captioned by trip or list', () => { + const photos = photosOf({ + images: [mediaImage('/a.jpg'), mediaImage('/a.jpg', 'list'), mediaImage('/b.jpg', 'list')], + journey_photos: [], + files: [], + }); + expect(photos).toEqual([ + { id: 'img:/a.jpg', src: '/a.jpg', thumbSrc: '/a.jpg', caption: 'Rome 2026' }, + { id: 'img:/b.jpg', src: '/b.jpg', thumbSrc: '/b.jpg', caption: 'Favourites' }, + ]); + }); + + it('FE-COMP-PLACEMEDIA-002: journey photos follow with their own sizes, caption or journey title', () => { + const photos = photosOf({ + images: [mediaImage('/a.jpg')], + journey_photos: [journeyPhoto(), journeyPhoto({ journey_photo_id: 71, photo_id: 701, caption: ' Sunset ' })], + files: [], + }); + expect(photos.slice(1)).toEqual([ + { + id: 'jp:70', + src: '/api/photos/700/original', + thumbSrc: '/api/photos/700/thumbnail', + caption: 'Italy journey', + provider: 'local', + mediaType: 'image', + }, + expect.objectContaining({ id: 'jp:71', caption: 'Sunset' }), + ]); + }); + + it('FE-COMP-PLACEMEDIA-003: nothing read yet is no pictures', () => { + expect(photosOf(null)).toEqual([]); + }); +}); + +describe('usePlaceMedia', () => { + it('FE-COMP-PLACEMEDIA-004: reads through the first origin and opens and closes a picture', async () => { + media.mockResolvedValue({ images: [mediaImage('/a.jpg')], journey_photos: [], files: [mediaFile()] }); + const { result } = mount(); + await waitFor(() => expect(result.current.photos).toHaveLength(1)); + expect(media).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal)); + expect(result.current.files).toEqual([mediaFile()]); + expect(result.current.open).toBeNull(); + act(() => result.current.setOpen(0)); + expect(result.current.open).toBe(0); + act(() => result.current.close()); + expect(result.current.open).toBeNull(); + }); + + it('FE-COMP-PLACEMEDIA-005: a list origin reads through its saved place; no origin reads nothing', async () => { + media.mockResolvedValue({ images: [], journey_photos: [], files: [] }); + mount(libraryEntry({ origins: [listOrigin()] })); + await waitFor(() => expect(media).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal))); + media.mockClear(); + const { result } = mount(null); + expect(media).not.toHaveBeenCalled(); + expect(result.current.photos).toEqual([]); + expect(result.current.files).toEqual([]); + }); + + it('FE-COMP-PLACEMEDIA-006: a failed read shows none, and another entry hides the old pictures', async () => { + media.mockResolvedValueOnce({ images: [mediaImage('/a.jpg')], journey_photos: [], files: [] }); + const view = mount(); + await waitFor(() => expect(view.result.current.photos).toHaveLength(1)); + media.mockRejectedValueOnce(new Error('offline')); + view.rerender({ e: libraryEntry({ origins: [listOrigin()] }) }); + expect(view.result.current.photos).toEqual([]); + await waitFor(() => expect(media).toHaveBeenCalledTimes(2)); + expect(view.result.current.files).toEqual([]); + }); +}); diff --git a/client/src/components/Collections/usePlaceVisits.test.ts b/client/src/components/Collections/usePlaceVisits.test.ts new file mode 100644 index 000000000..4bafcbd83 --- /dev/null +++ b/client/src/components/Collections/usePlaceVisits.test.ts @@ -0,0 +1,115 @@ +// FE-COMP-PLACEVISITS-001 to FE-COMP-PLACEVISITS-007: a place's visits, read through its first origin. +import { renderHook, waitFor } from '@testing-library/react'; +import type { PlaceVisitsForPlaceResponse } from '@trek/shared'; +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'; + +import { libraryEntry, listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary'; +import { placeVisitsRepo } from '../../repo/placeVisitsRepo'; +import { tripPlaceEntry, usePlaceVisits } from './usePlaceVisits'; + +const VISITS: PlaceVisitsForPlaceResponse = { + visits: [ + { + visited_on: '2026-07-02', + visited_time: '10:00', + trip: { id: 5, title: 'Rome 2026' }, + place_id: 42, + day_id: 3, + day_number: 2, + name: 'Colosseum', + participants: [], + }, + ], + visit_count: 1, + last_visit: '2026-07-02', +}; + +let forPlace: MockInstance; + +beforeEach(() => { + forPlace = vi.spyOn(placeVisitsRepo, 'forPlace').mockResolvedValue(VISITS); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('tripPlaceEntry', () => { + it('FE-COMP-PLACEVISITS-001: a trip place becomes a one-origin entry keyed by the trip place', () => { + const entry = tripPlaceEntry( + { id: 5, title: 'Rome 2026', start_date: '2026-07-01', end_date: '2026-07-05' }, + { id: 42, name: 'Colosseum', address: 'Piazza', lat: 41.9, lng: 12.5 } + ); + expect(entry).toMatchObject({ key: 'trip:42', name: 'Colosseum', address: 'Piazza', lat: 41.9, lng: 12.5 }); + expect(entry.origins).toEqual([ + { + kind: 'trip', + trip_id: 5, + trip_title: 'Rome 2026', + trip_start: '2026-07-01', + trip_end: '2026-07-05', + place_id: 42, + can_edit: true, + read_only: false, + }, + ]); + }); + + it('FE-COMP-PLACEVISITS-002: missing place facts and trip dates turn into nulls', () => { + const entry = tripPlaceEntry({ id: 5, title: 'Rome' }, { id: 42, name: 'Colosseum' }); + expect(entry).toMatchObject({ address: null, lat: null, lng: null, category: null, image_url: null }); + expect(entry.origins[0]).toMatchObject({ trip_start: null, trip_end: null }); + }); +}); + +describe('usePlaceVisits', () => { + it('FE-COMP-PLACEVISITS-003: without an entry nothing is read and nothing loads', () => { + const { result } = renderHook(() => usePlaceVisits({ entry: null })); + expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: false }); + expect(forPlace).not.toHaveBeenCalled(); + }); + + it('FE-COMP-PLACEVISITS-004: reads a trip origin by its trip place and hands back the visits', async () => { + const { result } = renderHook(() => usePlaceVisits({ entry: libraryEntry() })); + expect(result.current.loading).toBe(true); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(forPlace).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal)); + expect(result.current.visits).toEqual(VISITS.visits); + expect(result.current.count).toBe(1); + expect(result.current.lastVisit).toBe('2026-07-02'); + }); + + it('FE-COMP-PLACEVISITS-005: reads a list origin by its saved place', async () => { + const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] }); + const { result } = renderHook(() => usePlaceVisits({ entry })); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(forPlace).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal)); + }); + + it('FE-COMP-PLACEVISITS-006: a failed read shows no visits rather than loading forever', async () => { + forPlace.mockRejectedValue(new Error('offline')); + const { result } = renderHook(() => usePlaceVisits({ entry: libraryEntry() })); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: false }); + }); + + it('FE-COMP-PLACEVISITS-007: another entry does not show the last one visits and aborts the old read', async () => { + const { result, rerender } = renderHook(({ entry }) => usePlaceVisits({ entry }), { + initialProps: { entry: libraryEntry() }, + }); + await waitFor(() => expect(result.current.count).toBe(1)); + const firstSignal = forPlace.mock.calls[0][2] as AbortSignal; + let resolveSecond: (r: PlaceVisitsForPlaceResponse) => void = () => undefined; + forPlace.mockReturnValueOnce( + new Promise((resolve) => { + resolveSecond = resolve; + }) + ); + rerender({ entry: libraryEntry({ key: 'trip:7', origins: [tripOrigin({ place_id: 7 })] }) }); + expect(firstSignal.aborted).toBe(true); + expect(result.current).toEqual({ visits: [], count: 0, lastVisit: null, loading: true }); + resolveSecond({ visits: [], visit_count: 3, last_visit: '2025-01-01' }); + await waitFor(() => expect(result.current.count).toBe(3)); + expect(forPlace).toHaveBeenLastCalledWith('trip', 7, expect.any(AbortSignal)); + }); +}); diff --git a/client/src/components/Collections/usePlacesLibrary.test.ts b/client/src/components/Collections/usePlacesLibrary.test.ts index eb03a5e51..9a4dbd71e 100644 --- a/client/src/components/Collections/usePlacesLibrary.test.ts +++ b/client/src/components/Collections/usePlacesLibrary.test.ts @@ -15,6 +15,7 @@ import { } from '../../../tests/helpers/placesLibrary'; import { OnlineOnlyError } from '../../repo/onlineOnly'; import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; +import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'; import type { TranslationFn } from '../../types'; import { entryHasPosition, firstOrigin, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary'; @@ -61,6 +62,7 @@ beforeEach(() => { detail.mockReset(); coverPhoto.mockReset(); coverPhoto.mockResolvedValue(null); + useSaveToCollectionStore.setState({ version: 0 }); }); describe('parseEntryKey and entryHasPosition', () => { @@ -439,3 +441,41 @@ describe('usePlacesLibrary: the cover', () => { expect(firstOrigin([trip], 'own:9')).toBeNull(); }); }); + +describe('usePlacesLibrary: personal tags and outside saves', () => { + it('FE-COMP-PLACESLIBHOOK-027: picked tags go to the server, a second pick of one drops it, and reset clears them', async () => { + const { result } = await mountLoaded(libraryPage([])); + expect(result.current.tagIds).toEqual([]); + + act(() => { + result.current.toggleTag(4); + result.current.toggleTag(7); + }); + expect(result.current.tagIds).toEqual([4, 7]); + expect(result.current.filtered).toBe(true); + await waitFor(() => + expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, tag_ids: [4, 7] }, expect.any(AbortSignal)) + ); + + act(() => result.current.toggleTag(4)); + expect(result.current.tagIds).toEqual([7]); + await waitFor(() => + expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, tag_ids: [7] }, expect.any(AbortSignal)) + ); + + act(() => result.current.resetFilters()); + expect(result.current.tagIds).toEqual([]); + expect(result.current.filtered).toBe(false); + await waitFor(() => expect(list).toHaveBeenLastCalledWith(FIRST_PAGE, expect.any(AbortSignal))); + }); + + it('FE-COMP-PLACESLIBHOOK-028: a place saved to a list anywhere reads the overview again', async () => { + const { result } = await mountLoaded(libraryPage([])); + expect(list).toHaveBeenCalledTimes(1); + + list.mockResolvedValueOnce(libraryPage([libraryEntry()])); + act(() => useSaveToCollectionStore.getState().bumpVersion()); + await waitFor(() => expect(result.current.entries).toHaveLength(1)); + expect(list).toHaveBeenCalledTimes(2); + }); +}); diff --git a/client/src/components/Collections/useTripCopyPicker.test.ts b/client/src/components/Collections/useTripCopyPicker.test.ts index a827a9c3d..5c3f6d91e 100644 --- a/client/src/components/Collections/useTripCopyPicker.test.ts +++ b/client/src/components/Collections/useTripCopyPicker.test.ts @@ -1,4 +1,4 @@ -// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-011: the "Copy to trip" picker logic +// FE-COMP-TRIPCOPYHOOK-001 to FE-COMP-TRIPCOPYHOOK-013: the "Copy to trip" picker logic // behind both the desktop dialog and the phone sheet. import { act, renderHook, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest'; @@ -184,4 +184,40 @@ describe('useTripCopyPicker', () => { expect(result.current.includeNotes).toBe(false); expect(result.current.offersCarry).toBe(false); }); + + it('FE-COMP-TRIPCOPYHOOK-012: own tags stay private unless picked, and only the offered ones go along', async () => { + const carryOptions = { + hasNotes: false, + tags: [], + personalTags: [ + { id: 3, name: 'Coffee' }, + { id: 4, name: 'Wine' }, + ], + }; + const { result, props } = setup({ carryOptions }); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(result.current.offersCarry).toBe(true); + await act(() => result.current.handleCopy(1)); + expect(props.onCopy).toHaveBeenLastCalledWith(1, {}); + act(() => { + result.current.togglePersonalTag(4); + result.current.togglePersonalTag(99); + result.current.togglePersonalTag(3); + result.current.togglePersonalTag(3); + }); + expect(result.current.personalTagIds).toEqual([4, 99]); + await act(() => result.current.handleCopy(2)); + expect(props.onCopy).toHaveBeenLastCalledWith(2, { personal_tag_ids: [4] }); + }); + + it('FE-COMP-TRIPCOPYHOOK-013: a reopened picker drops the picked own tags', async () => { + const carryOptions = { hasNotes: false, tags: [], personalTags: [{ id: 3, name: 'Coffee' }] }; + const { result, rerender, props } = setup({ carryOptions }); + act(() => result.current.togglePersonalTag(3)); + expect(result.current.personalTagIds).toEqual([3]); + rerender({ ...props, open: false }); + rerender({ ...props, open: true, carryOptions: { hasNotes: false, tags: [], personalTags: [] } }); + expect(result.current.personalTagIds).toEqual([]); + expect(result.current.offersCarry).toBe(false); + }); }); diff --git a/client/src/components/Collections/useTripLists.test.ts b/client/src/components/Collections/useTripLists.test.ts new file mode 100644 index 000000000..c206cd634 --- /dev/null +++ b/client/src/components/Collections/useTripLists.test.ts @@ -0,0 +1,322 @@ +// FE-COMP-TRIPLISTS-001 to FE-COMP-TRIPLISTS-014: the lists a trip draws on (PLC-15) and +// their saved places as pins on the trip map (PLC-16), behind the desktop stage and the phone map. +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { Collection, TripCollectionLayerPlace, TripCollectionLink } from '@trek/shared'; +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; + +import { resetAllStores } from '../../../tests/helpers/store'; +import { addListener, removeListener } from '../../api/websocket'; +import { useCollectionStore } from '../../store/collectionStore'; +import { useTripCollectionsStore } from '../../store/tripCollectionsStore'; +import { useTripStore } from '../../store/tripStore'; +import { SAVED_PLACE_POI_CATEGORY, type Poi } from '../Map/poiCategories'; +import { savedPlaceIdOf, savedPlacePoi, useTripLists } from './useTripLists'; + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +const TRIP = 4; +const KEY = `anon:${TRIP}`; + +function link(collectionId: number, over: Partial = {}): TripCollectionLink { + return { + collection_id: collectionId, + name: `List ${collectionId}`, + color: null, + role: 'owner', + place_count: 2, + linked_by: 1, + created_at: null, + ...over, + }; +} + +function layerPlace(id: number, collectionId: number, over: Partial = {}) { + return { + id, + collection_id: collectionId, + name: `Place ${id}`, + lat: 1, + lng: 2, + category: null, + status: 'want', + in_trip: false, + trip_place_id: null, + ...over, + } satisfies TripCollectionLayerPlace; +} + +function list(id: number, over: Partial = {}): Collection { + return { id, name: `List ${id}`, color: null, icon: null, ...over } as Collection; +} + +let addToast: Mock>; +let load: Mock; +let loadLayer: Mock; +let linkFn: Mock; +let unlinkFn: Mock; +let loadAll: Mock; +let copyToTrip: Mock; +let refreshPlaces: Mock; + +function seedEntry(entry: { + links: TripCollectionLink[]; + canLink?: boolean; + layer?: TripCollectionLayerPlace[] | null; +}) { + useTripCollectionsStore.setState({ + trips: { [KEY]: { links: entry.links, canLink: entry.canLink ?? true, layer: entry.layer ?? null } }, + }); +} + +function setup(canEdit = true) { + return renderHook(({ edit }: { edit: boolean }) => useTripLists({ tripId: TRIP, canEdit: edit, t }), { + initialProps: { edit: canEdit }, + }); +} + +beforeEach(() => { + resetAllStores(); + addToast = vi.fn>(); + window.__addToast = addToast; + load = vi.fn().mockResolvedValue(undefined); + loadLayer = vi.fn().mockResolvedValue([]); + linkFn = vi.fn().mockResolvedValue(undefined); + unlinkFn = vi.fn().mockResolvedValue(undefined); + loadAll = vi.fn().mockResolvedValue(undefined); + copyToTrip = vi.fn().mockResolvedValue({ copied: 1, skipped: [] }); + refreshPlaces = vi.fn().mockResolvedValue(undefined); + useTripCollectionsStore.setState({ trips: {}, load, loadLayer, link: linkFn, unlink: unlinkFn }); + useCollectionStore.setState({ collections: [], loadAll, copyToTrip } as never); + useTripStore.setState({ refreshPlaces } as never); +}); + +afterEach(() => { + delete window.__addToast; +}); + +describe('savedPlacePoi / savedPlaceIdOf', () => { + it('FE-COMP-TRIPLISTS-001: a saved place becomes a saved-place pin in its list look, and maps back to its id', () => { + const poi = savedPlacePoi(layerPlace(7, 9, { name: 'Café', lat: 3, lng: 4 }), { color: '#f00', icon: 'coffee' }); + expect(poi).toMatchObject({ + osm_id: 'saved:7', + name: 'Café', + lat: 3, + lng: 4, + category: SAVED_PLACE_POI_CATEGORY, + poi_type: SAVED_PLACE_POI_CATEGORY, + source: 'list', + color: '#f00', + icon: 'coffee', + }); + expect(savedPlaceIdOf(poi)).toBe(7); + }); + + it('FE-COMP-TRIPLISTS-002: an empty look leaves colour and icon out; other or broken ids are not ours', () => { + const poi = savedPlacePoi(layerPlace(7, 9), { color: null, icon: '' }); + expect(poi).not.toHaveProperty('color'); + expect(poi).not.toHaveProperty('icon'); + expect(savedPlaceIdOf({ osm_id: 'node/123' })).toBeNull(); + expect(savedPlaceIdOf({ osm_id: 'saved:abc' })).toBeNull(); + expect(savedPlaceIdOf({ osm_id: 'saved:0' })).toBeNull(); + expect(savedPlaceIdOf({ osm_id: 'saved:-3' })).toBeNull(); + }); +}); + +describe('useTripLists', () => { + it('FE-COMP-TRIPLISTS-003: reads the links on mount, listens for pushes and stops on unmount', async () => { + const { result, unmount } = setup(); + await waitFor(() => expect(load).toHaveBeenCalledWith(TRIP)); + expect(addListener).toHaveBeenCalled(); + expect(result.current.links).toEqual([]); + expect(result.current.canLink).toBe(false); + expect(result.current.visible).toEqual([]); + expect(result.current.pois).toEqual([]); + unmount(); + expect(removeListener).toHaveBeenCalled(); + }); + + it('FE-COMP-TRIPLISTS-004: a failed read of the links stays quiet', async () => { + load.mockRejectedValue(new Error('offline')); + setup(); + await waitFor(() => expect(load).toHaveBeenCalled()); + await Promise.resolve(); + expect(addToast).not.toHaveBeenCalled(); + }); + + it('FE-COMP-TRIPLISTS-005: the layer starts off; showing a list reads it, remembers the choice and pins its places', async () => { + seedEntry({ links: [link(9), link(10)] }); + useCollectionStore.setState({ collections: [list(9, { color: '#0a0', icon: 'star' })] }); + const { result } = setup(); + expect(loadLayer).not.toHaveBeenCalled(); + + act(() => result.current.toggle(9)); + expect(result.current.visible).toEqual([9]); + expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([9]); + await waitFor(() => expect(loadLayer).toHaveBeenCalledWith(TRIP)); + + act(() => { + useTripCollectionsStore.setState({ + trips: { + [KEY]: { + links: [link(9), link(10, { color: '#00f' })], + canLink: true, + layer: [layerPlace(1, 9), layerPlace(2, 9, { in_trip: true }), layerPlace(3, 10)], + }, + }, + }); + }); + // Only the shown list, and only what the trip does not have yet. + expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1']); + expect(result.current.pois[0]).toMatchObject({ color: '#0a0', icon: 'star' }); + + act(() => result.current.toggle(10)); + // List 10 is not among the reader's lists, so its link's colour stands in. + expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1', 'saved:3']); + expect(result.current.pois[1]).toMatchObject({ color: '#00f' }); + expect(result.current.pois[1]).not.toHaveProperty('icon'); + + act(() => result.current.toggle(9)); + expect(result.current.visible).toEqual([10]); + expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([10]); + }); + + it('FE-COMP-TRIPLISTS-006: the remembered choice comes back, without what is no longer linked or not a number', () => { + localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify([9, 11, 'x', 1.5])); + seedEntry({ links: [link(9)], layer: [layerPlace(1, 9)] }); + const { result } = setup(); + expect(result.current.visible).toEqual([9]); + expect(result.current.pois.map((p) => p.osm_id)).toEqual(['saved:1']); + // The layer was there already, so it is not read again. + expect(loadLayer).not.toHaveBeenCalled(); + }); + + it('FE-COMP-TRIPLISTS-007: broken or non-list storage shows nothing', () => { + seedEntry({ links: [link(9)] }); + localStorage.setItem(`trek:tripListsShown:${TRIP}`, '{not json'); + expect(setup().result.current.visible).toEqual([]); + localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify({ 9: true })); + expect(setup().result.current.visible).toEqual([]); + }); + + it('FE-COMP-TRIPLISTS-008: a failed layer read toasts the error', async () => { + loadLayer.mockRejectedValue({ response: { data: { error: 'No layer' } } }); + localStorage.setItem(`trek:tripListsShown:${TRIP}`, JSON.stringify([9])); + seedEntry({ links: [link(9)] }); + setup(); + await waitFor(() => expect(addToast).toHaveBeenCalledWith('No layer', 'error', undefined)); + }); + + it('FE-COMP-TRIPLISTS-009: a tap on a saved pin asks to add it when the reader may edit; other pins pass on', () => { + const { result, rerender } = setup(true); + const saved = { osm_id: 'saved:5', name: 'Bakery' } as Poi; + let claimed = false; + act(() => { + claimed = result.current.claim(saved); + }); + expect(claimed).toBe(true); + expect(result.current.pending).toEqual({ id: 5, name: 'Bakery' }); + act(() => result.current.cancelPending()); + expect(result.current.pending).toBeNull(); + + expect(result.current.claim({ osm_id: 'node/1', name: 'Café' } as Poi)).toBe(false); + + rerender({ edit: false }); + act(() => { + claimed = result.current.claim(saved); + }); + // Still ours, so the map does nothing else with it, but a reader cannot add it. + expect(claimed).toBe(true); + expect(result.current.pending).toBeNull(); + }); + + it('FE-COMP-TRIPLISTS-010: adding the pending place copies it, toasts, and reads the trip and layer again', async () => { + const { result } = setup(); + act(() => { + result.current.claim({ osm_id: 'saved:5', name: 'Bakery' } as Poi); + }); + await act(async () => { + await result.current.addPending(); + }); + expect(copyToTrip).toHaveBeenCalledWith(TRIP, [5]); + expect(addToast).toHaveBeenCalledWith('tripLists.added:{"name":"Bakery"}', 'success', undefined); + expect(refreshPlaces).toHaveBeenCalledWith(TRIP); + expect(loadLayer).toHaveBeenCalledWith(TRIP); + expect(result.current.pending).toBeNull(); + expect(result.current.busy).toBe(false); + }); + + it('FE-COMP-TRIPLISTS-011: a place the trip has already gets an info note; a failed copy toasts and keeps it pending', async () => { + copyToTrip.mockResolvedValueOnce({ copied: 0, skipped: [{ id: 5, name: 'Bakery' }] }); + const { result } = setup(); + act(() => { + result.current.claim({ osm_id: 'saved:5', name: 'Bakery' } as Poi); + }); + await act(async () => { + await result.current.addPending(); + }); + expect(addToast).toHaveBeenCalledWith('tripLists.alreadyInTrip:{"name":"Bakery"}', 'info', undefined); + + copyToTrip.mockRejectedValueOnce({ response: { data: { error: 'Nope' } } }); + act(() => { + result.current.claim({ osm_id: 'saved:6', name: 'Bar' } as Poi); + }); + await act(async () => { + await result.current.addPending(); + }); + expect(addToast).toHaveBeenLastCalledWith('Nope', 'error', undefined); + expect(result.current.pending).toEqual({ id: 6, name: 'Bar' }); + expect(result.current.busy).toBe(false); + }); + + it('FE-COMP-TRIPLISTS-012: adding with nothing pending copies nothing', async () => { + const { result } = setup(); + await act(async () => { + await result.current.addPending(); + }); + expect(copyToTrip).not.toHaveBeenCalled(); + }); + + it('FE-COMP-TRIPLISTS-013: linking shows the new list on the map; unlinking goes through the store; failures toast', async () => { + seedEntry({ links: [link(9)] }); + useCollectionStore.setState({ collections: [list(9), list(12)] }); + const { result } = setup(); + expect(result.current.linkable.map((c) => c.id)).toEqual([12]); + + linkFn.mockImplementation(async () => { + seedEntry({ links: [link(9), link(12)] }); + }); + await act(async () => { + await result.current.link(12); + }); + expect(linkFn).toHaveBeenCalledWith(TRIP, 12); + expect(result.current.visible).toEqual([12]); + expect(JSON.parse(localStorage.getItem(`trek:tripListsShown:${TRIP}`) ?? 'null')).toEqual([12]); + expect(result.current.linkable).toEqual([]); + + await act(async () => { + await result.current.unlink(9); + }); + expect(unlinkFn).toHaveBeenCalledWith(TRIP, 9); + + unlinkFn.mockRejectedValueOnce(new Error('boom')); + await act(async () => { + await result.current.unlink(12); + }); + // No server message, so the generic one. + expect(addToast).toHaveBeenLastCalledWith('common.error', 'error', undefined); + }); + + it('FE-COMP-TRIPLISTS-014: the reader lists are read once for the picker, a failure toasts', async () => { + const { result } = setup(); + act(() => result.current.loadLinkable()); + expect(loadAll).toHaveBeenCalledTimes(1); + + loadAll.mockRejectedValueOnce({ response: { data: { error: 'Down' } } }); + act(() => result.current.loadLinkable()); + await waitFor(() => expect(addToast).toHaveBeenCalledWith('Down', 'error', undefined)); + + act(() => useCollectionStore.setState({ collections: [list(9)] })); + act(() => result.current.loadLinkable()); + expect(loadAll).toHaveBeenCalledTimes(2); + }); +}); diff --git a/client/src/components/Map/poiCategories.test.ts b/client/src/components/Map/poiCategories.test.ts index 349e6593d..15c592e30 100644 --- a/client/src/components/Map/poiCategories.test.ts +++ b/client/src/components/Map/poiCategories.test.ts @@ -1,7 +1,7 @@ -// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-005 +// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-007 import { describe, it, expect } from 'vitest' -import { Coffee, Fuel, MapPin, Signpost } from 'lucide-react' -import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES } from './poiCategories' +import { Bookmark, Coffee, Fuel, Heart, MapPin, Signpost } from 'lucide-react' +import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES, SAVED_PLACE_POI_CATEGORY } from './poiCategories' import { POI_DEFAULT_COLOR } from './pluginPoiIcons' const PLUGIN_KEY = 'plugin:trail-finder/trailheads' @@ -31,4 +31,15 @@ describe('poiAppearance', () => { expect(poiAppearance({ category, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: null }) } }) + it('FE-COMP-POIAPPEAR-006: a saved place of a linked list wears the list symbol in the list colour', () => { + expect(SAVED_PLACE_POI_CATEGORY).toBe('saved-place') + expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, color: '#E11D48', icon: 'Heart' })).toEqual({ color: '#E11D48', Icon: Heart }) + }) + + it('FE-COMP-POIAPPEAR-007: a saved place without a valid #rrggbb colour or known symbol falls back to the accent and a bookmark', () => { + for (const color of [undefined, '', 'red', '#fff', '#12345g', 'var(--x)']) { + expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, color }).color).toBe('var(--accent)') + } + expect(poiAppearance({ category: SAVED_PLACE_POI_CATEGORY, icon: 'NoSuchIcon' }).Icon).toBe(Bookmark) + }) }) diff --git a/client/src/components/Planner/PlacesSidebar.b4a.test.tsx b/client/src/components/Planner/PlacesSidebar.b4a.test.tsx index 194556cd9..858f36147 100644 --- a/client/src/components/Planner/PlacesSidebar.b4a.test.tsx +++ b/client/src/components/Planner/PlacesSidebar.b4a.test.tsx @@ -72,7 +72,7 @@ describe('B4A Places pool', () => { 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.filterCounts).toEqual({ all: 3, unplanned: 1, planned: 1, visited: 0, tracks: 1 }) expect(sidebar.hasTracks).toBe(false) act(() => sidebar.setPlacesSort('name')) expect(sidebar.filtered.map(place => place.id)).toEqual([3, 4, 2]) @@ -101,7 +101,7 @@ describe('B4A Places pool', () => { const { rerender } = render() 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 }) + expect(sidebar.filterCounts).toEqual({ all: 1, unplanned: 1, planned: 0, visited: 0, tracks: 0 }) rerender() expect(sidebar.filtered).toEqual([]) expect(sidebar.filterCounts.all).toBe(0) diff --git a/client/src/components/Planner/usePlacesPool.test.ts b/client/src/components/Planner/usePlacesPool.test.ts index f2b1f0db9..b46943a52 100644 --- a/client/src/components/Planner/usePlacesPool.test.ts +++ b/client/src/components/Planner/usePlacesPool.test.ts @@ -66,6 +66,15 @@ describe('places pool helpers', () => { ]); expect(placesFilterTabs(t, true).map((tab) => tab.id)).toEqual(['all', 'unplanned', 'planned', 'tracks']); expect(placesFilterTabs(t, true)[3].label).toBe('places.filterTracks'); + // Visited (PLC-23) sits before tracks, once the reader has been somewhere on the trip. + expect(placesFilterTabs(t, true, true).map((tab) => tab.id)).toEqual([ + 'all', + 'unplanned', + 'planned', + 'visited', + 'tracks', + ]); + expect(placesFilterTabs(t, false, true)[3].label).toBe('places.filterVisited'); }); it('FE-PLANNER-POOL-003: the category filter toggles ids in the trip store, a new set each time', () => { diff --git a/client/src/components/Planner/usePlacesSidebar.test.tsx b/client/src/components/Planner/usePlacesSidebar.test.tsx index 969901f88..4769e0d18 100644 --- a/client/src/components/Planner/usePlacesSidebar.test.tsx +++ b/client/src/components/Planner/usePlacesSidebar.test.tsx @@ -1,4 +1,4 @@ -// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-060 +// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-061 import { http, HttpResponse } from 'msw'; import userEvent from '@testing-library/user-event'; import { render, screen, fireEvent, act, waitFor } from '../../../tests/helpers/render'; @@ -10,6 +10,7 @@ import { useTripStore } from '../../store/tripStore'; import { usePermissionsStore } from '../../store/permissionsStore'; import { useAddonStore } from '../../store/addonStore'; import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'; +import { usePlaceVisitsStore } from '../../store/placeVisitsStore'; import { ContextMenu } from '../shared/ContextMenu'; import type { Place } from '../../types'; import { usePlacesSidebar, type PlacesSidebarProps, type SidebarState } from './usePlacesSidebar'; @@ -201,7 +202,7 @@ describe('usePlacesSidebar filtering', () => { expect(S.hasTracks).toBe(false); expect(names()).toEqual(expect.arrayContaining(['Legacy track', 'Ordinary place'])); expect(names()).not.toContain('Tour place'); - expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, tracks: 1 }); + expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, visited: 0, tracks: 1 }); expect(S.localities).toEqual([{ country: 'Austria', count: 2, regions: [] }]); act(() => { S.setRatingFilter(4); }); @@ -219,7 +220,7 @@ describe('usePlacesSidebar filtering', () => { })} />); expect(S.hasTracks).toBe(true); - expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, tracks: 2 }); + expect(S.filterCounts).toEqual({ all: 2, unplanned: 2, planned: 0, visited: 0, tracks: 2 }); act(() => { S.setFilter('tracks'); }); expect(names()).toEqual(expect.arrayContaining(['Legacy track', 'Dormant Tour'])); }); @@ -776,14 +777,14 @@ describe('usePlacesSidebar filter panel', () => { const other = buildPlace({ id: 3, name: 'Beta', category_id: null }); const assignments = { '9': [buildAssignment({ place: planned, day_id: 9 })] }; render(); - expect(S.filterCounts).toEqual({ all: 3, unplanned: 2, planned: 1, tracks: 1 }); + expect(S.filterCounts).toEqual({ all: 3, unplanned: 2, planned: 1, visited: 0, tracks: 1 }); act(() => { S.setSearch('alpha'); }); act(() => { S.setRatingFilter(5); }); - expect(S.filterCounts).toEqual({ all: 2, unplanned: 1, planned: 1, tracks: 1 }); + expect(S.filterCounts).toEqual({ all: 2, unplanned: 1, planned: 1, visited: 0, tracks: 1 }); act(() => { S.setCategoryFilters(new Set(['uncategorized'])); }); - expect(S.filterCounts).toEqual({ all: 0, unplanned: 0, planned: 0, tracks: 0 }); + expect(S.filterCounts).toEqual({ all: 0, unplanned: 0, planned: 0, visited: 0, tracks: 0 }); }); it('FE-PLANNER-PSHOOK-054: while a day is open "planned" counts that day only', () => { @@ -806,6 +807,23 @@ describe('usePlacesSidebar filter panel', () => { expect(S.selectedIds.size).toBe(0); }); + it('FE-PLANNER-PSHOOK-061: the places the reader visited are counted, offered and filtered (PLC-23)', async () => { + const userId = useAuthStore.getState().user?.id; + const entry = { placeIds: [2], places: [] }; + const loadTripVisited = vi.fn(async () => { + usePlaceVisitsStore.setState({ visited: { [`${userId}:1`]: entry } }); + return entry; + }); + usePlaceVisitsStore.setState({ visited: {}, loadTripVisited }); + render(); + expect(S.hasVisited).toBe(false); + await waitFor(() => expect(S.filterCounts.visited).toBe(1)); + expect(loadTripVisited).toHaveBeenCalledWith(1); + expect(S.hasVisited).toBe(true); + act(() => { S.pickFilter('visited'); }); + expect(names()).toEqual(['Beta']); + }); + }); describe('usePlacesSidebar row menu entries', () => { diff --git a/client/src/hooks/useTripVisitedIds.test.ts b/client/src/hooks/useTripVisitedIds.test.ts new file mode 100644 index 000000000..414108f18 --- /dev/null +++ b/client/src/hooks/useTripVisitedIds.test.ts @@ -0,0 +1,62 @@ +// FE-HOOK-TRIPVISITED-001 to FE-HOOK-TRIPVISITED-004: the trip's visited places for the place filter. +import { renderHook, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildUser } from '../../tests/helpers/factories'; +import { resetAllStores, seedStore } from '../../tests/helpers/store'; +import { addListener, removeListener } from '../api/websocket'; +import { placeVisitsRepo } from '../repo/placeVisitsRepo'; +import { useAuthStore } from '../store/authStore'; +import { usePlaceVisitsStore } from '../store/placeVisitsStore'; +import { useTripVisitedIds } from './useTripVisitedIds'; + +const VISITED = { place_ids: [3, 7], places: [] }; + +beforeEach(() => { + resetAllStores(); + vi.restoreAllMocks(); + vi.mocked(addListener).mockClear(); + vi.mocked(removeListener).mockClear(); + usePlaceVisitsStore.setState({ visited: {}, revision: 0 }); + seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true }); +}); + +describe('useTripVisitedIds', () => { + it('FE-HOOK-TRIPVISITED-001: reads the trip and hands back its visited place ids', async () => { + const read = vi.spyOn(placeVisitsRepo, 'tripVisited').mockResolvedValue(VISITED); + const { result } = renderHook(() => useTripVisitedIds(4)); + expect(result.current.size).toBe(0); + await waitFor(() => expect(result.current.size).toBe(2)); + expect(read).toHaveBeenCalledWith(4); + expect(result.current.has(3)).toBe(true); + expect(result.current.has(5)).toBe(false); + }); + + it('FE-HOOK-TRIPVISITED-002: without a trip nothing is read and the set stays empty', () => { + const read = vi.spyOn(placeVisitsRepo, 'tripVisited').mockResolvedValue(VISITED); + const { result } = renderHook(() => useTripVisitedIds(null)); + expect(read).not.toHaveBeenCalled(); + expect(result.current.size).toBe(0); + }); + + it('FE-HOOK-TRIPVISITED-003: offline the set stays empty and nothing throws', async () => { + const read = vi.spyOn(placeVisitsRepo, 'tripVisited').mockRejectedValue(new Error('offline')); + const { result } = renderHook(() => useTripVisitedIds(4)); + await waitFor(() => expect(read).toHaveBeenCalledTimes(1)); + expect(result.current.size).toBe(0); + }); + + it('FE-HOOK-TRIPVISITED-004: follows the trip events while mounted and stops on unmount', async () => { + vi.spyOn(placeVisitsRepo, 'tripVisited').mockResolvedValue(VISITED); + const { result, unmount, rerender } = renderHook(() => useTripVisitedIds(4)); + await waitFor(() => expect(result.current.size).toBe(2)); + const first = result.current; + rerender(); + // The same answer keeps the same set, so the filters do not run again. + expect(result.current).toBe(first); + expect(addListener).toHaveBeenCalledTimes(1); + const listener = vi.mocked(addListener).mock.calls[0][0]; + unmount(); + expect(removeListener).toHaveBeenCalledWith(listener); + }); +}); diff --git a/client/src/mobile/screens/collections/MEntryTagsSection.test.tsx b/client/src/mobile/screens/collections/MEntryTagsSection.test.tsx new file mode 100644 index 000000000..6e6d4c91e --- /dev/null +++ b/client/src/mobile/screens/collections/MEntryTagsSection.test.tsx @@ -0,0 +1,132 @@ +// FE-MOB-ENTRYTAGS-001 to FE-MOB-ENTRYTAGS-006: the reader's own tags on a place in the +// phone sheet of All places (PLC-21), rendered against a mocked useEntryTags. +import type { Tag } from '@trek/shared'; + +import { bothOrigins } from '../../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../../tests/helpers/render'; +import type { useEntryTags } from '../../../components/Collections/useEntryTags'; +import MEntryTagsSection from './MEntryTagsSection'; + +type EntryTags = ReturnType; + +const hook = vi.hoisted(() => ({ state: null as unknown as EntryTags, args: [] as unknown[] })); +vi.mock('../../../components/Collections/useEntryTags', () => ({ + useEntryTags: (args: unknown) => { + hook.args.push(args); + return hook.state; + }, +})); + +vi.mock('../../../components/shared/ConfirmDialog', () => ({ + default: ({ isOpen, onConfirm, title }: { isOpen: boolean; onConfirm: () => void; title: string }) => + isOpen ? ( +
+ +
+ ) : null, +})); + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +const tag = (id: number, name: string, color = '#aa0000'): Tag => ({ id, user_id: 1, trip_id: null, name, color }); +const BEACH = tag(1, 'Beach'); +const WINE = tag(3, 'Wine', ''); + +function state(over: Partial = {}): EntryTags { + return { + all: [BEACH, WINE], + assigned: [], + assignedIds: [], + query: '', + setQuery: vi.fn(), + matches: [BEACH, WINE], + canCreate: false, + toggle: vi.fn(() => Promise.resolve()), + createAndAdd: vi.fn(() => Promise.resolve()), + rename: vi.fn(() => Promise.resolve()), + destroy: vi.fn(() => Promise.resolve()), + busy: false, + ...over, + }; +} + +function mount(over: Partial = {}) { + hook.state = state(over); + render(); + return hook.state; +} + +const openPicker = () => fireEvent.click(screen.getByRole('button', { name: 'placeTags.add' })); + +beforeEach(() => { + hook.args.length = 0; +}); + +describe('MEntryTagsSection', () => { + it('FE-MOB-ENTRYTAGS-001: says the tags are private until the picker opens, and the button closes it again', () => { + mount(); + expect(screen.getByText('placeTags.private')).toBeInTheDocument(); + openPicker(); + expect(screen.queryByText('placeTags.private')).toBeNull(); + const close = screen.getByRole('button', { name: 'common.close' }); + expect(close).toHaveAttribute('aria-expanded', 'true'); + fireEvent.click(close); + expect(screen.queryByRole('textbox', { name: 'placeTags.search' })).toBeNull(); + }); + + it('FE-MOB-ENTRYTAGS-002: shows the carried tags as chips and ticks them in the picker', () => { + const tags = mount({ assigned: [{ id: 3, name: 'Wine', color: null }], assignedIds: [3] }); + expect(screen.getByText('Wine')).toBeInTheDocument(); + openPicker(); + expect(screen.getByRole('button', { name: 'Wine' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByRole('button', { name: 'Beach' })).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(screen.getByRole('button', { name: 'Beach' })); + expect(tags.toggle).toHaveBeenCalledWith(1); + }); + + it('FE-MOB-ENTRYTAGS-003: types into the search and makes a new tag from it by tap or Enter', () => { + const tags = mount({ query: ' Rooftop ', matches: [], canCreate: true }); + openPicker(); + const search = screen.getByRole('textbox', { name: 'placeTags.search' }); + fireEvent.change(search, { target: { value: 'R' } }); + expect(tags.setQuery).toHaveBeenCalledWith('R'); + fireEvent.click(screen.getByRole('button', { name: 'placeTags.create:{"name":"Rooftop"}' })); + fireEvent.submit(search); + expect(tags.createAndAdd).toHaveBeenCalledTimes(2); + }); + + it('FE-MOB-ENTRYTAGS-004: no match and nothing to make says so, and Enter makes nothing', () => { + const tags = mount({ query: 'zz', matches: [] }); + openPicker(); + expect(screen.getByText('placeTags.none')).toBeInTheDocument(); + fireEvent.submit(screen.getByRole('textbox', { name: 'placeTags.search' })); + expect(tags.createAndAdd).not.toHaveBeenCalled(); + }); + + it('FE-MOB-ENTRYTAGS-005: renames a tag in place, or cancels', () => { + const tags = mount(); + openPicker(); + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[1]); + const input = screen.getByRole('textbox', { name: 'placeTags.rename' }); + expect(input).toHaveValue('Wine'); + fireEvent.change(input, { target: { value: 'Red wine' } }); + fireEvent.submit(input); + expect(tags.rename).toHaveBeenCalledWith(3, 'Red wine'); + + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.rename' })[0]); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + expect(screen.queryByRole('textbox', { name: 'placeTags.rename' })).toBeNull(); + expect(tags.rename).toHaveBeenCalledTimes(1); + }); + + it('FE-MOB-ENTRYTAGS-006: deleting asks first and then deletes the tag', () => { + const tags = mount(); + openPicker(); + fireEvent.click(screen.getAllByRole('button', { name: 'placeTags.delete' })[0]); + expect(screen.getByRole('dialog', { name: 'placeTags.deleteTitle:{"name":"Beach"}' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'confirm' })); + expect(tags.destroy).toHaveBeenCalledWith(1); + }); +}); diff --git a/client/src/mobile/screens/collections/MOriginNotesSection.test.tsx b/client/src/mobile/screens/collections/MOriginNotesSection.test.tsx new file mode 100644 index 000000000..7b3ce27cc --- /dev/null +++ b/client/src/mobile/screens/collections/MOriginNotesSection.test.tsx @@ -0,0 +1,83 @@ +// FE-MOB-ORIGINNOTES-001 to FE-MOB-ORIGINNOTES-004: the notes of a place on the phone sheet. +import type { PlacesLibraryDetailResponse } from '@trek/shared'; +import type { MockInstance } from 'vitest'; + +import { + libraryDetail, + libraryEntry, + listDetail, + listOrigin, + tripDetail, + tripOrigin, +} from '../../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render'; +import { placesLibraryRepo } from '../../../repo/placesLibraryRepo'; +import MOriginNotesSection from './MOriginNotesSection'; + +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('../../../components/shared/Toast', () => { + const toast = { error: toastError, success: vi.fn(), warning: vi.fn(), info: vi.fn() }; + return { useToast: () => toast }; +}); + +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +function data(listNotes: string | null, canEdit = true): PlacesLibraryDetailResponse { + const entry = libraryEntry({ + origins: [tripOrigin({ can_edit: canEdit }), listOrigin({ can_edit: canEdit })], + }); + return libraryDetail(entry, [tripDetail(), listDetail({ notes: listNotes })]); +} + +let saveNotes: MockInstance; + +beforeEach(() => { + toastError.mockReset(); + saveNotes = vi.spyOn(placesLibraryRepo, 'saveNotes').mockResolvedValue(undefined); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('MOriginNotesSection', () => { + it('FE-MOB-ORIGINNOTES-001: nothing to read and nowhere to write leaves the section out', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-MOB-ORIGINNOTES-002: a read-only note shows its text and source, without pencil or plus', () => { + render(); + expect(screen.getByText('COLLECTIONS.NOTES')).toBeInTheDocument(); + expect(screen.getByText('Favourites')).toBeInTheDocument(); + expect(screen.getByText('Ask for Marco')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'placeNotes.edit' })).toBeNull(); + expect(screen.queryByRole('button', { name: 'placeNotes.add' })).toBeNull(); + }); + + it('FE-MOB-ORIGINNOTES-003: edits a note and saves the change, a failure toasts and keeps it open', async () => { + const onSaved = vi.fn(); + saveNotes.mockRejectedValueOnce(new Error('offline')); + render(); + fireEvent.click(screen.getByRole('button', { name: 'placeNotes.edit' })); + const field = screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Favourites"}' }); + expect(field).toHaveValue('Ask for Marco'); + fireEvent.change(field, { target: { value: 'Ask for Giulia' } }); + fireEvent.click(screen.getByRole('button', { name: 'common.save' })); + await waitFor(() => expect(toastError).toHaveBeenCalledWith('common.error')); + expect(screen.getByRole('textbox')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'common.save' })); + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(saveNotes).toHaveBeenLastCalledWith({ kind: 'list', collection_place_id: 900 }, 'Ask for Giulia'); + expect(screen.queryByRole('textbox')).toBeNull(); + }); + + it('FE-MOB-ORIGINNOTES-004: the plus asks where with several empty places, a pick opens it and cancel closes it', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'placeNotes.add' })); + fireEvent.click(screen.getByRole('button', { name: /Rome 2026/ })); + expect(screen.getByRole('textbox', { name: 'placeNotes.fieldLabel:{"source":"Rome 2026"}' })).toHaveValue(''); + fireEvent.click(screen.getByRole('button', { name: 'common.cancel' })); + expect(screen.queryByRole('textbox')).toBeNull(); + }); +}); diff --git a/client/src/mobile/screens/collections/MPlaceActivitiesSection.test.tsx b/client/src/mobile/screens/collections/MPlaceActivitiesSection.test.tsx new file mode 100644 index 000000000..5be23ed7e --- /dev/null +++ b/client/src/mobile/screens/collections/MPlaceActivitiesSection.test.tsx @@ -0,0 +1,92 @@ +// FE-M-PLACEACTSECTION-001 to FE-M-PLACEACTSECTION-005: the tours and bookings of a place +// on the phone (PLC-18), against a mocked hook. +import { + activitiesState, + activityCandidate, + listSource, + placeActivity, + tripSource, +} from '../../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../../tests/helpers/render'; +import { usePlaceActivities } from '../../../components/Collections/usePlaceActivities'; +import MPlaceActivitiesSection from './MPlaceActivitiesSection'; + +const mockNavigate = vi.fn(); +vi.mock('react-router', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, useNavigate: () => mockNavigate }; +}); + +vi.mock('../../../components/Collections/usePlaceActivities', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, usePlaceActivities: vi.fn() }; +}); + +const hook = vi.mocked(usePlaceActivities); +const t = (k: string) => k; + +function show(state = activitiesState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + mockNavigate.mockClear(); + hook.mockReset(); +}); + +describe('MPlaceActivitiesSection', () => { + it('FE-M-PLACEACTSECTION-001: is not there with nothing linked and nothing to link', () => { + show(); + expect(screen.queryByText('PLACEACTIVITIES.TITLE')).toBeNull(); + }); + + it('FE-M-PLACEACTSECTION-002: an activity opens where it lives, a said link comes off again', () => { + const linked = placeActivity(); + const implicit = placeActivity({ key: 'reservation:8', title: 'Dinner', can_unlink: false }); + const state = show(activitiesState({ activities: [linked, implicit] })); + expect(screen.getByText('PLACEACTIVITIES.TITLE')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Colosseum tickets/ })); + expect(mockNavigate).toHaveBeenCalledWith('/trips/5?booking=7'); + const unlink = screen.getAllByRole('button', { name: 'placeActivities.unlink' }); + expect(unlink).toHaveLength(1); + fireEvent.click(unlink[0]); + expect(state.unlink).toHaveBeenCalledWith(linked); + expect(screen.queryByRole('button', { name: 'placeActivities.link' })).toBeNull(); + }); + + it('FE-M-PLACEACTSECTION-003: with nothing linked yet the round button opens the picker', () => { + const state = show(activitiesState({ canLink: true })); + expect(screen.getByText('placeActivities.none')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'placeActivities.link' })); + expect(state.openPicker).toHaveBeenCalledTimes(1); + expect(state.closePicker).not.toHaveBeenCalled(); + }); + + it('FE-M-PLACEACTSECTION-004: an open picker lists the candidates, links one, and the button closes it', () => { + const tour = activityCandidate({ key: 'collection_tour:3', type: 'tour', title: 'Old town walk' }); + const state = show( + activitiesState({ + canLink: true, + picking: [ + { source: tripSource(), candidates: [activityCandidate()] }, + { source: listSource(), candidates: [tour] }, + ], + }) + ); + expect(screen.queryByText('placeActivities.none')).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: /Old town walk/ })); + expect(state.link).toHaveBeenCalledWith(listSource(), tour); + fireEvent.click(screen.getByRole('button', { name: 'common.close' })); + expect(state.closePicker).toHaveBeenCalledTimes(1); + expect(state.openPicker).not.toHaveBeenCalled(); + }); + + it('FE-M-PLACEACTSECTION-005: a picker without candidates says so, and a running write disables the buttons', () => { + show(activitiesState({ canLink: true, busy: true, picking: [{ source: tripSource(), candidates: [] }] })); + expect(screen.getByText('placeActivities.nothingToLink')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'common.close' })).toBeDisabled(); + }); +}); diff --git a/client/src/mobile/screens/collections/MPlaceHistorySection.test.tsx b/client/src/mobile/screens/collections/MPlaceHistorySection.test.tsx new file mode 100644 index 000000000..0988c0ec8 --- /dev/null +++ b/client/src/mobile/screens/collections/MPlaceHistorySection.test.tsx @@ -0,0 +1,66 @@ +// FE-M-PLACEHISTSECTION-001 to FE-M-PLACEHISTSECTION-004: the change history of a place +// on the phone (PLC-14), against a mocked hook. +import { historyEntries, historyEntry, historyState } from '../../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../../tests/helpers/render'; +import { usePlaceHistory } from '../../../components/Collections/usePlaceHistory'; +import MPlaceHistorySection from './MPlaceHistorySection'; + +vi.mock('../../../components/Collections/usePlaceHistory', () => ({ usePlaceHistory: vi.fn() })); + +const hook = vi.mocked(usePlaceHistory); +const t = (k: string) => k; + +function show(state = historyState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + hook.mockReset(); +}); + +describe('MPlaceHistorySection', () => { + it('FE-M-PLACEHISTSECTION-001: is not there before the first change', () => { + show(); + expect(screen.queryByText('PLACEHISTORY.TITLE')).toBeNull(); + }); + + it('FE-M-PLACEHISTSECTION-002: a change shows from and to, where, who and when', () => { + show( + historyState({ + entries: [ + historyEntry(), + historyEntry({ + id: 2, + field: 'opening_hours', + automatic: true, + origin: { kind: 'list', collection_id: 9, collection_name: 'Favourites', collection_place_id: 900 }, + }), + ], + }) + ); + expect(screen.getByText('PLACEHISTORY.TITLE')).toBeInTheDocument(); + expect(screen.getByText('Colosseo')).toHaveClass('line-through'); + expect(screen.getByText('Colosseum')).toBeInTheDocument(); + expect(screen.getByText(/Rome 2026, anna/)).toBeInTheDocument(); + expect(screen.getByText('placeHistory.field.opening_hours')).toBeInTheDocument(); + expect(screen.getByText(/Favourites, placeHistory\.automatic/)).toBeInTheDocument(); + expect(screen.queryByRole('button')).toBeNull(); + }); + + it('FE-M-PLACEHISTSECTION-003: shows three at first, then all, then reads more', () => { + const state = show(historyState({ entries: historyEntries(4), hasMore: true })); + expect(screen.getAllByRole('listitem')).toHaveLength(3); + fireEvent.click(screen.getByRole('button', { name: 'placeHistory.showAll' })); + expect(screen.getAllByRole('listitem')).toHaveLength(4); + fireEvent.click(screen.getByRole('button', { name: 'placeHistory.more' })); + expect(state.more).toHaveBeenCalledTimes(1); + }); + + it('FE-M-PLACEHISTSECTION-004: a few changes with more on the server still offer "show all"; loading waits', () => { + show(historyState({ entries: historyEntries(2), hasMore: true, loadingMore: true })); + expect(screen.getByRole('button', { name: 'placeHistory.showAll' })).toBeDisabled(); + }); +}); diff --git a/client/src/mobile/screens/collections/MPlaceMediaSection.test.tsx b/client/src/mobile/screens/collections/MPlaceMediaSection.test.tsx new file mode 100644 index 000000000..24b4d0688 --- /dev/null +++ b/client/src/mobile/screens/collections/MPlaceMediaSection.test.tsx @@ -0,0 +1,65 @@ +// FE-M-PLACEMEDIASECTION-001 to FE-M-PLACEMEDIASECTION-004: the pictures and trip files of +// a place on the phone (PLC-19, PLC-20), against a mocked hook. +import { mediaFile, mediaState, photos } from '../../../../tests/helpers/placeExtras'; +import { libraryEntry } from '../../../../tests/helpers/placesLibrary'; +import { fireEvent, render, screen } from '../../../../tests/helpers/render'; +import { usePlaceMedia } from '../../../components/Collections/usePlaceMedia'; +import MPlaceMediaSection from './MPlaceMediaSection'; + +vi.mock('../../../components/Collections/usePlaceMedia', () => ({ usePlaceMedia: vi.fn() })); +vi.mock('../../../components/Journey/PhotoLightbox', () => ({ + default: (p: { photos: { id: string }[]; startIndex: number; label?: string; onClose: () => void }) => ( +
+ {`${p.photos.length} from ${p.startIndex}`} + +
+ ), +})); + +const hook = vi.mocked(usePlaceMedia); +const t = (k: string) => k; + +function show(state = mediaState()) { + hook.mockReturnValue(state); + render(); + return state; +} + +beforeEach(() => { + hook.mockReset(); +}); + +describe('MPlaceMediaSection', () => { + it('FE-M-PLACEMEDIASECTION-001: is not there without pictures or files', () => { + show(); + expect(screen.queryByText('PLACES.MEDIA.PHOTOS')).toBeNull(); + expect(screen.queryByText('PLACES.MEDIA.FILES')).toBeNull(); + }); + + it('FE-M-PLACEMEDIASECTION-002: shows six and counts the rest; a tap opens that picture', () => { + const state = show(mediaState({ photos: photos(9) })); + expect(screen.getByText('PLACES.MEDIA.PHOTOS')).toBeInTheDocument(); + expect(screen.queryByText('PLACES.MEDIA.FILES')).toBeNull(); + expect(screen.getAllByRole('button')).toHaveLength(6); + expect(screen.getByText('+3')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Photo 4' })); + expect(state.setOpen).toHaveBeenCalledWith(4); + }); + + it('FE-M-PLACEMEDIASECTION-003: files alone show without a picture row and link to their trip', () => { + show(mediaState({ files: [mediaFile()] })); + expect(screen.queryByText('PLACES.MEDIA.PHOTOS')).toBeNull(); + const file = screen.getByRole('link', { name: /tickets\.pdf/ }); + expect(file).toHaveAttribute('href', '/trips/5/files?file=31'); + expect(file).toHaveTextContent('Rome 2026'); + }); + + it('FE-M-PLACEMEDIASECTION-004: the open picture shows in the lightbox, which closes again', () => { + const state = show(mediaState({ photos: photos(2), open: 1 })); + expect(screen.getByRole('dialog', { name: 'Colosseum' })).toHaveTextContent('2 from 1'); + fireEvent.click(screen.getByRole('button', { name: 'close lightbox' })); + expect(state.close).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/mobile/screens/collections/MVisitsSection.test.tsx b/client/src/mobile/screens/collections/MVisitsSection.test.tsx new file mode 100644 index 000000000..dc0ec57cd --- /dev/null +++ b/client/src/mobile/screens/collections/MVisitsSection.test.tsx @@ -0,0 +1,87 @@ +// FE-MOB-VISITS-001 to FE-MOB-VISITS-005: the visits of a place on the phone sheets. +import type { PlaceVisit } from '@trek/shared'; + +import { libraryEntry } from '../../../../tests/helpers/placesLibrary'; +import { render, screen } from '../../../../tests/helpers/render'; +import { visitDate } from '../../../components/Collections/libraryDates'; +import { usePlaceVisits } from '../../../components/Collections/usePlaceVisits'; +import MVisitsSection, { MTripPlaceVisits } from './MVisitsSection'; + +vi.mock('../../../components/Collections/usePlaceVisits', async (importOriginal) => ({ + ...(await importOriginal()), + usePlaceVisits: vi.fn(), +})); + +const hook = vi.mocked(usePlaceVisits); +const t = (k: string, p?: Record) => (p ? `${k}:${JSON.stringify(p)}` : k); + +function visit(over: Partial = {}): PlaceVisit { + return { + visited_on: '2026-07-02', + visited_time: null, + trip: { id: 5, title: 'Rome 2026' }, + place_id: 42, + day_id: 3, + day_number: 2, + name: 'Colosseum', + participants: [], + ...over, + }; +} + +function visits(list: PlaceVisit[], lastVisit: string | null = '2026-07-02') { + hook.mockReturnValue({ visits: list, count: list.length, lastVisit, loading: false }); +} + +const summary = (count: number) => + `visits.summary:${JSON.stringify({ count, date: visitDate('2026-07-02', null, 'en-GB') })}`; + +beforeEach(() => { + hook.mockReset(); +}); + +describe('MVisitsSection', () => { + it('FE-MOB-VISITS-001: not there at all without a visit', () => { + visits([], null); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('FE-MOB-VISITS-002: a card per visit with its day, time and trip, under the summary', () => { + visits([visit({ visited_time: '09:15' }), visit({ day_id: 8, trip: { id: 6, title: 'Lazio' } })]); + render(); + expect(screen.getByText('VISITS.TITLE')).toBeInTheDocument(); + expect(screen.getByText(summary(2))).toBeInTheDocument(); + expect(screen.getByText(visitDate('2026-07-02', '09:15', 'en-GB') as string)).toBeInTheDocument(); + expect(screen.getByText('Rome 2026')).toBeInTheDocument(); + expect(screen.getByText('Lazio')).toBeInTheDocument(); + }); + + it('FE-MOB-VISITS-003: shows at most three companions, and none for a visit alone', () => { + const people = ['anna', 'ben', 'cleo', 'dan'].map((username, i) => ({ id: i + 1, username, avatar_url: null })); + visits([visit({ participants: people }), visit({ day_id: 4, participants: [people[3]] })]); + render(); + expect(screen.getByText('A')).toBeInTheDocument(); + expect(screen.getByText('B')).toBeInTheDocument(); + expect(screen.getByText('C')).toBeInTheDocument(); + expect(screen.queryByText('D')).toBeNull(); + }); +}); + +describe('MTripPlaceVisits', () => { + const trip = { id: 5, title: 'Rome 2026' }; + const place = { id: 42, name: 'Colosseum' }; + + it('FE-MOB-VISITS-004: sums up the visits of the trip place', () => { + visits([visit()]); + render(); + expect(screen.getByText(summary(1))).toBeInTheDocument(); + expect(hook).toHaveBeenCalledWith({ entry: expect.objectContaining({ key: 'trip:42' }) }); + }); + + it('FE-MOB-VISITS-005: not shown before the first visit', () => { + visits([], null); + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/client/src/mobile/screens/trip/places/placesBrowserModel.test.ts b/client/src/mobile/screens/trip/places/placesBrowserModel.test.ts index 4c1a521db..2533194da 100644 --- a/client/src/mobile/screens/trip/places/placesBrowserModel.test.ts +++ b/client/src/mobile/screens/trip/places/placesBrowserModel.test.ts @@ -34,6 +34,12 @@ describe('placesBrowserModel — planned pool', () => { const out = filterPool(named, { filter: 'planned', categoryFilters: noCats, search: 'eiff', plannedIds }) expect(out.map(p => p.id)).toEqual([3]) }) + + it('MOBILE-POOL-visited: the visited pool keeps the places in the visited set, and none without it', () => { + const visitedIds = new Set([2]) + expect(filterPool(places, { filter: 'visited', categoryFilters: noCats, search: '', plannedIds, visitedIds }).map(p => p.id)).toEqual([2]) + expect(filterPool(places, { filter: 'visited', categoryFilters: noCats, search: '', plannedIds })).toEqual([]) + }) }) // FE-MOB-PMODEL-001 to FE-MOB-PMODEL-012 diff --git a/client/src/repo/placeActivitiesRepo.test.ts b/client/src/repo/placeActivitiesRepo.test.ts new file mode 100644 index 000000000..95e855cac --- /dev/null +++ b/client/src/repo/placeActivitiesRepo.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { placeActivitiesApi } from '../api/placeActivities'; +import { OnlineOnlyError } from './onlineOnly'; +import { placeActivitiesRepo } from './placeActivitiesRepo'; + +// FE-REPO-PLACE-ACTIVITIES-001 to FE-REPO-PLACE-ACTIVITIES-003 + +const network = vi.hoisted(() => ({ offline: false })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline })); + +const response = { activities: [], can_link: true }; +const tripSource = { kind: 'trip', trip_id: 4, place_id: 7 } as const; +const listSource = { kind: 'list', collection_id: 2, collection_place_id: 8 } as const; + +beforeEach(() => { + network.offline = false; + vi.restoreAllMocks(); +}); + +describe('placeActivitiesRepo', () => { + it('FE-REPO-PLACE-ACTIVITIES-001: reads and writes only online', async () => { + network.offline = true; + const read = vi.spyOn(placeActivitiesApi, 'tripPlace'); + await expect(placeActivitiesRepo.tripPlace(4, 7)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.tripCandidates(4, 7)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.linkTrip(4, 7, { tour_id: 11 })).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.savedPlace(8)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.savedCandidates(8)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.linkSaved(8, 5)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect( + placeActivitiesRepo.unlink({ source: tripSource, target: { kind: 'tour', trip_id: 4, tour_id: 11 } }) + ).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeActivitiesRepo.libraryEntry('trip', 7)).rejects.toBeInstanceOf(OnlineOnlyError); + expect(read).not.toHaveBeenCalled(); + }); + + it('FE-REPO-PLACE-ACTIVITIES-002: passes each read and link on', async () => { + const signal = new AbortController().signal; + const tripPlace = vi.spyOn(placeActivitiesApi, 'tripPlace').mockResolvedValue(response); + const tripCandidates = vi.spyOn(placeActivitiesApi, 'tripCandidates').mockResolvedValue({ candidates: [] }); + const linkTrip = vi.spyOn(placeActivitiesApi, 'linkTrip').mockResolvedValue(response); + const savedPlace = vi.spyOn(placeActivitiesApi, 'savedPlace').mockResolvedValue(response); + const savedCandidates = vi.spyOn(placeActivitiesApi, 'savedCandidates').mockResolvedValue({ candidates: [] }); + const linkSaved = vi.spyOn(placeActivitiesApi, 'linkSaved').mockResolvedValue(response); + const entry = vi.spyOn(placeActivitiesApi, 'libraryEntry').mockResolvedValue({ activities: [], sources: [] }); + expect(await placeActivitiesRepo.tripPlace(4, 7, signal)).toBe(response); + expect(await placeActivitiesRepo.tripCandidates(4, 7, signal)).toEqual({ candidates: [] }); + expect(await placeActivitiesRepo.linkTrip(4, 7, { reservation_id: 9 })).toBe(response); + expect(await placeActivitiesRepo.savedPlace(8, signal)).toBe(response); + expect(await placeActivitiesRepo.savedCandidates(8, signal)).toEqual({ candidates: [] }); + expect(await placeActivitiesRepo.linkSaved(8, 5)).toBe(response); + expect(await placeActivitiesRepo.libraryEntry('list', 8, signal)).toEqual({ activities: [], sources: [] }); + expect(tripPlace).toHaveBeenCalledWith(4, 7, signal); + expect(tripCandidates).toHaveBeenCalledWith(4, 7, signal); + expect(linkTrip).toHaveBeenCalledWith(4, 7, { reservation_id: 9 }); + expect(savedPlace).toHaveBeenCalledWith(8, signal); + expect(savedCandidates).toHaveBeenCalledWith(8, signal); + expect(linkSaved).toHaveBeenCalledWith(8, 5); + expect(entry).toHaveBeenCalledWith('list', 8, signal); + }); + + it('FE-REPO-PLACE-ACTIVITIES-003: unlinks through the route the source and target name', async () => { + const booking = vi.spyOn(placeActivitiesApi, 'unlinkTripBooking').mockResolvedValue(response); + const tour = vi.spyOn(placeActivitiesApi, 'unlinkTripTour').mockResolvedValue(response); + const kept = vi.spyOn(placeActivitiesApi, 'unlinkSaved').mockResolvedValue(response); + await placeActivitiesRepo.unlink({ + source: tripSource, + target: { kind: 'reservation', trip_id: 4, reservation_id: 9 }, + }); + await placeActivitiesRepo.unlink({ source: tripSource, target: { kind: 'tour', trip_id: 4, tour_id: 11 } }); + await placeActivitiesRepo.unlink({ + source: listSource, + target: { kind: 'collection_tour', collection_id: 2, collection_tour_id: 5 }, + }); + expect(booking).toHaveBeenCalledWith(4, 7, 9); + expect(tour).toHaveBeenCalledWith(4, 7, 11); + expect(kept).toHaveBeenCalledWith(8, 5); + await expect( + placeActivitiesRepo.unlink({ + source: listSource, + target: { kind: 'tour', trip_id: 4, tour_id: 11 }, + }) + ).rejects.toThrow('A saved place only links kept tours'); + await expect( + placeActivitiesRepo.unlink({ + source: tripSource, + target: { kind: 'collection_tour', collection_id: 2, collection_tour_id: 5 }, + }) + ).rejects.toThrow('A trip place only links bookings and tours of its trip'); + }); +}); diff --git a/client/src/repo/placeHistoryRepo.test.ts b/client/src/repo/placeHistoryRepo.test.ts new file mode 100644 index 000000000..8e1c591fb --- /dev/null +++ b/client/src/repo/placeHistoryRepo.test.ts @@ -0,0 +1,34 @@ +import type { PlaceHistoryPageResponse } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { placeHistoryApi } from '../api/placeHistory'; +import { OnlineOnlyError } from './onlineOnly'; +import { placeHistoryRepo } from './placeHistoryRepo'; + +// FE-REPO-PLACE-HISTORY-001 to FE-REPO-PLACE-HISTORY-002 + +const network = vi.hoisted(() => ({ offline: false })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline })); + +beforeEach(() => { + network.offline = false; + vi.restoreAllMocks(); +}); + +describe('placeHistoryRepo', () => { + it('FE-REPO-PLACE-HISTORY-001: reads only online, never from a cache', async () => { + network.offline = true; + const history = vi.spyOn(placeHistoryApi, 'history'); + await expect(placeHistoryRepo.history('trip', 4)).rejects.toBeInstanceOf(OnlineOnlyError); + expect(history).not.toHaveBeenCalled(); + }); + + it('FE-REPO-PLACE-HISTORY-002: passes the call on with its page and signal and answers what the server said', async () => { + const page: PlaceHistoryPageResponse = { entries: [], next_cursor: null }; + const history = vi.spyOn(placeHistoryApi, 'history').mockResolvedValue(page); + const signal = new AbortController().signal; + expect(await placeHistoryRepo.history('list', 9, { cursor: '5' }, signal)).toBe(page); + expect(await placeHistoryRepo.history('trip', 4)).toBe(page); + expect(history).toHaveBeenNthCalledWith(1, 'list', 9, { cursor: '5' }, signal); + expect(history).toHaveBeenNthCalledWith(2, 'trip', 4, {}, undefined); + }); +}); diff --git a/client/src/repo/placeTagsRepo.test.ts b/client/src/repo/placeTagsRepo.test.ts new file mode 100644 index 000000000..1ba0805e3 --- /dev/null +++ b/client/src/repo/placeTagsRepo.test.ts @@ -0,0 +1,54 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { placeTagsApi } from '../api/placeTags'; +import { OnlineOnlyError } from './onlineOnly'; +import { placeTagsRepo } from './placeTagsRepo'; + +// FE-REPO-PLACE-TAGS-001 to FE-REPO-PLACE-TAGS-002 + +const network = vi.hoisted(() => ({ offline: false })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline })); + +const tag = { id: 3, user_id: 1, trip_id: null, name: 'Wine', color: '#aa0000' }; + +beforeEach(() => { + network.offline = false; + vi.restoreAllMocks(); +}); + +describe('placeTagsRepo', () => { + it('FE-REPO-PLACE-TAGS-001: reads and writes only online', async () => { + network.offline = true; + const list = vi.spyOn(placeTagsApi, 'list'); + await expect(placeTagsRepo.list()).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeTagsRepo.create('Wine')).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeTagsRepo.update(3, { name: 'X' })).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeTagsRepo.remove(3)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeTagsRepo.setForEntry('trip:1', [3])).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(placeTagsRepo.bulk({ keys: ['trip:1'], add: [3] })).rejects.toBeInstanceOf(OnlineOnlyError); + expect(list).not.toHaveBeenCalled(); + }); + + it('FE-REPO-PLACE-TAGS-002: passes each call on and keeps only personal tags', async () => { + vi.spyOn(placeTagsApi, 'list').mockResolvedValue({ tags: [tag, { ...tag, id: 4, trip_id: 9 }] }); + const create = vi.spyOn(placeTagsApi, 'create').mockResolvedValue({ tag }); + const update = vi.spyOn(placeTagsApi, 'update').mockResolvedValue({ tag }); + const remove = vi.spyOn(placeTagsApi, 'remove').mockResolvedValue({ success: true }); + const entry = { key: 'trip:1' } as never; + const setForEntry = vi.spyOn(placeTagsApi, 'setForEntry').mockResolvedValue({ entry }); + const bulk = vi.spyOn(placeTagsApi, 'bulk').mockResolvedValue({ entries: [entry] }); + + expect(await placeTagsRepo.list()).toEqual([tag]); + expect(await placeTagsRepo.create('Wine')).toBe(tag); + expect(await placeTagsRepo.create('Wine', '#aa0000')).toBe(tag); + expect(await placeTagsRepo.update(3, { color: '#000000' })).toBe(tag); + await placeTagsRepo.remove(3); + expect(await placeTagsRepo.setForEntry('trip:1', [3])).toBe(entry); + expect(await placeTagsRepo.bulk({ keys: ['trip:1'], remove: [3] })).toEqual([entry]); + + expect(create.mock.calls).toEqual([[{ name: 'Wine' }], [{ name: 'Wine', color: '#aa0000' }]]); + expect(update).toHaveBeenCalledWith(3, { color: '#000000' }); + expect(remove).toHaveBeenCalledWith(3); + expect(setForEntry).toHaveBeenCalledWith({ key: 'trip:1', tag_ids: [3] }); + expect(bulk).toHaveBeenCalledWith({ keys: ['trip:1'], remove: [3] }); + }); +}); diff --git a/client/src/repo/placeVisitsRepo.test.ts b/client/src/repo/placeVisitsRepo.test.ts new file mode 100644 index 000000000..b39fd88c9 --- /dev/null +++ b/client/src/repo/placeVisitsRepo.test.ts @@ -0,0 +1,48 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { placeVisitsApi } from '../api/placeVisits'; +import { OnlineOnlyError } from './onlineOnly'; +import { placeVisitsRepo } from './placeVisitsRepo'; + +// FE-REPO-PLACE-VISITS-001 to FE-REPO-PLACE-VISITS-002 + +const network = vi.hoisted(() => ({ offline: false })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline })); + +beforeEach(() => { + network.offline = false; + vi.restoreAllMocks(); +}); + +type Method = keyof typeof placeVisitsRepo; +type Call = (...args: unknown[]) => Promise; + +/** Every repo method with the arguments it is called with here. */ +const calls: Array<[Method, unknown[]]> = [ + ['list', [{ trip_id: 4 }]], + ['forPlace', ['trip', 3]], + ['tripVisited', [4]], + ['media', ['list', 9]], +]; + +describe('placeVisitsRepo', () => { + it('FE-REPO-PLACE-VISITS-001: reads only online, and only reads', async () => { + network.offline = true; + const spies = calls.map(([name]) => vi.spyOn(placeVisitsApi, name)); + const results = await Promise.allSettled(calls.map(([name, args]) => (placeVisitsRepo[name] as Call)(...args))); + for (const result of results) { + expect(result.status).toBe('rejected'); + if (result.status === 'rejected') expect(result.reason).toBeInstanceOf(OnlineOnlyError); + } + for (const spy of spies) expect(spy).not.toHaveBeenCalled(); + expect(Object.keys(placeVisitsRepo).sort()).toEqual(calls.map(([name]) => name).sort()); + }); + + it('FE-REPO-PLACE-VISITS-002: passes each call on with its arguments', async () => { + const spies = calls.map(([name]) => vi.spyOn(placeVisitsApi, name).mockResolvedValue({ name } as never)); + const answers = await Promise.all(calls.map(([name, args]) => (placeVisitsRepo[name] as Call)(...args))); + calls.forEach(([name, args], index) => { + expect(answers[index]).toEqual({ name }); + expect(spies[index]).toHaveBeenCalledWith(...args); + }); + }); +}); diff --git a/client/src/store/placeActivitiesStore.test.ts b/client/src/store/placeActivitiesStore.test.ts new file mode 100644 index 000000000..c5074cd0e --- /dev/null +++ b/client/src/store/placeActivitiesStore.test.ts @@ -0,0 +1,154 @@ +// FE-STORE-PLACEACTIVITIES-001 to FE-STORE-PLACEACTIVITIES-004: the bookings and tours of a +// place, read per account, linked and unlinked, and read again on a push. +import { waitFor } from '@testing-library/react'; +import type { PlaceActivity, PlaceLibraryActivitySource } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildUser } from '../../tests/helpers/factories'; +import { resetAllStores, seedStore } from '../../tests/helpers/store'; +import { addListener } from '../api/websocket'; +import { placeActivitiesRepo } from '../repo/placeActivitiesRepo'; +import { useAuthStore } from './authStore'; +import { + placeActivitiesEntry, + usePlaceActivitiesStore, + watchPlaceActivities, + type PlaceActivitiesEntry, + type PlaceActivitiesTarget, +} from './placeActivitiesStore'; + +const booking: PlaceActivity = { + key: 'reservation:9', + type: 'booking', + origin: { kind: 'trip', trip_id: 4, trip_title: 'Rome' }, + target: { kind: 'reservation', trip_id: 4, reservation_id: 9 }, + source: { kind: 'trip', trip_id: 4, place_id: 7 }, + title: 'Guided tour', + booking_type: 'tour', + booking_status: 'confirmed', + tour_type: null, + starts_at: null, + ends_at: null, + date: null, + day_number: null, + explicit: true, + implicit_via: null, + can_unlink: true, +}; +const kept: PlaceActivity = { + ...booking, + key: 'collection_tour:5', + type: 'tour', + origin: { kind: 'list', collection_id: 2, collection_name: 'Hikes' }, + target: { kind: 'collection_tour', collection_id: 2, collection_tour_id: 5 }, + source: { kind: 'list', collection_id: 2, collection_place_id: 8 }, +}; +const tripOrigin: PlaceLibraryActivitySource = { + source: { kind: 'trip', trip_id: 4, place_id: 7 }, + origin: { kind: 'trip', trip_id: 4, trip_title: 'Rome' }, + can_link: true, +}; +const trip = { kind: 'trip', tripId: 4, placeId: 7 } as const; +const saved = { kind: 'list', collectionPlaceId: 8 } as const; +const entryTarget = { kind: 'entry', entryKind: 'trip', id: 7 } as const; +const entry = (target: PlaceActivitiesTarget): PlaceActivitiesEntry | undefined => + placeActivitiesEntry(usePlaceActivitiesStore.getState(), target); + +beforeEach(() => { + resetAllStores(); + vi.restoreAllMocks(); + vi.mocked(addListener).mockClear(); + usePlaceActivitiesStore.setState({ entries: {} }); + seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true }); +}); + +describe('placeActivitiesStore', () => { + it('FE-STORE-PLACEACTIVITIES-001: reads a trip place, a saved place and an entry for the signed-in account', async () => { + vi.spyOn(placeActivitiesRepo, 'tripPlace').mockResolvedValue({ activities: [booking], can_link: true }); + vi.spyOn(placeActivitiesRepo, 'savedPlace').mockResolvedValue({ activities: [kept], can_link: false }); + vi.spyOn(placeActivitiesRepo, 'libraryEntry').mockResolvedValue({ activities: [booking], sources: [tripOrigin] }); + const store = usePlaceActivitiesStore.getState(); + await store.load(trip); + await store.load(saved); + await store.load(entryTarget); + expect(entry(trip)).toEqual({ activities: [booking], canLink: true, sources: [] }); + expect(entry(saved)).toEqual({ activities: [kept], canLink: false, sources: [] }); + expect(entry(entryTarget)).toEqual({ activities: [booking], canLink: true, sources: [tripOrigin] }); + seedStore(useAuthStore, { user: buildUser({ id: 2 }) }); + expect(entry(trip)).toBeUndefined(); + }); + + it('FE-STORE-PLACEACTIVITIES-002: links and unlinks, reading held entries of All places with that origin again', async () => { + vi.spyOn(placeActivitiesRepo, 'libraryEntry').mockResolvedValue({ activities: [], sources: [tripOrigin] }); + await usePlaceActivitiesStore.getState().load(entryTarget); + const linkTrip = vi + .spyOn(placeActivitiesRepo, 'linkTrip') + .mockResolvedValue({ activities: [booking], can_link: true }); + const again = vi + .spyOn(placeActivitiesRepo, 'libraryEntry') + .mockResolvedValue({ activities: [booking], sources: [tripOrigin] }); + await usePlaceActivitiesStore.getState().linkTrip(4, 7, { reservation_id: 9 }); + expect(linkTrip).toHaveBeenCalledWith(4, 7, { reservation_id: 9 }); + expect(entry(trip)?.activities).toEqual([booking]); + expect(again).toHaveBeenCalledWith('trip', 7); + expect(entry(entryTarget)?.activities).toEqual([booking]); + + vi.spyOn(placeActivitiesRepo, 'unlink').mockResolvedValue({ activities: [], can_link: true }); + await usePlaceActivitiesStore.getState().unlink(booking); + expect(entry(trip)?.activities).toEqual([]); + + vi.spyOn(placeActivitiesRepo, 'linkSaved').mockResolvedValue({ activities: [kept], can_link: true }); + await usePlaceActivitiesStore.getState().linkSaved(8, 5); + expect(entry(saved)?.activities).toEqual([kept]); + }); + + it('FE-STORE-PLACEACTIVITIES-003: a trip push reads the held place and the entries it is an origin of', async () => { + usePlaceActivitiesStore.setState({ + entries: { + '1:trip:4:7': { activities: [], canLink: true, sources: [] }, + '1:trip:4:99': { activities: [], canLink: true, sources: [] }, + '1:entry:trip:7': { activities: [], canLink: true, sources: [tripOrigin] }, + '2:trip:4:7': { activities: [], canLink: true, sources: [] }, + }, + }); + const tripPlace = vi + .spyOn(placeActivitiesRepo, 'tripPlace') + .mockResolvedValue({ activities: [booking], can_link: true }); + const library = vi + .spyOn(placeActivitiesRepo, 'libraryEntry') + .mockResolvedValue({ activities: [booking], sources: [tripOrigin] }); + const stop = watchPlaceActivities(); + const listener = vi.mocked(addListener).mock.calls[0][0] as (event: Record) => void; + listener({ type: 'placeActivities:changed', placeId: 'x' }); + listener({ type: 'tripAddons:changed', placeId: 7 }); + expect(tripPlace).not.toHaveBeenCalled(); + listener({ type: 'placeActivities:changed', tripId: 4, placeId: 7 }); + await waitFor(() => expect(entry(trip)?.activities).toEqual([booking])); + await waitFor(() => expect(entry(entryTarget)?.activities).toEqual([booking])); + expect(tripPlace).toHaveBeenCalledTimes(1); + expect(library).toHaveBeenCalledTimes(1); + stop(); + }); + + it('FE-STORE-PLACEACTIVITIES-004: a list push reads its saved places and the ones not known yet, a failure keeps the last answer', async () => { + usePlaceActivitiesStore.setState({ + entries: { + '1:list:8': { activities: [kept], canLink: true, sources: [] }, + '1:list:12': { activities: [], canLink: true, sources: [] }, + '1:list:13': { + activities: [{ ...kept, source: { kind: 'list', collection_id: 3, collection_place_id: 13 } }], + canLink: true, + sources: [], + }, + }, + }); + const savedPlace = vi.spyOn(placeActivitiesRepo, 'savedPlace').mockRejectedValue(new Error('offline')); + const stop = watchPlaceActivities(); + const listener = vi.mocked(addListener).mock.calls[0][0] as (event: Record) => void; + listener({ type: 'collections:updated', collectionId: 2 }); + await waitFor(() => expect(savedPlace).toHaveBeenCalledTimes(2)); + expect(savedPlace).toHaveBeenCalledWith(8); + expect(savedPlace).toHaveBeenCalledWith(12); + expect(entry(saved)?.activities).toEqual([kept]); + stop(); + }); +}); diff --git a/client/src/store/placeTagsStore.test.ts b/client/src/store/placeTagsStore.test.ts new file mode 100644 index 000000000..cd083d701 --- /dev/null +++ b/client/src/store/placeTagsStore.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { placeTagsRepo } from '../repo/placeTagsRepo'; +import { subscribePlaceTags, usePlaceTagsStore } from './placeTagsStore'; + +// FE-STORE-PLACE-TAGS-001 to FE-STORE-PLACE-TAGS-003 + +const ws = vi.hoisted(() => ({ listeners: new Set<(event: Record) => void>() })); +vi.mock('../api/websocket', () => ({ + addListener: (fn: (event: Record) => void) => ws.listeners.add(fn), + removeListener: (fn: (event: Record) => void) => ws.listeners.delete(fn), +})); + +const tag = (id: number, name: string) => ({ id, user_id: 1, trip_id: null, name, color: '#aa0000' }); + +beforeEach(() => { + vi.restoreAllMocks(); + usePlaceTagsStore.setState({ tags: [], loaded: false }); +}); + +describe('placeTagsStore', () => { + it('FE-STORE-PLACE-TAGS-001: loads the tags by name and keeps them in order through each change', async () => { + vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([tag(2, 'Wine'), tag(1, 'Beach')]); + vi.spyOn(placeTagsRepo, 'create').mockResolvedValue(tag(3, 'Coffee')); + vi.spyOn(placeTagsRepo, 'update').mockResolvedValue(tag(2, 'Art')); + vi.spyOn(placeTagsRepo, 'remove').mockResolvedValue(undefined); + const store = usePlaceTagsStore.getState(); + await store.load(); + expect(usePlaceTagsStore.getState().loaded).toBe(true); + await store.create('Coffee'); + expect(usePlaceTagsStore.getState().tags.map((t) => t.name)).toEqual(['Beach', 'Coffee', 'Wine']); + await store.update(2, { name: 'Art' }); + expect(usePlaceTagsStore.getState().tags.map((t) => t.name)).toEqual(['Art', 'Beach', 'Coffee']); + await store.remove(1); + expect(usePlaceTagsStore.getState().tags.map((t) => t.id)).toEqual([2, 3]); + }); + + it('FE-STORE-PLACE-TAGS-002: passes the entry changes on and answers the entries', async () => { + const entry = { key: 'trip:1' } as never; + const set = vi.spyOn(placeTagsRepo, 'setForEntry').mockResolvedValue(entry); + const bulk = vi.spyOn(placeTagsRepo, 'bulk').mockResolvedValue([entry]); + expect(await usePlaceTagsStore.getState().setForEntry('trip:1', [3])).toBe(entry); + expect(await usePlaceTagsStore.getState().bulk({ keys: ['trip:1'], add: [3] })).toEqual([entry]); + expect(set).toHaveBeenCalledWith('trip:1', [3]); + expect(bulk).toHaveBeenCalledWith({ keys: ['trip:1'], add: [3] }); + }); + + it('FE-STORE-PLACE-TAGS-003: a tags:changed push reads the list again once it was loaded', async () => { + const list = vi.spyOn(placeTagsRepo, 'list').mockResolvedValue([tag(1, 'Beach')]); + const unsubscribe = subscribePlaceTags(); + const push = (type: string) => ws.listeners.forEach((fn) => fn({ type })); + push('tags:changed'); + expect(list).not.toHaveBeenCalled(); + usePlaceTagsStore.setState({ loaded: true }); + push('trip:updated'); + push('tags:changed'); + await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(1)); + list.mockRejectedValueOnce(new Error('offline')); + push('tags:changed'); + await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(2)); + expect(usePlaceTagsStore.getState().tags.map((t) => t.name)).toEqual(['Beach']); + unsubscribe(); + expect(ws.listeners.size).toBe(0); + }); +}); diff --git a/client/src/store/placeVisitsStore.test.ts b/client/src/store/placeVisitsStore.test.ts new file mode 100644 index 000000000..fad5e42d1 --- /dev/null +++ b/client/src/store/placeVisitsStore.test.ts @@ -0,0 +1,75 @@ +// FE-STORE-PLACEVISITS-001 to FE-STORE-PLACEVISITS-003: the trip places the account visited, +// read per account, and read again after a pushed change to a trip's plan. +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildUser } from '../../tests/helpers/factories'; +import { resetAllStores, seedStore } from '../../tests/helpers/store'; +import { addListener } from '../api/websocket'; +import { placeVisitsRepo } from '../repo/placeVisitsRepo'; +import { useAuthStore } from './authStore'; +import { refreshTripVisited, tripVisitedEntry, usePlaceVisitsStore, watchPlaceVisits } from './placeVisitsStore'; + +const visited = { place_ids: [3], places: [{ place_id: 3, visit_count: 2, last_visit: '2026-07-02' }] }; +const entry = (tripId: number) => tripVisitedEntry(usePlaceVisitsStore.getState(), tripId); + +beforeEach(() => { + resetAllStores(); + vi.restoreAllMocks(); + vi.mocked(addListener).mockClear(); + usePlaceVisitsStore.setState({ visited: {}, revision: 0 }); + seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true }); +}); + +describe('placeVisitsStore', () => { + it('FE-STORE-PLACEVISITS-001: reads the visited places of a trip for the signed-in account', async () => { + vi.spyOn(placeVisitsRepo, 'tripVisited').mockResolvedValue(visited); + expect(await usePlaceVisitsStore.getState().loadTripVisited(4)).toEqual({ + placeIds: [3], + places: visited.places, + }); + expect(entry(4)?.placeIds).toEqual([3]); + seedStore(useAuthStore, { user: buildUser({ id: 2 }) }); + expect(entry(4)).toBeUndefined(); + expect(tripVisitedEntry(usePlaceVisitsStore.getState(), null)).toBeUndefined(); + }); + + it('FE-STORE-PLACEVISITS-002: a plan change moves the revision and reads the held trips of this account again, once per burst', async () => { + vi.useFakeTimers(); + try { + const read = vi.spyOn(placeVisitsRepo, 'tripVisited').mockResolvedValue(visited); + usePlaceVisitsStore.setState({ + visited: { '1:4': { placeIds: [], places: [] }, '2:6': { placeIds: [], places: [] } }, + }); + const stop = watchPlaceVisits(); + const listener = vi.mocked(addListener).mock.calls[0][0] as (event: Record) => void; + listener({ type: 'atlas:changed' }); + listener({ type: 'place:created', tripId: 4 }); + await vi.advanceTimersByTimeAsync(1000); + expect(usePlaceVisitsStore.getState().revision).toBe(0); + listener({ type: 'assignment:created', tripId: 4 }); + listener({ type: 'assignment:moved', tripId: 4 }); + listener({ type: 'day:updated', tripId: 9 }); + expect(usePlaceVisitsStore.getState().revision).toBe(0); + await vi.advanceTimersByTimeAsync(1000); + expect(usePlaceVisitsStore.getState().revision).toBe(1); + expect(read).toHaveBeenCalledTimes(1); + expect(read).toHaveBeenCalledWith(4); + expect(entry(4)?.placeIds).toEqual([3]); + listener({ type: 'trips:changed' }); + stop(); + await vi.advanceTimersByTimeAsync(1000); + expect(usePlaceVisitsStore.getState().revision).toBe(1); + } finally { + vi.useRealTimers(); + } + }); + + it('FE-STORE-PLACEVISITS-003: reading again offline keeps the last answer', async () => { + usePlaceVisitsStore.setState({ visited: { '1:4': { placeIds: [3], places: visited.places } } }); + vi.spyOn(placeVisitsRepo, 'tripVisited').mockRejectedValue(new Error('offline')); + refreshTripVisited(); + expect(usePlaceVisitsStore.getState().revision).toBe(1); + await Promise.resolve(); + await Promise.resolve(); + expect(entry(4)?.placeIds).toEqual([3]); + }); +}); diff --git a/client/src/utils/placesFilter.test.ts b/client/src/utils/placesFilter.test.ts index ab659e421..f15b62bdf 100644 --- a/client/src/utils/placesFilter.test.ts +++ b/client/src/utils/placesFilter.test.ts @@ -107,4 +107,15 @@ describe('placesFilter', () => { expect(withoutTagFilters(filters, [9])).toBe(filters) expect(withoutTagFilters(filters, [])).toBe(filters) }) + it('FE-UTIL-PLFILTER-011: "visited" keeps only the places the reader was at, and nothing without the set', () => { + const been = buildPlace({ id: 1 }) + const notYet = buildPlace({ id: 2 }) + const visitedIds = new Set([1]) + expect(matchesPoolFilter(been, 'visited', { plannedIds: null, visitedIds })).toBe(true) + expect(matchesPoolFilter(notYet, 'visited', { plannedIds: null, visitedIds })).toBe(false) + expect(matchesPoolFilter(been, 'visited', { plannedIds: null })).toBe(false) + expect(matchesPoolFilter(been, 'visited', { plannedIds: null, visitedIds: null })).toBe(false) + // The other pools do not read the visited set. + expect(matchesPoolFilter(notYet, 'all', { plannedIds: null, visitedIds })).toBe(true) + }) }) diff --git a/client/tests/helpers/placeExtras.ts b/client/tests/helpers/placeExtras.ts new file mode 100644 index 000000000..60edadc9c --- /dev/null +++ b/client/tests/helpers/placeExtras.ts @@ -0,0 +1,186 @@ +import type { + PlaceActivity, + PlaceActivityCandidate, + PlaceHistoryEntry, + PlaceLibraryActivitySource, + PlaceMediaFile, + PlaceMediaImage, + PlaceMediaJourneyPhoto, +} from '@trek/shared'; +import { vi } from 'vitest'; + +import type { usePlaceActivities } from '../../src/components/Collections/usePlaceActivities'; +import type { usePlaceHistory } from '../../src/components/Collections/usePlaceHistory'; +import type { usePlaceMedia } from '../../src/components/Collections/usePlaceMedia'; + +/* + * Builders for the extras of a place of All places: its tours and bookings + * (PLC-18), its change history (PLC-14) and its pictures and files (PLC-19, + * PLC-20). A booking of trip 5 "Rome 2026" on trip place 42 unless told otherwise. + */ + +export function activityCandidate(over: Partial = {}): PlaceActivityCandidate { + return { + key: 'reservation:7', + type: 'booking', + origin: { kind: 'trip', trip_id: 5, trip_title: 'Rome 2026' }, + target: { kind: 'reservation', trip_id: 5, reservation_id: 7 }, + title: 'Colosseum tickets', + booking_type: 'tour', + booking_status: 'confirmed', + tour_type: null, + starts_at: null, + ends_at: null, + date: null, + day_number: null, + ...over, + }; +} + +export function placeActivity(over: Partial = {}): PlaceActivity { + return { + ...activityCandidate(), + source: { kind: 'trip', trip_id: 5, place_id: 42 }, + explicit: true, + implicit_via: null, + can_unlink: true, + ...over, + }; +} + +/** A tour kept in list 9 "Favourites", linked to saved place 900. */ +export function listTour(over: Partial = {}): PlaceActivity { + return placeActivity({ + key: 'collection_tour:3', + type: 'tour', + origin: { kind: 'list', collection_id: 9, collection_name: 'Favourites' }, + target: { kind: 'collection_tour', collection_id: 9, collection_tour_id: 3 }, + source: { kind: 'list', collection_id: 9, collection_place_id: 900 }, + title: 'Old town walk', + booking_type: null, + booking_status: null, + tour_type: 'walk', + ...over, + }); +} + +export function tripSource(over: Partial = {}): PlaceLibraryActivitySource { + return { + source: { kind: 'trip', trip_id: 5, place_id: 42 }, + origin: { kind: 'trip', trip_id: 5, trip_title: 'Rome 2026' }, + can_link: true, + ...over, + }; +} + +export function listSource(over: Partial = {}): PlaceLibraryActivitySource { + return { + source: { kind: 'list', collection_id: 9, collection_place_id: 900 }, + origin: { kind: 'list', collection_id: 9, collection_name: 'Favourites' }, + can_link: true, + ...over, + }; +} + +export function historyEntry(over: Partial = {}): PlaceHistoryEntry { + return { + id: 1, + origin: { kind: 'trip', trip_id: 5, trip_title: 'Rome 2026', place_id: 42 }, + field: 'name', + old_value: 'Colosseo', + new_value: 'Colosseum', + editor: { id: 2, username: 'anna', avatar_url: null }, + automatic: false, + changed_at: '2026-12-02 14:30:00', + ...over, + }; +} + +/** `count` changes with the ids 1..count. */ +export function historyEntries(count: number, from = 1): PlaceHistoryEntry[] { + return Array.from({ length: count }, (_, i) => + historyEntry({ id: from + i, new_value: `Name ${from + i}`, old_value: null }) + ); +} + +export function mediaImage(url: string, kind: 'trip' | 'list' = 'trip'): PlaceMediaImage { + return kind === 'trip' + ? { kind: 'trip', image_url: url, trip_id: 5, trip_title: 'Rome 2026', place_id: 42 } + : { kind: 'list', image_url: url, collection_id: 9, collection_name: 'Favourites', collection_place_id: 900 }; +} + +export function journeyPhoto(over: Partial = {}): PlaceMediaJourneyPhoto { + return { + journey_id: 3, + journey_title: 'Italy journey', + entry_id: 11, + entry_date: '2026-12-02', + journey_photo_id: 70, + photo_id: 700, + provider: 'local', + asset_id: null, + owner_id: 2, + file_path: null, + thumbnail_path: null, + width: 800, + height: 600, + media_type: 'image', + caption: null, + taken_at: null, + ...over, + }; +} + +export function mediaFile(over: Partial = {}): PlaceMediaFile { + return { + file_id: 31, + trip_id: 5, + trip_title: 'Rome 2026', + place_id: 42, + original_name: 'tickets.pdf', + mime_type: 'application/pdf', + file_size: 1200, + created_at: null, + url: '/trips/5/files?file=31', + ...over, + }; +} + +/** What the activities hook hands a view, with spies for its handlers. */ +export function activitiesState( + over: Partial> = {} +): ReturnType { + return { + activities: [], + canLink: false, + picking: null, + closePicker: vi.fn(), + openPicker: vi.fn().mockResolvedValue(undefined), + link: vi.fn().mockResolvedValue(undefined), + unlink: vi.fn().mockResolvedValue(undefined), + busy: false, + ...over, + }; +} + +/** What the history hook hands a view. */ +export function historyState( + over: Partial> = {} +): ReturnType { + return { entries: [], hasMore: false, loadingMore: false, more: vi.fn().mockResolvedValue(undefined), ...over }; +} + +/** What the media hook hands a view. */ +export function mediaState(over: Partial> = {}): ReturnType { + return { photos: [], files: [], open: null, setOpen: vi.fn(), close: vi.fn(), ...over }; +} + +/** `count` pictures as the media hook hands them out. */ +export function photos(count: number): ReturnType['photos'] { + return Array.from({ length: count }, (_, i) => ({ + id: `img:/p${i}.jpg`, + src: `/p${i}.jpg`, + thumbSrc: `/p${i}.jpg`, + caption: `Photo ${i}`, + })); +} diff --git a/client/tests/helpers/placesLibrary.ts b/client/tests/helpers/placesLibrary.ts index a836899b0..15f590253 100644 --- a/client/tests/helpers/placesLibrary.ts +++ b/client/tests/helpers/placesLibrary.ts @@ -143,6 +143,8 @@ export function libraryState(over: Partial = {}): PlacesLibr setSort: vi.fn(), status: 'all', setStatus: vi.fn(), + tagIds: [], + toggleTag: vi.fn(), filtered: false, resetFilters: vi.fn(), entries: [], diff --git a/client/tests/helpers/storeRegistry.ts b/client/tests/helpers/storeRegistry.ts index 188b87513..4acb5fc3b 100644 --- a/client/tests/helpers/storeRegistry.ts +++ b/client/tests/helpers/storeRegistry.ts @@ -9,6 +9,7 @@ import { useInAppNotificationStore } from '../../src/store/inAppNotificationStor import { useMailIngestStore } from '../../src/store/mailIngestStore'; import { usePaddleObstacleStore } from '../../src/store/paddleObstacleStore'; import { usePermissionsStore } from '../../src/store/permissionsStore'; +import { usePlaceVisitsStore } from '../../src/store/placeVisitsStore'; import { useSettingsStore } from '../../src/store/settingsStore'; import { useTourMapViewportStore } from '../../src/store/tourMapViewportStore'; import { useTourMapVisibilityStore } from '../../src/store/tourMapVisibilityStore'; @@ -60,6 +61,8 @@ export const RESET_STORES: Record = { useTripAddonsStore, // The lists linked to each trip: one test's links must not show on the next test's trip. useTripCollectionsStore, + // The visited places per trip: one test's confirmed visits must not mark the next test's places. + usePlaceVisitsStore, }; /** Not reset so far; moving one into RESET_STORES changes what every file that resets starts from. */ diff --git a/client/tests/unit/mobile/collections/MLibraryPlaceSheet.test.tsx b/client/tests/unit/mobile/collections/MLibraryPlaceSheet.test.tsx index 068cf139c..5d8896fb9 100644 --- a/client/tests/unit/mobile/collections/MLibraryPlaceSheet.test.tsx +++ b/client/tests/unit/mobile/collections/MLibraryPlaceSheet.test.tsx @@ -1,4 +1,4 @@ -// FE-MOB-LIBPLACESHEET-001 to FE-MOB-LIBPLACESHEET-012 +// FE-MOB-LIBPLACESHEET-001 to FE-MOB-LIBPLACESHEET-015 import userEvent from '@testing-library/user-event'; import type { PlacesLibraryDetailResponse } from '@trek/shared'; import type { ComponentProps } from 'react'; @@ -21,6 +21,24 @@ import { render, screen, within } from '../../../helpers/render'; import { resetAllStores } from '../../../helpers/store'; const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] })); +/** The props each section below the origins was last handed; they read their own stores. */ +const sections = vi.hoisted(() => ({}) as Record>); +const section = vi.hoisted( + () => (name: string) => + function Section(props: Record) { + sections[name] = props; + return
; + } +); + +vi.mock('../../../../src/mobile/screens/collections/MEntryTagsSection', () => ({ default: section('tags') })); +vi.mock('../../../../src/mobile/screens/collections/MOriginNotesSection', () => ({ default: section('notes') })); +vi.mock('../../../../src/mobile/screens/collections/MPlaceMediaSection', () => ({ default: section('media') })); +vi.mock('../../../../src/mobile/screens/collections/MVisitsSection', () => ({ default: section('visits') })); +vi.mock('../../../../src/mobile/screens/collections/MPlaceActivitiesSection', () => ({ + default: section('activities'), +})); +vi.mock('../../../../src/mobile/screens/collections/MPlaceHistorySection', () => ({ default: section('history') })); vi.mock('../../../../src/components/Planner/placeNavigation', () => ({ getNavigationTargets: () => nav.targets, @@ -96,6 +114,7 @@ function setup(over: Partial = {}) { onOpenTrip: vi.fn(), onSaveToList: vi.fn(), onCopyToTrip: vi.fn(), + onNotesSaved: vi.fn(), ...over, }; const view = render(); @@ -106,6 +125,7 @@ beforeEach(() => { resetAllStores(); nav.targets = []; vi.mocked(openNavigationTarget).mockClear(); + for (const key of Object.keys(sections)) delete sections[key]; }); describe('MLibraryPlaceSheet: the sheet', () => { @@ -151,7 +171,7 @@ describe('MLibraryPlaceSheet: the sheet', () => { }); describe('MLibraryPlaceSheet: where the place sits', () => { - it('FE-MOB-LIBPLACESHEET-006: a trip shows its days, its name there, a stay, a booking and its notes', async () => { + it('FE-MOB-LIBPLACESHEET-006: a trip shows its days, its name there, a stay and a booking, its notes go below', async () => { const user = userEvent.setup(); const { props } = setup(); expect(screen.getByText('IN YOUR TRIPS')).toBeInTheDocument(); @@ -161,12 +181,13 @@ describe('MLibraryPlaceSheet: where the place sits', () => { expect(within(card).getByText('Called Colosseo here')).toBeInTheDocument(); expect(within(card).getByText('Stay')).toBeInTheDocument(); expect(within(card).getByText('Booking')).toBeInTheDocument(); - expect(within(card).getByText('Book the underground tour')).toBeInTheDocument(); + // The notes moved out of the card into the notes section under the origins. + expect(within(card).queryByText('Book the underground tour')).not.toBeInTheDocument(); await user.click(card); expect(props.onOpenTrip).toHaveBeenCalledWith(5, 42); }); - it('FE-MOB-LIBPLACESHEET-007: a list shows its status, its name there, labels, votes and notes', async () => { + it('FE-MOB-LIBPLACESHEET-007: a list shows its status, its name there, labels and votes', async () => { const user = userEvent.setup(); const { props } = setup(); expect(screen.getByText('IN YOUR LISTS')).toBeInTheDocument(); @@ -175,7 +196,7 @@ describe('MLibraryPlaceSheet: where the place sits', () => { expect(within(card).getByText('Called Il Colosseo here')).toBeInTheDocument(); expect(within(card).getByText('Must see')).toBeInTheDocument(); expect(within(card).getByText('4.0 from 1 vote')).toBeInTheDocument(); - expect(within(card).getByText('Go at sunset')).toBeInTheDocument(); + expect(within(card).queryByText('Go at sunset')).not.toBeInTheDocument(); await user.click(card); expect(props.onOpenList).toHaveBeenCalledWith(9, 900); }); @@ -241,3 +262,35 @@ describe('MLibraryPlaceSheet: what to do with it', () => { expect(openNavigationTarget).not.toHaveBeenCalled(); }); }); + +describe('MLibraryPlaceSheet: the look of its origins and the sections below', () => { + it('FE-MOB-LIBPLACESHEET-013: a trip with a cover shows it, a list wears its own colour', () => { + const entry = libraryEntry({ + origins: [tripOrigin({ trip_cover: '/uploads/covers/rome.jpg' }), listOrigin({ collection_color: '#ff0000' })], + }); + setup({ data: libraryDetail(entry, [tripDetail(), listDetail()]) }); + const trip = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' }); + expect(trip.querySelector('img')).toHaveAttribute('src', '/uploads/covers/rome.jpg'); + const list = screen.getByRole('button', { name: 'Open in the list: Favourites' }); + const tile = list.querySelector('[style*="color"]'); + expect(tile?.style.color).toBe('rgb(255, 0, 0)'); + }); + + it('FE-MOB-LIBPLACESHEET-014: tags, notes, media, visits, activities and history follow, wired to the place', () => { + const { props } = setup(); + for (const name of ['tags', 'notes', 'media', 'visits', 'activities', 'history']) { + expect(screen.getByTestId(`section-${name}`)).toBeInTheDocument(); + } + expect(sections.tags).toMatchObject({ data: props.data, onChanged: props.onNotesSaved }); + expect(sections.notes).toMatchObject({ data: props.data, onSaved: props.onNotesSaved }); + expect(sections.media).toMatchObject({ entry: props.data?.entry }); + expect(sections.visits).toMatchObject({ entry: props.data?.entry, language: 'en' }); + expect(sections.activities).toMatchObject({ entry: props.data?.entry, language: 'en' }); + expect(sections.history).toMatchObject({ entry: props.data?.entry, language: 'en' }); + }); + + it('FE-MOB-LIBPLACESHEET-015: while it loads no section is drawn', () => { + setup({ data: null, loading: true }); + expect(screen.queryByTestId('section-notes')).toBeNull(); + }); +}); diff --git a/client/tests/unit/mobile/collections/MPlacesLibrary.test.tsx b/client/tests/unit/mobile/collections/MPlacesLibrary.test.tsx index 0caa6574b..9445bf793 100644 --- a/client/tests/unit/mobile/collections/MPlacesLibrary.test.tsx +++ b/client/tests/unit/mobile/collections/MPlacesLibrary.test.tsx @@ -347,6 +347,9 @@ describe('MPlacesLibrary: the place sheet', () => { await picker.onCopy(7, carry); }); expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry); + // The copy adds an origin, so the place is read again; a saved note does the same. + expect(captured(seen.lib).reload).toHaveBeenCalledTimes(1); + expect(captured(seen.sheet).onNotesSaved).toBe(captured(seen.lib).reload); act(() => picker.onClose()); expect(screen.queryByTestId('trip-picker')).not.toBeInTheDocument(); diff --git a/client/tests/unit/mobile/trip/MPlacesBrowser.test.tsx b/client/tests/unit/mobile/trip/MPlacesBrowser.test.tsx index d48094e1a..891abf5e6 100644 --- a/client/tests/unit/mobile/trip/MPlacesBrowser.test.tsx +++ b/client/tests/unit/mobile/trip/MPlacesBrowser.test.tsx @@ -7,11 +7,12 @@ import { toursApi } from '../../../../src/api/client' import type { CollectionListResponse, TourListItem } from '@trek/shared' import { useAddonStore } from '../../../../src/store/addonStore' import { useTripStore } from '../../../../src/store/tripStore' +import { usePlaceVisitsStore } from '../../../../src/store/placeVisitsStore' import { resetAllStores, seedStore } from '../../../helpers/store' import type { MTripShellApi, TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell' import type { AssignmentsMap, Category, Day, Place } from '../../../../src/types' -// FE-MOB-PBROW-001 to FE-MOB-PBROW-037 +// FE-MOB-PBROW-001 to FE-MOB-PBROW-038 const CATEGORIES = [ { id: 1, name: 'Sights', color: '#123456', icon: 'landmark' }, @@ -522,4 +523,20 @@ describe('MPlacesBrowser', () => { expect(within(row('Typed Cafe')).getByRole('img', { name: 'places.noCoordinates' })).toBeInTheDocument() expect(within(row('Louvre')).queryByRole('img', { name: 'places.noCoordinates' })).toBeNull() }) + + it('FE-MOB-PBROW-038: the "visited" chip appears once the reader visited a place of the trip, and narrows to it (PLC-23)', async () => { + const entry = { placeIds: [2], places: [] } + const loadTripVisited = vi.fn(async () => { + usePlaceVisitsStore.setState({ visited: { 'anon:1': entry } }) + return entry + }) + usePlaceVisitsStore.setState({ visited: {}, loadTripVisited }) + renderBrowser() + expect(screen.queryByRole('button', { name: 'places.filterVisited' })).toBeNull() + const chip = await screen.findByRole('button', { name: 'places.filterVisited' }) + expect(loadTripVisited).toHaveBeenCalledWith(1) + fireEvent.click(chip) + await waitFor(() => expect(screen.queryByText('Louvre')).toBeNull()) + expect(screen.getByText('Eiffel Tower')).toBeInTheDocument() + }) })