mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 02:56:10 +00:00
feat(places): tags on places, owned by the trip
A place keeps its one category, which decides its marker, and can now carry any number of tags as extra labels to filter by. - Tags belong to the trip (tags.trip_id): every member sees the same list and whoever may edit the trip's places adds, renames and deletes. Personal tags stay what they were. - The place form picks them on desktop and mobile through one shared hook, usePlaceTags, and can add a new tag to the trip on the spot. - The existing category filter of the places list lists the tags as well. - Tags show on the place (inspector pills, phone place sheet); the marker is untouched. - MCP: create_place, create_and_assign_place and update_place take `tags`, and list/create/update/delete_trip_tag manage a trip's tags. - /api/trips/:tripId/tags and the tripTags:changed event keep every client of the trip in step.
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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<TripTagListResponse> =>
|
||||
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<TripTagResponse> =>
|
||||
apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data),
|
||||
};
|
||||
@@ -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 {
|
||||
|
||||
@@ -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(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
|
||||
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(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
|
||||
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(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
|
||||
|
||||
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(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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 && <PlaceFormTags tags={S.tagField} t={t} />}
|
||||
|
||||
{/* 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
|
||||
|
||||
@@ -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> = {}): 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(<PlaceFormTags tags={field()} t={t} />);
|
||||
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(<PlaceFormTags tags={tags} t={t} />);
|
||||
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(<PlaceFormTags tags={tags} t={t} />);
|
||||
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(<PlaceFormTags tags={idle} t={t} />);
|
||||
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(<PlaceFormTags tags={ready} t={t} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
|
||||
expect(ready.addNew).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -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, string | number>) => 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 (
|
||||
<DialogSection label={t('places.tags')}>
|
||||
<div role="group" aria-label={t('places.tags')} className={ROW}>
|
||||
{tags.options.map((tag) => (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
aria-pressed={tag.on}
|
||||
onClick={() => tags.toggle(tag.id)}
|
||||
className={`${CHIP} ${tag.on ? CHIP_ON : CHIP_OFF}`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<TagIcon
|
||||
size={12}
|
||||
strokeWidth={2.2}
|
||||
className="flex-none"
|
||||
style={{ color: tag.on ? undefined : tag.color }}
|
||||
/>
|
||||
<span className="truncate">{tag.name}</span>
|
||||
</button>
|
||||
))}
|
||||
<span className={NEW_TAG}>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => 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')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={ADD_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</DialogSection>
|
||||
);
|
||||
}
|
||||
@@ -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(<PlaceInspector {...defaultProps} place={{ ...place, id: 716, category_id: cat.id, tags }} />);
|
||||
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' }] },
|
||||
|
||||
@@ -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}
|
||||
</span>
|
||||
)}
|
||||
{tags.map((tag) => (
|
||||
<span key={tag.id} className={HEAD_PILL} style={fs(10.5)}>
|
||||
<TagIcon size={11} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
{time && <TimePill>{time}</TimePill>}
|
||||
{rating != null && rating > 0 && (
|
||||
<span className={HEAD_PILL} style={fs(10.5)}>
|
||||
|
||||
@@ -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<typeof userEvent.setup>;
|
||||
|
||||
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(<PlacesSidebar {...props} />);
|
||||
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(<PlacesSidebar {...props} />);
|
||||
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(<PlacesSidebar {...props} />);
|
||||
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(<PlacesSidebar {...props} />);
|
||||
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(<PlacesSidebar {...props} categories={[]} />);
|
||||
await openFilter(user);
|
||||
expect(screen.getByRole('button', { name: 'Monument' })).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
seedStore(useTripStore, { tripTags: [] });
|
||||
render(<PlacesSidebar {...props} categories={[]} places={[garden]} />);
|
||||
expect(screen.queryByRole('button', { name: 'Categories' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<FilterDropdown name={t('categories.title')} label={label} active={categoryFilters.size > 0} badge={categoryFilters.size}
|
||||
icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
|
||||
<FilterDropdown name={t('categories.title')} label={categoryFilterLabel(S, tags)} active={categoryFilters.size > 0}
|
||||
badge={categoryFilters.size} icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
|
||||
{categories.map(c => (
|
||||
<CategoryChoice
|
||||
key={c.id}
|
||||
@@ -282,6 +292,21 @@ function CategoryFilter(S: SidebarState) {
|
||||
label={t('places.noCategory')}
|
||||
/>
|
||||
)}
|
||||
{/* The tags, in the same list: a place has one category and any number of these. */}
|
||||
{tags.length > 0 && <Eyebrow className="px-1.5 pb-1 pt-2">{t('places.tags')}</Eyebrow>}
|
||||
{tags.map(tag => (
|
||||
<CategoryChoice
|
||||
key={tagFilterKey(tag.id)}
|
||||
on={categoryFilters.has(tagFilterKey(tag.id))}
|
||||
onClick={() => toggleCategoryFilter(tagFilterKey(tag.id))}
|
||||
tile={(
|
||||
<span className="grid h-[22px] w-[22px] flex-none place-items-center rounded-[7px] bg-surface-tertiary text-content-faint">
|
||||
<Tag size={11} strokeWidth={2.2} style={{ color: tag.color }} />
|
||||
</span>
|
||||
)}
|
||||
label={tag.name}
|
||||
/>
|
||||
))}
|
||||
{categoryFilters.size > 0 && (
|
||||
<button type="button" onClick={() => setCategoryFilters(new Set())}
|
||||
className="mt-1 flex w-full items-center gap-1.5 rounded-[9px] border-t border-edge-faint px-1.5 pb-1 pt-2 text-start font-semibold text-content-muted hover:text-content"
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// FE-PLANNER-PLTAGS-001 to FE-PLANNER-PLTAGS-008: the tags of the place form, the one logic
|
||||
// path behind the desktop dialog and the phone sheet.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { useState, type KeyboardEvent } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildTag } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { useTripStore, type TripStoreState } from '../../store/tripStore';
|
||||
import type { Place, Tag } from '../../types';
|
||||
import { DEFAULT_FORM } from './PlaceFormModal.helpers';
|
||||
import { usePlaceTags } from './usePlaceTags';
|
||||
|
||||
const t = (key: string) => key;
|
||||
const makeToast = () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() });
|
||||
|
||||
const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' });
|
||||
const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' });
|
||||
/** A traveller's personal tag, put on the place through the API: the trip does not list it. */
|
||||
const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' };
|
||||
|
||||
const addTripTag = vi.fn<TripStoreState['addTripTag']>();
|
||||
let toast: ReturnType<typeof makeToast>;
|
||||
|
||||
function setOnline(online: boolean): void {
|
||||
Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
setOnline(true);
|
||||
toast = makeToast();
|
||||
addTripTag.mockReset();
|
||||
useTripStore.setState({ tripTags: [monument, zone], addTripTag });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setOnline(true);
|
||||
});
|
||||
|
||||
/** The hook over a form of its own, as both shells run it. */
|
||||
function setup(place: Pick<Place, 'tags'> | null = null) {
|
||||
return renderHook(() => {
|
||||
const [form, setForm] = useState(DEFAULT_FORM);
|
||||
return { form, field: usePlaceTags({ tripId: 5, place, tags: form.tags, setForm, t, toast }) };
|
||||
});
|
||||
}
|
||||
|
||||
function key(name: string) {
|
||||
const preventDefault = vi.fn();
|
||||
return { event: { key: name, preventDefault } as unknown as KeyboardEvent<HTMLInputElement>, preventDefault };
|
||||
}
|
||||
|
||||
describe('usePlaceTags', () => {
|
||||
it('FE-PLANNER-PLTAGS-001: offers the tags of the trip by name, none ticked for a new place', () => {
|
||||
const { result } = setup();
|
||||
expect(result.current.field.options).toEqual([
|
||||
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
|
||||
{ id: 8, name: 'Zone', color: '#10b981', on: false },
|
||||
]);
|
||||
// Nothing was touched, so the save has no tags to send.
|
||||
expect(result.current.form.tags).toBeUndefined();
|
||||
expect(result.current.field.canAdd).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-002: ticks what the place carries and keeps a personal tag of it on offer', () => {
|
||||
const { result } = setup({ tags: [{ id: 8, name: 'Zone (old name)' }, personal] });
|
||||
expect(result.current.field.options).toEqual([
|
||||
{ id: 50, name: 'Hidden gem', color: '#f59e0b', on: true },
|
||||
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
|
||||
// The trip's own name and colour, not the copy on the place.
|
||||
{ id: 8, name: 'Zone', color: '#10b981', on: true },
|
||||
]);
|
||||
expect(result.current.form.tags).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-003: a tick writes the whole set into the form, starting from what the place carries', () => {
|
||||
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }, personal] });
|
||||
|
||||
act(() => result.current.field.toggle(7));
|
||||
expect(result.current.form.tags).toEqual([8, 50, 7]);
|
||||
expect(result.current.field.options.map((tag) => tag.on)).toEqual([true, true, true]);
|
||||
|
||||
act(() => result.current.field.toggle(50));
|
||||
expect(result.current.form.tags).toEqual([8, 7]);
|
||||
|
||||
act(() => result.current.field.toggle(8));
|
||||
act(() => result.current.field.toggle(7));
|
||||
// Every tag off is an answer too: the save takes the tags off the place.
|
||||
expect(result.current.form.tags).toEqual([]);
|
||||
expect(result.current.field.options.map((tag) => tag.on)).toEqual([false, false, false]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-004: a typed name becomes a tag of the trip, ticked, and the field is empty again', async () => {
|
||||
const viewpoint = buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' });
|
||||
addTripTag.mockResolvedValue(viewpoint);
|
||||
const { result } = setup();
|
||||
|
||||
act(() => result.current.field.setName(' Viewpoint '));
|
||||
expect(result.current.field.canAdd).toBe(true);
|
||||
await act(() => result.current.field.addNew());
|
||||
|
||||
expect(addTripTag).toHaveBeenCalledWith(5, { name: 'Viewpoint', color: expect.stringMatching(/^#[0-9a-f]{6}$/) });
|
||||
expect(result.current.form.tags).toEqual([9]);
|
||||
expect(result.current.field.name).toBe('');
|
||||
expect(result.current.field.saving).toBe(false);
|
||||
expect(toast.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-005: a name the trip has already ticks that tag once, and an empty name asks nothing', async () => {
|
||||
addTripTag.mockResolvedValue(zone);
|
||||
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }] });
|
||||
|
||||
act(() => result.current.field.setName(' '));
|
||||
expect(result.current.field.canAdd).toBe(false);
|
||||
await act(() => result.current.field.addNew());
|
||||
expect(addTripTag).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.field.setName('zone'));
|
||||
await act(() => result.current.field.addNew());
|
||||
expect(result.current.form.tags).toEqual([8]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-006: a tag that could not be added says so and keeps the name; offline it asks for a connection', async () => {
|
||||
addTripTag.mockRejectedValue(new Error('refused'));
|
||||
const { result } = setup();
|
||||
act(() => result.current.field.setName('Viewpoint'));
|
||||
|
||||
await act(() => result.current.field.addNew());
|
||||
expect(toast.error).toHaveBeenLastCalledWith('places.tagCreateError');
|
||||
expect(result.current.field.name).toBe('Viewpoint');
|
||||
expect(result.current.field.saving).toBe(false);
|
||||
expect(result.current.form.tags).toBeUndefined();
|
||||
|
||||
setOnline(false);
|
||||
await act(() => result.current.field.addNew());
|
||||
expect(toast.error).toHaveBeenLastCalledWith('common.needsConnection');
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-007: Enter in the name field adds the tag instead of saving the place; an empty field leaves the key alone', async () => {
|
||||
addTripTag.mockResolvedValue(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
|
||||
const { result } = setup();
|
||||
|
||||
const empty = key('Enter');
|
||||
act(() => result.current.field.handleNameKey(empty.event));
|
||||
expect(empty.preventDefault).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.field.setName('Viewpoint'));
|
||||
const letter = key('a');
|
||||
act(() => result.current.field.handleNameKey(letter.event));
|
||||
expect(letter.preventDefault).not.toHaveBeenCalled();
|
||||
expect(addTripTag).not.toHaveBeenCalled();
|
||||
|
||||
const enter = key('Enter');
|
||||
act(() => result.current.field.handleNameKey(enter.event));
|
||||
await waitFor(() => expect(result.current.form.tags).toEqual([9]));
|
||||
expect(enter.preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(addTripTag).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-PLTAGS-008: a tick made while a tag is on its way is kept, and a second request waits for the first', async () => {
|
||||
let answer: (tag: Tag) => void = () => undefined;
|
||||
addTripTag.mockReturnValue(new Promise<Tag>((resolve) => (answer = resolve)));
|
||||
const { result } = setup();
|
||||
act(() => result.current.field.setName('Viewpoint'));
|
||||
|
||||
let pending: Promise<void> = Promise.resolve();
|
||||
act(() => {
|
||||
pending = result.current.field.addNew();
|
||||
});
|
||||
expect(result.current.field.saving).toBe(true);
|
||||
expect(result.current.field.canAdd).toBe(false);
|
||||
await act(() => result.current.field.addNew());
|
||||
expect(addTripTag).toHaveBeenCalledTimes(1);
|
||||
|
||||
act(() => result.current.field.toggle(7));
|
||||
await act(async () => {
|
||||
answer(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
|
||||
await pending;
|
||||
});
|
||||
expect(result.current.form.tags).toEqual([7, 9]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useMemo, useState, type Dispatch, type KeyboardEvent, type SetStateAction } from 'react';
|
||||
|
||||
import type { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Place } from '../../types';
|
||||
import { offlineOr } from '../../utils/needsConnection';
|
||||
import { nextTagColor, placeTagIds, tagChoices } from '../../utils/placeTags';
|
||||
import type { useToast } from '../shared/Toast';
|
||||
import type { PlaceFormData } from './PlaceFormModal.helpers';
|
||||
|
||||
type Translate = ReturnType<typeof useTranslation>['t'];
|
||||
type Toast = ReturnType<typeof useToast>;
|
||||
|
||||
interface PlaceTagsOptions {
|
||||
tripId: number | string;
|
||||
/** The place being edited, for the tags it carries already; none while a place is being added. */
|
||||
place: Pick<Place, 'tags'> | null | undefined;
|
||||
/** The form's own tags: absent until one is ticked or unticked. */
|
||||
tags: PlaceFormData['tags'];
|
||||
setForm: Dispatch<SetStateAction<PlaceFormData>>;
|
||||
t: Translate;
|
||||
toast: Toast;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the place form: the one logic path behind the desktop dialog and the
|
||||
* phone sheet, which draw their own markup over it. It offers the trip's tags and any
|
||||
* personal tag the place carries already, keeps which of them are ticked in the form
|
||||
* itself, so the save sends them, and adds a new tag to the trip, ticked straight away.
|
||||
*/
|
||||
export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTagsOptions) {
|
||||
const tripTags = useTripStore((s) => s.tripTags);
|
||||
const addTripTag = useTripStore((s) => s.addTripTag);
|
||||
const carried = place?.tags;
|
||||
const saved = useMemo(() => placeTagIds(carried), [carried]);
|
||||
const selected = tags ?? saved;
|
||||
const options = useMemo(
|
||||
() => tagChoices(tripTags, carried).map((tag) => ({ ...tag, on: selected.includes(tag.id) })),
|
||||
[tripTags, carried, selected]
|
||||
);
|
||||
const [name, setName] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
/** Changes the ticked set from what it is when the change lands, not from what it was when it was asked for. */
|
||||
const change = (next: (ids: number[]) => number[]) =>
|
||||
setForm((prev) => ({ ...prev, tags: next(prev.tags ?? saved) }));
|
||||
|
||||
const toggle = (id: number) =>
|
||||
change((ids) => (ids.includes(id) ? ids.filter((other) => other !== id) : [...ids, id]));
|
||||
|
||||
/** The typed name becomes a tag of the trip, or is the one it has already, and is ticked. */
|
||||
const addNew = async () => {
|
||||
const wanted = name.trim();
|
||||
if (!wanted || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const tag = await addTripTag(tripId, { name: wanted, color: nextTagColor(tripTags) });
|
||||
change((ids) => (ids.includes(tag.id) ? ids : [...ids, tag.id]));
|
||||
setName('');
|
||||
} catch {
|
||||
toast.error(offlineOr(t, t('places.tagCreateError')));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** Enter in the name field adds the tag; with a name typed it never reaches the place's own save. */
|
||||
const handleNameKey = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter' || !name.trim()) return;
|
||||
e.preventDefault();
|
||||
void addNew();
|
||||
};
|
||||
|
||||
return { options, toggle, name, setName, saving, canAdd: !!name.trim() && !saving, addNew, handleNameKey };
|
||||
}
|
||||
|
||||
export type PlaceTagsField = ReturnType<typeof usePlaceTags>;
|
||||
@@ -1,9 +1,9 @@
|
||||
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-016: the places pool's search, filters and
|
||||
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-017: the places pool's search, filters and
|
||||
// multi-select behind the desktop sidebar ('exit') and the phone browser ('prune').
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildPlace } from '../../../tests/helpers/factories';
|
||||
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { collectionsApi } from '../../api/collections';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
placesFilterTabs,
|
||||
poolHasTracks,
|
||||
usePlacesCategoryFilter,
|
||||
usePlacesFilterTags,
|
||||
usePlacesPool,
|
||||
type PlacesPoolOptions,
|
||||
} from './usePlacesPool';
|
||||
@@ -287,4 +288,29 @@ describe('usePlacesPool', () => {
|
||||
act(() => result.current.setSelectedIds(new Set([12345])));
|
||||
expect(result.current.selectedIds.size).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-POOL-017: the filter offers the tags of the trip and any other a listed place carries, by name', () => {
|
||||
const monument = buildTag({ id: 7, name: 'Monument', color: '#6366f1' });
|
||||
const zone = buildTag({ id: 8, name: 'Zone', color: 'not a colour' });
|
||||
seedStore(useTripStore, { tripTags: [zone, monument] });
|
||||
const places = [
|
||||
buildPlace({ tags: [{ id: 7, name: 'Monument (old name)' }] }),
|
||||
buildPlace({ tags: [{ id: 50, name: 'Hidden gem', color: '#f59e0b' }] }),
|
||||
buildPlace(),
|
||||
];
|
||||
const { result, rerender } = renderHook((listed: typeof places) => usePlacesFilterTags(listed), {
|
||||
initialProps: places,
|
||||
});
|
||||
expect(result.current).toEqual([
|
||||
{ id: 50, name: 'Hidden gem', color: '#f59e0b' },
|
||||
// The trip's own name, not the copy on the place.
|
||||
{ id: 7, name: 'Monument', color: '#6366f1' },
|
||||
// A colour that is no plain hex value is left out: the row keeps the colour of its text.
|
||||
{ id: 8, name: 'Zone', color: undefined },
|
||||
]);
|
||||
// The same places and tags are the same list, so a row does not redraw for nothing.
|
||||
const first = result.current;
|
||||
rerender(places);
|
||||
expect(result.current).toBe(first);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Place } from '../../types';
|
||||
import { offlineOr } from '../../utils/needsConnection';
|
||||
import { tagChoices } from '../../utils/placeTags';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
/** What the pool shows: everything, what is not on a day yet, what is, or the tracks. */
|
||||
@@ -30,8 +31,8 @@ export function placesFilterTabs(t: Translate, hasTracks: boolean) {
|
||||
|
||||
/**
|
||||
* The category filter of the places pool: a set of category ids (plus the
|
||||
* no-category bucket), many at once. It lives in the trip store, so the list
|
||||
* and the map markers filter on the same values (#1541).
|
||||
* no-category bucket) and of tags, many at once. It lives in the trip store, so
|
||||
* the list and the map markers filter on the same values (#1541).
|
||||
*/
|
||||
export function usePlacesCategoryFilter() {
|
||||
const categoryFilters = useTripStore((s) => s.placesCategoryFilter);
|
||||
@@ -45,6 +46,15 @@ export function usePlacesCategoryFilter() {
|
||||
return { categoryFilters, setCategoryFilters, toggleCategoryFilter };
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags the category filter offers under the categories, for both shells: the
|
||||
* trip's own, and any other tag one of the listed places carries.
|
||||
*/
|
||||
export function usePlacesFilterTags(places: Place[]) {
|
||||
const tripTags = useTripStore((s) => s.tripTags);
|
||||
return useMemo(() => tagChoices(tripTags, ...places.map((place) => place.tags)), [tripTags, places]);
|
||||
}
|
||||
|
||||
export interface PlacesPoolOptions {
|
||||
tripId: number;
|
||||
/** Every place of the trip: a selected place that is gone from here is gone. */
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Tag } from '@trek/shared';
|
||||
import { offlineDb } from './offlineDb';
|
||||
|
||||
/** The trip's tags as the server last listed them; none while the device never read them. */
|
||||
export async function cachedTripTags(tripId: number): Promise<Tag[]> {
|
||||
return (await offlineDb.tripTags.get(tripId))?.tags ?? [];
|
||||
}
|
||||
|
||||
/** Keeps the trip's tags as the server listed them. */
|
||||
export async function cacheTripTags(tripId: number, tags: Tag[]): Promise<void> {
|
||||
await offlineDb.tripTags.put({ tripId, tags });
|
||||
}
|
||||
@@ -70,6 +70,16 @@ interface CachedTourDraft {
|
||||
draft: TourDraft;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags a trip owns, as the server last listed them: one row per trip, so the
|
||||
* place form and the category filter still offer them offline. Not the `tags`
|
||||
* table, which holds the signed-in user's personal ones.
|
||||
*/
|
||||
interface CachedTripTags {
|
||||
tripId: number;
|
||||
tags: Tag[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A road route as the router answered it, kept on the device so a trip opens
|
||||
* with its roads drawn instead of asking the router for every leg again (#2794).
|
||||
@@ -293,6 +303,7 @@ export class TrekOfflineDb extends Dexie {
|
||||
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
|
||||
tourDrafts!: Table<CachedTourDraft, number>;
|
||||
routeCache!: Table<CachedRoute, string>;
|
||||
tripTags!: Table<CachedTripTags, number>;
|
||||
|
||||
constructor(name: string = ANON_DB_NAME) {
|
||||
super(name);
|
||||
@@ -385,6 +396,10 @@ export class TrekOfflineDb extends Dexie {
|
||||
// whole route shown opens drawn instead of re-routing every leg (#2794). Not per
|
||||
// trip: the same waypoints are the same road in any trip; `savedAt` to prune.
|
||||
this.version(14).stores({ routeCache: 'key, savedAt' });
|
||||
|
||||
// v15: the tags a trip owns, one list per trip, so they are offered offline
|
||||
// and go with the trip.
|
||||
this.version(15).stores({ tripTags: 'tripId' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,10 +701,12 @@ export async function clearTripData(tripId: number): Promise<void> {
|
||||
offlineDb.ferrataTiles,
|
||||
offlineDb.tourStationVisits,
|
||||
offlineDb.tourDrafts,
|
||||
offlineDb.tripTags,
|
||||
],
|
||||
async () => {
|
||||
await offlineDb.roadtripPreferences.delete(tripId);
|
||||
await offlineDb.tourDrafts.delete(tripId);
|
||||
await offlineDb.tripTags.delete(tripId);
|
||||
await offlineDb.budgetSettlements.delete(tripId);
|
||||
await offlineDb.days.where('trip_id').equals(tripId).delete();
|
||||
await offlineDb.places.where('trip_id').equals(tripId).delete();
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// FE-MOB-PFILTER-TAGS-001 to FE-MOB-PFILTER-TAGS-003: the tags in the phone's category filter,
|
||||
// which ticks them into the same set as the categories.
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildCategory, buildPlace, buildTag } from '../../../../../tests/helpers/factories';
|
||||
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../../../tests/helpers/store';
|
||||
import { useTripStore } from '../../../../store/tripStore';
|
||||
import { MCategoryFilterList } from './MPlacesFilterControls';
|
||||
|
||||
const park = buildCategory({ id: 4, name: 'Park' });
|
||||
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
|
||||
const tower = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }] });
|
||||
// A traveller's personal tag, put on the place through the API: the trip does not list it.
|
||||
const market = buildPlace({ category_id: 4, tags: [{ id: 50, name: 'Hidden gem' }] });
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
useTripStore.setState({ tripTags: [monument] });
|
||||
});
|
||||
|
||||
describe('MCategoryFilterList: tags', () => {
|
||||
it('FE-MOB-PFILTER-TAGS-001: lists the tags after the categories, the ones of the trip and any other a place carries', () => {
|
||||
render(<MCategoryFilterList categories={[park]} places={[tower, market]} />);
|
||||
expect(screen.getAllByRole('checkbox').map((row) => row.textContent)).toEqual(['Park', 'Hidden gem', 'Monument']);
|
||||
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-PFILTER-TAGS-002: a tag is ticked into the set the categories filter through, and out of it again', () => {
|
||||
render(<MCategoryFilterList categories={[park]} places={[tower, market]} />);
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Monument' }));
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Park' }));
|
||||
expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['tag:7', '4']);
|
||||
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'true');
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Monument' }));
|
||||
expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['4']);
|
||||
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-PFILTER-TAGS-003: a trip without tags lists the categories alone', () => {
|
||||
useTripStore.setState({ tripTags: [] });
|
||||
render(<MCategoryFilterList categories={[park]} places={[buildPlace({ category_id: 4 })]} />);
|
||||
expect(screen.getAllByRole('checkbox').map((row) => row.textContent)).toEqual(['Park']);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ReactNode } from 'react'
|
||||
import { Check, MapPin, Star } from 'lucide-react'
|
||||
import { Check, MapPin, Star, Tag as TagIcon } from 'lucide-react'
|
||||
import MChip from '../../../components/MChip'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
|
||||
import { RATING_FLOORS, UNCATEGORIZED } from '../../../../utils/placesFilter'
|
||||
import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../../../utils/placesFilter'
|
||||
import { useTranslation } from '../../../../i18n'
|
||||
import { usePlacesCategoryFilter } from '../../../../components/Planner/usePlacesPool'
|
||||
import { usePlacesCategoryFilter, usePlacesFilterTags } from '../../../../components/Planner/usePlacesPool'
|
||||
import type { Category, Place } from '../../../../types'
|
||||
|
||||
/**
|
||||
@@ -48,10 +48,14 @@ function CategoryFilterRow({ checked, onToggle, label, children }: {
|
||||
)
|
||||
}
|
||||
|
||||
/** The trip's categories as a multi-select, plus "no category" while a place has none. */
|
||||
/**
|
||||
* The trip's categories as a multi-select, plus "no category" while a place has
|
||||
* none, and after them the tags, which filter through the same set.
|
||||
*/
|
||||
export function MCategoryFilterList({ categories, places }: { categories: Category[]; places: Place[] }) {
|
||||
const { t } = useTranslation()
|
||||
const { categoryFilters, toggleCategoryFilter: toggle } = usePlacesCategoryFilter()
|
||||
const tags = usePlacesFilterTags(places)
|
||||
return (
|
||||
<>
|
||||
{categories.map(c => {
|
||||
@@ -76,6 +80,16 @@ export function MCategoryFilterList({ categories, places }: { categories: Catego
|
||||
<MapPin size={14} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</CategoryFilterRow>
|
||||
)}
|
||||
{tags.map(tag => (
|
||||
<CategoryFilterRow
|
||||
key={tagFilterKey(tag.id)}
|
||||
checked={categoryFilters.has(tagFilterKey(tag.id))}
|
||||
onToggle={() => toggle(tagFilterKey(tag.id))}
|
||||
label={tag.name}
|
||||
>
|
||||
<TagIcon size={14} strokeWidth={2} className="flex-none text-m-faint" style={{ color: tag.color }} />
|
||||
</CategoryFilterRow>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,12 +12,14 @@ import {
|
||||
type PlaceFormData,
|
||||
} from '../../../../components/Planner/PlaceFormModal.helpers'
|
||||
import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'
|
||||
import { usePlaceTags } from '../../../../components/Planner/usePlaceTags'
|
||||
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
|
||||
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
|
||||
import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
|
||||
import PlCategoryPicker from './PlCategoryPicker'
|
||||
import { PlTagPicker } from './PlTags'
|
||||
import PlTimeFields from './PlTimeFields'
|
||||
import PlFileAttach from './PlFileAttach'
|
||||
import MLinkedCosts from './MLinkedCosts'
|
||||
@@ -91,6 +93,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
// the edit chrome doesn't flip to "add" while fading out.
|
||||
const [sheetPlace, setSheetPlace] = useState<Place | null>(null)
|
||||
const [sheetAssignmentId, setSheetAssignmentId] = useState<number | null>(null)
|
||||
const tagField = usePlaceTags({ tripId: planner.tripId, place: sheetPlace, tags: form.tags, setForm, t, toast })
|
||||
|
||||
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
|
||||
const { language, locale } = useTranslation()
|
||||
@@ -342,6 +345,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-3 uppercase">{t('places.formCategory')}</Eyebrow>
|
||||
<PlCategoryPicker planner={planner} value={form.category_id} onChange={id => handleChange('category_id', id)} />
|
||||
<PlTagPicker tags={tagField} t={t} />
|
||||
|
||||
{/* Times live per day-assignment — only editable when one is in context.
|
||||
Same for the day-specific note (#2163). */}
|
||||
|
||||
@@ -31,6 +31,7 @@ import type { Assignment, Day, Reservation, TripMember } from '../../../../types
|
||||
import PlacePhotoGallery from '../../../../components/Planner/PlacePhotoGallery'
|
||||
import { ActionCircle, Eyebrow, INNER_CLS } from './MTripSheetUi'
|
||||
import { FormSheetBody } from './PlSheetChrome'
|
||||
import { PlTagChips } from './PlTags'
|
||||
|
||||
/**
|
||||
* Place inspector sheet (glass card), opened by the current place selection —
|
||||
@@ -235,6 +236,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
|
||||
<span dir="auto" className="truncate">{category.name}</span>
|
||||
</span>
|
||||
)}
|
||||
<PlTagChips tags={place.tags} />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// FE-MOB-PLTAGS-001 to FE-MOB-PLTAGS-005: the phone's tag markup, which is the picker of the
|
||||
// place form (its state is usePlaceTags', tested on its own) and the chips of the place sheet.
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
|
||||
import type { PlaceTagsField } from '../../../../components/Planner/usePlaceTags';
|
||||
import { PlTagChips, PlTagPicker } from './PlTags';
|
||||
|
||||
const t = (key: string) => key;
|
||||
|
||||
function field(overrides: Partial<PlaceTagsField> = {}): 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('PlTagPicker', () => {
|
||||
it('FE-MOB-PLTAGS-001: labels the tags and shows each as a chip that says whether it is on', () => {
|
||||
render(<PlTagPicker tags={field()} t={t} />);
|
||||
expect(screen.getAllByText('places.tags').length).toBeGreaterThan(0);
|
||||
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-MOB-PLTAGS-002: a tap on a chip switches that tag', () => {
|
||||
const tags = field();
|
||||
render(<PlTagPicker tags={tags} t={t} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Monument' }));
|
||||
expect(tags.toggle).toHaveBeenCalledTimes(1);
|
||||
expect(tags.toggle).toHaveBeenCalledWith(7);
|
||||
});
|
||||
|
||||
it('FE-MOB-PLTAGS-003: a new tag is typed and confirmed, and the confirm waits for a name', () => {
|
||||
const idle = field();
|
||||
const { unmount } = render(<PlTagPicker tags={idle} t={t} />);
|
||||
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
|
||||
const input = screen.getByRole('textbox', { name: 'places.newTag' });
|
||||
fireEvent.change(input, { target: { value: 'Viewpoint' } });
|
||||
expect(idle.setName).toHaveBeenCalledWith('Viewpoint');
|
||||
fireEvent.keyDown(input, { key: 'Enter' });
|
||||
expect(idle.handleNameKey).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
|
||||
const ready = field({ name: 'Viewpoint', canAdd: true });
|
||||
render(<PlTagPicker tags={ready} t={t} />);
|
||||
expect(screen.getByRole('textbox', { name: 'places.newTag' })).toHaveValue('Viewpoint');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
|
||||
expect(ready.addNew).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlTagChips', () => {
|
||||
it('FE-MOB-PLTAGS-004: shows the tags a place carries, each once and by name', () => {
|
||||
const { container } = render(
|
||||
<PlTagChips
|
||||
tags={[
|
||||
{ id: 8, name: 'Zone', color: '#10b981' },
|
||||
{ id: 7, name: 'Monument' },
|
||||
{ id: 8, name: 'Zone' },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByText('Monument')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Zone')).toHaveLength(1);
|
||||
expect(container.textContent).toBe('MonumentZone');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLTAGS-005: draws nothing for a place without tags, or with tags that have no name yet', () => {
|
||||
const { container, rerender } = render(<PlTagChips tags={undefined} />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
rerender(<PlTagChips tags={[{ id: 9 }]} />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
|
||||
import { Check, Tag as TagIcon } from 'lucide-react';
|
||||
|
||||
import type { PlaceTagsField } from '../../../../components/Planner/usePlaceTags';
|
||||
import type { Place } from '../../../../types';
|
||||
import { tagChoices } from '../../../../utils/placeTags';
|
||||
import MChip from '../../../components/MChip';
|
||||
import { Eyebrow, FIELD_CLS } from './PlSheetChrome';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
const LABEL = 'mb-[6px] mt-3 uppercase';
|
||||
const PICKER = 'flex flex-wrap gap-[6px]';
|
||||
const NEW_TAG = 'mt-2 flex items-center gap-2';
|
||||
const CONFIRM =
|
||||
'flex h-10 w-10 flex-none items-center justify-center rounded-[12px] bg-m-act text-m-actfg disabled:opacity-40';
|
||||
const CHIPS = 'mt-[6px] flex flex-wrap gap-1';
|
||||
const CHIP =
|
||||
'inline-flex max-w-full items-center gap-1 rounded-full border border-[color:var(--m-faint)] px-2 py-[2px] font-geist text-caption font-semibold text-m-muted';
|
||||
|
||||
/**
|
||||
* The tags of the place form on the phone: its label, every tag on offer as a chip to
|
||||
* switch on or off, and a field that adds a new one to the trip. The state is
|
||||
* usePlaceTags', run by the sheet; this is its markup.
|
||||
*/
|
||||
export function PlTagPicker({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
|
||||
return (
|
||||
<>
|
||||
<Eyebrow className={LABEL}>{t('places.tags')}</Eyebrow>
|
||||
<div role="group" aria-label={t('places.tags')} className={PICKER}>
|
||||
{tags.options.map((tag) => (
|
||||
<MChip key={tag.id} pressable active={tag.on} onClick={() => tags.toggle(tag.id)}>
|
||||
<TagIcon
|
||||
size={12}
|
||||
strokeWidth={2.2}
|
||||
className="flex-none"
|
||||
style={{ color: tag.on ? undefined : tag.color }}
|
||||
/>
|
||||
{tag.name}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
<div className={NEW_TAG}>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={FIELD_CLS}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void tags.addNew()}
|
||||
disabled={!tags.canAdd}
|
||||
aria-label={t('places.addTag')}
|
||||
className={CONFIRM}
|
||||
>
|
||||
<Check size={15} strokeWidth={2.4} />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<div className={CHIPS}>
|
||||
{shown.map((tag) => (
|
||||
<span key={tag.id} className={CHIP}>
|
||||
<TagIcon size={10} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
|
||||
<span dir="auto" className="truncate">
|
||||
{tag.name}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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' }))
|
||||
|
||||
@@ -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<string, unknown>): Record<string, unknown> {
|
||||
const { fieldOrigins: _origins, ...row } = data
|
||||
return row
|
||||
async function placeRow(tripId: number, data: Record<string, unknown>, before?: Place): Promise<Record<string, unknown>> {
|
||||
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<Place>),
|
||||
...(await placeRow(Number(tripId), data) as Partial<Place>),
|
||||
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<Place>),
|
||||
...(await placeRow(Number(tripId), data, existing) as Partial<Place>),
|
||||
id: Number(id),
|
||||
trip_id: Number(tripId),
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
@@ -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<TripTagListResponse> {
|
||||
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<Tag> {
|
||||
requireOnline();
|
||||
const id = Number(tripId);
|
||||
const { tag } = await tripTagsApi.create(id, body);
|
||||
await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
|
||||
return tag;
|
||||
},
|
||||
};
|
||||
@@ -719,6 +719,13 @@ export const STORE_REFRESHES: Partial<Record<TrekWsTripEventName, StoreRefresh>>
|
||||
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)
|
||||
}),
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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<TripStoreState>['setState'];
|
||||
type GetState = StoreApi<TripStoreState>['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<void>;
|
||||
/** 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<Tag>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<TripStoreState> {
|
||||
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;
|
||||
},
|
||||
});
|
||||
@@ -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<TripStoreState>((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<TripStoreState>((set, get) => ({
|
||||
budgetItems: [],
|
||||
files: [],
|
||||
reservations: [],
|
||||
tripTags: [],
|
||||
selectedDayId: null,
|
||||
placesFilter: 'all',
|
||||
placesCategoryFilter: new Set<string>(),
|
||||
@@ -179,7 +184,7 @@ export const useTripStore = create<TripStoreState>((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<TripStoreState>((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<TripStoreState>((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<TripStoreState>((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<TripStoreState>((set, get) => ({
|
||||
...createBudgetSlice(set, get),
|
||||
...createReservationsSlice(set, get),
|
||||
...createFilesSlice(set, get),
|
||||
...createTripTagsSlice(set, get),
|
||||
}))
|
||||
|
||||
@@ -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<void> {
|
||||
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.
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<Place['tags']>[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<number, TagChoice>();
|
||||
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<number>;
|
||||
/** The tags with another name or colour, as they are now. */
|
||||
renamed: ReadonlyMap<number, Tag>;
|
||||
}
|
||||
|
||||
/** 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<number>();
|
||||
const renamed = new Map<number, Tag>();
|
||||
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<P extends { tags?: PlaceTag[] }>(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 };
|
||||
}
|
||||
@@ -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<string>()
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<string>): 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<string>): 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<string>, goneTagIds: Iterable<number>): Set<string> {
|
||||
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
|
||||
|
||||
@@ -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()],
|
||||
})),
|
||||
|
||||
@@ -57,6 +57,7 @@ const HISTORY: Record<number, StoreSpec> = {
|
||||
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<string, Record<string, unknown>> {
|
||||
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<number, UpgradeCase> = {
|
||||
]);
|
||||
},
|
||||
},
|
||||
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', () => {
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Trips> | null;
|
||||
trip_id?: number | null;
|
||||
collection_place_tags_inverse = new Collection<CollectionPlaces>(this);
|
||||
place_tags_inverse = new Collection<Places>(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(),
|
||||
},
|
||||
|
||||
@@ -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<RoadtripDayBoundaries>(this);
|
||||
roadtrip_preferences_collection = new Collection<RoadtripPreferences>(this);
|
||||
share_tokens_collection = new Collection<ShareTokens>(this);
|
||||
tags_collection = new Collection<Tags>(this);
|
||||
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
|
||||
todo_items_collection = new Collection<TodoItems>(this);
|
||||
tour_drafts_collection = new Collection<TourDrafts>(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(),
|
||||
|
||||
@@ -8,4 +8,5 @@ export interface TagsTable {
|
||||
name: string;
|
||||
color: InsertOptional<string | null>;
|
||||
created_at: InsertOptional<string | null>;
|
||||
trip_id: InsertOptional<number | null>;
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
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)');
|
||||
}
|
||||
}
|
||||
@@ -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<TagRow, Tags> = true;
|
||||
@@ -45,6 +46,9 @@ export interface TagForPlaceRow {
|
||||
*/
|
||||
type PlaceTagsKyselyDB = Pick<DB, 'place_tags'>;
|
||||
|
||||
/** `tags` alone, for the reads that name their columns. */
|
||||
type TagsKyselyDB = Pick<DB, 'tags'>;
|
||||
|
||||
/**
|
||||
* `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<Tags> {
|
||||
* `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<TagRow> {
|
||||
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<TagRow> {
|
||||
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<Tags> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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<TagsKyselyDB>()
|
||||
.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<TagRow[]> {
|
||||
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<TagRow | null> {
|
||||
const tag = await this.findOne({ id, trip: tripId });
|
||||
return tag ? (toRow(tag) as TagRow) : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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<void> {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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<number[]> {
|
||||
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<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
|
||||
|
||||
@@ -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: [],
|
||||
},
|
||||
|
||||
@@ -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) {}
|
||||
|
||||
@@ -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],
|
||||
})
|
||||
|
||||
@@ -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<Tag[]> {
|
||||
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<Tag | undefined> {
|
||||
@@ -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<Tag> {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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<Tag[]> {
|
||||
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<Tag> {
|
||||
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<Tag> {
|
||||
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<void> {
|
||||
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<number> {
|
||||
const tid = toRowId(tripId);
|
||||
if (tid === null) throw tripNotFound();
|
||||
await requireTripWrite({ access: this.access, permissions: this.permissions }, 'place_edit', tid, writer);
|
||||
return tid;
|
||||
}
|
||||
}
|
||||
@@ -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<number, number>();
|
||||
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.
|
||||
|
||||
@@ -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<string, unknown>, 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<string, unknown>) =>
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<ReturnType<typeof build>>;
|
||||
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' });
|
||||
});
|
||||
});
|
||||
@@ -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<voi
|
||||
});
|
||||
}
|
||||
|
||||
/** The tag a setup gave a scene's trip, by the scene's number. */
|
||||
const tripTagOf = new Map<number, number>();
|
||||
|
||||
/** A tag of the scene's trip, for the cases that rename or delete one. */
|
||||
async function tripTag(s: Scene, app: INestApplication): Promise<void> {
|
||||
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'],
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -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<MikroORM> {
|
||||
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);
|
||||
});
|
||||
@@ -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' });
|
||||
|
||||
@@ -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<unknown>): 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();
|
||||
});
|
||||
});
|
||||
@@ -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]));
|
||||
});
|
||||
});
|
||||
@@ -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': 'يحفظ المكان ثم يفتح محرر التكاليف.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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ů.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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': 'Αποθηκεύει την τοποθεσία και ανοίγει τον επεξεργαστή εξόδων.',
|
||||
|
||||
@@ -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': 'שומר את המקום ואז פותח את עורך ההוצאות.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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': '場所を保存してから費用エディタを開きます。',
|
||||
|
||||
@@ -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': '장소를 저장한 뒤 비용 편집기를 엽니다.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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': 'Сохраняет место и открывает редактор расходов.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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': 'บันทึกสถานที่ จากนั้นเปิดตัวแก้ไขต้นทุน',
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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': 'Зберігає місце й відкриває редактор витрат.',
|
||||
|
||||
@@ -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í.',
|
||||
|
||||
@@ -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': '先儲存地點,然後開啟費用編輯器。',
|
||||
|
||||
@@ -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': '先保存地点,然后打开费用编辑器。',
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<typeof placeImportMapRequestSchema>;
|
||||
|
||||
/**
|
||||
* 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(),
|
||||
|
||||
@@ -19,6 +19,7 @@ const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {
|
||||
'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', () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user