diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index 3e2439144..ec5791f7e 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -12,7 +12,7 @@ "react-hooks/set-state-in-effect": 189, "@typescript-eslint/no-floating-promises": 162, "react-hooks/exhaustive-deps": 113, - "@typescript-eslint/no-unused-vars": 122, + "@typescript-eslint/no-unused-vars": 121, "react-hooks/immutability": 28, "max-lines-per-function": 127, "react-hooks/static-components": 50, diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index 9503b0f61..905e8a2cf 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -698,6 +698,12 @@ "desktop": ["src/components/Planner/PlaceFormModal.tsx"], "mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"] }, + { + "feature": "Place add/edit form: tags", + "hooks": ["src/components/Planner/usePlaceTags.ts"], + "desktop": ["src/components/Planner/PlaceFormModal.tsx"], + "mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"] + }, { "feature": "Place detail actions", "hooks": ["src/components/Planner/usePlaceActions.ts"], @@ -1172,6 +1178,7 @@ "src/mobile/screens/trip/sheets/MTripSheetUi.tsx": "Phone sheet UI primitives (eyebrow, headers, stat boxes, action circles) and a time display helper.", "src/mobile/screens/trip/sheets/PlFileAttach.tsx": "Markup only; pending files and link actions come through props from the phone form sheets.", "src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).", + "src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.", "src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.", "src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.", "src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.", diff --git a/client/src/api/tripTags.ts b/client/src/api/tripTags.ts new file mode 100644 index 000000000..786176e25 --- /dev/null +++ b/client/src/api/tripTags.ts @@ -0,0 +1,11 @@ +import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse } from '@trek/shared'; +import apiClient from './client'; + +/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */ +export const tripTagsApi = { + list: (tripId: number | string): Promise => + apiClient.get(`/trips/${tripId}/tags`).then((r) => r.data), + /** Answers the trip's existing tag when it already has one of that name. */ + create: (tripId: number | string, body: TripTagCreateRequest): Promise => + apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data), +}; diff --git a/client/src/components/Planner/PlaceFormModal.helpers.ts b/client/src/components/Planner/PlaceFormModal.helpers.ts index 98fe596dc..8cebe5d58 100644 --- a/client/src/components/Planner/PlaceFormModal.helpers.ts +++ b/client/src/components/Planner/PlaceFormModal.helpers.ts @@ -47,6 +47,11 @@ export interface PlaceFormData { // Which shareable fields the user typed and which a pick or the details column filled // (placeFieldOrigins.ts). Rides along to the save as `fieldOrigins`; never shown. fieldOrigins?: PlaceFieldOrigins + // The ids of the place's tags, always the whole set, as the save takes them. Absent + // until one is ticked or unticked in the form (usePlaceTags): a missing key writes + // nothing, so a save that never touched the tags cannot undo a tag put on the place + // elsewhere in the meantime. + tags?: number[] } export function isGoogleMapsUrl(input: string): boolean { diff --git a/client/src/components/Planner/PlaceFormModal.tags.test.tsx b/client/src/components/Planner/PlaceFormModal.tags.test.tsx new file mode 100644 index 000000000..214d0032e --- /dev/null +++ b/client/src/components/Planner/PlaceFormModal.tags.test.tsx @@ -0,0 +1,99 @@ +// FE-PLANNER-PLACEFORM-TAGS-001 to FE-PLANNER-PLACEFORM-TAGS-004: the place's tags in the +// desktop dialog. The logic is usePlaceTags', tested on its own; this is the form around it. +import userEvent from '@testing-library/user-event'; +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildPlace, buildTag } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup'; +import { render, screen, waitFor, within } from '../../../tests/helpers/render'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { useTripStore } from '../../store/tripStore'; +import PlaceFormModal from './PlaceFormModal'; + +vi.mock('../shared/CustomTimePicker', async () => ({ + default: (await import('../../../tests/helpers/placeForm')).TimePickerStub, +})); + +const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' }); +const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' }); + +const tagGroup = () => screen.getByRole('group', { name: 'Tags' }); +const tagSwitch = (name: string) => within(tagGroup()).getByRole('button', { name }); + +beforeEach(() => { + resetAllStores(); + seedPlaceFormStores(); + seedStore(useTripStore, { tripTags: [monument, zone] }); +}); + +describe('PlaceFormModal, the tags', () => { + it('FE-PLANNER-PLACEFORM-TAGS-001: a new place is saved with the tags ticked in the form', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue(undefined); + render(); + expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'false'); + + await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Belem Tower'); + await user.click(tagSwitch('Monument')); + expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'true'); + await user.click(screen.getByRole('button', { name: /^Add$/i })); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Belem Tower', tags: [7] })); + }); + + it('FE-PLANNER-PLACEFORM-TAGS-002: an edit starts from the tags the place carries and saves the whole set', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue(undefined); + const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] }); + render(); + expect(tagSwitch('Zone')).toHaveAttribute('aria-pressed', 'true'); + + await user.click(tagSwitch('Monument')); + await user.click(tagSwitch('Zone')); + await user.click(screen.getByRole('button', { name: /^Update$/i })); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: [7] })); + }); + + it('FE-PLANNER-PLACEFORM-TAGS-003: an edit that never touched the tags leaves them out of the save', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue(undefined); + const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] }); + render(); + + await user.click(screen.getByRole('button', { name: /^Update$/i })); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0]).not.toHaveProperty('tags'); + }); + + it('FE-PLANNER-PLACEFORM-TAGS-004: a name typed into the tag field becomes a tag of the trip, ticked, without saving the place', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue(undefined); + let sent: unknown; + server.use( + http.post('/api/trips/1/tags', async ({ request }) => { + sent = await request.json(); + return HttpResponse.json({ tag: buildTag({ id: 9, trip_id: 1, name: 'Viewpoint' }) }, { status: 201 }); + }) + ); + render(); + const field = screen.getByRole('textbox', { name: 'New tag' }); + expect(screen.getByRole('button', { name: 'Add tag' })).toBeDisabled(); + + await user.type(field, 'Viewpoint{Enter}'); + + expect(await within(tagGroup()).findByRole('button', { name: 'Viewpoint' })).toHaveAttribute( + 'aria-pressed', + 'true' + ); + expect(sent).toMatchObject({ name: 'Viewpoint' }); + expect(field).toHaveValue(''); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Viewpoint', 'Zone']); + expect(onSave).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Planner/PlaceFormModal.tsx b/client/src/components/Planner/PlaceFormModal.tsx index 3e19e5fac..e3597a7d8 100644 --- a/client/src/components/Planner/PlaceFormModal.tsx +++ b/client/src/components/Planner/PlaceFormModal.tsx @@ -23,6 +23,8 @@ import { prefillForm, savedCategoryId, type PlaceFormData, type PlacePrefill, } from './PlaceFormModal.helpers' import { useNewCategory, usePlaceForm } from './usePlaceForm' +import { usePlaceTags } from './usePlaceTags' +import { PlaceFormTags } from './PlaceFormTags' import { usePlaceSearch } from './usePlaceSearch' import { guessCategoryId } from '@trek/shared' import { offersGoogleRetry } from '../../utils/placeSource' @@ -128,6 +130,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) { const image = usePlaceImageField({ place, imageUrl: form.image_url, pendingImage, canUploadFiles, stageUpload, stageAttached, removeImage, }) + const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast }) // The index the picked place came from, as its row named it, shown as a pill // in the head band. Null for a place typed by hand or taken from the saved list. const [pickedSource, setPickedSource] = useState(null) @@ -451,6 +454,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) { handlePaste, pickImage, image, + tagField, adoptDescription, hasTimeError, handleSubmit, @@ -792,6 +796,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) { )} + {/* Extra labels next to the one category, to filter the places by. Not for a + stop on a drive, which is not an activity anyone looks up by its tags. */} + {!serviceStop && } {/* The day in context: its times and its own note. Both live on the day-assignment, not on the pool place (#2163), so they are only shown diff --git a/client/src/components/Planner/PlaceFormTags.test.tsx b/client/src/components/Planner/PlaceFormTags.test.tsx new file mode 100644 index 000000000..bc05bb605 --- /dev/null +++ b/client/src/components/Planner/PlaceFormTags.test.tsx @@ -0,0 +1,68 @@ +// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-004: the markup of the place form's tags +// on the desktop. The state behind it is usePlaceTags', tested on its own. +import { describe, expect, it, vi } from 'vitest'; + +import { fireEvent, render, screen, within } from '../../../tests/helpers/render'; +import { PlaceFormTags } from './PlaceFormTags'; +import type { PlaceTagsField } from './usePlaceTags'; + +const t = (key: string) => key; + +function field(overrides: Partial = {}): PlaceTagsField { + return { + options: [ + { id: 7, name: 'Monument', color: '#6366f1', on: true }, + { id: 8, name: 'Zone', on: false }, + ], + toggle: vi.fn(), + name: '', + setName: vi.fn(), + saving: false, + canAdd: false, + addNew: vi.fn(() => Promise.resolve()), + handleNameKey: vi.fn(), + ...overrides, + }; +} + +describe('PlaceFormTags', () => { + it('FE-PLANNER-PLFORMTAGS-001: shows every tag on offer as a switch that says whether it is on', () => { + render(); + const group = screen.getByRole('group', { name: 'places.tags' }); + expect(within(group).getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true'); + expect(within(group).getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false'); + }); + + it('FE-PLANNER-PLFORMTAGS-002: a click on a tag switches that tag', () => { + const tags = field(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Zone' })); + expect(tags.toggle).toHaveBeenCalledTimes(1); + expect(tags.toggle).toHaveBeenCalledWith(8); + }); + + it('FE-PLANNER-PLFORMTAGS-003: the name of a new tag is typed into the field, whose keys go to the hook', () => { + const tags = field({ name: 'View' }); + render(); + const input = screen.getByRole('textbox', { name: 'places.newTag' }); + expect(input).toHaveValue('View'); + expect(input).toHaveAttribute('maxlength', '50'); + fireEvent.change(input, { target: { value: 'Viewpoint' } }); + expect(tags.setName).toHaveBeenCalledWith('Viewpoint'); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(tags.handleNameKey).toHaveBeenCalledTimes(1); + }); + + it('FE-PLANNER-PLFORMTAGS-004: the add button waits for a name, then adds the tag; a trip without tags shows the field alone', () => { + const idle = field({ options: [] }); + const { unmount } = render(); + expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled(); + expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(1); + unmount(); + + const ready = field({ name: 'Viewpoint', canAdd: true }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'places.addTag' })); + expect(ready.addNew).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/components/Planner/PlaceFormTags.tsx b/client/src/components/Planner/PlaceFormTags.tsx new file mode 100644 index 000000000..1f229b862 --- /dev/null +++ b/client/src/components/Planner/PlaceFormTags.tsx @@ -0,0 +1,71 @@ +import { TRIP_TAG_NAME_MAX } from '@trek/shared'; +import { Plus, Tag as TagIcon } from 'lucide-react'; + +import { DialogSection, fs } from '../shared/DialogShell'; +import type { PlaceTagsField } from './usePlaceTags'; + +type Translate = (key: string, params?: Record) => string; + +const ROW = 'flex flex-wrap items-center gap-1.5'; +const CHIP = + 'inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium transition-colors'; +const CHIP_ON = 'border-transparent bg-accent text-accent-text'; +const CHIP_OFF = 'border-edge bg-surface-input text-content-secondary hover:text-content'; +const NEW_TAG = 'inline-flex min-w-0 items-center gap-1'; +const NEW_TAG_INPUT = + 'w-36 min-w-0 rounded-full border border-dashed border-edge bg-transparent px-2.5 py-1 text-content outline-none placeholder:text-content-faint focus:border-solid focus:border-content-faint'; +const ADD_BUTTON = + 'grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content disabled:cursor-default disabled:opacity-50'; + +/** + * The tags of the place form on the desktop: every tag on offer as a switch, and a + * field that adds a new one to the trip. The state is usePlaceTags'; this is its markup. + */ +export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) { + return ( + +
+ {tags.options.map((tag) => ( + + ))} + + tags.setName(e.target.value)} + onKeyDown={tags.handleNameKey} + maxLength={TRIP_TAG_NAME_MAX} + aria-label={t('places.newTag')} + placeholder={t('places.newTag')} + className={NEW_TAG_INPUT} + style={fs(12, 'body')} + /> + + +
+
+ ); +} diff --git a/client/src/components/Planner/PlaceInspector.test.tsx b/client/src/components/Planner/PlaceInspector.test.tsx index 42a31b527..c8c71c625 100644 --- a/client/src/components/Planner/PlaceInspector.test.tsx +++ b/client/src/components/Planner/PlaceInspector.test.tsx @@ -1782,6 +1782,17 @@ describe('PlaceInspector', () => { expect(header.textContent).not.toContain('·'); }); + it('FE-PLANNER-INSPECTOR-106b: the tags of the place are pills beside its category, each once and by name', () => { + const tags = [{ id: 8, name: 'Zone', color: '#10b981' }, { id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }]; + render(); + const header = document.querySelector('header') as HTMLElement; + const pills = ['Landmark', 'Monument', 'Zone'].map(name => within(header).getByText(name)); + expect(pills[0].compareDocumentPosition(pills[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(pills[1].compareDocumentPosition(pills[2]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // The tag's own colour is on its mark only; the pill and the marker keep theirs. + expect((pills[2].querySelector('svg') as SVGElement).style.color).toBe('rgb(16, 185, 129)'); + }); + it('FE-PLANNER-INSPECTOR-107: the rating block is labelled and quotes the first usable review', async () => { vi.mocked(mapsApi.details).mockResolvedValue({ place: { rating: 4.1, reviews: [{ text: 'meh' }, { text: 'Lovely staff and view' }] }, diff --git a/client/src/components/Planner/PlaceInspectorHead.tsx b/client/src/components/Planner/PlaceInspectorHead.tsx index d17b65753..43ab54f8f 100644 --- a/client/src/components/Planner/PlaceInspectorHead.tsx +++ b/client/src/components/Planner/PlaceInspectorHead.tsx @@ -1,8 +1,20 @@ -import { Banknote, ChevronDown, ChevronUp, Mail, MapPin, MapPinOff, Phone, Star, X } from 'lucide-react'; +import { + Banknote, + ChevronDown, + ChevronUp, + Mail, + MapPin, + MapPinOff, + Phone, + Star, + Tag as TagIcon, + X, +} from 'lucide-react'; import type { KeyboardEvent, ReactNode, RefObject } from 'react'; import { useTranslation } from '../../i18n'; import type { Category, Place } from '../../types'; +import { tagChoices } from '../../utils/placeTags'; import AssistantAskButton from '../Assistant/AssistantAskButton'; import DawarichIcon from '../shared/DawarichIcon'; import { NEUTRAL_TINT, fs } from '../shared/DialogShell'; @@ -84,9 +96,12 @@ export function InspectorHead({ const hasCoords = !!(place.lat && place.lng); // A typed address that never got coordinates: the place has no marker, and says why (#2837). const offMap = addressWithoutCoordinates(place); + // The extra labels of the place, beside its one category. They never reach the marker. + const tags = tagChoices(place.tags); const hasPills = openNow !== null || !!category || + tags.length > 0 || !!time || rating != null || !!price || @@ -174,6 +189,12 @@ export function InspectorHead({ {category.name} )} + {tags.map((tag) => ( + + + {tag.name} + + ))} {time && {time}} {rating != null && rating > 0 && ( diff --git a/client/src/components/Planner/PlacesSidebar.tags.test.tsx b/client/src/components/Planner/PlacesSidebar.tags.test.tsx new file mode 100644 index 000000000..295b86af1 --- /dev/null +++ b/client/src/components/Planner/PlacesSidebar.tags.test.tsx @@ -0,0 +1,149 @@ +// FE-PLANNER-SIDEBAR-TAGS-001 to FE-PLANNER-SIDEBAR-TAGS-005: the tags in the category filter +// of the desktop places list. The predicate itself is covered in utils/placesFilter.test.ts. +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildCategory, buildPlace, buildTag, buildTrip, buildUser } from '../../../tests/helpers/factories'; +import { render, screen, within } from '../../../tests/helpers/render'; +import { resetAllStores, seedStore } from '../../../tests/helpers/store'; +import { useAuthStore } from '../../store/authStore'; +import { useTripStore } from '../../store/tripStore'; +import PlacesSidebar from './PlacesSidebar'; + +// The rows' pictures would ask the server for photos. +vi.mock('../../services/photoService', () => ({ + getCached: vi.fn(() => null), + isLoading: vi.fn(() => false), + fetchPhoto: vi.fn(), + onThumbReady: vi.fn(() => () => undefined), +})); + +const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' }); +const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' }); +const park = buildCategory({ id: 4, name: 'Park', color: '#22c55e' }); + +const tower = buildPlace({ + name: 'Belem Tower', + address: 'Lisbon', + category_id: 4, + tags: [{ id: 7, name: 'Monument' }], +}); +const garden = buildPlace({ name: 'Estrela Garden', address: 'Lisbon', category_id: 4 }); +const market = buildPlace({ + name: 'Time Out Market', + address: 'Lisbon', + category_id: null, + // A traveller's personal tag, put on the place through the API: the trip does not list it. + tags: [ + { id: 8, name: 'Zone' }, + { id: 50, name: 'Hidden gem' }, + ], +}); + +const props = { + tripId: 1, + places: [tower, garden, market], + categories: [park], + assignments: {}, + selectedDayId: null, + selectedPlaceId: null, + onPlaceClick: vi.fn(), + onAddPlace: vi.fn(), + onAssignToDay: vi.fn(), + onEditPlace: vi.fn(), + onDeletePlace: vi.fn(), + days: [], + isMobile: false, +}; + +type User = ReturnType; + +const trigger = () => screen.getByRole('button', { name: 'Categories' }); + +async function openFilter(user: User) { + if (trigger().getAttribute('aria-expanded') !== 'true') await user.click(trigger()); +} + +/** What the closed filter says is in force, read from its tooltip. */ +async function filterLabel(user: User) { + if (trigger().getAttribute('aria-expanded') === 'true') await user.click(trigger()); + // The tip opens when the pointer comes in, so it leaves first. + await user.unhover(trigger()); + await user.hover(trigger()); + const text = (await screen.findByRole('tooltip')).textContent; + await user.unhover(trigger()); + return text; +} + +beforeEach(() => { + resetAllStores(); + seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true }); + seedStore(useTripStore, { trip: buildTrip({ id: 1 }), tripTags: [monument, zone] }); +}); + +describe('PlacesSidebar category filter: tags', () => { + it('FE-PLANNER-SIDEBAR-TAGS-001: lists the tags under the categories, the ones of the trip and any other a place carries', async () => { + const user = userEvent.setup(); + render(); + await openFilter(user); + expect(screen.getByText('Tags')).toBeInTheDocument(); + for (const name of ['Park', 'No Category', 'Hidden gem', 'Monument', 'Zone']) { + expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'false'); + } + }); + + it('FE-PLANNER-SIDEBAR-TAGS-002: a ticked tag keeps the places that carry it', async () => { + const user = userEvent.setup(); + render(); + await openFilter(user); + await user.click(screen.getByRole('button', { name: 'Monument' })); + expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByText('Belem Tower')).toBeInTheDocument(); + expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument(); + expect(screen.queryByText('Time Out Market')).not.toBeInTheDocument(); + expect(useTripStore.getState().placesCategoryFilter).toEqual(new Set(['tag:7'])); + expect(await filterLabel(user)).toBe('Categories: Monument'); + }); + + it('FE-PLANNER-SIDEBAR-TAGS-003: a category and a tag ticked together both have to hold, and the filter names them', async () => { + const user = userEvent.setup(); + render(); + await openFilter(user); + await user.click(screen.getByRole('button', { name: 'Park' })); + expect(screen.getByText('Estrela Garden')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Monument' })); + expect(screen.getByText('Belem Tower')).toBeInTheDocument(); + expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument(); + expect(within(trigger()).getByText('2')).toBeInTheDocument(); + expect(await filterLabel(user)).toBe('Categories: Park, Monument'); + }); + + it('FE-PLANNER-SIDEBAR-TAGS-004: clearing the filter unticks the tags as well', async () => { + const user = userEvent.setup(); + render(); + await openFilter(user); + await user.click(screen.getByRole('button', { name: 'Zone' })); + await user.click(screen.getByRole('button', { name: 'No Category' })); + expect(screen.getByText('Time Out Market')).toBeInTheDocument(); + expect(screen.queryByText('Belem Tower')).not.toBeInTheDocument(); + expect(await filterLabel(user)).toBe('Categories: No Category, Zone'); + + await openFilter(user); + await user.click(screen.getByText('Clear filter')); + expect(useTripStore.getState().placesCategoryFilter.size).toBe(0); + expect(screen.getByText('Belem Tower')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false'); + }); + + it('FE-PLANNER-SIDEBAR-TAGS-005: a trip with tags and no category still has the filter; with neither it has none', async () => { + const user = userEvent.setup(); + const { unmount } = render(); + await openFilter(user); + expect(screen.getByRole('button', { name: 'Monument' })).toBeInTheDocument(); + unmount(); + + seedStore(useTripStore, { tripTags: [] }); + render(); + expect(screen.queryByRole('button', { name: 'Categories' })).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Planner/PlacesSidebarHeader.tsx b/client/src/components/Planner/PlacesSidebarHeader.tsx index f6d2049c6..6b544f132 100644 --- a/client/src/components/Planner/PlacesSidebarHeader.tsx +++ b/client/src/components/Planner/PlacesSidebarHeader.tsx @@ -8,9 +8,10 @@ import { Eyebrow } from './bookings/bookingParts' import { tintOf } from './planParts' import { CategoryTile } from './PlacesBulkCategoryModal' import type { SidebarState } from './usePlacesSidebar' -import { placesFilterTabs } from './usePlacesPool' +import { placesFilterTabs, usePlacesFilterTags } from './usePlacesPool' import { PLACES_SORTS, type PlacesSort } from './placesSort' -import { RATING_FLOORS, UNCATEGORIZED } from '../../utils/placesFilter' +import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../utils/placesFilter' +import type { TagChoice } from '../../utils/placeTags' /** * Below this the two labels stop fitting side by side and both buttons fall back @@ -249,22 +250,31 @@ function FilterDropdown({ label, active, badge, icon, open, setOpen, name, child ) } -/** Which categories to show, many at once; the label says what is in force. */ +/** + * What the category filter says is in force: nothing, the one name, or how many + * categories. Once a tag is ticked too it is no count of categories any more, so + * the names say it. + */ +function categoryFilterLabel({ t, categories, categoryFilters }: SidebarState, tags: TagChoice[]): string { + if (categoryFilters.size === 0) return t('places.allCategories') + const tagNames = tags.filter(tag => categoryFilters.has(tagFilterKey(tag.id))).map(tag => tag.name) + if (tagNames.length === 0 && categoryFilters.size > 1) { + return `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}` + } + const names = categories.filter(c => categoryFilters.has(String(c.id))).map(c => c.name) + if (categoryFilters.has(UNCATEGORIZED)) names.push(t('places.noCategory')) + return [...names, ...tagNames].join(', ') || t('places.allCategories') +} + +/** Which categories and which tags to show, many at once; the label says what is in force. */ function CategoryFilter(S: SidebarState) { const { t, places, categories, categoryFilters, setCategoryFilters, toggleCategoryFilter } = S const [open, setOpen] = useState(false) - if (categories.length === 0) return null - let label = t('places.allCategories') - if (categoryFilters.size === 1) { - const only = categories.find(c => categoryFilters.has(String(c.id))) - if (categoryFilters.has(UNCATEGORIZED)) label = t('places.noCategory') - else if (only) label = only.name - } else if (categoryFilters.size > 1) { - label = `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}` - } + const tags = usePlacesFilterTags(places) + if (categories.length === 0 && tags.length === 0) return null return ( - 0} badge={categoryFilters.size} - icon={} open={open} setOpen={setOpen}> + 0} + badge={categoryFilters.size} icon={} open={open} setOpen={setOpen}> {categories.map(c => ( )} + {/* The tags, in the same list: a place has one category and any number of these. */} + {tags.length > 0 && {t('places.tags')}} + {tags.map(tag => ( + toggleCategoryFilter(tagFilterKey(tag.id))} + tile={( + + + + )} + label={tag.name} + /> + ))} {categoryFilters.size > 0 && ( + + + ); +} + +/** The tags a place carries, under its category on the phone's place sheet; nothing for a place without any. */ +export function PlTagChips({ tags }: { tags: Place['tags'] }) { + const shown = tagChoices(tags); + if (shown.length === 0) return null; + return ( +
+ {shown.map((tag) => ( + + + + {tag.name} + + + ))} +
+ ); +} diff --git a/client/src/repo/placeRepo.offline.test.ts b/client/src/repo/placeRepo.offline.test.ts index e9242d661..fa7435c77 100644 --- a/client/src/repo/placeRepo.offline.test.ts +++ b/client/src/repo/placeRepo.offline.test.ts @@ -1,4 +1,4 @@ -// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030 +// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030 to FE-REPO-PLACE-032 // Offline write paths (mutation queue + optimistic Dexie rows) and the bulk // online paths, which tests/unit/repo/placeRepo.test.ts does not touch. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' @@ -8,7 +8,7 @@ import { server } from '../../tests/helpers/msw/server' import { placeRepo } from './placeRepo' import { offlineDb, clearAll } from '../db/offlineDb' import type { QueuedMutation } from '../db/offlineDb' -import { buildPlace } from '../../tests/helpers/factories' +import { buildPlace, buildTag } from '../../tests/helpers/factories' function setOnline(v: boolean): void { Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true }) @@ -66,6 +66,37 @@ describe('placeRepo — field origins offline', () => { }) }) +describe('placeRepo — tags offline', () => { + it('FE-REPO-PLACE-031: the queued body names the tags by id, the optimistic row carries the tags themselves', async () => { + const monument = buildTag({ id: 7, trip_id: 3, name: 'Monument' }) + await offlineDb.tripTags.put({ tripId: 3, tags: [monument] }) + + const { place } = await placeRepo.create(3, { name: 'Belem Tower', tags: [7, 99] }) + + // The trip's tag as the device knows it; an id it does not know shows nothing until the sync. + expect(place.tags).toEqual([monument]) + expect((await offlineDb.places.get(place.id))?.tags).toEqual([monument]) + expect((await queue())[0].body).toEqual({ name: 'Belem Tower', tags: [7, 99] }) + }) + + it('FE-REPO-PLACE-032: an update keeps a tag of the place the trip does not list, and a write without tags leaves them', async () => { + const zone = buildTag({ id: 8, trip_id: 3, name: 'Zone' }) + await offlineDb.tripTags.put({ tripId: 3, tags: [zone] }) + const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' } + await offlineDb.places.put(buildPlace({ id: 12, trip_id: 3, tags: [personal] })) + + const tagged = await placeRepo.update(3, 12, { tags: [50, 8] }) + expect(tagged.place.tags).toEqual([personal, zone]) + + const renamed = await placeRepo.update(3, 12, { name: 'Renamed' }) + expect(renamed.place.tags).toEqual([personal, zone]) + + const cleared = await placeRepo.update(3, 12, { tags: [] }) + expect(cleared.place.tags).toEqual([]) + expect((await offlineDb.places.get(12))?.tags).toEqual([]) + }) +}) + describe('placeRepo.update — offline', () => { it('FE-REPO-PLACE-003: merges into the cached row and sends the concurrency token', async () => { await offlineDb.places.put(buildPlace({ id: 90, trip_id: 3, name: 'Old', updated_at: '2026-01-01T00:00:00.000Z' })) diff --git a/client/src/repo/placeRepo.ts b/client/src/repo/placeRepo.ts index 849b968f8..0da4415e9 100644 --- a/client/src/repo/placeRepo.ts +++ b/client/src/repo/placeRepo.ts @@ -1,4 +1,5 @@ import { placesApi } from '../api/client' +import { cachedTripTags } from '../db/cacheTripTags' import { offlineDb, replaceTripRows, upsertPlaces } from '../db/offlineDb' import { mutationQueue, generateUUID, nextTempId } from '../sync/mutationQueue' import { isEffectivelyOffline } from '../sync/networkMode' @@ -8,11 +9,15 @@ import type { Place } from '../types' /** * What of a write the optimistic row keeps. `fieldOrigins` says which fields the * user typed; it travels in the queued body for the server's origin tracking and - * is no column of the place. + * is no column of the place. `tags` names the place's tags by id, while a row + * carries the tags themselves, so the row gets the ones the device knows by those + * ids: the trip's cached ones, and those the place had before. */ -function placeRow(data: Record): Record { - const { fieldOrigins: _origins, ...row } = data - return row +async function placeRow(tripId: number, data: Record, before?: Place): Promise> { + const { fieldOrigins: _origins, tags, ...row } = data + if (!Array.isArray(tags)) return row + const known = [...(await cachedTripTags(tripId)), ...(before?.tags ?? [])] + return { ...row, tags: tags.flatMap(id => known.find(tag => tag.id === id) ?? []) } } export const placeRepo = { @@ -35,7 +40,7 @@ export const placeRepo = { if (isEffectivelyOffline()) { const tempId = nextTempId() const tempPlace: Place = { - ...(placeRow(data) as Partial), + ...(await placeRow(Number(tripId), data) as Partial), id: tempId, trip_id: Number(tripId), name: (data.name as string) ?? 'New place', @@ -66,7 +71,7 @@ export const placeRepo = { // a row without it is invisible and never cleaned up. const optimistic: Place = { ...(existing ?? {} as Place), - ...(placeRow(data) as Partial), + ...(await placeRow(Number(tripId), data, existing) as Partial), id: Number(id), trip_id: Number(tripId), } diff --git a/client/src/repo/tripTagRepo.test.ts b/client/src/repo/tripTagRepo.test.ts new file mode 100644 index 000000000..b93d802b3 --- /dev/null +++ b/client/src/repo/tripTagRepo.test.ts @@ -0,0 +1,96 @@ +// FE-REPO-TRIPTAG-001 to FE-REPO-TRIPTAG-007: the tags a trip owns, read through to the +// server and kept on this device, read from there without a connection, and added +// online only. +import 'fake-indexeddb/auto'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildTag } from '../../tests/helpers/factories'; +import { clearAll, clearTripData, offlineDb } from '../db/offlineDb'; +import { isEffectivelyOffline } from '../sync/networkMode'; +import { OnlineOnlyError } from './onlineOnly'; +import { tripTagRepo } from './tripTagRepo'; + +const { client } = vi.hoisted(() => ({ client: { get: vi.fn(), post: vi.fn() } })); + +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) })); +vi.mock('../api/client', () => ({ default: client, apiClient: client })); + +const monument = buildTag({ id: 7, trip_id: 4, name: 'Monument' }); +const zone = buildTag({ id: 8, trip_id: 4, name: 'Zone' }); +/** An axios failure that never reached the server. */ +const networkError = () => Object.assign(new Error('Network Error'), { isAxiosError: true }); + +beforeEach(async () => { + await clearAll(); + vi.clearAllMocks(); + vi.mocked(isEffectivelyOffline).mockReturnValue(false); +}); + +describe('tripTagRepo', () => { + it('FE-REPO-TRIPTAG-001: reads the tags of the trip and keeps them on this device', async () => { + client.get.mockResolvedValue({ data: { tags: [monument, zone] } }); + + expect(await tripTagRepo.list('4')).toEqual({ tags: [monument, zone] }); + + expect(client.get).toHaveBeenCalledWith('/trips/4/tags'); + expect((await offlineDb.tripTags.get(4))?.tags).toEqual([monument, zone]); + }); + + it('FE-REPO-TRIPTAG-002: without a connection answers what the device last read, and nothing for a trip it never read', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [monument] }); + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + + expect(await tripTagRepo.list(4)).toEqual({ tags: [monument] }); + expect(await tripTagRepo.list(5)).toEqual({ tags: [] }); + expect(client.get).not.toHaveBeenCalled(); + }); + + it('FE-REPO-TRIPTAG-003: a request that never reached the server falls back to the device, a refusal does not', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [zone] }); + client.get.mockRejectedValueOnce(networkError()); + expect(await tripTagRepo.list(4)).toEqual({ tags: [zone] }); + + const refused = Object.assign(new Error('Forbidden'), { isAxiosError: true, response: { status: 403 } }); + client.get.mockRejectedValueOnce(refused); + await expect(tripTagRepo.list(4)).rejects.toBe(refused); + }); + + it('FE-REPO-TRIPTAG-004: a new tag is sent to the trip and joins the list on this device, by name', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [zone] }); + client.post.mockResolvedValue({ data: { tag: monument } }); + + expect(await tripTagRepo.create(4, { name: 'Monument', color: '#6366f1' })).toEqual(monument); + + expect(client.post).toHaveBeenCalledWith('/trips/4/tags', { name: 'Monument', color: '#6366f1' }); + expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + }); + + it('FE-REPO-TRIPTAG-005: the tag the trip has already under that name is not kept twice', async () => { + await offlineDb.tripTags.put({ tripId: 4, tags: [monument, zone] }); + client.post.mockResolvedValue({ data: { tag: zone } }); + + await tripTagRepo.create(4, { name: 'zone' }); + + expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.id)).toEqual([7, 8]); + }); + + it('FE-REPO-TRIPTAG-006: adding a tag needs a connection, and says so before anything is sent', async () => { + vi.mocked(isEffectivelyOffline).mockReturnValue(true); + + await expect(tripTagRepo.create(4, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError); + + expect(client.post).not.toHaveBeenCalled(); + expect(await offlineDb.tripTags.get(4)).toBeUndefined(); + }); + + it('FE-REPO-TRIPTAG-007: the tags kept for a trip go with it, and another trip keeps its own', async () => { + await offlineDb.tripTags.bulkPut([ + { tripId: 4, tags: [monument] }, + { tripId: 5, tags: [zone] }, + ]); + + await clearTripData(4); + + expect(await offlineDb.tripTags.get(4)).toBeUndefined(); + expect((await offlineDb.tripTags.get(5))?.tags).toEqual([zone]); + }); +}); diff --git a/client/src/repo/tripTagRepo.ts b/client/src/repo/tripTagRepo.ts new file mode 100644 index 000000000..ff398e9b1 --- /dev/null +++ b/client/src/repo/tripTagRepo.ts @@ -0,0 +1,37 @@ +import type { Tag, TripTagCreateRequest, TripTagListResponse } from '@trek/shared'; + +import { tripTagsApi } from '../api/tripTags'; +import { cachedTripTags, cacheTripTags } from '../db/cacheTripTags'; +import { withTripTag } from '../utils/placeTags'; +import { requireOnline } from './onlineOnly'; +import { onlineThenCache } from './withOfflineFallback'; + +/** + * The tags a trip owns. Reading them works offline, from the list the device last + * read. Adding one is online only, on purpose: the place it is then put on is saved + * with the tag's id, and a queued place cannot name a tag the server has not made. + * Putting a tag the trip already has on a place is the place's own write, which the + * offline queue holds like any other. + */ +export const tripTagRepo = { + async list(tripId: number | string): Promise { + const id = Number(tripId); + return onlineThenCache( + async () => { + const result = await tripTagsApi.list(id); + await cacheTripTags(id, result.tags); + return result; + }, + async () => ({ tags: await cachedTripTags(id) }) + ); + }, + + /** The new tag, or the one the trip already has under that name. */ + async create(tripId: number | string, body: TripTagCreateRequest): Promise { + requireOnline(); + const id = Number(tripId); + const { tag } = await tripTagsApi.create(id, body); + await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag)); + return tag; + }, +}; diff --git a/client/src/store/slices/remoteEventHandler.ts b/client/src/store/slices/remoteEventHandler.ts index f7903ff3c..e52333299 100644 --- a/client/src/store/slices/remoteEventHandler.ts +++ b/client/src/store/slices/remoteEventHandler.ts @@ -719,6 +719,13 @@ export const STORE_REFRESHES: Partial> const tripId = get().trip?.id if (tripId) void get().reloadPackingItems(tripId) }), + // A tag of the trip added, renamed or deleted elsewhere: the event says only + // that the list changed, and the read takes a rename or a delete into the + // places that carry the tag. + 'tripTags:changed': get => refreshOncePerBurst('tripTags', () => { + const tripId = get().trip?.id + if (tripId) void get().loadTripTags(tripId) + }), } /** diff --git a/client/src/store/slices/tripTagsSlice.test.ts b/client/src/store/slices/tripTagsSlice.test.ts new file mode 100644 index 000000000..2d987a111 --- /dev/null +++ b/client/src/store/slices/tripTagsSlice.test.ts @@ -0,0 +1,135 @@ +// FE-STORE-TRIPTAGS-001 to FE-STORE-TRIPTAGS-006: the tags of the open trip in the store, +// and what a tag renamed or deleted elsewhere does to the places that carry it. +import 'fake-indexeddb/auto'; +import { http, HttpResponse } from 'msw'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { buildAssignment, buildPlace, buildTag, buildTrip } from '../../../tests/helpers/factories'; +import { server } from '../../../tests/helpers/msw/server'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { clearAll } from '../../db/offlineDb'; +import { OnlineOnlyError } from '../../repo/onlineOnly'; +import { useTripStore } from '../tripStore'; + +const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' }); +const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' }); + +function setOnline(online: boolean): void { + Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true }); +} + +/** What the server lists as the tags of trip 5. */ +function serve(tags: unknown[]): void { + server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ tags }))); +} + +beforeEach(async () => { + await clearAll(); + resetAllStores(); + setOnline(true); + useTripStore.setState({ trip: buildTrip({ id: 5 }) }); +}); + +afterEach(() => { + setOnline(true); +}); + +describe('tripTagsSlice', () => { + it('FE-STORE-TRIPTAGS-001: reads the tags of the open trip, and drops an answer for a trip that is no longer open', async () => { + serve([monument, zone]); + await useTripStore.getState().loadTripTags(5); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + + server.use( + http.get('/api/trips/6/tags', () => HttpResponse.json({ tags: [buildTag({ id: 9, name: 'Other trip' })] })) + ); + await useTripStore.getState().loadTripTags(6); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + }); + + it('FE-STORE-TRIPTAGS-002: a tag renamed or deleted elsewhere is taken into the places and visits that carry it', async () => { + const tagged = buildPlace({ + id: 21, + trip_id: 5, + tags: [ + { id: 7, name: 'Monument', color: '#6366f1' }, + { id: 8, name: 'Zone' }, + ], + }); + const untouched = buildPlace({ id: 22, trip_id: 5, tags: [{ id: 50, name: 'Hidden gem' }] }); + const visit = buildAssignment({ id: 31, place: { ...tagged } }); + const otherVisit = buildAssignment({ id: 32, place: { ...untouched } }); + useTripStore.setState({ + tripTags: [monument, zone], + places: [tagged, untouched], + assignments: { '11': [visit, otherVisit] }, + placesCategoryFilter: new Set(['4', 'tag:7', 'tag:8']), + }); + serve([{ ...monument, name: 'Landmark', color: '#ef4444' }]); + + await useTripStore.getState().loadTripTags(5); + + const state = useTripStore.getState(); + expect(state.tripTags.map((tag) => tag.name)).toEqual(['Landmark']); + expect(state.places[0].tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]); + expect(state.assignments['11'][0].place.tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]); + // What carries none of the changed tags is the same object as before. + expect(state.places[1]).toBe(untouched); + expect(state.assignments['11'][1]).toBe(otherVisit); + // The deleted tag no longer filters; the renamed one and the category still do. + expect([...state.placesCategoryFilter]).toEqual(['4', 'tag:7']); + }); + + it('FE-STORE-TRIPTAGS-003: a reading that changes no tag on a place leaves the places and the filter as they are', async () => { + const tagged = buildPlace({ id: 21, trip_id: 5, tags: [{ id: 7, name: 'Monument', color: '#6366f1' }] }); + const filter = new Set(['tag:7']); + const assignments = { '11': [buildAssignment({ id: 31, place: { ...tagged } })] }; + useTripStore.setState({ tripTags: [monument], places: [tagged], assignments, placesCategoryFilter: filter }); + serve([monument, zone]); + + await useTripStore.getState().loadTripTags(5); + + const state = useTripStore.getState(); + expect(state.tripTags).toHaveLength(2); + expect(state.places[0]).toBe(tagged); + expect(state.assignments).toBe(assignments); + expect(state.placesCategoryFilter).toBe(filter); + }); + + it('FE-STORE-TRIPTAGS-004: a reading the server refuses keeps the tags on screen', async () => { + useTripStore.setState({ tripTags: [monument] }); + server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ error: 'Trip not found' }, { status: 404 }))); + + await useTripStore.getState().loadTripTags(5); + + expect(useTripStore.getState().tripTags).toEqual([monument]); + }); + + it('FE-STORE-TRIPTAGS-005: a new tag joins the list by name, and the one the trip has already is not listed twice', async () => { + useTripStore.setState({ tripTags: [zone] }); + let sent: unknown; + server.use( + http.post('/api/trips/5/tags', async ({ request }) => { + sent = await request.json(); + return HttpResponse.json({ tag: monument }, { status: 201 }); + }) + ); + + expect(await useTripStore.getState().addTripTag(5, { name: 'Monument', color: '#6366f1' })).toEqual(monument); + expect(sent).toEqual({ name: 'Monument', color: '#6366f1' }); + expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + + await useTripStore.getState().addTripTag(5, { name: 'monument' }); + expect(useTripStore.getState().tripTags.map((tag) => tag.id)).toEqual([7, 8]); + }); + + it('FE-STORE-TRIPTAGS-006: without a connection a new tag is refused and the list stays; another trip starts without tags', async () => { + useTripStore.setState({ tripTags: [zone] }); + setOnline(false); + + await expect(useTripStore.getState().addTripTag(5, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError); + expect(useTripStore.getState().tripTags).toEqual([zone]); + + useTripStore.getState().resetTrip(); + expect(useTripStore.getState().tripTags).toEqual([]); + }); +}); diff --git a/client/src/store/slices/tripTagsSlice.ts b/client/src/store/slices/tripTagsSlice.ts new file mode 100644 index 000000000..57b5c8c78 --- /dev/null +++ b/client/src/store/slices/tripTagsSlice.ts @@ -0,0 +1,64 @@ +import type { Tag, TripTagCreateRequest } from '@trek/shared'; +import type { StoreApi } from 'zustand'; + +import { tripTagRepo } from '../../repo/tripTagRepo'; +import { withoutTagFilters } from '../../utils/placesFilter'; +import { tagChanges, withTagChanges, withTripTag } from '../../utils/placeTags'; +import type { TripStoreState } from '../tripStore'; + +type SetState = StoreApi['setState']; +type GetState = StoreApi['getState']; + +export interface TripTagsSlice { + /** The tags the open trip owns, the same list for everybody on it (`tags` holds the user's personal ones). */ + tripTags: Tag[]; + /** Reads the trip's tags again: on a reconnect, and when they changed elsewhere (`tripTags:changed`). */ + loadTripTags: (tripId: number | string) => Promise; + /** Adds a tag to the trip, or hands back the one it already has under that name. Needs a connection. */ + addTripTag: (tripId: number | string, data: TripTagCreateRequest) => Promise; +} + +/** + * The store once the trip's tags were read again. A place carries a copy of each of + * its tags, so a tag renamed, recoloured or deleted elsewhere is taken into the places + * and into the visits that embed them, and a deleted one leaves the category filter. + */ +function withTripTags(state: TripStoreState, tags: Tag[]): Partial { + const changes = tagChanges(state.tripTags, tags); + if (!changes) return { tripTags: tags }; + return { + tripTags: tags, + places: state.places.map((place) => withTagChanges(place, changes)), + assignments: Object.fromEntries( + Object.entries(state.assignments).map(([dayId, visits]) => [ + dayId, + visits.map((visit) => { + const place = visit.place && withTagChanges(visit.place, changes); + return place === visit.place ? visit : { ...visit, place }; + }), + ]) + ), + placesCategoryFilter: withoutTagFilters(state.placesCategoryFilter, changes.removed), + }; +} + +export const createTripTagsSlice = (set: SetState, get: GetState): TripTagsSlice => ({ + tripTags: [], + + loadTripTags: async (tripId) => { + try { + const { tags } = await tripTagRepo.list(tripId); + // Another trip was opened while the answer was on its way. + if (String(get().trip?.id) !== String(tripId)) return; + set((state) => withTripTags(state, tags)); + } catch { + // The tags on screen stay; the next reload or reconnect reads them again. + } + }, + + addTripTag: async (tripId, data) => { + const tag = await tripTagRepo.create(tripId, data); + set((state) => ({ tripTags: withTripTag(state.tripTags, tag) })); + return tag; + }, +}); diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.ts index 80c975bbf..2ce87b045 100644 --- a/client/src/store/tripStore.ts +++ b/client/src/store/tripStore.ts @@ -10,6 +10,7 @@ import { todoRepo } from '../repo/todoRepo' import { budgetRepo } from '../repo/budgetRepo' import { reservationRepo } from '../repo/reservationRepo' import { fileRepo } from '../repo/fileRepo' +import { tripTagRepo } from '../repo/tripTagRepo' import { isEffectivelyOnline } from '../sync/networkMode' import { createPlacesSlice } from './slices/placesSlice' import { createAssignmentsSlice } from './slices/assignmentsSlice' @@ -20,6 +21,7 @@ import { createTodoSlice } from './slices/todoSlice' import { createBudgetSlice } from './slices/budgetSlice' import { createReservationsSlice } from './slices/reservationsSlice' import { createFilesSlice } from './slices/filesSlice' +import { createTripTagsSlice } from './slices/tripTagsSlice' import { handleRemoteEvent } from './slices/remoteEventHandler' import type { Trip, Day, Place, Assignment, DayNote, PackingItem, TodoItem, @@ -36,6 +38,7 @@ import type { TodoSlice } from './slices/todoSlice' import type { BudgetSlice } from './slices/budgetSlice' import type { ReservationsSlice } from './slices/reservationsSlice' import type { FilesSlice } from './slices/filesSlice' +import type { TripTagsSlice } from './slices/tripTagsSlice' import type { PlacesRatingFloor } from '../utils/placesFilter' /** The part of the world the trip's plan map shows, as its last move left it. */ @@ -63,7 +66,8 @@ export interface TripStoreState TodoSlice, BudgetSlice, ReservationsSlice, - FilesSlice { + FilesSlice, + TripTagsSlice { trip: Trip | null days: Day[] places: Place[] @@ -152,7 +156,7 @@ export const useTripStore = create((set, get) => ({ // Clear every trip-scoped slice so switching trips (or losing access to one) // can never leave a previous trip's data visible. Global tags/categories are - // left intact. Called at the top of loadTrip. + // left intact; the trip's own tags go with it. Called at the top of loadTrip. resetTrip: () => set({ trip: null, days: [], @@ -164,6 +168,7 @@ export const useTripStore = create((set, get) => ({ budgetItems: [], files: [], reservations: [], + tripTags: [], selectedDayId: null, placesFilter: 'all', placesCategoryFilter: new Set(), @@ -179,7 +184,7 @@ export const useTripStore = create((set, get) => ({ get().resetTrip() set({ isLoading: true, error: null }) try { - const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData] = await Promise.all([ + const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData, tripTagsData] = await Promise.all([ tripRepo.get(tripId), dayRepo.list(tripId), placeRepo.list(tripId), @@ -197,6 +202,9 @@ export const useTripStore = create((set, get) => ({ isEffectivelyOnline() ? categoriesApi.list().catch(() => offlineDb.categories.toArray().then(categories => ({ categories }))) : offlineDb.categories.toArray().then(categories => ({ categories })), + // The trip's own tags, non-fatal like the three above: without them the + // places still show the tags they carry. + tripTagRepo.list(tripId).catch(() => ({ tags: [] as Tag[] })), ]) const assignmentsMap: AssignmentsMap = {} @@ -219,6 +227,7 @@ export const useTripStore = create((set, get) => ({ files: filesData.files, tags: tagsData.tags, categories: categoriesData.categories, + tripTags: tripTagsData.tags, isLoading: false, }) } catch (err: unknown) { @@ -241,6 +250,7 @@ export const useTripStore = create((set, get) => ({ get().loadBudgetItems(tripId), get().loadReservations(tripId), get().loadFiles(tripId), + get().loadTripTags(tripId), ]) // Accommodations live in planner-local state, not this store — nudge the // planner to reload them too (e.g. a trip date change made while offline). @@ -344,4 +354,5 @@ export const useTripStore = create((set, get) => ({ ...createBudgetSlice(set, get), ...createReservationsSlice(set, get), ...createFilesSlice(set, get), + ...createTripTagsSlice(set, get), })) diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.ts index a9abc1ae1..6ed327632 100644 --- a/client/src/sync/tripSyncManager.ts +++ b/client/src/sync/tripSyncManager.ts @@ -1,5 +1,6 @@ import { roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo' import { tourRepo } from '../repo/tourRepo' +import { tripTagRepo } from '../repo/tripTagRepo' /** * Trip sync manager — seeds Dexie with trip data for offline use. * @@ -155,6 +156,14 @@ async function syncTrip(tripId: number): Promise { await roadtripPreferencesRepo.read(tripId).catch(() => { /* optional cache */ }) } + // The trip's own tags, which the repo keeps as it reads them. Never fatal either. + try { + await tripTagRepo.list(tripId) + } catch { + // An optional cache: the places carry the tags they have, so without this + // list only the unused ones are missing offline, until the next sync. + } + // Tours, the same way: optional, and never fatal. Without them every Tour // reads as a plain place offline. Asked only while the addon is on, so a // sync of many trips does not spend a refused request on each. diff --git a/client/src/utils/placeTags.test.ts b/client/src/utils/placeTags.test.ts new file mode 100644 index 000000000..a1b6a8832 --- /dev/null +++ b/client/src/utils/placeTags.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; + +import { buildPlace, buildTag } from '../../tests/helpers/factories'; +import { nextTagColor, placeTagIds, tagChanges, tagChoices, withTagChanges, withTripTag } from './placeTags'; + +describe('placeTags', () => { + it('FE-UTIL-PLTAGS-001: offers each tag once and by name, as the first list that has it says', () => { + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const carried = [ + { id: 2, name: 'Zone (old name)', color: '#000000' }, + { id: 9, name: 'Hidden gem', color: '#f97316' }, + ]; + expect(tagChoices([zone, monument], carried, undefined)).toEqual([ + { id: 9, name: 'Hidden gem', color: '#f97316' }, + { id: 1, name: 'Monument', color: '#6366f1' }, + { id: 2, name: 'Zone', color: '#10b981' }, + ]); + expect(tagChoices()).toEqual([]); + expect(tagChoices(undefined)).toEqual([]); + }); + + it('FE-UTIL-PLTAGS-002: leaves out a copy that cannot be shown and a colour that is no plain hex value', () => { + const choices = tagChoices([ + { name: 'No id' }, + { id: 3 }, + { id: 4, name: 'Painted', color: 'url(https://example.test/pixel)' }, + { id: 5, name: 'Plain' }, + ]); + expect(choices).toEqual([ + { id: 4, name: 'Painted', color: undefined }, + { id: 5, name: 'Plain', color: undefined }, + ]); + expect(choices[0].color).toBeUndefined(); + }); + + it('FE-UTIL-PLTAGS-003: names the tags of a place by id, each once, whatever else the copy lacks', () => { + expect(placeTagIds([{ id: 4, name: 'A' }, { id: 5 }, { name: 'No id' }, { id: 4, name: 'A' }])).toEqual([4, 5]); + expect(placeTagIds(undefined)).toEqual([]); + }); + + it('FE-UTIL-PLTAGS-004: colours new tags by turn', () => { + const first = nextTagColor([]); + const second = nextTagColor([buildTag()]); + expect(first).toMatch(/^#[0-9a-f]{6}$/); + expect(second).toMatch(/^#[0-9a-f]{6}$/); + expect(second).not.toBe(first); + // Past the last colour it starts over. + expect(nextTagColor(Array.from({ length: 8 }, () => buildTag()))).toBe(first); + }); + + it('FE-UTIL-PLTAGS-005: adds a tag to the list by name, and replaces the one of the same id', () => { + const monument = buildTag({ id: 1, name: 'Monument' }); + const zone = buildTag({ id: 2, name: 'Zone' }); + const added = withTripTag([zone], monument); + expect(added.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + const renamed = withTripTag(added, { ...zone, name: 'Area' }); + expect(renamed.map((tag) => [tag.id, tag.name])).toEqual([ + [2, 'Area'], + [1, 'Monument'], + ]); + }); + + it('FE-UTIL-PLTAGS-006: tells which tags were renamed, recoloured or deleted between two readings', () => { + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const walk = buildTag({ id: 3, name: 'Walk', color: '#f97316' }); + expect(tagChanges([monument, zone], [monument, zone])).toBeNull(); + // A new tag is on no place yet, so it changes nothing there. + expect(tagChanges([monument], [monument, zone])).toBeNull(); + const changes = tagChanges( + [monument, zone, walk], + [ + { ...monument, name: 'Landmark' }, + { ...walk, color: '#ef4444' }, + ] + ); + expect([...(changes?.removed ?? [])]).toEqual([2]); + expect([...(changes?.renamed.keys() ?? [])]).toEqual([1, 3]); + }); + + it('FE-UTIL-PLTAGS-007: takes the changes into the copies a place carries, and leaves an untouched place alone', () => { + const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' }); + const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' }); + const changes = tagChanges([monument, zone], [{ ...monument, name: 'Landmark', color: '#ef4444' }]); + if (!changes) throw new Error('expected changes'); + const place = buildPlace({ + tags: [ + { id: 1, name: 'Monument', color: '#6366f1', created_at: '2026-01-01' }, + { id: 2, name: 'Zone' }, + { id: 9, name: 'Own' }, + { name: 'No id' }, + ], + }); + expect(withTagChanges(place, changes).tags).toEqual([ + { id: 1, name: 'Landmark', color: '#ef4444', created_at: '2026-01-01' }, + { id: 9, name: 'Own' }, + { name: 'No id' }, + ]); + const untouched = buildPlace({ tags: [{ id: 9, name: 'Own' }] }); + expect(withTagChanges(untouched, changes)).toBe(untouched); + const untagged = buildPlace(); + expect(withTagChanges(untagged, changes)).toBe(untagged); + }); +}); diff --git a/client/src/utils/placeTags.ts b/client/src/utils/placeTags.ts new file mode 100644 index 000000000..cabf68d00 --- /dev/null +++ b/client/src/utils/placeTags.ts @@ -0,0 +1,80 @@ +import type { Place, Tag } from '@trek/shared'; + +import { safeHexColor } from './safeColor'; + +/** A tag as a place carries it: the compact row of a place list, where every field is optional. */ +type PlaceTag = NonNullable[number]; + +/** A tag as a picker, a filter row and a chip show it. */ +export interface TagChoice { + id: number; + name: string; + /** Absent for a colour that is no plain hex value: the chip then keeps the colour of its text. */ + color?: string; +} + +/** + * The tags of the given lists, each once and by name, as far as they can be shown. A tag + * reads as the first list that has it says, so with the trip's own tags ahead of the + * copies a place carries, the name and the colour are the current ones. + */ +export function tagChoices(...lists: (readonly PlaceTag[] | undefined)[]): TagChoice[] { + const choices = new Map(); + for (const tag of lists.flatMap((list) => list ?? [])) { + if (tag.id == null || !tag.name || choices.has(tag.id)) continue; + choices.set(tag.id, { id: tag.id, name: tag.name, color: safeHexColor(tag.color, '') || undefined }); + } + return [...choices.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** The ids of the tags a place carries, as a write names them. */ +export function placeTagIds(carried: readonly PlaceTag[] | undefined): number[] { + return [...new Set((carried ?? []).flatMap((tag) => (tag.id == null ? [] : [tag.id])))]; +} + +// What a new tag is coloured with, one after the other, so the tags of a trip tell apart at a glance. +const NEW_TAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b']; + +/** The colour the next new tag of a trip gets. */ +export function nextTagColor(tripTags: readonly unknown[]): string { + return NEW_TAG_COLORS[tripTags.length % NEW_TAG_COLORS.length]; +} + +/** The trip's tags with one more, or with the one of that id as it is now, by name as the server lists them. */ +export function withTripTag(tripTags: readonly Tag[], tag: Tag): Tag[] { + return [...tripTags.filter((other) => other.id !== tag.id), tag].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** What changed between two readings of a trip's tags, as far as the copies on its places go. */ +interface TagChanges { + /** The tags that are gone. */ + removed: ReadonlySet; + /** The tags with another name or colour, as they are now. */ + renamed: ReadonlyMap; +} + +/** Null when no tag was renamed, recoloured or deleted between the two readings. */ +export function tagChanges(before: readonly Tag[], after: readonly Tag[]): TagChanges | null { + const now = new Map(after.map((tag) => [tag.id, tag])); + const removed = new Set(); + const renamed = new Map(); + for (const old of before) { + const tag = now.get(old.id); + if (!tag) removed.add(old.id); + else if (tag.name !== old.name || tag.color !== old.color) renamed.set(tag.id, tag); + } + return removed.size > 0 || renamed.size > 0 ? { removed, renamed } : null; +} + +/** A place with its tags as the trip has them now; the same object when none of its tags changed. */ +export function withTagChanges

(place: P, changes: TagChanges): P { + const touched = (tag: PlaceTag) => tag.id != null && (changes.removed.has(tag.id) || changes.renamed.has(tag.id)); + if (!place.tags?.some(touched)) return place; + const tags = place.tags + .filter((tag) => tag.id == null || !changes.removed.has(tag.id)) + .map((tag) => { + const now = tag.id == null ? undefined : changes.renamed.get(tag.id); + return now ? { ...tag, name: now.name, color: now.color } : tag; + }); + return { ...place, tags }; +} diff --git a/client/src/utils/placesFilter.test.ts b/client/src/utils/placesFilter.test.ts index 741f65e78..ab659e421 100644 --- a/client/src/utils/placesFilter.test.ts +++ b/client/src/utils/placesFilter.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest' import { buildPlace } from '../../tests/helpers/factories' import { RATING_FLOORS, countActivePlacesFilters, matchesCategoryFilter, matchesPlacesFilter, - matchesPoolFilter, matchesRatingFloor, + matchesPoolFilter, matchesRatingFloor, tagFilterKey, withoutTagFilters, } from './placesFilter' const NONE = new Set() @@ -67,4 +67,44 @@ describe('placesFilter', () => { expect(countActivePlacesFilters({ filter: 'all', categoryFilters: new Set(['1', '2']), ratingFilter: 'all' })).toBe(1) expect(countActivePlacesFilters({ filter: 'tracks', categoryFilters: new Set(['1']), ratingFilter: 3 })).toBe(3) }) + + it('FE-UTIL-PLFILTER-008: a ticked tag keeps the places that carry it, whatever their category', () => { + const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }] }) + const plain = buildPlace({ category_id: 4 }) + const bare = buildPlace({ category_id: null, tags: [{ id: 8, name: 'Zone' }] }) + expect(tagFilterKey(7)).toBe('tag:7') + expect(matchesCategoryFilter(monument, new Set(['tag:7']))).toBe(true) + expect(matchesCategoryFilter(plain, new Set(['tag:7']))).toBe(false) + expect(matchesCategoryFilter(bare, new Set(['tag:7']))).toBe(false) + // Several ticked tags: carrying one of them is enough. + expect(matchesCategoryFilter(bare, new Set(['tag:7', 'tag:8']))).toBe(true) + // A copy without an id (a row still being written) matches no tag. + expect(matchesCategoryFilter(buildPlace({ tags: [{ name: 'Zone' }] }), new Set(['tag:8']))).toBe(false) + }) + + it('FE-UTIL-PLFILTER-009: categories and tags ticked together both have to hold', () => { + const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }] }) + const other = buildPlace({ category_id: 5, tags: [{ id: 7, name: 'Monument' }] }) + const untagged = buildPlace({ category_id: 4 }) + const bare = buildPlace({ category_id: null, tags: [{ id: 7, name: 'Monument' }] }) + const both = new Set(['4', 'tag:7']) + expect(matchesCategoryFilter(monument, both)).toBe(true) + expect(matchesCategoryFilter(other, both)).toBe(false) + expect(matchesCategoryFilter(untagged, both)).toBe(false) + expect(matchesCategoryFilter(bare, both)).toBe(false) + expect(matchesCategoryFilter(bare, new Set(['uncategorized', 'tag:7']))).toBe(true) + // The whole filter follows: the tag narrows the list and the map alike. + const state = { filter: 'all', categoryFilters: both, ratingFilter: 'all' as const } + expect(matchesPlacesFilter(monument, state, { plannedIds: null })).toBe(true) + expect(matchesPlacesFilter(untagged, state, { plannedIds: null })).toBe(false) + expect(countActivePlacesFilters(state)).toBe(1) + }) + + it('FE-UTIL-PLFILTER-010: a tag that is gone leaves the filter, and a filter without it stays the same set', () => { + const filters = new Set(['4', 'tag:7', 'tag:8']) + expect([...withoutTagFilters(filters, [7])]).toEqual(['4', 'tag:8']) + expect([...withoutTagFilters(filters, new Set([7, 8, 9]))]).toEqual(['4']) + expect(withoutTagFilters(filters, [9])).toBe(filters) + expect(withoutTagFilters(filters, [])).toBe(filters) + }) }) diff --git a/client/src/utils/placesFilter.ts b/client/src/utils/placesFilter.ts index a4fce60c9..c91993bbc 100644 --- a/client/src/utils/placesFilter.ts +++ b/client/src/utils/placesFilter.ts @@ -2,12 +2,12 @@ import type { Place } from '../types' /** * The trip's places filter, in one place: the pool (all / unplanned / planned / - * tracks), the category set and the minimum rating. The desktop list, the phone - * list and the map markers of both shells apply this same predicate to the same - * values, held in the trip store (#1541). The map keeps two deliberate - * differences of its own: with a day open, "planned" shows that day's plan only - * (#2024), and the stops of collapsed days are left off the map (except under - * "planned"). + * tracks), the category set, which the tags filter through as well, and the + * minimum rating. The desktop list, the phone list and the map markers of both + * shells apply this same predicate to the same values, held in the trip store + * (#1541). The map keeps two deliberate differences of its own: with a day + * open, "planned" shows that day's plan only (#2024), and the stops of + * collapsed days are left off the map (except under "planned"). */ /** A minimum of average stars: 'all', or a floor that unrated places fall through. */ @@ -19,12 +19,36 @@ export const RATING_FLOORS = ['all', 5, 4, 3, 2, 1] as const /** The pseudo category id that stands for "no category". */ export const UNCATEGORIZED = 'uncategorized' +const TAG_KEY = 'tag:' + +/** A tag's entry in the category filter set, which holds category ids, UNCATEGORIZED and these. */ +export const tagFilterKey = (tagId: number): string => `${TAG_KEY}${tagId}` + +/** + * The ticked categories and the ticked tags are two questions with one answer each: + * a place passes when it is in one of the ticked categories, if any is ticked, and + * carries one of the ticked tags, if any is ticked. + */ export function matchesCategoryFilter(place: Place, categoryFilters: ReadonlySet): boolean { if (categoryFilters.size === 0) return true + const tagsTicked = [...categoryFilters].filter(key => key.startsWith(TAG_KEY)).length + if (tagsTicked > 0 && !carriesTickedTag(place, categoryFilters)) return false + if (tagsTicked === categoryFilters.size) return true if (place.category_id == null) return categoryFilters.has(UNCATEGORIZED) return categoryFilters.has(String(place.category_id)) } +function carriesTickedTag(place: Place, ticked: ReadonlySet): boolean { + return (place.tags ?? []).some(tag => tag.id != null && ticked.has(tagFilterKey(tag.id))) +} + +/** The filter set without the entries of tags that are gone; the same set when it held none of them. */ +export function withoutTagFilters(categoryFilters: Set, goneTagIds: Iterable): Set { + const gone = [...goneTagIds].map(tagFilterKey).filter(key => categoryFilters.has(key)) + if (gone.length === 0) return categoryFilters + return new Set([...categoryFilters].filter(key => !gone.includes(key))) +} + export function matchesRatingFloor(place: Place, floor: PlacesRatingFloor): boolean { if (floor === 'all') return true return place.rating_avg != null && place.rating_avg >= floor diff --git a/client/tests/helpers/msw/handlers/tags.ts b/client/tests/helpers/msw/handlers/tags.ts index c57238e0d..e51782329 100644 --- a/client/tests/helpers/msw/handlers/tags.ts +++ b/client/tests/helpers/msw/handlers/tags.ts @@ -5,6 +5,9 @@ import { createTagRequestSchema, tagListResponseSchema, tagSchema, + tripTagCreateRequestSchema, + tripTagListResponseSchema, + tripTagResponseSchema, } from '@trek/shared'; import { z } from 'zod'; import { buildCategory, buildTag } from '../../factories'; @@ -22,6 +25,16 @@ export const tagsHandlers = [ }) ), + // The tags a trip owns: none unless a test serves its own. + contractHandler('get', '/api/trips/:tripId/tags', { response: tripTagListResponseSchema }, () => ({ tags: [] })), + + contractHandler( + 'post', + '/api/trips/:tripId/tags', + { request: tripTagCreateRequestSchema, response: tripTagResponseSchema }, + ({ body, params }) => ({ tag: buildTag({ ...body, trip_id: Number(params.tripId) }) }) + ), + contractHandler('get', '/api/categories', { response: categoryListResponseSchema }, () => ({ categories: [buildCategory(), buildCategory()], })), diff --git a/client/tests/unit/db/offlineDb.upgrade.test.ts b/client/tests/unit/db/offlineDb.upgrade.test.ts index b569ed482..f46b1b4a9 100644 --- a/client/tests/unit/db/offlineDb.upgrade.test.ts +++ b/client/tests/unit/db/offlineDb.upgrade.test.ts @@ -57,6 +57,7 @@ const HISTORY: Record = { 12: { tourStationVisits: '[assignment_id+station_key], trip_id, assignment_id' }, 13: { tourDrafts: 'tripId' }, 14: { routeCache: 'key, savedAt' }, + 15: { tripTags: 'tripId' }, }; const HISTORY_VERSIONS = Object.keys(HISTORY) @@ -138,6 +139,7 @@ function rowsAt(version: number): Record> { tourStationVisits: { assignment_id: 71, station_key: 'stop-01', status: 'visited', trip_id: 1 }, tourDrafts: { tripId: 1, draft: { payload: '{"version":11}', updated_at: '2026-10-22 09:00:00' } }, routeCache: { key: 'driving:km:11.5,48.1;11.6,48.2', route: { coordinates: [], legs: [] }, savedAt: 13 }, + tripTags: { tripId: 1, tags: [{ id: 91, trip_id: 1, name: 'Viewpoint', color: '#10b981' }] }, }; const tables = schemaAt(version); return Object.fromEntries(Object.entries(all).filter(([table]) => table in tables)); @@ -364,6 +366,28 @@ const UPGRADE_CASES: Record = { ]); }, }, + 15: { + intent: 'adds the tags a trip owns, one list per trip, and keeps the road routes kept on the device', + check: async (db) => { + expect((await db.routeCache.get('driving:km:11.5,48.1;11.6,48.2'))?.savedAt).toBe(13); + await db.table('tripTags').bulkPut([ + { tripId: 1, tags: [{ id: 91, name: 'Viewpoint' }] }, + { tripId: 2, tags: [] }, + ]); + // One row per trip: the list read again replaces the one kept before. + await db.table('tripTags').put({ + tripId: 1, + tags: [ + { id: 91, name: 'Lookout' }, + { id: 92, name: 'Zone' }, + ], + }); + expect(await db.tripTags.count()).toBe(2); + expect((await db.tripTags.get(1))?.tags.map((tag) => tag.name)).toEqual(['Lookout', 'Zone']); + // The user's personal tags stay in their own table, as they were. + expect(await db.tags.count()).toBe(1); + }, + }, }; describe('offlineDb upgrades', () => { diff --git a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx index b9aa4d6b3..deeb46e63 100644 --- a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx @@ -11,7 +11,7 @@ import { server } from '../../../helpers/msw/server' import { resetAllStores, seedStore } from '../../../helpers/store' import { fireEvent, render, screen, waitFor } from '../../../helpers/render' -// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-049, plus the 009b, 025b and 029b variants +// FE-MOB-PLEDIT-001 to FE-MOB-PLEDIT-050, plus the 009b, 025b and 029b variants // planner.t echoes the key, so every label/placeholder is asserted as its key. const CATEGORIES = [ @@ -730,4 +730,31 @@ describe('MPlaceEditSheet', () => { fireEvent.change(screen.getByPlaceholderText('places.formLng'), { target: { value: '139.79' } }) expect(screen.queryByText('places.noCoordinatesFormHint')).not.toBeInTheDocument() }) + + it('FE-MOB-PLEDIT-050: the tags ticked in the form are saved as the whole set, and an untouched form sends none', async () => { + seedStore(useTripStore, { + tripTags: [ + { id: 7, trip_id: 1, user_id: 1, name: 'Monument', color: '#6366f1' }, + { id: 8, trip_id: 1, user_id: 1, name: 'Zone', color: '#10b981' }, + ], + }) + const tagged = { ...EDITED, tags: [{ id: 8, name: 'Zone' }] } as unknown as Place + const { planner, unmount } = setup({ editingPlace: tagged }) + expect(screen.getByRole('group', { name: 'places.tags' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'true') + expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'false') + + fireEvent.click(screen.getByRole('button', { name: 'Monument' })) + expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true') + fireEvent.click(submit()) + await waitFor(() => expect(planner.handleSavePlace).toHaveBeenCalledTimes(1)) + expect(planner.handleSavePlace).toHaveBeenCalledWith(expect.objectContaining({ tags: [8, 7] })) + unmount() + + // Nothing ticked or unticked: the save names no tags, so it cannot undo one put on elsewhere. + const untouched = setup({ editingPlace: tagged }) + fireEvent.click(submit()) + await waitFor(() => expect(untouched.planner.handleSavePlace).toHaveBeenCalledTimes(1)) + expect(vi.mocked(untouched.planner.handleSavePlace).mock.calls[0][0]).not.toHaveProperty('tags') + }) }) diff --git a/client/tests/unit/remoteEventHandler/broadcastParity.test.ts b/client/tests/unit/remoteEventHandler/broadcastParity.test.ts index 552c07a3f..3b4aeb8bc 100644 --- a/client/tests/unit/remoteEventHandler/broadcastParity.test.ts +++ b/client/tests/unit/remoteEventHandler/broadcastParity.test.ts @@ -182,4 +182,20 @@ describe('remoteEventHandler > broadcast parity', () => { expect(reload).toHaveBeenCalledTimes(1); expect(reload).toHaveBeenCalledWith(5); }); + + it('FE-BCAST-027: a burst of tripTags:changed reads the tags of the open trip once, and none without a trip', () => { + vi.useFakeTimers(); + const load = vi.fn(async () => undefined); + useTripStore.setState({ loadTripTags: load }); + send({ type: 'tripTags:changed' }); + vi.advanceTimersByTime(300); + expect(load).not.toHaveBeenCalled(); + + useTripStore.setState({ trip: buildTrip({ id: 5 }) }); + for (let i = 0; i < 3; i++) send({ type: 'tripTags:changed', tripId: 5 }); + expect(load).not.toHaveBeenCalled(); + vi.advanceTimersByTime(300); + expect(load).toHaveBeenCalledTimes(1); + expect(load).toHaveBeenCalledWith(5); + }); }); diff --git a/client/tests/unit/sync/tripSyncManager.test.ts b/client/tests/unit/sync/tripSyncManager.test.ts index a24b20dbf..a6adc2f44 100644 --- a/client/tests/unit/sync/tripSyncManager.test.ts +++ b/client/tests/unit/sync/tripSyncManager.test.ts @@ -21,6 +21,7 @@ import { buildTodoItem, buildBudgetItem, buildReservation, + buildTag, buildTripFile, } from '../../helpers/factories'; @@ -293,6 +294,27 @@ describe('tripSyncManager.syncAll — bundle upsert', () => { expect(meta!.lastSyncedAt).toBeGreaterThanOrEqual(before); expect(meta!.lastSyncedAt).toBeLessThanOrEqual(after); }); + + it("keeps the trip's own tags for offline, and a trip whose tags cannot be read still syncs", async () => { + const tag = buildTag({ id: 7, trip_id: 302, name: 'Monument' }); + server.use( + http.get('/api/trips', () => + HttpResponse.json({ + trips: [buildTrip({ id: 302, end_date: dateOffset(5) }), buildTrip({ id: 303, end_date: dateOffset(5) })], + }), + ), + http.get('/api/trips/302/bundle', () => HttpResponse.json(makeBundle(302))), + http.get('/api/trips/303/bundle', () => HttpResponse.json(makeBundle(303))), + http.get('/api/trips/302/tags', () => HttpResponse.json({ tags: [tag] })), + http.get('/api/trips/303/tags', () => HttpResponse.json({ error: 'Trip not found' }, { status: 404 })), + ); + + expect(await tripSyncManager.syncAll()).toEqual({ status: 'done', trips: 2 }); + + expect((await offlineDb.tripTags.get(302))?.tags).toEqual([tag]); + expect(await offlineDb.tripTags.get(303)).toBeUndefined(); + expect(await offlineDb.syncMeta.get(303)).toBeDefined(); + }); }); describe('tripSyncManager.syncAll — tours', () => { diff --git a/server/scripts/query-api-baseline.json b/server/scripts/query-api-baseline.json index 2185f4108..d04ac5630 100644 --- a/server/scripts/query-api-baseline.json +++ b/server/scripts/query-api-baseline.json @@ -34,7 +34,7 @@ "src/db/repositories/RoadtripDayTracks.repository.ts": 1, "src/db/repositories/RoadtripPreferences.repository.ts": 1, "src/db/repositories/RoadtripVias.repository.ts": 6, - "src/db/repositories/Tags.repository.ts": 3, + "src/db/repositories/Tags.repository.ts": 2, "src/db/repositories/TodoItems.repository.ts": 2, "src/db/repositories/TripDocumentLinks.repository.ts": 5, "src/db/repositories/TripInviteTokens.repository.ts": 4, diff --git a/server/src/db/entities/Tags.entity.ts b/server/src/db/entities/Tags.entity.ts index c74fc3943..efadd8919 100644 --- a/server/src/db/entities/Tags.entity.ts +++ b/server/src/db/entities/Tags.entity.ts @@ -3,6 +3,7 @@ import { TagsRepository } from '../repositories/Tags.repository'; import { DbTimestampType } from '../types'; import { CollectionPlaces } from './CollectionPlaces.entity'; import { Places } from './Places.entity'; +import { Trips } from './Trips.entity'; import { Users } from './Users.entity'; export class Tags { @@ -13,6 +14,8 @@ export class Tags { name!: string; color?: string | null = '#10b981'; created_at?: string | null; + trip?: Ref | null; + trip_id?: number | null; collection_place_tags_inverse = new Collection(this); place_tags_inverse = new Collection(this); } @@ -27,6 +30,8 @@ export const TagsSchema = defineEntity({ name: p.text(), color: p.text().nullable(), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_tags_trip_id'), + trip_id: p.integer().nullable().persist(false).index('idx_tags_trip_id'), collection_place_tags_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_tags').hidden(), place_tags_inverse: () => p.manyToMany(Places).mappedBy('place_tags').hidden(), }, diff --git a/server/src/db/entities/Trips.entity.ts b/server/src/db/entities/Trips.entity.ts index a9d5d0b7a..b0f7d5be9 100644 --- a/server/src/db/entities/Trips.entity.ts +++ b/server/src/db/entities/Trips.entity.ts @@ -31,6 +31,7 @@ import { Reservations } from './Reservations.entity'; import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity'; import { RoadtripPreferences } from './RoadtripPreferences.entity'; import { ShareTokens } from './ShareTokens.entity'; +import { Tags } from './Tags.entity'; import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity'; import { TodoItems } from './TodoItems.entity'; import { TourDrafts } from './TourDrafts.entity'; @@ -93,6 +94,7 @@ export class Trips { roadtrip_day_boundaries_collection = new Collection(this); roadtrip_preferences_collection = new Collection(this); share_tokens_collection = new Collection(this); + tags_collection = new Collection(this); todo_category_assignees_collection = new Collection(this); todo_items_collection = new Collection(this); tour_drafts_collection = new Collection(this); @@ -171,6 +173,7 @@ export const TripsSchema = defineEntity({ roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('trip').hidden(), roadtrip_preferences_collection: () => p.oneToMany(RoadtripPreferences).mappedBy('trip').hidden(), share_tokens_collection: () => p.oneToMany(ShareTokens).mappedBy('trip').hidden(), + tags_collection: () => p.oneToMany(Tags).mappedBy('trip').hidden(), todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('trip').hidden(), todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('trip').hidden(), tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(), diff --git a/server/src/db/kysely/Tags.table.ts b/server/src/db/kysely/Tags.table.ts index a21c0f785..fa344b27c 100644 --- a/server/src/db/kysely/Tags.table.ts +++ b/server/src/db/kysely/Tags.table.ts @@ -8,4 +8,5 @@ export interface TagsTable { name: string; color: InsertOptional; created_at: InsertOptional; + trip_id: InsertOptional; } diff --git a/server/src/db/migrations/Migration20200101046440_a_trip_owns_its_tags.ts b/server/src/db/migrations/Migration20200101046440_a_trip_owns_its_tags.ts new file mode 100644 index 000000000..ec2016e98 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046440_a_trip_owns_its_tags.ts @@ -0,0 +1,21 @@ +import { addColumnIfMissing } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * A tag can belong to a trip. Every tag used to be one person's: a place of a + * shared trip carried labels only their owner could list, pick again or rename, + * and a co-traveller had to make their own tag of the same name. + * + * A tag with `trip_id` set is the trip's own. Every member reads it, anyone who + * may edit the trip's places may change it, and it goes when the trip goes. + * `user_id` keeps who created it. The column stays null on every existing row, + * which leaves those what they were: personal tags. + */ +export class Migration20200101046440_a_trip_owns_its_tags extends Migration { + override name = 'Migration20200101046440_a_trip_owns_its_tags'; + + override async up(): Promise { + await addColumnIfMissing(this, 'tags', 'trip_id', 'trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE'); + this.addSql('CREATE INDEX IF NOT EXISTS idx_tags_trip_id ON tags (trip_id)'); + } +} diff --git a/server/src/db/repositories/Tags.repository.ts b/server/src/db/repositories/Tags.repository.ts index 5484aab3d..777e558e5 100644 --- a/server/src/db/repositories/Tags.repository.ts +++ b/server/src/db/repositories/Tags.repository.ts @@ -4,13 +4,14 @@ import { findOwnedByUser, listForOwner } from './_shared/owned-lookup'; import { toRow, type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; -/** A `tags` row as the API emits it. */ +/** A `tags` row as the API emits it. `trip_id` is null on a personal tag and names the trip on one of its own. */ export interface TagRow { id: number; user_id: number; name: string; color: string | null; created_at: string | null; + trip_id: number | null; } const _tagRowKeys: AssertRowKeys = true; @@ -45,6 +46,9 @@ export interface TagForPlaceRow { */ type PlaceTagsKyselyDB = Pick; +/** `tags` alone, for the reads that name their columns. */ +type TagsKyselyDB = Pick; + /** * `place_tags` joined to `places` for TP46 (`trips.service.ts::copy`'s * place-tags read). The `trip_id` the caller passes stays `number | string` @@ -97,11 +101,18 @@ export class TagsRepository extends TrekRepository { * `id` and the `defaultRaw` `created_at` the same way a legacy * INSERT-then-reselect pair did. */ - async createTag(input: { user_id: number; name: string; color: string }): Promise { + async createTag(input: { + user_id: number; + name: string; + color: string | null; + /** The trip the tag is for; left out, it is `user_id`'s personal one. */ + trip_id?: number; + }): Promise { const id = await this.insert({ user: input.user_id, name: input.name, color: input.color, + ...(input.trip_id === undefined ? {} : { trip: input.trip_id }), }); const inserted = await this.findOne({ id }); if (!inserted) { @@ -193,22 +204,39 @@ export class TagsRepository extends TrekRepository { // --------------------------------------------------------------------------- /** - * PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id FROM tags WHERE - * id IN (${…}) ``, the ownership half of tag scoping: the caller - * (`tagsOnTrip`) intersects these rows' `user_id` against the trip's - * roster, and an id belonging to nobody on the roster drops silently. - * `$in` for the dynamic list (rule 17b). + * PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id, trip_id FROM tags + * WHERE id IN (${…}) ``, what decides whether a trip may put a tag on a + * place: the caller keeps a trip's own tag for that trip and a personal one + * (`trip_id` null) while its `user_id` is on the roster, and every other id + * drops silently. */ - async findByIds(ids: number[]): Promise<{ id: number; user_id: number }[]> { + async findByIds(ids: number[]): Promise<{ id: number; user_id: number; trip_id: number | null }[]> { if (ids.length === 0) return []; - // `t.user` (unaliased, not separately joined) resolves to the physical - // `user_id` column and comes back keyed as `user_id` on the raw driver - // row — `TripsRepository.findAccessible`'s `.select(['t.id', 't.user', - // 't.currency'])` establishes the same shape. - return this.qb('t') - .select(['t.id', 't.user']) - .where({ id: { $in: ids } }) - .execute<{ id: number; user_id: number }[]>('all', false); + return await this.kysely() + .selectFrom('tags') + .select(['id', 'user_id', 'trip_id']) + .where('id', 'in', ids) + .execute(); + } + + // --------------------------------------------------------------------------- + // A trip's own tags (`trip_id` set): one list for everybody on the trip. + // --------------------------------------------------------------------------- + + /** `SELECT * FROM tags WHERE trip_id = ? ORDER BY name ASC`: the trip's own tags, whoever created them. */ + async listByTrip(tripId: number): Promise { + const tags = await this.find({ trip: tripId }, { orderBy: { name: 'asc' } }); + return tags.map((tag) => toRow(tag) as TagRow); + } + + /** + * `SELECT * FROM tags WHERE id = ? AND trip_id = ?`: one tag of the trip, or + * null for a personal tag and for another trip's, so a write scoped to a trip + * cannot reach either. + */ + async findByIdAndTrip(id: number, tripId: number): Promise { + const tag = await this.findOne({ id, trip: tripId }); + return tag ? (toRow(tag) as TagRow) : null; } // --------------------------------------------------------------------------- diff --git a/server/src/nest/collections/collections.service.ts b/server/src/nest/collections/collections.service.ts index 27911e796..521460efe 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -658,18 +658,18 @@ export class CollectionsService { // ------------------------------------------------------------------------- /** - * A tag has no list of its own, only a `user_id`, so "belongs here" resolves - * through the people on the list — the same shape places.service uses against - * a trip roster. Off-list tag ids drop silently rather than being stored and - * read straight back out: the tag read-back ships `tags.user_id`, so an - * unfiltered id answers who owns a tag the caller cannot otherwise see. + * A personal tag has no list of its own, only a `user_id`, so "belongs here" resolves + * through the people on the list — the same shape places.service uses against a trip + * roster. Every other id drops silently, a trip's own tag included (it labels that + * trip's places only), rather than being stored and read straight back out: the + * read-back ships `tags.user_id`, so it answers who owns a tag the caller cannot see. */ private async attachTags(collectionPlaceId: number, tagIds: number[] | undefined): Promise { if (!tagIds || tagIds.length === 0) return; const unique = [...new Set(tagIds)]; const eligible = await this.collectionMemberIds(await this.collectionIdOfPlace(collectionPlaceId)); const owned = await this.tags.findByIds(unique); - const eligibleTagIds = owned.filter(t => eligible.has(t.user_id)).map(t => t.id); + const eligibleTagIds = owned.filter(t => t.trip_id === null && eligible.has(t.user_id)).map(t => t.id); await this.collectionPlaces.attachTags(collectionPlaceId, eligibleTagIds); } diff --git a/server/src/nest/places/places.mcp.ts b/server/src/nest/places/places.mcp.ts index 543d7e214..4bc0d0ed0 100644 --- a/server/src/nest/places/places.mcp.ts +++ b/server/src/nest/places/places.mcp.ts @@ -11,6 +11,7 @@ import { placeImportListRequestSchema, placeEmailField, placeOpeningHoursSchema, + placeTagIdsSchema, placeWebsiteSchema, roadtripStopTypeSchema, type PlaceOpeningHours, @@ -100,23 +101,24 @@ export class PlacesMcp { price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'), currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'), stop_type: roadtripStopTypeSchema.optional().describe('Marks the place as a stop on a drive rather than a destination: fuel, charging, rest_area, campsite, restaurant, sights or hotel. A service stop is left out of the stop count for the day, so a day with a charger between four places still reads as four stops. Leave unset for an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'), + tags: placeTagIdsSchema.optional().describe('Ids of the tags to put on the place: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Any other id is ignored'), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'places', mode: 'write' }, }) async createPlace( - { tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours, image_url, price, currency, stop_type }: { + { tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours, image_url, price, currency, stop_type, tags }: { tripId: number; name: string; description?: string; lat?: number; lng?: number; address?: string; category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string; notes?: string; website?: string; phone?: string; email?: string | null; opening_hours?: PlaceOpeningHours | null; image_url?: string; price?: number; currency?: string; - stop_type?: RoadtripStopType; + stop_type?: RoadtripStopType; tags?: number[]; }, ctx: McpContext, ) { if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess(); if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied(); - const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type }); + const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type, tags }); this.guards.safeBroadcast(tripId, 'place:created', { place }); await this.origins.record(place.id, null, AGENT); // The journey hook the REST route and the plugin RPC run after the same write. @@ -150,17 +152,18 @@ export class PlacesMcp { price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'), currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'), stop_type: roadtripStopTypeSchema.optional().describe('Marks the place as a stop on a drive rather than a destination: fuel, charging, rest_area, campsite, restaurant, sights or hotel. A service stop is left out of the stop count for the day, so a day with a charger between four places still reads as four stops. Leave unset for an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'), + tags: placeTagIdsSchema.optional().describe('Ids of the tags to put on the place: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Any other id is ignored'), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'places', mode: 'write' }, }) async createAndAssignPlace( - { tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, place_notes, website, phone, email, opening_hours, image_url, assignment_notes, price, currency, stop_type }: { + { tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, place_notes, website, phone, email, opening_hours, image_url, assignment_notes, price, currency, stop_type, tags }: { tripId: number; dayId: number; name: string; description?: string; lat?: number; lng?: number; address?: string; category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string; place_notes?: string; website?: string; phone?: string; email?: string | null; opening_hours?: PlaceOpeningHours | null; image_url?: string; assignment_notes?: string; - price?: number; currency?: string; stop_type?: RoadtripStopType; + price?: number; currency?: string; stop_type?: RoadtripStopType; tags?: number[]; }, ctx: McpContext, ) { @@ -169,7 +172,7 @@ export class PlacesMcp { if (!(await this.assignments.dayExists(dayId, tripId))) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true }; try { const result = await this.uow.transactional(async () => { - const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes: place_notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type }); + const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes: place_notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type, tags }); const assignment = await this.assignments.createAssignment(dayId, place.id, assignment_notes ?? null); return { place, assignment }; }); @@ -213,12 +216,13 @@ export class PlacesMcp { amap_poi_id: z.string().optional().describe('Amap (高德地图) POI ID, amap:-prefixed (e.g. "amap:B000A83M61")'), stop_type: roadtripStopTypeSchema.nullable().optional().describe('What kind of stop on a drive this is: fuel, charging, rest_area, campsite, restaurant, sights or hotel. Pass null to turn a service stop back into an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'), fill_percent: z.number().int().min(1).max(100).nullable().optional().describe('How full THIS stop fills the tank, 1-100. A motorway rapid charger is worth about 80 %, the one at the hotel 100 %. Pass null to follow whatever the traveller set as their default fill.'), + tags: placeTagIdsSchema.optional().describe('The whole set of tag ids the place should carry afterwards: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Send the ids it keeps along with the new ones, and an empty list to clear them. Leave out to keep its tags as they are'), }, annotations: TOOL_ANNOTATIONS_WRITE, access: { group: 'places', mode: 'write' }, }) async updatePlace( - { tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours, image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent }: { + { tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours, image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags }: { tripId: number; placeId: number; name?: string; description?: string; lat?: number; lng?: number; address?: string; category_id?: number; price?: number; currency?: string; place_time?: string | null; end_time?: string | null; duration_minutes?: number | null; notes?: string; website?: string; phone?: string; @@ -226,14 +230,14 @@ export class PlacesMcp { image_url?: string | null; transport_mode?: 'walking' | 'driving' | 'cycling' | 'transit' | 'flight'; osm_id?: string; google_place_id?: string; google_ftid?: string; amap_poi_id?: string; stop_type?: RoadtripStopType | null; - fill_percent?: number | null; + fill_percent?: number | null; tags?: number[]; }, ctx: McpContext, ) { if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess(); if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied(); const before = await this.origins.valuesBefore(placeId); - const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent }); + const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags }); // No base version is sent, so the update never answers a conflict; the guard only narrows the type. if (!place || isUpdateConflict(place)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true }; this.guards.safeBroadcast(tripId, 'place:updated', { place }); diff --git a/server/src/nest/places/places.service.ts b/server/src/nest/places/places.service.ts index e0673b6ac..c70460ad4 100644 --- a/server/src/nest/places/places.service.ts +++ b/server/src/nest/places/places.service.ts @@ -210,16 +210,16 @@ export class PlacesService { } /** - * The subset of `tagIds` that someone on this trip owns. A tag has no trip of - * its own, only a `user_id`, so "belongs to this trip" resolves through the - * roster — which keeps the shared case working: a member tags a place, another - * member re-saves it and sends the id back, and the tag survives because its - * owner is still on the trip. Scoping to the caller instead would quietly strip - * a co-traveller's tag on every foreign edit. + * The subset of `tagIds` this trip may put on a place: the tags it owns, and the + * personal tags of anybody on its roster. A personal tag has no trip, only a + * `user_id`, so it resolves through the roster, which keeps the shared case + * working: a member tags a place, another re-saves it and sends the id back, and + * the tag survives because its owner is still on the trip. Scoping to the caller + * instead would quietly strip a co-traveller's tag on every foreign edit. * - * Off-roster ids drop silently. The place body is an open record, so an id can - * arrive from an older client that had no business knowing it existed, and the - * read-back join hands `tags.user_id` straight to the caller. + * Every other id drops silently, another trip's tag included. The place body is an + * open record, so an id can arrive from a client that had no business knowing it + * existed, and the read-back join hands the tag straight to the caller. */ private async tagsOnTrip(tripId: string | number, tagIds: number[]): Promise { const unique = [...new Set(tagIds)]; @@ -229,9 +229,9 @@ export class PlacesService { // precedent: each domain converts its own `DatabaseService`-delegated // callers as it lands. const roster = await this.tripMembersRepo.rosterUserIds(tripId); - // PL2 — `SELECT id, user_id FROM tags WHERE id IN (${…})`. - const owned = await this.tagsRepo.findByIds(unique); - return owned.filter(t => roster.has(t.user_id)).map(t => t.id); + // PL2 — `SELECT id, user_id, trip_id FROM tags WHERE id IN (${…})`. + const rows = await this.tagsRepo.findByIds(unique); + return rows.filter(t => (t.trip_id === null ? roster.has(t.user_id) : t.trip_id === Number(tripId))).map(t => t.id); } broadcast(tripId: string, event: E, payload: TrekWsPayload, socketId: string | undefined): void { diff --git a/server/src/nest/plugins/protocol/output-contract.ts b/server/src/nest/plugins/protocol/output-contract.ts index c4d577ec6..317e56635 100644 --- a/server/src/nest/plugins/protocol/output-contract.ts +++ b/server/src/nest/plugins/protocol/output-contract.ts @@ -325,7 +325,9 @@ export const PLUGIN_ENTITY_CONTRACT = { tag: { table: 'tags', columns: ['id', 'user_id', 'name', 'color', 'created_at'], - withheld: [], + // Which trip a tag belongs to is the host's own scoping: tags.* answers the acting + // user's personal tags, and a trip's own reach a plugin on that trip's places. + withheld: ['trip_id'], wholeRow: true, derived: [], }, diff --git a/server/src/nest/tags/tags.dto.ts b/server/src/nest/tags/tags.dto.ts index aefbb4d89..df0858c14 100644 --- a/server/src/nest/tags/tags.dto.ts +++ b/server/src/nest/tags/tags.dto.ts @@ -1,3 +1,5 @@ +import { tripTagCreateRequestSchema, tripTagUpdateRequestSchema } from '@trek/shared'; + import { createZodDto } from 'nestjs-zod'; import { z } from 'zod'; @@ -23,3 +25,10 @@ const tagBody = z.looseObject({ name: z.unknown().optional(), color: z.unknown() export class TagCreateDto extends createZodDto(tagBody) {} export class TagUpdateDto extends createZodDto(tagBody) {} + +/** + * The trip tag routes are new, so they take the shared contracts as written: the + * pipe trims the name, refuses an empty one and a colour that is not hex. + */ +export class TripTagCreateDto extends createZodDto(tripTagCreateRequestSchema) {} +export class TripTagUpdateDto extends createZodDto(tripTagUpdateRequestSchema) {} diff --git a/server/src/nest/tags/tags.module.ts b/server/src/nest/tags/tags.module.ts index 439023120..f34e636b7 100644 --- a/server/src/nest/tags/tags.module.ts +++ b/server/src/nest/tags/tags.module.ts @@ -1,10 +1,16 @@ import { Tags } from '../../db/entities/Tags.entity'; +import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; +import { PermissionsModule } from '../permissions/permissions.module'; import { RealtimeModule } from '../realtime/realtime.module'; +import { TripMembershipModule } from '../trip-membership/trip-membership.module'; import { TagWritesService } from './tag-writes.service'; import { TagsController } from './tags.controller'; import { TagsMcp } from './tags.mcp'; import { TagsRpc } from './tags.rpc'; import { TagsService } from './tags.service'; +import { TripTagsController } from './trip-tags.controller'; +import { TripTagsMcp } from './trip-tags.mcp'; +import { TripTagsService } from './trip-tags.service'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { Module } from '@nestjs/common'; @@ -15,15 +21,26 @@ import { Module } from '@nestjs/common'; * @InjectRepository(Tags) in the service — the forFeature + * @InjectRepository wiring pattern every domain copies (settings.module.ts's * precedent comment). + * + * Two surfaces over the one table: a user's personal tags (TagsController, + * TagsMcp, TagsRpc) and the tags a trip owns (TripTagsController, TripTagsMcp), + * which take the trip's access and `place_edit` instead of an owner. */ @Module({ - // RealtimeModule for TagWritesService, which tells a user's other tabs that their tags changed. - imports: [RealtimeModule, MikroOrmModule.forFeature([Tags])], - controllers: [TagsController], + // RealtimeModule for the two write services, which tell the other tabs that the tags changed; + // TripMembershipModule and PermissionsModule for the trip gate, McpSharedModule for the tools' writer. + imports: [ + RealtimeModule, + TripMembershipModule, + PermissionsModule, + McpSharedModule, + MikroOrmModule.forFeature([Tags]), + ], + controllers: [TagsController, TripTagsController], // TagsRpc must stay in providers: the plugin RPC registry discovers marked // PROVIDERS only, and a missing entry here would leave tags.* answering // PERMISSION_DENIED with no other symptom. - providers: [TagsService, TagWritesService, TagsMcp, TagsRpc], + providers: [TagsService, TagWritesService, TripTagsService, TagsMcp, TripTagsMcp, TagsRpc], // For in-container consumers (TagsRpc). exports: [TagsService], }) diff --git a/server/src/nest/tags/tags.service.ts b/server/src/nest/tags/tags.service.ts index e08d985a5..e2b6cbd41 100644 --- a/server/src/nest/tags/tags.service.ts +++ b/server/src/nest/tags/tags.service.ts @@ -12,6 +12,11 @@ import type { Tag } from '@trek/shared'; * here, exactly as they did over raw SQL, while the SQL itself lives in the * repository. All consumers are in-container — the plugin RPC surface * injects this class into TagsRpc. + * + * This is the personal surface: a user's own tags. A tag that belongs to a trip + * (`trip_id` set) names its creator in `user_id` as well, but it is the trip's, + * so `list` leaves it out and `getByIdAndUser` does not find it; TripTagsService + * reads and writes those under the trip's own rights. */ @Injectable() export class TagsService { @@ -24,7 +29,8 @@ export class TagsService { // either) — these casts keep that same trust boundary at the service layer // instead of inside a raw-SQL call. async list(userId: number): Promise { - return (await this.tags.listByUser(userId)) as unknown as Tag[]; + const own = (await this.tags.listByUser(userId)).filter((tag) => tag.trip_id === null); + return own as unknown as Tag[]; } async getByIdAndUser(id: string | number, userId: number): Promise { @@ -39,7 +45,8 @@ export class TagsService { const rowId = toRowId(id); if (rowId === null) return undefined; const tag = await this.tags.findByIdAndUser(rowId, userId); - return (tag as unknown as Tag | null) ?? undefined; + if (!tag || tag.trip_id !== null) return undefined; + return tag as unknown as Tag; } async create(userId: number, name: string, color?: string): Promise { diff --git a/server/src/nest/tags/trip-tags.controller.ts b/server/src/nest/tags/trip-tags.controller.ts new file mode 100644 index 000000000..b1ec0368b --- /dev/null +++ b/server/src/nest/tags/trip-tags.controller.ts @@ -0,0 +1,71 @@ +import type { User } from '../../types'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard'; +import { TripTagCreateDto, TripTagUpdateDto } from './tags.dto'; +import { TripTagsService } from './trip-tags.service'; +import { Body, Controller, Delete, Get, Headers, Param, Post, Put, UseGuards } from '@nestjs/common'; +import { successResponseSchema, tripTagListResponseSchema, tripTagResponseSchema } from '@trek/shared'; + +/** + * /api/trips/:tripId/tags — the tags a trip owns, shared by everybody on it. + * + * Reading takes trip access (404 otherwise); the writes add the `place_edit` + * permission (403), the one a tag is put on a place with. Bodies validate against + * the @trek/shared trip tag contracts through the Zod pipe. Create answers 201 with + * the tag of that name, which is the trip's existing one when it has it already; + * a rename onto another tag's name is a 409. Every write tells the trip's other + * sockets `tripTags:changed`. + */ +@Controller('api/trips/:tripId/tags') +@UseGuards(JwtAuthGuard, TripAccessGuard) +export class TripTagsController { + constructor(private readonly tripTags: TripTagsService) {} + + @Get() + @ResponseContract(tripTagListResponseSchema) + async list(@CurrentUser() user: User, @Param('tripId') tripId: string) { + return { tags: await this.tripTags.list(tripId, user.id) }; + } + + @RequirePermission('place_edit') + @Post() + @ResponseContract(tripTagResponseSchema) + async create( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Body() body: TripTagCreateDto, + @Headers('x-socket-id') socketId?: string, + ) { + const writer = this.tripTags.restWriter(tripId, user, socketId); + return { tag: await this.tripTags.create(tripId, { name: body.name, color: body.color }, writer) }; + } + + @RequirePermission('place_edit') + @Put(':id') + @ResponseContract(tripTagResponseSchema) + async update( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: TripTagUpdateDto, + @Headers('x-socket-id') socketId?: string, + ) { + const writer = this.tripTags.restWriter(tripId, user, socketId); + return { tag: await this.tripTags.update(tripId, id, { name: body.name, color: body.color }, writer) }; + } + + @RequirePermission('place_edit') + @Delete(':id') + @ResponseContract(successResponseSchema) + async remove( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + await this.tripTags.remove(tripId, id, this.tripTags.restWriter(tripId, user, socketId)); + return { success: true }; + } +} diff --git a/server/src/nest/tags/trip-tags.mcp.ts b/server/src/nest/tags/trip-tags.mcp.ts new file mode 100644 index 000000000..9ed42a49e --- /dev/null +++ b/server/src/nest/tags/trip-tags.mcp.ts @@ -0,0 +1,97 @@ +import { + McpController, + Tool, + type McpContext, + TOOL_ANNOTATIONS_DELETE, + TOOL_ANNOTATIONS_READONLY, + TOOL_ANNOTATIONS_WRITE, + ok, +} from '../../nest-mcp'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { TripTagsService } from './trip-tags.service'; +import { hexColorSchema, idSchema, tripTagNameSchema } from '@trek/shared'; + +/** + * The tags a trip owns, as MCP tools: adapters over TripTagsService, the same + * use cases the /api/trips/:tripId/tags routes run. The service holds the trip + * gate and sends `tripTags:changed`, so a refusal reads the same on both + * surfaces and a tag an assistant adds shows up for every member at once. + * + * In the `places` scope group like the personal tag tools, since a tag only + * ever labels places. The ids go into `tags` on create_place and update_place. + */ +@McpController() +export class TripTagsMcp { + constructor( + private readonly tripTags: TripTagsService, + private readonly guards: McpToolGuardsService, + ) {} + + @Tool({ + name: 'list_trip_tags', + description: + 'List the tags a trip owns: the labels every member of the trip sees, filters its places by and can put on them. Pass their ids as `tags` to create_place, create_and_assign_place and update_place. list_tags answers the personal tags of the current user instead.', + inputSchema: { + tripId: idSchema, + }, + annotations: TOOL_ANNOTATIONS_READONLY, + access: { group: 'places', mode: 'read' }, + }) + async listTripTags({ tripId }: { tripId: number }, ctx: McpContext) { + return ok({ tags: await this.tripTags.list(tripId, ctx.userId) }); + } + + @Tool({ + name: 'create_trip_tag', + description: + "Add a tag to a trip, shared by everybody on it. A name stands once per trip, whatever its case: asking for a name the trip already has answers that tag instead of making a second one, so call this freely before tagging places. Needs the right to edit the trip's places.", + inputSchema: { + tripId: idSchema, + name: tripTagNameSchema, + color: hexColorSchema.optional().describe('Hex color string e.g. #6366f1'), + }, + annotations: TOOL_ANNOTATIONS_WRITE, + access: { group: 'places', mode: 'write' }, + }) + async createTripTag({ tripId, name, color }: { tripId: number; name: string; color?: string }, ctx: McpContext) { + const tag = await this.tripTags.create(tripId, { name, color }, await this.guards.tripWriter(tripId, ctx.userId)); + return ok({ tag }); + } + + @Tool({ + name: 'update_trip_tag', + description: + "Rename or recolour a tag of a trip. Every place that carries it shows the change, for every member. A name another tag of the trip already has is refused. Needs the right to edit the trip's places.", + inputSchema: { + tripId: idSchema, + tagId: idSchema, + name: tripTagNameSchema.optional(), + color: hexColorSchema.optional().describe('Hex color string e.g. #6366f1'), + }, + annotations: TOOL_ANNOTATIONS_WRITE, + access: { group: 'places', mode: 'write' }, + }) + async updateTripTag( + { tripId, tagId, name, color }: { tripId: number; tagId: number; name?: string; color?: string }, + ctx: McpContext, + ) { + const writer = await this.guards.tripWriter(tripId, ctx.userId); + return ok({ tag: await this.tripTags.update(tripId, tagId, { name, color }, writer) }); + } + + @Tool({ + name: 'delete_trip_tag', + description: + "Delete a tag of a trip. It comes off every place of the trip that carried it, for every member; the places themselves stay. Needs the right to edit the trip's places.", + inputSchema: { + tripId: idSchema, + tagId: idSchema, + }, + annotations: TOOL_ANNOTATIONS_DELETE, + access: { group: 'places', mode: 'write' }, + }) + async deleteTripTag({ tripId, tagId }: { tripId: number; tagId: number }, ctx: McpContext) { + await this.tripTags.remove(tripId, tagId, await this.guards.tripWriter(tripId, ctx.userId)); + return ok({ success: true }); + } +} diff --git a/server/src/nest/tags/trip-tags.service.ts b/server/src/nest/tags/trip-tags.service.ts new file mode 100644 index 000000000..d9f4be09a --- /dev/null +++ b/server/src/nest/tags/trip-tags.service.ts @@ -0,0 +1,118 @@ +import { Tags } from '../../db/entities/Tags.entity'; +import type { TagRow, TagsRepository } from '../../db/repositories/Tags.repository'; +import type { User } from '../../types'; +import { conflict, DomainError } from '../common/domain-error'; +import { toRowId } from '../common/row-id'; +import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer'; +import { UnitOfWork } from '../database/unit-of-work'; +import { PermissionsService } from '../permissions/permissions.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { TripAccessService } from '../trip-membership/trip-access.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { Tag } from '@trek/shared'; + +/** The colour a tag gets when its creator names none, the same as a personal tag's. */ +const DEFAULT_TAG_COLOR = '#10b981'; + +const tagNotFound = () => new DomainError(404, 'Tag not found', { mcpMessage: 'Tag not found.' }); +const nameTaken = () => conflict('A tag with this name already exists'); + +/** Two names are one tag when they read the same, whatever their case. */ +const sameName = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase(); + +/** A stored row as the contract types it; the columns the contract narrows are always set on a trip's tag. */ +const asTag = (row: TagRow): Tag => row as unknown as Tag; + +/** + * A trip's own tags, one method per use case, for REST and MCP alike. + * + * A tag of a trip belongs to the trip, not to the member who created it: every + * member reads the same list, and anyone who may edit the trip's places + * (`place_edit`, the right a tag is put on a place with) may add to it, rename + * and delete. Each write holds the trip gate, its checks, the write and the + * `tripTags:changed` it sends, so both surfaces tell the trip the same thing. + * + * A name stands once per trip, whatever its case: asking for one the trip has + * answers that tag, and renaming onto another tag's name is refused. Two members + * tagging the same idea end up on one tag, which is what a shared filter needs. + */ +@Injectable() +export class TripTagsService { + constructor( + @InjectRepository(Tags) private readonly tags: TagsRepository, + private readonly access: TripAccessService, + private readonly permissions: PermissionsService, + private readonly realtime: RealtimeService, + private readonly uow: UnitOfWork, + ) {} + + /** The REST caller of a tag write: its event skips the socket that made the request. */ + restWriter(tripId: string, user: User, socketId: string | undefined): TripWriter { + return restTripWriter(this.realtime, tripId, user, socketId); + } + + /** The trip's tags by name, for anybody who can see the trip. */ + async list(tripId: string | number, userId: number): Promise { + const tid = toRowId(tripId); + if (tid === null || !(await this.access.findAccessible(tid, userId))) throw tripNotFound(); + return (await this.tags.listByTrip(tid)).map(asTag); + } + + /** The tag of that name on the trip, created when the trip has none yet. */ + async create(tripId: string | number, input: { name: string; color?: string }, writer: TripWriter): Promise { + const tid = await this.gate(tripId, writer); + const name = input.name.trim(); + const { tag, created } = await this.uow.transactional(async () => { + const existing = (await this.tags.listByTrip(tid)).find((row) => sameName(row.name, name)); + if (existing) return { tag: existing, created: false }; + const color = input.color ?? DEFAULT_TAG_COLOR; + return { tag: await this.tags.createTag({ user_id: writer.userId, trip_id: tid, name, color }), created: true }; + }); + if (created) writer.events.emit('tripTags:changed', {}); + return asTag(tag); + } + + /** Rename or recolour a tag of the trip; a field that is left out keeps its value. */ + async update( + tripId: string | number, + tagId: string | number, + changes: { name?: string; color?: string }, + writer: TripWriter, + ): Promise { + const tid = await this.gate(tripId, writer); + const id = toRowId(tagId); + const name = changes.name?.trim(); + const tag = await this.uow.transactional(async () => { + const onTrip = await this.tags.listByTrip(tid); + const current = onTrip.find((row) => row.id === id); + if (!current) throw tagNotFound(); + if (name && onTrip.some((row) => row.id !== current.id && sameName(row.name, name))) throw nameTaken(); + const patched = await this.tags.patch(current.id, { + ...(name ? { name } : {}), + ...(changes.color ? { color: changes.color } : {}), + }); + // Read in this transaction a statement ago, so the patch finds the row. + return patched as TagRow; + }); + writer.events.emit('tripTags:changed', {}); + return asTag(tag); + } + + /** Delete a tag of the trip; it comes off every place that carried it. */ + async remove(tripId: string | number, tagId: string | number, writer: TripWriter): Promise { + const tid = await this.gate(tripId, writer); + const id = toRowId(tagId); + if (id === null || !(await this.tags.findByIdAndTrip(id, tid))) throw tagNotFound(); + await this.tags.remove(id); + writer.events.emit('tripTags:changed', {}); + } + + /** The gate of every write: the writer sees the trip (404) and may edit its places (403). */ + private async gate(tripId: string | number, writer: TripWriter): Promise { + const tid = toRowId(tripId); + if (tid === null) throw tripNotFound(); + await requireTripWrite({ access: this.access, permissions: this.permissions }, 'place_edit', tid, writer); + return tid; + } +} diff --git a/server/src/nest/trips/trips.service.ts b/server/src/nest/trips/trips.service.ts index 2b020298a..b1dfc814f 100644 --- a/server/src/nest/trips/trips.service.ts +++ b/server/src/nest/trips/trips.service.ts @@ -48,6 +48,7 @@ import { StorageReleaseService } from '../storage/storage-release.service'; import { SettingsService } from '../settings/settings.service'; import { escapeLikePattern } from '../places/places.helpers'; import { NotFoundError, ValidationError } from '../common/domain-errors'; +import { inOrder } from '../common/in-order'; import { UnitOfWork } from '../database/unit-of-work'; import { legacyBoundIntegerText } from '../common/row-id'; import { appClock } from '../common/timezoneService'; @@ -712,10 +713,15 @@ export class TripsService { if (newDayId && newPlaceId) await this.roadtripDayTracksRepo.upsertTrack(newDayId, newPlaceId, t.stray_km); // TP45 } + // The trip's own tags are written again as the copy's; a personal tag stays its owner's one row. + const tagMap = new Map(); + await inOrder(await this.tagsRepo.listByTrip(Number(sourceTripId)), async ({ id, name, color }) => { + tagMap.set(id, (await this.tagsRepo.createTag({ user_id: newOwnerId, trip_id: newTripId, name, color })).id); + }); const oldTags = await this.tagsRepo.listPlaceTagsForTrip(sourceTripId); // TP46 for (const t of oldTags) { const newPlaceId = placeMap.get(t.place_id); - if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [t.tag_id]); // TP47 + if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [tagMap.get(t.tag_id) ?? t.tag_id]); // TP47 } // The `tours` facet goes first: the import record, obstacle decisions, packing link and waypoints need it. diff --git a/server/tests/e2e/trip-tags-mcp.e2e.test.ts b/server/tests/e2e/trip-tags-mcp.e2e.test.ts new file mode 100644 index 000000000..32b5bc44f --- /dev/null +++ b/server/tests/e2e/trip-tags-mcp.e2e.test.ts @@ -0,0 +1,225 @@ +/** + * Trip tags e2e for an MCP client: the four trip tag tools and the `tags` the + * place tools take, called through a real MCP session on the whole app + * (buildApp, the real registry with its scopes and error mapper, the real + * services and a migrated temp SQLite), the way an assistant tags a trip. + */ +import { buildApp } from '../../src/bootstrap'; +import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { PermissionsService } from '../../src/nest/permissions/permissions.service'; +import { makePlace, makeTag, tagPlace } from '../helpers/factories/places'; +import { addTripMember, makeDay, makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { MikroORM } from '@mikro-orm/core'; +import { Client } from '@modelcontextprotocol/sdk/client/index'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory'; +import type { INestApplication } from '@nestjs/common'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +let app: INestApplication; +let orm: MikroORM; + +interface TagAnswer { + id: number; + name: string; + color: string; + trip_id?: number | null; + user_id?: number; +} +interface Answer { + tags?: TagAnswer[]; + tag?: TagAnswer; + place?: { id: number; tags: TagAnswer[] }; + success?: boolean; +} + +const NO_ACCESS = 'Trip not found or access denied.'; + +/** The tools `userId` is offered with `scopes`, and one call of `tool`: its JSON, or the text of its error. */ +async function call(userId: number, tool: string, args: Record, scopes: string[] | null = null) { + const server = createLocalMcpServer('TREK trip tags e2e'); + const around = (_info: unknown, run: () => unknown): unknown => withRequestContext(orm, run); + await withRequestContext(orm, () => + app + .get(McpRegistryService) + .attach(server, { userId, scopes, isStaticToken: false }, { include: (kind) => kind === 'tool', around }), + ); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'trip-tags-e2e', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + try { + const offered = (await client.listTools()).tools.map((entry) => entry.name); + if (!offered.includes(tool)) return { offered, answer: null, error: null }; + const result = await client.callTool({ name: tool, arguments: args }); + const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : []; + const text = content[0]?.text ?? ''; + if (result.isError === true) return { offered, answer: null, error: text }; + return { offered, answer: JSON.parse(text) as Answer, error: null }; + } finally { + await client.close(); + await server.close(); + } +} + +const names = (answer: Answer | null) => (answer?.tags ?? []).map((tag) => tag.name); +const tagIds = (answer: Answer | null) => (answer?.place?.tags ?? []).map((tag) => tag.id).sort((a, b) => a - b); + +/** A trip of `owner` with `member` on it; `stranger` is on neither and has a trip of their own. */ +async function scene() { + const { user: owner } = await makeUser(orm); + const { user: member } = await makeUser(orm); + const { user: stranger } = await makeUser(orm); + const trip = await makeTrip(orm, owner.id, { title: 'Lisbon' }); + await addTripMember(orm, trip.id, member.id, owner.id); + const elsewhere = await makeTrip(orm, stranger.id, { title: 'Porto' }); + return { owner, member, stranger, trip, elsewhere }; +} + +beforeAll(async () => { + app = await buildApp(); + orm = app.get(MikroORM); +}, 60_000); + +afterAll(async () => { + await app?.close(); +}); + +describe('the tags of a trip over MCP', () => { + it('TRIPTAG-MCP-001: a member adds a tag every member then lists, renames and deletes', async () => { + const s = await scene(); + const tripId = s.trip.id; + + const created = await call(s.member.id, 'create_trip_tag', { tripId, name: ' Monument ', color: '#ff0000' }); + expect(created.error).toBeNull(); + expect(created.answer?.tag).toMatchObject({ name: 'Monument', color: '#ff0000', trip_id: tripId }); + const tagId = created.answer?.tag?.id ?? 0; + + // The same name again, in another case and by somebody else, is that tag. + const again = await call(s.owner.id, 'create_trip_tag', { tripId, name: 'MONUMENT' }); + expect(again.answer?.tag).toMatchObject({ id: tagId, name: 'Monument', color: '#ff0000' }); + expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument']); + + const renamed = await call(s.owner.id, 'update_trip_tag', { tripId, tagId, name: 'Landmark' }); + expect(renamed.answer?.tag).toMatchObject({ id: tagId, name: 'Landmark', color: '#ff0000' }); + expect(names((await call(s.member.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Landmark']); + + const deleted = await call(s.member.id, 'delete_trip_tag', { tripId, tagId }); + expect(deleted.answer).toEqual({ success: true }); + expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual([]); + }); + + it('TRIPTAG-MCP-002: lists the trip’s tags only, never a personal one or another trip’s', async () => { + const s = await scene(); + await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' }); + await makeTag(orm, s.owner.id, { name: 'personal' }); + await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' }); + + expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual(['Zone']); + // And the personal list keeps to itself. + expect(names((await call(s.owner.id, 'list_tags', {})).answer)).toEqual(['personal']); + }); + + it('TRIPTAG-MCP-003: refuses a trip the caller is not on, a tag that is not the trip’s and a taken name', async () => { + const s = await scene(); + const tripId = s.trip.id; + const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' }); + const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' }); + const personal = await makeTag(orm, s.owner.id, { name: 'personal' }); + + expect((await call(s.stranger.id, 'list_trip_tags', { tripId })).error).toBe(NO_ACCESS); + expect((await call(s.stranger.id, 'create_trip_tag', { tripId, name: 'Mine' })).error).toBe(NO_ACCESS); + expect((await call(s.stranger.id, 'update_trip_tag', { tripId, tagId: zone.id, name: 'Mine' })).error).toBe( + NO_ACCESS, + ); + expect((await call(s.stranger.id, 'delete_trip_tag', { tripId, tagId: zone.id })).error).toBe(NO_ACCESS); + + expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: personal.id, name: 'x' })).error).toBe( + 'Tag not found.', + ); + expect((await call(s.owner.id, 'delete_trip_tag', { tripId, tagId: personal.id })).error).toBe('Tag not found.'); + expect((await call(s.owner.id, 'update_trip_tag', { tripId, tagId: monument.id, name: 'zone' })).error).toBe( + 'A tag with this name already exists', + ); + expect(names((await call(s.owner.id, 'list_trip_tags', { tripId })).answer)).toEqual(['Monument', 'Zone']); + }); + + it('TRIPTAG-MCP-004: a write needs the right to edit the trip’s places', async () => { + const s = await scene(); + const check = vi.spyOn(app.get(PermissionsService), 'checkPermission').mockResolvedValue(false); + try { + const refused = await call(s.member.id, 'create_trip_tag', { tripId: s.trip.id, name: 'Zone' }); + expect(refused.error).toBe('You do not have permission to perform this action on this trip.'); + expect(names((await call(s.member.id, 'list_trip_tags', { tripId: s.trip.id })).answer)).toEqual([]); + } finally { + check.mockRestore(); + } + }); + + it('TRIPTAG-MCP-005: reading takes the places read scope and writing the write scope', async () => { + const { user } = await makeUser(orm); + const offeredTo = async (scopes: string[]) => (await call(user.id, 'no_such_tool', {}, scopes)).offered; + const writes = ['create_trip_tag', 'delete_trip_tag', 'update_trip_tag']; + const writesOf = (offered: string[]) => offered.filter((tool) => writes.includes(tool)).sort(); + + const reader = await offeredTo(['places:read']); + expect(reader).toContain('list_trip_tags'); + expect(writesOf(reader)).toEqual([]); + expect(writesOf(await offeredTo(['places:write']))).toEqual(writes); + expect(await offeredTo(['trips:read'])).not.toContain('list_trip_tags'); + }); +}); + +describe('tags on the MCP place tools', () => { + it('TRIPTAG-MCP-010: a new place takes the trip’s tags and the personal tags of people on it, nothing else', async () => { + const s = await scene(); + const tripId = s.trip.id; + const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' }); + const ownPersonal = await makeTag(orm, s.member.id, { name: 'mine' }); + const foreignTrip = await makeTag(orm, s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' }); + const foreignPersonal = await makeTag(orm, s.stranger.id, { name: 'theirs' }); + + const created = await call(s.member.id, 'create_place', { + tripId, + name: 'Belem Tower', + tags: [monument.id, ownPersonal.id, foreignTrip.id, foreignPersonal.id], + }); + + expect(created.error).toBeNull(); + expect(tagIds(created.answer)).toEqual([monument.id, ownPersonal.id].sort((a, b) => a - b)); + }); + + it('TRIPTAG-MCP-011: create_and_assign_place tags the place it plans', async () => { + const s = await scene(); + const day = await makeDay(orm, s.trip.id, { day_number: 1 }); + const zone = await makeTag(orm, s.owner.id, { trip: s.trip.id, name: 'Zone' }); + + const created = await call(s.owner.id, 'create_and_assign_place', { + tripId: s.trip.id, + dayId: day.id, + name: 'Alfama', + tags: [zone.id], + }); + + expect(created.error).toBeNull(); + expect(tagIds(created.answer)).toEqual([zone.id]); + }); + + it('TRIPTAG-MCP-012: an update replaces the tags it names, keeps them when it names none and clears them on []', async () => { + const s = await scene(); + const tripId = s.trip.id; + const place = await makePlace(orm, tripId, { name: 'Belem Tower' }); + const monument = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Monument' }); + const zone = await makeTag(orm, s.owner.id, { trip: tripId, name: 'Zone' }); + await tagPlace(orm, place.id, [monument.id]); + const update = (args: Record) => + call(s.member.id, 'update_place', { tripId, placeId: place.id, ...args }); + + expect(tagIds((await update({ notes: 'By the river' })).answer)).toEqual([monument.id]); + expect(tagIds((await update({ tags: [zone.id] })).answer)).toEqual([zone.id]); + expect(tagIds((await update({ tags: [] })).answer)).toEqual([]); + expect((await update({ tags: ['zone'] })).error).toBeTruthy(); + }); +}); diff --git a/server/tests/e2e/trip-tags.e2e.test.ts b/server/tests/e2e/trip-tags.e2e.test.ts new file mode 100644 index 000000000..d56b8fd33 --- /dev/null +++ b/server/tests/e2e/trip-tags.e2e.test.ts @@ -0,0 +1,269 @@ +/** + * Trip tags e2e: the /api/trips/:tripId/tags routes through the real + * JwtAuthGuard and TripAccessGuard against a migrated temp SQLite db + * (createSnapshotTestDb()). TripTagsService and the trip access check run + * their real queries; rows are seeded and read through the factories in + * tests/helpers/factories. The permission check is a spy, so a case can take + * the `place_edit` right away, and the broadcasts go to a FakeRealtimeService. + */ +import { Tags } from '../../src/db/entities/Tags.entity'; +import { TripMembers } from '../../src/db/entities/TripMembers.entity'; +import { Trips } from '../../src/db/entities/Trips.entity'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { PermissionsService } from '../../src/nest/permissions/permissions.service'; +import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; +import { RealtimeService } from '../../src/nest/realtime/realtime.service'; +import { TagsModule } from '../../src/nest/tags/tags.module'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { makeTag } from '../helpers/factories/places'; +import { countRows, deleteRows, findRow } from '../helpers/factories/rows'; +import { addTripMember, makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { FakeRealtimeService } from '../helpers/fake-realtime'; +import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; +import { TestUnitOfWorkModule } from '../helpers/test-uow'; +import { sessionCookie } from './harness'; +import { Test } from '@nestjs/testing'; + +import cookieParser from 'cookie-parser'; +import type { Server } from 'http'; +import request from 'supertest'; +import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest'; + +const db = createSnapshotTestDb(); +const realtime = new FakeRealtimeService(); +const broadcast = realtime.broadcastMock; + +// A spy on the container's PermissionsService, created in beforeAll once the app is built. +let checkPermission: MockInstance; + +let orm: TestOrm; + +const OWNER = 1; +const MEMBER = 2; +const STRANGER = 3; + +describe('Trip tags e2e (real auth and trip guards + real SQL over temp SQLite)', () => { + let server: Server; + let app: Awaited>; + let tripId: number; + let otherTripId: number; + + async function build() { + const moduleRef = await Test.createTestingModule({ + imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, TagsModule], + }) + .overrideProvider(RealtimeService) + .useValue(realtime) + .compile(); + const nest = moduleRef.createNestApplication(); + nest.use(cookieParser()); + nest.useGlobalFilters(new TrekExceptionFilter()); + // Mirror the production APP_PIPE (app.module.ts): the DTO-typed bodies + // validate by metatype, exactly as they do under buildApp(). + nest.useGlobalPipes(new ZodValidationPipe()); + await nest.init(); + return nest; + } + + const tagsPath = (trip = tripId) => `/api/trips/${trip}/tags`; + + beforeAll(async () => { + orm = await createTestOrm(db); + // Pinned ids: sessionCookie(n) signs for exactly these users. + await makeUser(orm, { id: OWNER, username: 'e2e-owner', email: 'owner@example.test' }); + await makeUser(orm, { id: MEMBER, username: 'e2e-member', email: 'member@example.test' }); + await makeUser(orm, { id: STRANGER, username: 'e2e-stranger', email: 'stranger@example.test' }); + app = await build(); + checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission'); + server = app.getHttpServer(); + }); + + beforeEach(async () => { + await deleteRows(orm, Tags); + await deleteRows(orm, TripMembers); + await deleteRows(orm, Trips); + tripId = (await makeTrip(orm, OWNER, { title: 'Lisbon' })).id; + await addTripMember(orm, tripId, MEMBER, OWNER); + otherTripId = (await makeTrip(orm, STRANGER, { title: 'Porto' })).id; + checkPermission.mockResolvedValue(true); + broadcast.mockClear(); + }); + + afterAll(async () => { + await app.close(); + await orm.close(); + }); + + it('401 without a session cookie', async () => { + const res = await request(server).get(tagsPath()); + expect(res.status).toBe(401); + }); + + it('200 list: the same tags for every member, by name, without personal ones', async () => { + await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' }); + await makeTag(orm, MEMBER, { trip: tripId, name: 'Activity' }); + await makeTag(orm, OWNER, { name: 'personal' }); + await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' }); + + const asOwner = await request(server).get(tagsPath()).set('Cookie', sessionCookie(OWNER)); + const asMember = await request(server).get(tagsPath()).set('Cookie', sessionCookie(MEMBER)); + + expect(asOwner.status).toBe(200); + expect(asOwner.body.tags.map((tag: { name: string }) => tag.name)).toEqual(['Activity', 'Zone']); + expect(asMember.body).toEqual(asOwner.body); + }); + + it('404 on every route for a trip the user is not on', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' }); + const cookie = sessionCookie(STRANGER); + + const list = await request(server).get(tagsPath()).set('Cookie', cookie); + const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' }); + const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' }); + const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie); + + for (const res of [list, create, update, remove]) { + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Trip not found' }); + } + expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Zone' }); + }); + + it('201 on create by a member: the tag is the trip’s, with the default colour, and the trip is told', async () => { + const res = await request(server) + .post(tagsPath()) + .set('Cookie', sessionCookie(MEMBER)) + .set('X-Socket-Id', 'sock-9') + .send({ name: ' Monument ' }); + + expect(res.status).toBe(201); + expect(res.body.tag).toMatchObject({ name: 'Monument', color: '#10b981', trip_id: tripId, user_id: MEMBER }); + expect(await findRow(orm, Tags, { id: res.body.tag.id })).toMatchObject({ name: 'Monument', trip_id: tripId }); + expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]); + }); + + it('201 on create with a name the trip has: answers that tag and makes no second one', async () => { + const existing = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' }); + + const res = await request(server) + .post(tagsPath()) + .set('Cookie', sessionCookie(MEMBER)) + .send({ name: 'MONUMENT', color: '#00ff00' }); + + expect(res.status).toBe(201); + expect(res.body.tag).toMatchObject({ id: existing.id, name: 'Monument', color: '#ff0000' }); + expect(await countRows(orm, Tags, { trip: tripId })).toBe(1); + expect(broadcast).not.toHaveBeenCalled(); + }); + + it('400 from the Zod pipe on create without a name, and with a colour that is not hex', async () => { + const cookie = sessionCookie(OWNER); + const unnamed = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: ' ' }); + const coloured = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Zone', color: 'red' }); + + expect(unnamed.status).toBe(400); + expect(unnamed.body.error).toContain('name'); + expect(coloured.status).toBe(400); + expect(coloured.body.error).toContain('color'); + expect(await countRows(orm, Tags, { trip: tripId })).toBe(0); + }); + + it('403 on every write without the right to edit the trip’s places; reading stays open', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' }); + checkPermission.mockResolvedValue(false); + const cookie = sessionCookie(MEMBER); + + const create = await request(server).post(tagsPath()).set('Cookie', cookie).send({ name: 'Mine' }); + const update = await request(server).put(`${tagsPath()}/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' }); + const remove = await request(server).delete(`${tagsPath()}/${tag.id}`).set('Cookie', cookie); + const list = await request(server).get(tagsPath()).set('Cookie', cookie); + + for (const res of [create, update, remove]) { + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: 'No permission' }); + } + expect(list.status).toBe(200); + expect(list.body.tags.map((row: { name: string }) => row.name)).toEqual(['Zone']); + expect(broadcast).not.toHaveBeenCalled(); + }); + + it('200 on update: a member renames and recolours a tag the owner created', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument', color: '#ff0000' }); + + const res = await request(server) + .put(`${tagsPath()}/${tag.id}`) + .set('Cookie', sessionCookie(MEMBER)) + .send({ name: 'Landmark', color: '#0ea5e9' }); + + expect(res.status).toBe(200); + expect(res.body.tag).toMatchObject({ id: tag.id, name: 'Landmark', color: '#0ea5e9', user_id: OWNER }); + expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, undefined]]); + }); + + it('409 on update onto the name of another tag of the trip', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' }); + await makeTag(orm, OWNER, { trip: tripId, name: 'Zone' }); + + const res = await request(server) + .put(`${tagsPath()}/${tag.id}`) + .set('Cookie', sessionCookie(OWNER)) + .send({ name: 'zone' }); + + expect(res.status).toBe(409); + expect(res.body).toEqual({ error: 'A tag with this name already exists' }); + expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' }); + }); + + it('404 on update and delete of a personal tag and of another trip’s tag', async () => { + const personal = await makeTag(orm, OWNER, { name: 'personal' }); + const foreign = await makeTag(orm, STRANGER, { trip: otherTripId, name: 'Elsewhere' }); + const cookie = sessionCookie(OWNER); + + const renamePersonal = await request(server) + .put(`${tagsPath()}/${personal.id}`) + .set('Cookie', cookie) + .send({ name: 'Mine' }); + const deletePersonal = await request(server).delete(`${tagsPath()}/${personal.id}`).set('Cookie', cookie); + const renameForeign = await request(server) + .put(`${tagsPath()}/${foreign.id}`) + .set('Cookie', cookie) + .send({ name: 'Mine' }); + const deleteForeign = await request(server).delete(`${tagsPath()}/${foreign.id}`).set('Cookie', cookie); + + for (const res of [renamePersonal, deletePersonal, renameForeign, deleteForeign]) { + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Tag not found' }); + } + expect(await countRows(orm, Tags, {})).toBe(2); + }); + + it('200 on delete: the row goes and the trip is told', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' }); + + const res = await request(server) + .delete(`${tagsPath()}/${tag.id}`) + .set('Cookie', sessionCookie(MEMBER)) + .set('X-Socket-Id', 'sock-9'); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ success: true }); + expect(await findRow(orm, Tags, { id: tag.id })).toBeNull(); + expect(broadcast.mock.calls).toEqual([[String(tripId), 'tripTags:changed', {}, 'sock-9']]); + }); + + it('a tag of a trip stays off its creator’s personal /api/tags, which cannot change it either', async () => { + const tag = await makeTag(orm, OWNER, { trip: tripId, name: 'Monument' }); + const cookie = sessionCookie(OWNER); + + const list = await request(server).get('/api/tags').set('Cookie', cookie); + const update = await request(server).put(`/api/tags/${tag.id}`).set('Cookie', cookie).send({ name: 'Mine' }); + const remove = await request(server).delete(`/api/tags/${tag.id}`).set('Cookie', cookie); + + expect(list.body).toEqual({ tags: [] }); + expect(update.status).toBe(404); + expect(remove.status).toBe(404); + expect(await findRow(orm, Tags, { id: tag.id })).toMatchObject({ name: 'Monument' }); + }); +}); diff --git a/server/tests/integration/broadcast-parity/plan.cases.ts b/server/tests/integration/broadcast-parity/plan.cases.ts index b8265097c..a46fc6742 100644 --- a/server/tests/integration/broadcast-parity/plan.cases.ts +++ b/server/tests/integration/broadcast-parity/plan.cases.ts @@ -5,6 +5,7 @@ import type { ListImportResult } from '../../../src/nest/places/places.helpers'; import { PlacesService } from '../../../src/nest/places/places.service'; import { StorageService } from '../../../src/nest/storage/storage.service'; import { makeDayAssignment } from '../../helpers/factories/itinerary'; +import { makeTag } from '../../helpers/factories/places'; import { insertRow, updateRows } from '../../helpers/factories/rows'; import type { CaseGroup, Scene } from './types'; import { MikroORM } from '@mikro-orm/core'; @@ -22,6 +23,8 @@ const dayPlanPath = (s: Scene, day: 0 | 1 | 2) => `/api/trips/${s.trip.id}/days/ /** The per-assignment routes of the scene's assignment. */ const assignmentPath = (s: Scene) => `/api/trips/${s.trip.id}/assignments/${s.assignment.id}`; const dayNotesPath = (s: Scene) => `/api/trips/${s.trip.id}/days/${s.days[0].id}/notes`; +/** The tags the scene's trip owns. */ +const tripTagsPath = (s: Scene) => `/api/trips/${s.trip.id}/tags`; const onAssignment = (s: Scene) => ({ tripId: s.trip.id, assignmentId: s.assignment.id }); /** One waypoint, the smallest file the importer turns into a place. */ @@ -88,9 +91,24 @@ async function boundaryOnSecondDay(s: Scene, app: INestApplication): Promise(); + +/** A tag of the scene's trip, for the cases that rename or delete one. */ +async function tripTag(s: Scene, app: INestApplication): Promise { + const tag = await makeTag(app.get(MikroORM), s.owner.id, { trip: s.trip.id, name: 'Monument' }); + tripTagOf.set(s.n, tag.id); +} + +const tripTagId = (s: Scene): number => { + const id = tripTagOf.get(s.n); + if (id === undefined) throw new Error(`scene ${s.n} has no trip tag from its setup`); + return id; +}; + /** - * The planner: places, the day plan, days, day notes, categories, and the - * collection places copied into a trip. + * The planner: places and the tags their trip owns, the day plan, days, day + * notes, categories, and the collection places copied into a trip. */ export const plan: CaseGroup = { name: 'plan', @@ -213,6 +231,30 @@ export const plan: CaseGroup = { }, expect: ['place:updated', 'place:updated'], }, + { + tool: 'create_trip_tag', + args: (s) => ({ tripId: s.trip.id, name: 'Monument' }), + rest: { method: 'post', path: tripTagsPath, body: () => ({ name: 'Monument' }) }, + expect: ['tripTags:changed'], + }, + { + tool: 'update_trip_tag', + setup: tripTag, + args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s), name: 'Landmark' }), + rest: { + method: 'put', + path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}`, + body: () => ({ name: 'Landmark' }), + }, + expect: ['tripTags:changed'], + }, + { + tool: 'delete_trip_tag', + setup: tripTag, + args: (s) => ({ tripId: s.trip.id, tagId: tripTagId(s) }), + rest: { method: 'delete', path: (s) => `${tripTagsPath(s)}/${tripTagId(s)}` }, + expect: ['tripTags:changed'], + }, { tool: 'assign_place_to_day', needs: ['place'], diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index f236ab59e..92aa6545b 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -111,6 +111,7 @@ const UNNUMBERED = [ 'Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip', 'Migration20200101046420_a_visit_keeps_its_own_stay', 'Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders', + 'Migration20200101046440_a_trip_owns_its_tags', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/repositories/Tags.repository.test.ts b/server/tests/unit/db/repositories/Tags.repository.test.ts index 854bde53b..b2cf5b406 100644 --- a/server/tests/unit/db/repositories/Tags.repository.test.ts +++ b/server/tests/unit/db/repositories/Tags.repository.test.ts @@ -4,7 +4,7 @@ import { withRequestContext } from '../../../../src/nest/database/request-contex import { UnitOfWork } from '../../../../src/nest/database/unit-of-work'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; import { createPlace, createTag, createTrip, createUser } from '../../../helpers/factories'; -import { tagPlace } from '../../../helpers/factories/places'; +import { makeTag, tagPlace } from '../../../helpers/factories/places'; import { findRows } from '../../../helpers/factories/rows'; import { resetTestDb } from '../../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; @@ -379,7 +379,76 @@ describe('TagsRepository', () => { // Plan 3c Task 4 — findByIds (PL2) and the place_tags pivot writes (PL5/PL12/PL13). // --------------------------------------------------------------------------- +describe('TagsRepository: the tags a trip owns', () => { + it('TRIPTAGREPO-001: listByTrip returns the rows of that trip by name, whoever created them, as SELECT * rows', async () => { + const { user: owner } = createUser(testDb); + const { user: member } = createUser(testDb, { username: 'trip_member' }); + const trip = createTrip(testDb, owner.id); + const other = createTrip(testDb, owner.id); + const zone = await makeTag(t, owner.id, { trip: trip.id, name: 'Zone' }); + const activity = await makeTag(t, member.id, { trip: trip.id, name: 'Activity' }); + await makeTag(t, owner.id, { trip: other.id, name: 'Elsewhere' }); + createTag(testDb, owner.id, { name: 'personal' }); + + const rows = await tags.listByTrip(trip.id); + + expect(rows).toStrictEqual([rawTag(activity.id), rawTag(zone.id)]); + expect(rows.map((row) => row.trip_id)).toEqual([trip.id, trip.id]); + expect(await tags.listByTrip(999999)).toEqual([]); + }); + + it('TRIPTAGREPO-002: findByIdAndTrip finds a tag of that trip, and neither a personal tag nor another trip’s', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const other = createTrip(testDb, user.id); + const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' }); + const ofOther = await makeTag(t, user.id, { trip: other.id, name: 'Elsewhere' }); + const personal = createTag(testDb, user.id, { name: 'personal' }); + + expect(await tags.findByIdAndTrip(ofTrip.id, trip.id)).toStrictEqual(rawTag(ofTrip.id)); + expect(await tags.findByIdAndTrip(ofOther.id, trip.id)).toBeNull(); + expect(await tags.findByIdAndTrip(personal.id, trip.id)).toBeNull(); + expect(await tags.findByIdAndTrip(999999, trip.id)).toBeNull(); + }); + + it('TRIPTAGREPO-003: createTag files the row under the trip it is given, and under none when it is given none', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + + const ofTrip = await tags.createTag({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' }); + const personal = await tags.createTag({ user_id: user.id, name: 'Monument', color: null }); + + expect(ofTrip).toStrictEqual(rawTag(ofTrip.id)); + expect(ofTrip).toMatchObject({ user_id: user.id, trip_id: trip.id, name: 'Monument', color: '#ff0000' }); + expect(personal).toMatchObject({ user_id: user.id, trip_id: null, color: null }); + }); + + it('TRIPTAGREPO-004: a personal tag still reads through listByUser and findByIdAndUser with a null trip', async () => { + const { user } = createUser(testDb); + const personal = createTag(testDb, user.id, { name: 'personal' }); + + expect((await tags.listByUser(user.id)).map((row) => row.trip_id)).toEqual([null]); + expect((await tags.findByIdAndUser(personal.id, user.id))?.trip_id).toBeNull(); + }); +}); + describe('TagsRepository.findByIds (PL2)', () => { + it('FINDBYIDSREPO-002: says which trip each tag belongs to, null for a personal one', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const ofTrip = await makeTag(t, user.id, { trip: trip.id, name: 'Monument' }); + const personal = createTag(testDb, user.id, { name: 'personal' }); + + const rows = await tags.findByIds([personal.id, ofTrip.id]); + + expect(rows.sort((a, b) => a.id - b.id)).toEqual( + [ + { id: personal.id, user_id: user.id, trip_id: null }, + { id: ofTrip.id, user_id: user.id, trip_id: trip.id }, + ].sort((a, b) => a.id - b.id), + ); + }); + it('FINDBYIDSREPO-001: returns id + user_id for the matching ids, empty input short-circuits', async () => { const { user: ownerA } = createUser(testDb); const { user: ownerB } = createUser(testDb, { username: 'owner_b' }); diff --git a/server/tests/unit/db/trip-tags-migration.test.ts b/server/tests/unit/db/trip-tags-migration.test.ts new file mode 100644 index 000000000..97311c6cb --- /dev/null +++ b/server/tests/unit/db/trip-tags-migration.test.ts @@ -0,0 +1,94 @@ +/** + * `Migration20200101046440_a_trip_owns_its_tags`: a tag can belong to a trip. + * Every tag from before stays a personal one, a trip's tag has to name a real + * trip, and it goes with that trip, taking itself off the places that carried it. + */ +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; +import type { MikroORM } from '@mikro-orm/sqlite'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046440_a_trip_owns_its_tags'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const index = names.indexOf(TARGET); + expect(index).toBeGreaterThan(0); + await migrateTo(orm, names[index - 1]); + return orm; +} + +describe('a trip owns its tags', () => { + it('TRIPTAG-MIG-001: keeps every existing tag personal, on the places it was on', async () => { + const orm = await ormBeforeTarget(); + try { + await rawExec( + orm, + "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')", + ); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon')"); + await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower')"); + await rawExec(orm, "INSERT INTO tags (id, user_id, name, color) VALUES (30, 1, 'hidden gem', '#ff0000')"); + await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30)'); + + await migrateTo(orm, TARGET); + + expect(await rawQuery(orm, 'SELECT id, user_id, trip_id, name, color FROM tags')).toEqual([ + { id: 30, user_id: 1, trip_id: null, name: 'hidden gem', color: '#ff0000' }, + ]); + expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags')).toEqual([{ place_id: 20, tag_id: 30 }]); + } finally { + await orm.close(true); + } + }, 30000); + + it('TRIPTAG-MIG-002: a tag of a trip names a real trip and goes when the trip goes', async () => { + const orm = await ormBeforeTarget(); + try { + await rawExec( + orm, + "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')", + ); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon'), (11, 1, 'Porto')"); + await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower'), (21, 11, 'Ribeira')"); + + await migrateTo(orm, TARGET); + + await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (30, 1, 10, 'Monument')"); + await rawExec(orm, "INSERT INTO tags (id, user_id, trip_id, name) VALUES (31, 1, 11, 'Zone')"); + await rawExec(orm, "INSERT INTO tags (id, user_id, name) VALUES (32, 1, 'personal')"); + await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30), (21, 31), (21, 32)'); + await expect( + rawExec(orm, "INSERT INTO tags (user_id, trip_id, name) VALUES (1, 999, 'Nowhere')"), + ).rejects.toThrow(/FOREIGN KEY/); + + await rawExec(orm, 'DELETE FROM trips WHERE id = 10'); + + expect(await rawQuery(orm, 'SELECT id, trip_id FROM tags ORDER BY id')).toEqual([ + { id: 31, trip_id: 11 }, + { id: 32, trip_id: null }, + ]); + expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags ORDER BY tag_id')).toEqual([ + { place_id: 21, tag_id: 31 }, + { place_id: 21, tag_id: 32 }, + ]); + } finally { + await orm.close(true); + } + }, 30000); + + it('TRIPTAG-MIG-003: the trip column is indexed, so deleting a trip does not scan every tag', async () => { + const orm = await ormBeforeTarget(); + try { + await migrateTo(orm, TARGET); + const indexes = await rawQuery<{ name: string }>(orm, "SELECT name FROM pragma_index_list('tags')"); + expect(indexes.map((index) => index.name)).toContain('idx_tags_trip_id'); + expect(await rawQuery(orm, "SELECT name FROM pragma_index_info('idx_tags_trip_id')")).toEqual([ + { name: 'trip_id' }, + ]); + } finally { + await orm.close(true); + } + }, 30000); +}); diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.ts index ef5035172..b33c72b5c 100644 --- a/server/tests/unit/nest/collections.service.test.ts +++ b/server/tests/unit/nest/collections.service.test.ts @@ -285,6 +285,16 @@ describe('saved places + dedup', () => { expect(res.place!.tags?.map((t) => t.name)).toContain('food'); }); + it('COLLECTIONS-SVC-012b: savePlace leaves out a tag that belongs to a trip', async () => { + const u = createUser(testDb).user; + const own = createTag(testDb, u.id, { name: 'food' }); + const ofTrip = createTag(testDb, u.id, { name: 'Monument' }); + await updateRows(await orm(), Tags, { id: ofTrip.id }, { trip: createTrip(testDb, u.id).id }); + const col = await svc.createCollection(u.id, { name: 'Tagged' }); + const res = await svc.savePlace(u.id, { collection_id: col.id, name: 'Ramen', tag_ids: [own.id, ofTrip.id] }); + expect(res.place?.tags?.map((t) => t.name)).toEqual(['food']); + }); + it('CL49 (Plan 3h Task 7 review, M1 coverage): updatePlace with tag_ids rewrites the tag set (CollectionPlacesRepository.deleteTags)', async () => { const u = createUser(testDb).user; const food = createTag(testDb, u.id, { name: 'food' }); diff --git a/server/tests/unit/nest/trip-tags.service.test.ts b/server/tests/unit/nest/trip-tags.service.test.ts new file mode 100644 index 000000000..367595b4c --- /dev/null +++ b/server/tests/unit/nest/trip-tags.service.test.ts @@ -0,0 +1,257 @@ +/** + * TripTagsService: the tags a trip owns, read by everybody on the trip and + * written under its `place_edit` right, whoever created them. The service + * comes out of TagsModule over a snapshot test db; rows are seeded through the + * ORM factories and broadcasts go to a FakeRealtimeService. + */ +import { Tags } from '../../../src/db/entities/Tags.entity'; +import { DomainError } from '../../../src/nest/common/domain-error'; +import { restTripWriter, type TripWriter } from '../../../src/nest/common/trip-writer'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { TagsModule } from '../../../src/nest/tags/tags.module'; +import { TagsService } from '../../../src/nest/tags/tags.service'; +import { TripTagsService } from '../../../src/nest/tags/trip-tags.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { makePlace, makeTag, tagPlace } from '../../helpers/factories/places'; +import { countRows, findRow, findRows } from '../../helpers/factories/rows'; +import { addTripMember, makeTrip } from '../../helpers/factories/trips'; +import { makeUser } from '../../helpers/factories/users'; +import { resetTestDb } from '../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { MikroORM } from '@mikro-orm/core'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let tripTags: TripTagsService; +const orm = () => t.get(MikroORM); + +beforeAll(async () => { + t = await createTestModule({ db, imports: [TagsModule] }); + tripTags = t.get(TripTagsService); +}); +beforeEach(() => { + resetTestDb(db); + t.realtime.broadcastMock.mockClear(); +}); +afterAll(async () => { + await t.close(); + db.close(); +}); + +const SOCKET = 'sock-1'; + +/** A REST caller, as the controller hands one in. */ +const writer = (userId: number, tripId: number): TripWriter => + restTripWriter(t.realtime, tripId, { id: userId, role: 'user' }, SOCKET); + +/** The status and text a write was refused with. */ +async function refusal(run: () => Promise): Promise<{ status: number; message: string }> { + const thrown: unknown = await run().then( + () => null, + (err: unknown) => err, + ); + expect(thrown).toBeInstanceOf(DomainError); + const refused = thrown as DomainError; + return { status: refused.getStatus(), message: refused.publicMessage }; +} + +const NOT_FOUND = { status: 404, message: 'Trip not found' }; +const NO_TAG = { status: 404, message: 'Tag not found' }; + +/** A trip of `owner` with `member` on it; `stranger` is on neither, and has a trip of their own. */ +async function scene() { + const { user: owner } = await makeUser(orm()); + const { user: member } = await makeUser(orm()); + const { user: stranger } = await makeUser(orm()); + const trip = await makeTrip(orm(), owner.id, { title: 'Lisbon' }); + await addTripMember(orm(), trip.id, member.id, owner.id); + const elsewhere = await makeTrip(orm(), stranger.id, { title: 'Porto' }); + return { owner, member, stranger, trip, elsewhere }; +} + +describe('list', () => { + it('TRIPTAG-SVC-001: every member reads the same tags, by name, whoever created them', async () => { + const s = await scene(); + await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Zone' }); + await makeTag(orm(), s.member.id, { trip: s.trip.id, name: 'Monument' }); + await makeTag(orm(), s.owner.id, { name: 'personal' }); + await makeTag(orm(), s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' }); + + const forOwner = await tripTags.list(s.trip.id, s.owner.id); + const forMember = await tripTags.list(String(s.trip.id), s.member.id); + + expect(forOwner.map((tag) => tag.name)).toEqual(['Monument', 'Zone']); + expect(forMember).toEqual(forOwner); + expect(forOwner.every((tag) => tag.trip_id === s.trip.id)).toBe(true); + }); + + it('TRIPTAG-SVC-002: a trip the reader is not on, or an id that is no trip, reads as not found', async () => { + const s = await scene(); + await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Zone' }); + + expect(await refusal(() => tripTags.list(s.trip.id, s.stranger.id))).toEqual(NOT_FOUND); + expect(await refusal(() => tripTags.list('abc', s.owner.id))).toEqual(NOT_FOUND); + }); +}); + +describe('create', () => { + it('TRIPTAG-SVC-010: stores the trimmed name under the trip and tells its other sockets', async () => { + const s = await scene(); + + const tag = await tripTags.create(s.trip.id, { name: ' Monument ' }, writer(s.member.id, s.trip.id)); + + expect(tag).toMatchObject({ name: 'Monument', color: '#10b981', trip_id: s.trip.id, user_id: s.member.id }); + expect(await findRow(orm(), Tags, { id: tag.id })).toMatchObject({ name: 'Monument', trip_id: s.trip.id }); + expect(t.realtime.broadcastMock.mock.calls).toEqual([[s.trip.id, 'tripTags:changed', {}, SOCKET]]); + }); + + it('TRIPTAG-SVC-011: takes the colour it is given', async () => { + const s = await scene(); + const tag = await tripTags.create(s.trip.id, { name: 'Zone', color: '#0ea5e9' }, writer(s.owner.id, s.trip.id)); + expect(tag.color).toBe('#0ea5e9'); + }); + + it('TRIPTAG-SVC-012: a name the trip has, whatever its case, answers that tag and writes nothing', async () => { + const s = await scene(); + const first = await tripTags.create( + s.trip.id, + { name: 'Monument', color: '#ff0000' }, + writer(s.owner.id, s.trip.id), + ); + t.realtime.broadcastMock.mockClear(); + + const again = await tripTags.create( + s.trip.id, + { name: ' monument', color: '#00ff00' }, + writer(s.member.id, s.trip.id), + ); + + expect(again).toEqual(first); + expect(await countRows(orm(), Tags, { trip: s.trip.id })).toBe(1); + expect(t.realtime.broadcastMock).not.toHaveBeenCalled(); + }); + + it('TRIPTAG-SVC-013: the same name on another trip, or as a personal tag, is a tag of its own', async () => { + const s = await scene(); + await makeTag(orm(), s.owner.id, { name: 'Monument' }); + await makeTag(orm(), s.stranger.id, { trip: s.elsewhere.id, name: 'Monument' }); + + const tag = await tripTags.create(s.trip.id, { name: 'Monument' }, writer(s.owner.id, s.trip.id)); + + expect(await countRows(orm(), Tags, { name: 'Monument' })).toBe(3); + expect(tag.trip_id).toBe(s.trip.id); + }); + + it('TRIPTAG-SVC-014: refuses a writer who is not on the trip, and one without the right to edit places', async () => { + const s = await scene(); + + expect(await refusal(() => tripTags.create(s.trip.id, { name: 'Zone' }, writer(s.stranger.id, s.trip.id)))).toEqual( + NOT_FOUND, + ); + expect(await refusal(() => tripTags.create('abc', { name: 'Zone' }, writer(s.owner.id, s.trip.id)))).toEqual( + NOT_FOUND, + ); + + vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValueOnce(false); + expect(await refusal(() => tripTags.create(s.trip.id, { name: 'Zone' }, writer(s.member.id, s.trip.id)))).toEqual({ + status: 403, + message: 'No permission', + }); + + expect(await countRows(orm(), Tags, { trip: s.trip.id })).toBe(0); + expect(t.realtime.broadcastMock).not.toHaveBeenCalled(); + }); +}); + +describe('update', () => { + it('TRIPTAG-SVC-020: renames and recolours a tag another member created, one field at a time', async () => { + const s = await scene(); + const tag = await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Monument', color: '#ff0000' }); + + const renamed = await tripTags.update(s.trip.id, tag.id, { name: ' Landmark ' }, writer(s.member.id, s.trip.id)); + expect(renamed).toMatchObject({ id: tag.id, name: 'Landmark', color: '#ff0000' }); + + const recoloured = await tripTags.update( + String(s.trip.id), + String(tag.id), + { color: '#0ea5e9' }, + writer(s.member.id, s.trip.id), + ); + expect(recoloured).toMatchObject({ id: tag.id, name: 'Landmark', color: '#0ea5e9', user_id: s.owner.id }); + expect(t.realtime.broadcastMock.mock.calls).toEqual([ + [s.trip.id, 'tripTags:changed', {}, SOCKET], + [s.trip.id, 'tripTags:changed', {}, SOCKET], + ]); + }); + + it('TRIPTAG-SVC-021: keeps its own name in another case, and refuses the name of another tag', async () => { + const s = await scene(); + const monument = await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Monument' }); + await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Zone' }); + + expect( + await tripTags.update(s.trip.id, monument.id, { name: 'MONUMENT' }, writer(s.owner.id, s.trip.id)), + ).toMatchObject({ name: 'MONUMENT' }); + expect( + await refusal(() => tripTags.update(s.trip.id, monument.id, { name: 'zone' }, writer(s.owner.id, s.trip.id))), + ).toEqual({ status: 409, message: 'A tag with this name already exists' }); + expect(await findRow(orm(), Tags, { id: monument.id })).toMatchObject({ name: 'MONUMENT' }); + }); + + it('TRIPTAG-SVC-022: a personal tag, another trip’s tag and an id that is none read as not found', async () => { + const s = await scene(); + const personal = await makeTag(orm(), s.owner.id, { name: 'personal' }); + const foreign = await makeTag(orm(), s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' }); + const as = writer(s.owner.id, s.trip.id); + + expect(await refusal(() => tripTags.update(s.trip.id, personal.id, { name: 'x' }, as))).toEqual(NO_TAG); + expect(await refusal(() => tripTags.update(s.trip.id, foreign.id, { name: 'x' }, as))).toEqual(NO_TAG); + expect(await refusal(() => tripTags.update(s.trip.id, 'abc', { name: 'x' }, as))).toEqual(NO_TAG); + expect(await findRows(orm(), Tags, { name: 'x' })).toEqual([]); + expect(t.realtime.broadcastMock).not.toHaveBeenCalled(); + }); +}); + +describe('remove', () => { + it('TRIPTAG-SVC-030: deletes the tag and takes it off the places that carried it', async () => { + const s = await scene(); + const place = await makePlace(orm(), s.trip.id, { name: 'Belem Tower' }); + const monument = await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Monument' }); + const zone = await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Zone' }); + await tagPlace(orm(), place.id, [monument.id, zone.id]); + + await tripTags.remove(s.trip.id, monument.id, writer(s.member.id, s.trip.id)); + + expect(await findRow(orm(), Tags, { id: monument.id })).toBeNull(); + expect((await findRows(orm(), Tags, { place_tags_inverse: place.id })).map((tag) => tag.id)).toEqual([zone.id]); + expect(t.realtime.broadcastMock.mock.calls).toEqual([[s.trip.id, 'tripTags:changed', {}, SOCKET]]); + }); + + it('TRIPTAG-SVC-031: leaves a personal tag, another trip’s tag and an id that is none alone', async () => { + const s = await scene(); + const personal = await makeTag(orm(), s.owner.id, { name: 'personal' }); + const foreign = await makeTag(orm(), s.stranger.id, { trip: s.elsewhere.id, name: 'Elsewhere' }); + const as = writer(s.owner.id, s.trip.id); + + expect(await refusal(() => tripTags.remove(s.trip.id, personal.id, as))).toEqual(NO_TAG); + expect(await refusal(() => tripTags.remove(s.trip.id, foreign.id, as))).toEqual(NO_TAG); + expect(await refusal(() => tripTags.remove(s.trip.id, 'abc', as))).toEqual(NO_TAG); + expect(await countRows(orm(), Tags, {})).toBe(2); + expect(t.realtime.broadcastMock).not.toHaveBeenCalled(); + }); +}); + +describe('the personal surface next to it', () => { + it('TRIPTAG-SVC-040: a tag of a trip is not on its creator’s own list, and not theirs to find there', async () => { + const s = await scene(); + const personal = await makeTag(orm(), s.owner.id, { name: 'personal' }); + const ofTrip = await makeTag(orm(), s.owner.id, { trip: s.trip.id, name: 'Monument' }); + const tags = t.get(TagsService); + + expect((await tags.list(s.owner.id)).map((tag) => tag.id)).toEqual([personal.id]); + expect(await tags.getByIdAndUser(personal.id, s.owner.id)).toMatchObject({ id: personal.id }); + expect(await tags.getByIdAndUser(ofTrip.id, s.owner.id)).toBeUndefined(); + }); +}); diff --git a/server/tests/unit/nest/trips.copy-trip-tags.test.ts b/server/tests/unit/nest/trips.copy-trip-tags.test.ts new file mode 100644 index 000000000..9f348a3e2 --- /dev/null +++ b/server/tests/unit/nest/trips.copy-trip-tags.test.ts @@ -0,0 +1,71 @@ +/** + * TripsService.copy and the tags a trip owns: the copy gets tags of its own + * under the person who copied it, its places carry those, and a personal tag + * stays the one row it was. The source keeps everything it had. + * + * Real in-memory SQLite over the container: the service comes out of + * TripsModule, and the rows are seeded and read through the ORM factories. + */ +import { Places } from '../../../src/db/entities/Places.entity'; +import { Tags } from '../../../src/db/entities/Tags.entity'; +import { TripsModule } from '../../../src/nest/trips/trips.module'; +import { TripsService } from '../../../src/nest/trips/trips.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { makePlace, makeTag, tagPlace } from '../../helpers/factories/places'; +import { findRow, findRows } from '../../helpers/factories/rows'; +import { makeTrip } from '../../helpers/factories/trips'; +import { makeUser } from '../../helpers/factories/users'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { MikroORM } from '@mikro-orm/core'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let svc: TripsService; +const orm = () => t.get(MikroORM); + +beforeAll(async () => { + t = await createTestModule({ db, imports: [TripsModule] }); + svc = t.get(TripsService); +}); + +afterAll(async () => { + await t.close(); + db.close(); +}); + +const ids = (rows: { id: number }[]): number[] => rows.map((row) => row.id).sort((a, b) => a - b); + +describe('copy: the tags a trip owns', () => { + it('TRIP-SVC-097: the copy owns tags of its own, on its own places, and a personal tag stays one row', async () => { + const { user: owner } = await makeUser(orm()); + const { user: copier } = await makeUser(orm()); + const trip = await makeTrip(orm(), owner.id, { title: 'Lisbon' }); + const tower = await makePlace(orm(), trip.id, { name: 'Belem Tower' }); + const monument = await makeTag(orm(), owner.id, { trip: trip.id, name: 'Monument', color: '#ff0000' }); + const zone = await makeTag(orm(), owner.id, { trip: trip.id, name: 'Zone' }); + const personal = await makeTag(orm(), owner.id, { name: 'hidden gem' }); + await tagPlace(orm(), tower.id, [monument.id, personal.id]); + + const newTripId = await svc.copy(trip.id, copier.id, 'Lisbon again'); + + // Every tag of the trip comes along, the one no place carries included. + const copies = await findRows(orm(), Tags, { trip: newTripId }, { name: 'asc' }); + expect(copies.map((tag) => ({ name: tag.name, color: tag.color, user_id: tag.user_id }))).toEqual([ + { name: 'Monument', color: '#ff0000', user_id: copier.id }, + { name: 'Zone', color: '#10b981', user_id: copier.id }, + ]); + expect(ids(copies)).not.toContain(monument.id); + + const copiedTower = await findRow(orm(), Places, { trip: newTripId, name: 'Belem Tower' }); + expect(copiedTower).not.toBeNull(); + const onCopy = await findRows(orm(), Tags, { place_tags_inverse: copiedTower?.id ?? 0 }); + const copiedMonument = copies.filter((tag) => tag.name === 'Monument'); + expect(ids(onCopy)).toEqual(ids([...copiedMonument, personal])); + + // The source keeps its own tags, on its own place. + expect(ids(await findRows(orm(), Tags, { trip: trip.id }))).toEqual(ids([monument, zone])); + expect(ids(await findRows(orm(), Tags, { place_tags_inverse: tower.id }))).toEqual(ids([monument, personal])); + }); +}); diff --git a/shared/src/i18n/ar/places.ts b/shared/src/i18n/ar/places.ts index a3c390dbc..fce5e78e7 100644 --- a/shared/src/i18n/ar/places.ts +++ b/shared/src/i18n/ar/places.ts @@ -191,6 +191,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'نباتي صرف', 'places.details.fact.internetAccess': 'واي فاي', 'places.categoryCreateError': 'فشل إنشاء الفئة', + 'places.tags': 'الوسوم', + 'places.newTag': 'وسم جديد', + 'places.addTag': 'إضافة وسم', + 'places.tagCreateError': 'فشل إنشاء الوسم', 'places.nameRequired': 'يرجى إدخال اسم', 'places.saveError': 'فشل الحفظ', 'places.createExpenseHint': 'يحفظ المكان ثم يفتح محرر التكاليف.', diff --git a/shared/src/i18n/az/places.ts b/shared/src/i18n/az/places.ts index 754721736..47f1ab833 100644 --- a/shared/src/i18n/az/places.ts +++ b/shared/src/i18n/az/places.ts @@ -171,6 +171,10 @@ const places: TranslationStrings = { 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Kateqoriya yaratmaq mümkün olmadı', + 'places.tags': 'Etiketlər', + 'places.newTag': 'Yeni etiket', + 'places.addTag': 'Etiket əlavə et', + 'places.tagCreateError': 'Etiket yaratmaq mümkün olmadı', 'places.nameRequired': 'Ad daxil edin', 'places.saveError': 'Yadda saxlamaq mümkün olmadı', 'places.createExpenseHint': 'Məkanı yadda saxlayır, sonra Xərclər redaktorunu açır.', diff --git a/shared/src/i18n/br/places.ts b/shared/src/i18n/br/places.ts index 6f2ab2c4a..fbc4480ed 100644 --- a/shared/src/i18n/br/places.ts +++ b/shared/src/i18n/br/places.ts @@ -159,6 +159,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegano', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Falha ao criar categoria', + 'places.tags': 'Etiquetas', + 'places.newTag': 'Nova etiqueta', + 'places.addTag': 'Adicionar etiqueta', + 'places.tagCreateError': 'Falha ao criar etiqueta', 'places.nameRequired': 'Digite um nome', 'places.saveError': 'Falha ao salvar', 'places.createExpenseHint': 'Salva o local e depois abre o editor de despesas.', diff --git a/shared/src/i18n/ca/places.ts b/shared/src/i18n/ca/places.ts index b90a53c76..2ff8d2a1a 100644 --- a/shared/src/i18n/ca/places.ts +++ b/shared/src/i18n/ca/places.ts @@ -157,6 +157,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegà', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': "No s'ha pogut crear la categoria", + 'places.tags': 'Etiquetes', + 'places.newTag': 'Etiqueta nova', + 'places.addTag': 'Afegeix etiqueta', + 'places.tagCreateError': "No s'ha pogut crear l'etiqueta", 'places.nameRequired': 'Introdueix un nom', 'places.saveError': "No s'ha pogut desar", 'places.createExpenseHint': 'Desa el lloc i després obre l’editor de despeses.', diff --git a/shared/src/i18n/cs/places.ts b/shared/src/i18n/cs/places.ts index ef1b6d3aa..d539864b5 100644 --- a/shared/src/i18n/cs/places.ts +++ b/shared/src/i18n/cs/places.ts @@ -167,6 +167,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Veganské', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Nepodařilo se vytvořit kategorii', + 'places.tags': 'Štítky', + 'places.newTag': 'Nový štítek', + 'places.addTag': 'Přidat štítek', + 'places.tagCreateError': 'Nepodařilo se vytvořit štítek', 'places.nameRequired': 'Prosím zadejte název', 'places.saveError': 'Uložení se nezdařilo', 'places.createExpenseHint': 'Uloží místo a poté otevře editor nákladů.', diff --git a/shared/src/i18n/de/places.ts b/shared/src/i18n/de/places.ts index f3276e79f..e0abfee51 100644 --- a/shared/src/i18n/de/places.ts +++ b/shared/src/i18n/de/places.ts @@ -160,6 +160,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegan', // same-as-en 'places.details.fact.internetAccess': 'WLAN', 'places.categoryCreateError': 'Fehler beim Erstellen der Kategorie', + 'places.tags': 'Tags', // same-as-en + 'places.newTag': 'Neuer Tag', + 'places.addTag': 'Tag hinzufügen', + 'places.tagCreateError': 'Fehler beim Erstellen des Tags', 'places.nameRequired': 'Bitte einen Namen eingeben', 'places.saveError': 'Fehler beim Speichern', 'places.createExpenseHint': 'Speichert den Ort und öffnet dann den Kosten-Editor.', diff --git a/shared/src/i18n/en/places.ts b/shared/src/i18n/en/places.ts index 84a459e45..ee605c48b 100644 --- a/shared/src/i18n/en/places.ts +++ b/shared/src/i18n/en/places.ts @@ -166,6 +166,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegan', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Failed to create category', + 'places.tags': 'Tags', + 'places.newTag': 'New tag', + 'places.addTag': 'Add tag', + 'places.tagCreateError': 'Failed to create tag', 'places.nameRequired': 'Please enter a name', 'places.saveError': 'Failed to save', 'places.createExpenseHint': 'Saves the place, then opens the Costs editor.', diff --git a/shared/src/i18n/es/places.ts b/shared/src/i18n/es/places.ts index c6f309d70..dc6d9170e 100644 --- a/shared/src/i18n/es/places.ts +++ b/shared/src/i18n/es/places.ts @@ -160,6 +160,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegano', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'No se pudo crear la categoría', + 'places.tags': 'Etiquetas', + 'places.newTag': 'Nueva etiqueta', + 'places.addTag': 'Añadir etiqueta', + 'places.tagCreateError': 'No se pudo crear la etiqueta', 'places.nameRequired': 'Introduce un nombre', 'places.saveError': 'No se pudo guardar', 'places.createExpenseHint': 'Guarda el lugar y luego abre el editor de gastos.', diff --git a/shared/src/i18n/et/places.ts b/shared/src/i18n/et/places.ts index 6fd831682..717fe8db8 100644 --- a/shared/src/i18n/et/places.ts +++ b/shared/src/i18n/et/places.ts @@ -160,6 +160,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegantoit', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Kategooria loomine ebaõnnestus', + 'places.tags': 'Sildid', + 'places.newTag': 'Uus silt', + 'places.addTag': 'Lisa silt', + 'places.tagCreateError': 'Sildi loomine ebaõnnestus', 'places.nameRequired': 'Sisesta nimi', 'places.saveError': 'Salvestamine ebaõnnestus', 'places.createExpenseHint': 'Salvestab koha ja avab seejärel kulude muutmise vaate.', diff --git a/shared/src/i18n/fr/places.ts b/shared/src/i18n/fr/places.ts index 4e744bd7b..c125594b4 100644 --- a/shared/src/i18n/fr/places.ts +++ b/shared/src/i18n/fr/places.ts @@ -160,6 +160,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Végan', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Impossible de créer la catégorie', + 'places.tags': 'Étiquettes', + 'places.newTag': 'Nouvelle étiquette', + 'places.addTag': 'Ajouter une étiquette', + 'places.tagCreateError': "Impossible de créer l'étiquette", 'places.nameRequired': 'Veuillez saisir un nom', 'places.saveError': "Échec de l'enregistrement", 'places.createExpenseHint': 'Enregistre le lieu, puis ouvre l’éditeur de dépenses.', diff --git a/shared/src/i18n/gr/places.ts b/shared/src/i18n/gr/places.ts index 664cc25ca..b464470c0 100644 --- a/shared/src/i18n/gr/places.ts +++ b/shared/src/i18n/gr/places.ts @@ -161,6 +161,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegan', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Αποτυχία δημιουργίας κατηγορίας', + 'places.tags': 'Ετικέτες', + 'places.newTag': 'Νέα ετικέτα', + 'places.addTag': 'Προσθήκη ετικέτας', + 'places.tagCreateError': 'Αποτυχία δημιουργίας ετικέτας', 'places.nameRequired': 'Παρακαλώ εισαγάγετε ένα όνομα', 'places.saveError': 'Αποτυχία αποθήκευσης', 'places.createExpenseHint': 'Αποθηκεύει την τοποθεσία και ανοίγει τον επεξεργαστή εξόδων.', diff --git a/shared/src/i18n/he/places.ts b/shared/src/i18n/he/places.ts index 99bb0b4d8..3265dba62 100644 --- a/shared/src/i18n/he/places.ts +++ b/shared/src/i18n/he/places.ts @@ -166,6 +166,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'טבעוני', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'יצירת הקטגוריה נכשלה', + 'places.tags': 'תגיות', + 'places.newTag': 'תגית חדשה', + 'places.addTag': 'הוספת תגית', + 'places.tagCreateError': 'יצירת התגית נכשלה', 'places.nameRequired': 'הזינו שם', 'places.saveError': 'השמירה נכשלה', 'places.createExpenseHint': 'שומר את המקום ואז פותח את עורך ההוצאות.', diff --git a/shared/src/i18n/hu/places.ts b/shared/src/i18n/hu/places.ts index 32792fe8b..ca2abe453 100644 --- a/shared/src/i18n/hu/places.ts +++ b/shared/src/i18n/hu/places.ts @@ -160,6 +160,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegán', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Nem sikerült létrehozni a kategóriát', + 'places.tags': 'Címkék', + 'places.newTag': 'Új címke', + 'places.addTag': 'Címke hozzáadása', + 'places.tagCreateError': 'Nem sikerült létrehozni a címkét', 'places.nameRequired': 'Kérjük, adj meg egy nevet', 'places.saveError': 'Nem sikerült menteni', 'places.createExpenseHint': 'Menti a helyet, majd megnyitja a költségszerkesztőt.', diff --git a/shared/src/i18n/id/places.ts b/shared/src/i18n/id/places.ts index c3666c1e6..e436dcbd6 100644 --- a/shared/src/i18n/id/places.ts +++ b/shared/src/i18n/id/places.ts @@ -150,6 +150,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegan', // same-as-en 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Gagal membuat kategori', + 'places.tags': 'Tag', + 'places.newTag': 'Tag baru', + 'places.addTag': 'Tambah tag', + 'places.tagCreateError': 'Gagal membuat tag', 'places.nameRequired': 'Harap masukkan nama', 'places.saveError': 'Gagal menyimpan', 'places.createExpenseHint': 'Menyimpan tempat, lalu membuka editor biaya.', diff --git a/shared/src/i18n/it/places.ts b/shared/src/i18n/it/places.ts index 16f701534..6fee51bde 100644 --- a/shared/src/i18n/it/places.ts +++ b/shared/src/i18n/it/places.ts @@ -159,6 +159,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegano', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Impossibile creare la categoria', + 'places.tags': 'Tag', + 'places.newTag': 'Nuovo tag', + 'places.addTag': 'Aggiungi tag', + 'places.tagCreateError': 'Impossibile creare il tag', 'places.nameRequired': 'Inserisci un nome', 'places.saveError': 'Impossibile salvare', 'places.createExpenseHint': 'Salva il luogo e poi apre l’editor dei costi.', diff --git a/shared/src/i18n/ja/places.ts b/shared/src/i18n/ja/places.ts index 90c65d738..73ac9e7c5 100644 --- a/shared/src/i18n/ja/places.ts +++ b/shared/src/i18n/ja/places.ts @@ -151,6 +151,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'ヴィーガン', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'カテゴリの作成に失敗しました', + 'places.tags': 'タグ', + 'places.newTag': '新しいタグ', + 'places.addTag': 'タグを追加', + 'places.tagCreateError': 'タグの作成に失敗しました', 'places.nameRequired': '名前を入力してください', 'places.saveError': '保存に失敗しました', 'places.createExpenseHint': '場所を保存してから費用エディタを開きます。', diff --git a/shared/src/i18n/ko/places.ts b/shared/src/i18n/ko/places.ts index dedb75016..3d8540209 100644 --- a/shared/src/i18n/ko/places.ts +++ b/shared/src/i18n/ko/places.ts @@ -150,6 +150,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': '비건', 'places.details.fact.internetAccess': '와이파이', 'places.categoryCreateError': '카테고리 생성 실패', + 'places.tags': '태그', + 'places.newTag': '새 태그', + 'places.addTag': '태그 추가', + 'places.tagCreateError': '태그 생성 실패', 'places.nameRequired': '이름을 입력하세요', 'places.saveError': '저장 실패', 'places.createExpenseHint': '장소를 저장한 뒤 비용 편집기를 엽니다.', diff --git a/shared/src/i18n/nl/places.ts b/shared/src/i18n/nl/places.ts index 1c2f3bcd4..df99b9695 100644 --- a/shared/src/i18n/nl/places.ts +++ b/shared/src/i18n/nl/places.ts @@ -159,6 +159,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Veganistisch', 'places.details.fact.internetAccess': 'Wifi', 'places.categoryCreateError': 'Categorie aanmaken mislukt', + 'places.tags': 'Tags', // same-as-en + 'places.newTag': 'Nieuwe tag', + 'places.addTag': 'Tag toevoegen', + 'places.tagCreateError': 'Tag aanmaken mislukt', 'places.nameRequired': 'Voer een naam in', 'places.saveError': 'Opslaan mislukt', 'places.createExpenseHint': 'Slaat de plaats op en opent daarna de kosten-editor.', diff --git a/shared/src/i18n/pl/places.ts b/shared/src/i18n/pl/places.ts index d3f37eb84..6a7713737 100644 --- a/shared/src/i18n/pl/places.ts +++ b/shared/src/i18n/pl/places.ts @@ -159,6 +159,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Wegańskie', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Nie udało się utworzyć kategorii', + 'places.tags': 'Tagi', + 'places.newTag': 'Nowy tag', + 'places.addTag': 'Dodaj tag', + 'places.tagCreateError': 'Nie udało się utworzyć tagu', 'places.nameRequired': 'Proszę podać nazwę', 'places.saveError': 'Nie udało się zapisać', 'places.createExpenseHint': 'Zapisuje miejsce i otwiera edytor kosztów.', diff --git a/shared/src/i18n/ru/places.ts b/shared/src/i18n/ru/places.ts index b59cd57b4..01e4f05a8 100644 --- a/shared/src/i18n/ru/places.ts +++ b/shared/src/i18n/ru/places.ts @@ -175,6 +175,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Веганское', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Не удалось создать категорию', + 'places.tags': 'Теги', + 'places.newTag': 'Новый тег', + 'places.addTag': 'Добавить тег', + 'places.tagCreateError': 'Не удалось создать тег', 'places.nameRequired': 'Введите название', 'places.saveError': 'Ошибка сохранения', 'places.createExpenseHint': 'Сохраняет место и открывает редактор расходов.', diff --git a/shared/src/i18n/sk/places.ts b/shared/src/i18n/sk/places.ts index 801b49f96..a799962ca 100644 --- a/shared/src/i18n/sk/places.ts +++ b/shared/src/i18n/sk/places.ts @@ -168,6 +168,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegánske', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Nepodarilo sa vytvoriť kategóriu', + 'places.tags': 'Štítky', + 'places.newTag': 'Nový štítok', + 'places.addTag': 'Pridať štítok', + 'places.tagCreateError': 'Nepodarilo sa vytvoriť štítok', 'places.nameRequired': 'Zadajte prosím názov', 'places.saveError': 'Uloženie zlyhalo', 'places.createExpenseHint': 'Uloží miesto a potom otvorí editor nákladov.', diff --git a/shared/src/i18n/sv/places.ts b/shared/src/i18n/sv/places.ts index 421c10ac5..9bdaf1239 100644 --- a/shared/src/i18n/sv/places.ts +++ b/shared/src/i18n/sv/places.ts @@ -159,6 +159,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Veganskt', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Det gick inte att skapa kategorin', + 'places.tags': 'Taggar', + 'places.newTag': 'Ny tagg', + 'places.addTag': 'Lägg till tagg', + 'places.tagCreateError': 'Det gick inte att skapa taggen', 'places.nameRequired': 'Ange ett namn', 'places.saveError': 'Det gick inte att spara', 'places.createExpenseHint': 'Sparar platsen och öppnar sedan kostnadsredigeraren.', diff --git a/shared/src/i18n/th/places.ts b/shared/src/i18n/th/places.ts index ed245d732..d8fb23883 100644 --- a/shared/src/i18n/th/places.ts +++ b/shared/src/i18n/th/places.ts @@ -142,6 +142,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'วีแกน', 'places.details.fact.internetAccess': 'อินเตอร์เน็ตไร้สาย', 'places.categoryCreateError': 'ไม่สามารถสร้างหมวดหมู่ได้', + 'places.tags': 'แท็ก', + 'places.newTag': 'แท็กใหม่', + 'places.addTag': 'เพิ่มแท็ก', + 'places.tagCreateError': 'ไม่สามารถสร้างแท็กได้', 'places.nameRequired': 'กรุณากรอกชื่อ', 'places.saveError': 'บันทึกไม่สำเร็จ', 'places.createExpenseHint': 'บันทึกสถานที่ จากนั้นเปิดตัวแก้ไขต้นทุน', diff --git a/shared/src/i18n/tr/places.ts b/shared/src/i18n/tr/places.ts index a6a04bd30..3f7253090 100644 --- a/shared/src/i18n/tr/places.ts +++ b/shared/src/i18n/tr/places.ts @@ -161,6 +161,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Vegan', // same-as-en 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Kategori oluşturulamadı', + 'places.tags': 'Etiketler', + 'places.newTag': 'Yeni etiket', + 'places.addTag': 'Etiket ekle', + 'places.tagCreateError': 'Etiket oluşturulamadı', 'places.nameRequired': 'Lütfen bir ad girin', 'places.saveError': 'Kaydedilemedi', 'places.createExpenseHint': 'Yeri kaydeder, sonra masraf düzenleyicisini açar.', diff --git a/shared/src/i18n/uk/places.ts b/shared/src/i18n/uk/places.ts index cb47f626c..2805b88b6 100644 --- a/shared/src/i18n/uk/places.ts +++ b/shared/src/i18n/uk/places.ts @@ -175,6 +175,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Веганське', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Не вдалося створити категорію', + 'places.tags': 'Теги', + 'places.newTag': 'Новий тег', + 'places.addTag': 'Додати тег', + 'places.tagCreateError': 'Не вдалося створити тег', 'places.nameRequired': 'Введіть назву', 'places.saveError': 'Помилка збереження', 'places.createExpenseHint': 'Зберігає місце й відкриває редактор витрат.', diff --git a/shared/src/i18n/vi/places.ts b/shared/src/i18n/vi/places.ts index c21db914f..59d690eb7 100644 --- a/shared/src/i18n/vi/places.ts +++ b/shared/src/i18n/vi/places.ts @@ -151,6 +151,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': 'Thuần chay', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': 'Không tạo được danh mục', + 'places.tags': 'Thẻ', + 'places.newTag': 'Thẻ mới', + 'places.addTag': 'Thêm thẻ', + 'places.tagCreateError': 'Không tạo được thẻ', 'places.nameRequired': 'Vui lòng nhập tên', 'places.saveError': 'Không lưu được', 'places.createExpenseHint': 'Lưu địa điểm rồi mở trình sửa chi phí.', diff --git a/shared/src/i18n/zh-TW/places.ts b/shared/src/i18n/zh-TW/places.ts index 099fd1544..2b8d84cd5 100644 --- a/shared/src/i18n/zh-TW/places.ts +++ b/shared/src/i18n/zh-TW/places.ts @@ -149,6 +149,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': '純素', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': '建立分類失敗', + 'places.tags': '標籤', + 'places.newTag': '新增標籤', + 'places.addTag': '新增標籤', + 'places.tagCreateError': '建立標籤失敗', 'places.nameRequired': '請輸入名稱', 'places.saveError': '儲存失敗', 'places.createExpenseHint': '先儲存地點,然後開啟費用編輯器。', diff --git a/shared/src/i18n/zh/places.ts b/shared/src/i18n/zh/places.ts index 57c135ab3..f341c5c9e 100644 --- a/shared/src/i18n/zh/places.ts +++ b/shared/src/i18n/zh/places.ts @@ -149,6 +149,10 @@ const places: TranslationStrings = { 'places.details.fact.vegan': '纯素', 'places.details.fact.internetAccess': 'Wi-Fi', 'places.categoryCreateError': '创建分类失败', + 'places.tags': '标签', + 'places.newTag': '新建标签', + 'places.addTag': '添加标签', + 'places.tagCreateError': '创建标签失败', 'places.nameRequired': '请输入名称', 'places.saveError': '保存失败', 'places.createExpenseHint': '先保存地点,然后打开费用编辑器。', diff --git a/shared/src/index.ts b/shared/src/index.ts index f5ae4f5df..0e196331c 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -30,6 +30,7 @@ export * from './maps/place-shadow.schema'; export * from './maps/route-usage.schema'; export * from './category/category.schema'; export * from './tag/tag.schema'; +export * from './tag/trip-tag.schema'; export * from './notification/notification.schema'; export * from './memories/memories.schema'; export * from './atlas/atlas.schema'; diff --git a/shared/src/place/place.schema.spec.ts b/shared/src/place/place.schema.spec.ts index 674694ce2..c8c9a5b53 100644 --- a/shared/src/place/place.schema.spec.ts +++ b/shared/src/place/place.schema.spec.ts @@ -3,6 +3,7 @@ import { placeBulkDeleteRequestSchema, placeImportListRequestSchema, placeSchema, + placeTagIdsSchema, placeUpdateRequestSchema, placeWebsiteSchema, } from './place.schema'; @@ -128,3 +129,29 @@ describe('placeWebsiteSchema (#2483)', () => { expect(shape.properties?.website).toEqual({ type: 'string', maxLength: 500 }); }); }); + +describe('placeTagIdsSchema', () => { + it('SHARED-PLACE-040: takes tag ids, none at all included, and nothing that is not an id', () => { + expect(placeTagIdsSchema.safeParse([3, 8]).success).toBe(true); + // An empty list is how a place loses its tags. + expect(placeTagIdsSchema.safeParse([]).success).toBe(true); + expect(placeTagIdsSchema.safeParse([0]).success).toBe(false); + expect(placeTagIdsSchema.safeParse(['3']).success).toBe(false); + expect(placeTagIdsSchema.safeParse([{ id: 3 }]).success).toBe(false); + }); + + it('SHARED-PLACE-041: stops at fifty tags on one place', () => { + const ids = Array.from({ length: 51 }, (_, i) => i + 1); + expect(placeTagIdsSchema.safeParse(ids.slice(0, 50)).success).toBe(true); + expect(placeTagIdsSchema.safeParse(ids).success).toBe(false); + }); + + it('SHARED-PLACE-042: the tool schema an MCP client reads is a plain list of integers', () => { + const shape = z.toJSONSchema(z.object({ tags: placeTagIdsSchema.optional() }), { io: 'input' }); + expect(shape.properties?.tags).toMatchObject({ + type: 'array', + maxItems: 50, + items: { type: 'integer', exclusiveMinimum: 0 }, + }); + }); +}); diff --git a/shared/src/place/place.schema.ts b/shared/src/place/place.schema.ts index 89764f845..b2447dae3 100644 --- a/shared/src/place/place.schema.ts +++ b/shared/src/place/place.schema.ts @@ -1,3 +1,4 @@ +import { idSchema } from '../common/primitives.schema'; import { tagSchema } from '../tag/tag.schema'; import { placeFieldOriginsSchema } from './place-contrib.schema'; import { placeEmailField, placeOpeningHoursField } from './place-hours'; @@ -345,6 +346,13 @@ export const placeImportMapRequestSchema = z.object({ }); export type PlaceImportMapRequest = z.infer; +/** + * A place's tags as a write names them: tag ids, and always the whole set, since an + * update replaces what the place had. The REST bodies above are open records and read + * the key as it comes; the MCP place tools take it through this schema. + */ +export const placeTagIdsSchema = z.array(idSchema).max(50); + /** Query filters for the place list. */ export const placeListQuerySchema = z.object({ search: z.string().optional(), diff --git a/shared/src/realtime/events.schema.spec.ts b/shared/src/realtime/events.schema.spec.ts index 559c3f6de..b1ad180c2 100644 --- a/shared/src/realtime/events.schema.spec.ts +++ b/shared/src/realtime/events.schema.spec.ts @@ -19,6 +19,7 @@ const FIXTURES: Record> = { 'place:created': { place: { id: 3, name: 'Louvre' } }, 'place:updated': { place: { id: 3, name: 'Louvre' } }, 'place:deleted': { placeId: 3 }, + 'tripTags:changed': {}, 'tours:changed': { placeIds: [3] }, 'tours:visits': { assignmentId: 9, visits: [{ assignment_id: 9, station_key: 'abcdef', status: 'visited' }] }, 'assignment:created': { assignment: { id: 9, day_id: 2 } }, @@ -219,9 +220,11 @@ describe('@trek/shared realtime event registry', () => { // writes that send them follow. // 42nd and 43rd user event: mailInbox:changed and mailInbox:settings, the // inbox of forwarded booking mails and its settings card. - expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(80); + // 81st trip event: tripTags:changed, so a tag a member adds to the trip, + // renames or deletes shows the same for everyone on it. + expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(81); expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(43); - expect(TREK_WS_EVENT_NAMES).toHaveLength(123); + expect(TREK_WS_EVENT_NAMES).toHaveLength(124); }); it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => { diff --git a/shared/src/realtime/events.schema.ts b/shared/src/realtime/events.schema.ts index 43ee28400..cfdea3541 100644 --- a/shared/src/realtime/events.schema.ts +++ b/shared/src/realtime/events.schema.ts @@ -65,6 +65,9 @@ export const TREK_WS_EVENTS = { 'place:created': { scope: 'trip', payload: z.object({ place: entity }) }, 'place:updated': { scope: 'trip', payload: z.object({ place: entity }) }, 'place:deleted': { scope: 'trip', payload: z.object({ placeId: id }) }, + // The trip's own tags changed (one added, renamed, recoloured or deleted): every + // client reads the list again and takes the change over into the places it holds. + 'tripTags:changed': { scope: 'trip', payload: empty }, // Invalidate the trip's Tours list; affected ids let peers exclude new Tours immediately. 'tours:changed': { scope: 'trip', payload: z.object({ placeIds: idList.optional() }) }, // CW-03: the stations of a city walk visited or skipped on one of its days, all of them as they are now. diff --git a/shared/src/tag/tag.schema.spec.ts b/shared/src/tag/tag.schema.spec.ts index 515c1fc5e..78eb94583 100644 --- a/shared/src/tag/tag.schema.spec.ts +++ b/shared/src/tag/tag.schema.spec.ts @@ -13,6 +13,13 @@ describe('tagSchema', () => { }).success, ).toBe(true); }); + + it('takes the trip a tag belongs to, null for a personal one', () => { + const tag = { id: 1, user_id: 5, name: 'Beach', color: '#10b981' }; + expect(tagSchema.safeParse({ ...tag, trip_id: 9 }).success).toBe(true); + expect(tagSchema.safeParse({ ...tag, trip_id: null }).success).toBe(true); + expect(tagSchema.safeParse({ ...tag, trip_id: 'nine' }).success).toBe(false); + }); }); describe('createTagRequestSchema', () => { diff --git a/shared/src/tag/tag.schema.ts b/shared/src/tag/tag.schema.ts index f82ca85ee..54b8cd797 100644 --- a/shared/src/tag/tag.schema.ts +++ b/shared/src/tag/tag.schema.ts @@ -11,11 +11,17 @@ import { z } from 'zod'; * * The bespoke 400 ("Tag name is required") and 404 ("Tag not found") messages are * reproduced in the controller so the bodies stay byte-identical. + * + * A tag can also belong to a trip (`trip_id` set, trip-tag.schema.ts). Those never + * show on /api/tags: they are the trip's, read and written under + * /api/trips/:tripId/tags. */ export const tagSchema = z.object({ id: z.number(), user_id: z.number(), + /** The trip the tag belongs to; null for a personal one. Absent on the compact rows a place list carries. */ + trip_id: z.number().nullable().optional(), name: z.string(), color: z.string(), created_at: z.string().optional(), diff --git a/shared/src/tag/trip-tag.schema.spec.ts b/shared/src/tag/trip-tag.schema.spec.ts new file mode 100644 index 000000000..2c3929fd8 --- /dev/null +++ b/shared/src/tag/trip-tag.schema.spec.ts @@ -0,0 +1,61 @@ +import { + TRIP_TAG_NAME_MAX, + tripTagCreateRequestSchema, + tripTagListResponseSchema, + tripTagResponseSchema, + tripTagUpdateRequestSchema, +} from './trip-tag.schema'; + +import { describe, it, expect } from 'vitest'; + +const tag = { id: 4, user_id: 1, trip_id: 9, name: 'Monument', color: '#10b981', created_at: '2026-11-16 09:44:00' }; + +describe('tripTagCreateRequestSchema', () => { + it('trims the name and takes it without a colour', () => { + expect(tripTagCreateRequestSchema.parse({ name: ' Monument ' })).toEqual({ name: 'Monument' }); + }); + + it('refuses a name that is empty once trimmed, or longer than the limit', () => { + expect(tripTagCreateRequestSchema.safeParse({}).success).toBe(false); + expect(tripTagCreateRequestSchema.safeParse({ name: ' ' }).success).toBe(false); + expect(tripTagCreateRequestSchema.safeParse({ name: 'x'.repeat(TRIP_TAG_NAME_MAX) }).success).toBe(true); + expect(tripTagCreateRequestSchema.safeParse({ name: 'x'.repeat(TRIP_TAG_NAME_MAX + 1) }).success).toBe(false); + }); + + it('takes a hex colour and nothing else as one', () => { + expect(tripTagCreateRequestSchema.safeParse({ name: 'Zone', color: '#0ea5e9' }).success).toBe(true); + expect(tripTagCreateRequestSchema.safeParse({ name: 'Zone', color: '#abc' }).success).toBe(true); + expect(tripTagCreateRequestSchema.safeParse({ name: 'Zone', color: 'red' }).success).toBe(false); + expect(tripTagCreateRequestSchema.safeParse({ name: 'Zone', color: 'url(x)' }).success).toBe(false); + }); + + it('drops keys the contract does not name', () => { + expect(tripTagCreateRequestSchema.parse({ name: 'Zone', trip_id: 3, user_id: 7 })).toEqual({ name: 'Zone' }); + }); +}); + +describe('tripTagUpdateRequestSchema', () => { + it('allows either field to be left out', () => { + expect(tripTagUpdateRequestSchema.parse({})).toEqual({}); + expect(tripTagUpdateRequestSchema.parse({ color: '#f59e0b' })).toEqual({ color: '#f59e0b' }); + expect(tripTagUpdateRequestSchema.parse({ name: ' Activity ' })).toEqual({ name: 'Activity' }); + }); + + it('refuses an empty name and a colour that is not hex', () => { + expect(tripTagUpdateRequestSchema.safeParse({ name: '' }).success).toBe(false); + expect(tripTagUpdateRequestSchema.safeParse({ color: 'green' }).success).toBe(false); + }); +}); + +describe('the trip tag responses', () => { + it('describe a tag row with its trip', () => { + expect(tripTagResponseSchema.safeParse({ tag }).success).toBe(true); + expect(tripTagListResponseSchema.safeParse({ tags: [tag, { ...tag, id: 5, name: 'Zone' }] }).success).toBe(true); + }); + + it('fail on a row without a name', () => { + expect(tripTagResponseSchema.safeParse({ tag: { id: 4, user_id: 1, trip_id: 9, color: '#10b981' } }).success).toBe( + false, + ); + }); +}); diff --git a/shared/src/tag/trip-tag.schema.ts b/shared/src/tag/trip-tag.schema.ts new file mode 100644 index 000000000..025901a4e --- /dev/null +++ b/shared/src/tag/trip-tag.schema.ts @@ -0,0 +1,38 @@ +import { hexColorSchema } from '../place/place.schema'; +import { tagSchema } from './tag.schema'; + +import { z } from 'zod'; + +/** + * Trip tag API contract, the single source of truth for /api/trips/:tripId/tags. + * + * A trip tag is a row of `tags` with `trip_id` set. It belongs to the trip rather + * than to one person, so every member reads the same list and anyone who may edit + * the trip's places (`place_edit`) may add to it, rename and delete. `user_id` keeps + * who created it. A name is unique within its trip, whatever its case. + */ + +/** The longest name a trip tag takes. */ +export const TRIP_TAG_NAME_MAX = 50; + +/** A trip tag's name as it is stored: trimmed, never empty. */ +export const tripTagNameSchema = z.string().trim().min(1).max(TRIP_TAG_NAME_MAX); + +export const tripTagCreateRequestSchema = z.object({ + name: tripTagNameSchema, + color: hexColorSchema.optional(), +}); +export type TripTagCreateRequest = z.infer; + +/** Both fields optional: one that is left out keeps its stored value. */ +export const tripTagUpdateRequestSchema = z.object({ + name: tripTagNameSchema.optional(), + color: hexColorSchema.optional(), +}); +export type TripTagUpdateRequest = z.infer; + +export const tripTagResponseSchema = z.object({ tag: tagSchema }); +export type TripTagResponse = z.infer; + +export const tripTagListResponseSchema = z.object({ tags: z.array(tagSchema) }); +export type TripTagListResponse = z.infer; diff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.md index 3a7c00885..bfaf3473d 100644 --- a/wiki/MCP-Tools-and-Resources.md +++ b/wiki/MCP-Tools-and-Resources.md @@ -57,8 +57,8 @@ Requires `places:read` or `places:write` scope. | Tool | Description | |---|---| | `list_places` | List places in a trip, optionally filtered by assignment status, category, tag, or search query. | -| `create_place` | Add a place with name, coordinates, address, category, notes, website, phone, email, and optional `google_place_id` / `osm_id` / `amap_poi_id`. `opening_hours` takes the place's own hours, seven days starting on Monday (`closed`, `open`, `close` as `HH:MM`), shown instead of looked-up hours; `null` clears them. An optional `stop_type` (`fuel`, `charging`, `rest_area`, `campsite`, `restaurant`, `sights` or `hotel`) marks it as a service stop on a drive rather than a destination, so it is left out of the day's stop count; see [Road-Trip](Road-Trip). Leave it unset for an ordinary place. | -| `update_place` | Update any field of an existing place including phone, email, opening hours, transport mode, timing, price and `stop_type`. Pass `stop_type: null` to turn a service stop back into an ordinary place. | +| `create_place` | Add a place with name, coordinates, address, category, notes, website, phone, email, and optional `google_place_id` / `osm_id` / `amap_poi_id`. `opening_hours` takes the place's own hours, seven days starting on Monday (`closed`, `open`, `close` as `HH:MM`), shown instead of looked-up hours; `null` clears them. An optional `stop_type` (`fuel`, `charging`, `rest_area`, `campsite`, `restaurant`, `sights` or `hotel`) marks it as a service stop on a drive rather than a destination, so it is left out of the day's stop count; see [Road-Trip](Road-Trip). Leave it unset for an ordinary place. `tags` takes the ids of the tags the place should carry: tags of the trip (`list_trip_tags`) or personal tags of someone on the trip; any other id is ignored. | +| `update_place` | Update any field of an existing place including phone, email, opening hours, transport mode, timing, price and `stop_type`. Pass `stop_type: null` to turn a service stop back into an ordinary place. `tags` replaces the place's tags with the given ids, `[]` clears them, and leaving it out keeps them. | | `rate_place` | Set or clear your own 1–5 star rating on a place. Every trip member rates independently and the place shows the average. Pass `null` to clear the vote. | | `bulk_update_places` | Update many places at once, applying the same field values (e.g. category, price, transport mode, `stop_type`) to every listed place in a single call. `stop_type: null` turns the listed service stops back into ordinary places. | | `delete_place` | Remove a place from a trip. Also removes all day assignments, the expenses linked to the place and any night booked at it, together with that night's reservation and the reservation's expense. Cannot be undone, so an assistant should warn before deleting a hotel that holds a booking. | @@ -179,10 +179,16 @@ Requires `places:read` or `places:write` scope. | Tool | Description | |---|---| -| `list_tags` | List all tags belonging to the current user. | -| `create_tag` | Create a new tag (user-scoped label for places) with optional hex color. | -| `update_tag` | Update the name or color of an existing tag. | -| `delete_tag` | Delete a tag (removes it from all attached places). | +| `list_tags` | List all personal tags belonging to the current user. A trip's own tags are not among them. | +| `create_tag` | Create a new personal tag (user-scoped label for places) with optional hex color. | +| `update_tag` | Update the name or color of an existing personal tag. | +| `delete_tag` | Delete a personal tag (removes it from all attached places). | +| `list_trip_tags` | List the tags a trip owns, the same list for every member of the trip. | +| `create_trip_tag` | Add a tag to a trip, with a name of up to 50 characters and an optional hex color. A trip has each name once, whatever its capitals: a name it already has returns that tag. Needs the permission to edit the trip's places. | +| `update_trip_tag` | Rename or recolour a tag of a trip, on every place that carries it. A name another tag of the trip has is refused. Needs the permission to edit the trip's places. | +| `delete_trip_tag` | Delete a tag of a trip and take it off every place that carried it. Needs the permission to edit the trip's places. | + +A trip's tags are the ones the app shows and filters by; see [Tags-and-Categories](Tags-and-Categories#trip-tags). Put them on a place with `tags` on `create_place`, `create_and_assign_place` and `update_place`. ### Maps & Weather diff --git a/wiki/Places-and-Search.md b/wiki/Places-and-Search.md index 09b87f24c..0c538229d 100644 --- a/wiki/Places-and-Search.md +++ b/wiki/Places-and-Search.md @@ -12,7 +12,7 @@ The right column of the Plan tab lists every place of the trip. Its head band ha 2. **Search**, which narrows the list to places whose name, address, description or notes contain what you type, and the **Select** button, see [Selecting several places](#selecting-several-places). 3. The filters and the order: - **Show**: **All**, **Unplanned**, **Planned**, and **Tracks** once the trip has one, each with its count. - - **Categories** (the tag icon): tick one or several categories, or **No Category**. A badge on the icon counts the categories in force, and **Clear filter** lifts them. + - **Categories** (the tag icon): tick one or several categories, or **No Category**. A badge on the icon counts the categories in force, and **Clear filter** lifts them. The trip's tags are listed after the categories: a ticked tag keeps the places that carry it, and together with a ticked category both have to hold. See [Trip Tags](Tags-and-Categories#trip-tags). - **Filter by rating** (the star): **All**, or a floor from **5+** down to **1+**. The map's markers follow the floor too. - **Filter by country or region** (the globe): every country the trip's places lie in, with its regions underneath, each with the number of places in it. Pick a country or one region; **All countries** is the default and **Clear filter** goes back to it. The button only appears once the trip spans more than one country or region. - **Sort by**: newest first (**Recently added**, the default), **Oldest first**, by name, **Highest rated** or **Recently changed**. The order applies to the list only, not to the map, and your browser remembers it. @@ -71,6 +71,7 @@ Click **Select** (the tick next to the search field) to switch the list into sel |---|---| | Name | Required. Typed into the head band. | | Category | Pick one, **No Category**, or create a new one with the **+** (a new category starts with the colour `#6366f1` and the `MapPin` icon). | +| Tags | Any number of the trip's tags, each a switch. **New tag** adds one to the trip and ticks it. They are extra labels to filter the places by and never change the marker, see [Trip Tags](Tags-and-Categories#trip-tags). | | Address | Free text. Typing an address does not place the pin: without a pick from the search, a pasted link, coordinates or a point on the map the place has no coordinates and does not appear on the map. The form says so under the field while that is the case. | | Latitude / Longitude | Decimal degrees. See [Entering coordinates manually](#entering-coordinates-manually). | | Start / End | Only when you edit the place from a day: the time of this visit. | @@ -275,7 +276,7 @@ Click a place in the places column, in a day, or on the map, and its inspector o ![The place inspector over the map: the photo, name, address, category and coordinates in its head, then the rating, the notes, the stay booked there under Bookings and the files, with Add to Day, Navigation, Save to Collection, Delete and Edit at its foot](assets/PlaceInspector.png) -- **The head band** shows the photo (a click opens it in a gallery, see [The photo gallery](#the-photo-gallery)), with a green ring while the place is open and a red one while it is closed, the name (double-click it to rename the place), the address on one line with the full address in a tooltip, and pills: **Open** or **Closed**, the category, the time of the visit, the Google rating, the phone number to call, the e-mail address, and the coordinates. A place with an address but no coordinates shows **No coordinates, so not on the map** instead, with a tooltip on how to fix it. The chevron (**Collapse**) folds the inspector to a slim bar with the photo and the name, so the place stays selected and its marker highlighted while you pan the map; **Expand** unfolds it again, and the next place you pick opens in full. **X** closes the inspector and deselects the place. +- **The head band** shows the photo (a click opens it in a gallery, see [The photo gallery](#the-photo-gallery)), with a green ring while the place is open and a red one while it is closed, the name (double-click it to rename the place), the address on one line with the full address in a tooltip, and pills: **Open** or **Closed**, the category, the place's tags, the time of the visit, the Google rating, the phone number to call, the e-mail address, and the coordinates. A place with an address but no coordinates shows **No coordinates, so not on the map** instead, with a tooltip on how to fix it. The chevron (**Collapse**) folds the inspector to a slim bar with the photo and the name, so the place stays selected and its marker highlighted while you pan the map; **Expand** unfolds it again, and the next place you pick opens in full. **X** closes the inspector and deselects the place. - **Rating**: every member's vote, see [Rating a place](#rating-a-place). - **Description**, **Notes** and **Notes for this day**, rendered as Markdown. - **Bookings** pinned to this stop, as small cards with the status, date, time and booking code. For a hotel, the stays booked there are listed too (see [Accommodations](Accommodations)). Click a card (*Open booking*) to open the booking's detail. Next to them, **Participants** says who joins this stop. diff --git a/wiki/Tags-and-Categories.md b/wiki/Tags-and-Categories.md index ddb5a7f7e..3f10091b4 100644 --- a/wiki/Tags-and-Categories.md +++ b/wiki/Tags-and-Categories.md @@ -1,9 +1,10 @@ # Tags and Categories -TREK has two independent labelling systems for places: +TREK has three ways to label a place: -- **Global Place Categories**: admin-managed, shared across every user on the instance (e.g. `Restaurant`, `Museum`). -- **Personal Tags**: user-scoped labels (e.g. `hidden gem`, `kid-friendly`). +- **Global Place Categories**: admin-managed, shared across every user on the instance (e.g. `Restaurant`, `Museum`). A place has one category, and it decides the marker. +- **Trip Tags**: extra labels a trip owns (e.g. `Monument`, `Activity`, `Old Town`). A place can carry any number of them, everybody on the trip sees the same ones, and the places list filters by them. +- **Personal Tags**: user-scoped labels (e.g. `hidden gem`, `kid-friendly`), reached through the API and MCP. ## Global Place Categories @@ -18,7 +19,7 @@ Categories classify places across all trips. Every user sees the same set of cat Categories appear in: - The **place form** when adding or editing a place: the category is the pill in the head band, and the **+** next to it (*New category*) creates one on the spot. -- The **places column** as filter options: the tag icon opens the categories, and a badge on it counts those in force. In select mode, **Change category** gives every ticked place the same category. +- The **places column** as filter options: the tag icon opens the categories, and a badge on it counts those in force. The trip's tags are in the same list, see [Trip Tags](#trip-tags). In select mode, **Change category** gives every ticked place the same category. - **Map markers**: the category icon and color are used to style each place's marker pin. - **Map hover cards**: resting the pointer on a marker shows the category with the place's name and address. - **Saved places** in [Collections](Collections), which use the same set. @@ -31,26 +32,59 @@ A place picked from the search or from a marker of the map's category buttons co > **AI / MCP:** `list_categories` lists the palette; `create_category`, `update_category` and `delete_category` are for admins only. +## Trip Tags + +A category says what kind of place something is, and a place has exactly one. Tags are the extra labels beside it: a cathedral in the category *Sights* can also be tagged `Monument`, `Rainy day` and `Old Town`, and you can then look at the trip through any one of them. A tag never changes the marker: its icon and colour stay the category's. + +**Fields per tag:** + +- **Name**: up to 50 characters. A trip has each name once, whatever its capitals: adding `monument` to a trip that has `Monument` gives you the tag that is there. +- **Color**: a hex value, shown on the tag's mark. A tag added in the app gets one from a small palette in turn; over the API the default is `#10b981`. + +### Who owns them + +A trip tag belongs to the **trip**, not to the person who made it. That is what keeps a shared trip in step: + +- Every member of the trip sees the same tags, on the places and in the pickers. +- Whoever may edit the trip's places (the permission **Add / edit / delete places**, `place_edit`, see [Admin-Permissions](Admin-Permissions)) can add a tag, rename it, recolour it and delete it. Nobody needs to be the one who created it. The app adds tags from the place form; renaming and deleting go through the API and MCP for now. +- The tags go with the trip: deleting the trip deletes them, and a copy of the trip gets its own copies, on the same places. +- Deleting a tag takes it off every place that carried it. +- TREK keeps who added a tag, so an account that is deleted takes the tags it added with it, like the notes it wrote. + +A change to the tags reaches the other members while they have the trip open: the pickers, the pills on the places and the filter follow without a reload. + +### Where they appear + +- **The place form**, on the desktop and on the phone: under **Tags**, every tag of the trip is a switch. Tick the ones the place should carry. To add a new one, type its name into **New tag** and press Enter or the button beside it: the tag is added to the trip and ticked. Saving the place saves its tags. A save that did not touch the tags leaves them alone, so it cannot undo a tag a fellow traveller put on the place in the meantime. +- **The category filter** of the places list: the tags are listed after the categories. Tick one or several: the list, and the map with it, keeps the places that carry one of the ticked tags. With categories ticked as well, both have to hold, so *Sights* and `Monument` together show the sights that are monuments. **Clear filter** lifts the tags too. +- **On the place**: pills beside the category in the head of the place inspector, and chips under the category on the phone's place sheet. + +Putting a tag the trip already has on a place works offline, like any other edit of a place. Adding a new tag needs a connection. + +> **API:** `GET /api/trips/:tripId/tags` lists the trip's tags for any member. `POST /api/trips/:tripId/tags` adds one (or answers the existing tag of that name), `PUT /api/trips/:tripId/tags/:id` renames or recolours it and `DELETE /api/trips/:tripId/tags/:id` removes it, each with the permission to edit places. A place is written with `tags`, the ids of the tags it should carry, always the whole set. Other clients hear a change as the WebSocket event `tripTags:changed`. + +> **AI / MCP:** `list_trip_tags`, `create_trip_tag`, `update_trip_tag` and `delete_trip_tag` manage a trip's tags, and `create_place`, `create_and_assign_place` and `update_place` take `tags`. See [MCP-Tools-and-Resources](MCP-Tools-and-Resources). + ## Personal Tags -Tags are personal labels owned by each user. They attach to individual places via a many-to-many relationship (`place_tags` table), so the same tag can be applied to as many places as you like, and a single place can carry multiple tags. +Personal tags are labels owned by one user rather than by a trip. They attach to individual places via the same many-to-many relationship as trip tags (`place_tags` table), so the same tag can be applied to as many places as you like, and a single place can carry multiple tags. **Fields per tag:** - **Name**: free-form text. - **Color**: hex value displayed alongside the tag name. Default: `#10b981` (emerald). -Tags are owned by their creator, but only the *list* is private. `GET /api/tags` and the `list_tags` MCP tool return only your own tags, and tag names carry no uniqueness constraint, so different users, or even the same user, can create tags with identical names without conflict. +Personal tags are owned by their creator, but only the *list* is private. `GET /api/tags` and the `list_tags` MCP tool return only your own personal tags, never a trip's, and their names carry no uniqueness constraint, so different users, or even the same user, can create tags with identical names without conflict. -A tag you attach to a place is **not** private. It becomes part of that place: the place read-back joins `place_tags` → `tags` with no owner filter, so every trip member gets it from `GET /api/trips/:id/places`, the day and assignment endpoints, and the MCP `list_places` tool and `trek://trips/{tripId}/places` resource, gated by trip access alone. The `?tag=` filter on the places list is likewise not user-scoped, so a member can filter by a co-traveller's tag ID. This is deliberate: a tag is kept as long as its owner is on the trip roster, so a co-traveller's tag is not silently stripped when another member re-saves the place. A tag owned by someone outside the trip is dropped instead. +A tag you attach to a place is **not** private. It becomes part of that place: the place read-back joins `place_tags` → `tags` with no owner filter, so every trip member gets it from `GET /api/trips/:id/places`, the day and assignment endpoints, and the MCP `list_places` tool and `trek://trips/{tripId}/places` resource, gated by trip access alone. The `?tag=` filter on the places list is likewise not user-scoped, so a member can filter by a co-traveller's tag ID. This is deliberate: a personal tag is kept as long as its owner is on the trip roster, so a co-traveller's tag is not silently stripped when another member re-saves the place. A personal tag owned by someone outside the trip is dropped instead, and so is a tag that belongs to another trip. If a trip has a public share link with the map/itinerary section enabled, the tags of places **scheduled on a day** also reach anonymous viewers, trimmed to the tag's ID, name and color, so the owner's user ID never leaves the server. Unscheduled places in the shared place pool carry no tags. -In practice these tags surface through the API and MCP rather than in the app: no view renders a place's tags yet. Deleting a tag automatically removes it from every place it was attached to. +In the app a personal tag on a place looks like any other tag of that place: it is a pill on the place and an entry of the category filter, and the place form keeps it ticked. The form does not offer it for other places, though: what it offers are the trip's own tags. Deleting a tag automatically removes it from every place it was attached to. ### Where to manage them -At the moment tags are exposed primarily through the MCP API: AI assistants connected to your instance can list, create, update, and delete tags (`list_tags`, `create_tag`, `update_tag`, `delete_tag`) and attach them to places through the place endpoints. A dedicated web UI for tag management is not yet available; the filter `tag` parameter on the places API and on the MCP `list_places` tool does support filtering places by a tag ID once one exists (the `trek://trips/{tripId}/places` MCP resource only filters by `assignment`). +Personal tags are managed through the MCP API: AI assistants connected to your instance can list, create, update, and delete them (`list_tags`, `create_tag`, `update_tag`, `delete_tag`) and attach them to places through the place endpoints. The app has no screen for them; the filter `tag` parameter on the places API and on the MCP `list_places` tool filters places by the ID of any tag, a trip's or a personal one (the `trek://trips/{tripId}/places` MCP resource only filters by `assignment`). > **AI / MCP:** See [MCP-Tools-and-Resources](MCP-Tools-and-Resources) for the full tag tool list. @@ -59,7 +93,8 @@ At the moment tags are exposed primarily through the MCP API: AI assistants conn | Use case | Use | |---|---| | Classifying a place by type (Restaurant, Museum, Hiking Trail…) | **Category** | -| Personal labels you want to apply to specific places | **Tag** | +| Extra labels the whole trip shares and filters by (Monument, Rainy day, Old Town…) | **Trip tag** | +| Labels of your own that follow you from trip to trip, set through an AI assistant | **Personal tag** | ## See also