The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(tours): prevent duplicate day assignments
elmocitoaf7dbce105be
diff --git a/client/src/components/Tours/ToursSidebar.test.tsx b/client/src/components/Tours/ToursSidebar.test.tsxindex 0879cbf7e..cad5e72f9 100644--- a/client/src/components/Tours/ToursSidebar.test.tsx+++ b/client/src/components/Tours/ToursSidebar.test.tsx@@ -129,6 +129,36 @@ describe('ToursSidebar', () => {expect(onToursChanged).not.toHaveBeenCalled()})+ it('disables already-assigned days and refreshes availability when the picker is reopened', async () => {+ const dayOne = { id: 7, trip_id: 1, day_number: 1, title: 'Day one', date: null } as never+ const dayTwo = { id: 8, trip_id: 1, day_number: 2, title: 'Day two', date: null } as never+ const dayThree = { id: 9, trip_id: 1, day_number: 3, title: 'Day three', date: null } as never+ useTripStore.setState({ assignments: { '7': [{ id: 1, day_id: 7, place_id: tour.place_id }] } as never })+ const onAssignToDay = vi.fn((placeId: number, dayId: number) => {+ useTripStore.setState(state => ({+ assignments: { ...state.assignments, [String(dayId)]: [{ id: 2, day_id: dayId, place_id: placeId }] } as never,+ }))+ return true+ })+ render(<ToursSidebar canAssign tripId={1} days={[dayOne, dayTwo, dayThree]} tours={[tour]} onAssignToDay={onAssignToDay} onSelectTour={vi.fn()} />)++ const openPicker = () => fireEvent.click(screen.getByRole('button', { name: /Add to day|Zum Tag hinzufügen/ }))+ openPicker()+ expect(screen.getByRole('button', { name: /Day one/ })).toBeDisabled()+ expect(screen.getByRole('button', { name: /Day two/ })).toBeEnabled()+ fireEvent.click(screen.getByRole('button', { name: /Day two/ }))+ expect(onAssignToDay).toHaveBeenCalledTimes(1)+ expect(onAssignToDay).toHaveBeenCalledWith(tour.place_id, 8)++ openPicker()+ expect(screen.getByRole('button', { name: /Day one/ })).toBeDisabled()+ expect(screen.getByRole('button', { name: /Day two/ })).toBeDisabled()+ expect(screen.getByRole('button', { name: /Day three/ })).toBeEnabled()+ fireEvent.click(screen.getByRole('button', { name: /Day three/ }))+ expect(onAssignToDay).toHaveBeenCalledTimes(2)+ expect(onAssignToDay).toHaveBeenLastCalledWith(tour.place_id, 9)+ })+it('neither refreshes nor reports success when assignment fails', async () => {toast.success.mockClear()const onToursChanged = vi.fn()diff --git a/client/src/components/Tours/ToursSidebar.tsx b/client/src/components/Tours/ToursSidebar.tsxindex 4157efc02..f61b1a907 100644--- a/client/src/components/Tours/ToursSidebar.tsx+++ b/client/src/components/Tours/ToursSidebar.tsx@@ -178,7 +178,7 @@ export default function ToursSidebar({ tripId, days, tours, loading = false, seltour={tour}selected={tour.place_id === selectedPlaceId}onSelect={(selectedTour, opener) => onSelectTour?.(selectedTour, opener)}- action={<TourDayMenu days={days} label={t('tours.addToDay')} disabled={!canAssign} onPick={(day, index) => { void handleAssign(tour, day, index) }} />}+ action={<TourDayMenu days={days} placeId={tour.place_id} label={t('tours.addToDay')} disabled={!canAssign} onPick={(day, index) => { void handleAssign(tour, day, index) }} />}/>))}</ul>diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsxindex 8f1cd1c78..82c0dde17 100644--- a/client/src/components/Tours/planner/TourPlannerPanels.tsx+++ b/client/src/components/Tours/planner/TourPlannerPanels.tsx@@ -471,6 +471,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTovariant="button"primarydays={days}+ placeId={planner.saveOutcome.place_id}label={t('tours.planner.assignToDay')}disabled={!canAssign || assigning}onPick={day => { void assignSavedTour(day.id) }}@@ -498,6 +499,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignToaction={canAssign && days.length > 0 ? (<TourDayMenudays={days}+ placeId={tour.place_id}label={`${t('tours.addToDay')}: ${tour.name}`}onPick={day => { if (canAssign) void onAssignToDay(tour.place_id, day.id) }}/>diff --git a/client/src/components/Tours/tourParts.tsx b/client/src/components/Tours/tourParts.tsxindex 27376056c..2449f8eab 100644--- a/client/src/components/Tours/tourParts.tsx+++ b/client/src/components/Tours/tourParts.tsx@@ -10,6 +10,7 @@ import { formatDate } from '../../utils/formatters'import { ContextMenu, useContextMenu } from '../shared/ContextMenu'import { DialogButton, fs } from '../shared/DialogShell'import { Tooltip } from '../shared/Tooltip'+import { useTripStore } from '../../store/tripStore'import { BOX, Eyebrow } from '../Planner/bookings/bookingParts'import { SoftPill } from '../Planner/planParts'import { hikeSourceBadgeLabel } from './tourPresentation'@@ -73,8 +74,9 @@ function dayMenuLabel(day: Day, index: number, t: Translate, locale: string): st* Putting a tour on a day: a round "+" on a row, or a footer button with a* chevron, both opening the trip's days as a menu.*/-export function TourDayMenu({ days, onPick, disabled = false, label, variant = 'round', primary = false }: {+export function TourDayMenu({ days, placeId, onPick, disabled = false, label, variant = 'round', primary = false }: {days: Day[]+ placeId?: numberonPick: (day: Day, index: number) => voiddisabled?: booleanlabel: string@@ -83,9 +85,16 @@ export function TourDayMenu({ days, onPick, disabled = false, label, variant = '}) {const { t, locale } = useTranslation()const menu = useContextMenu()- const items = days.map((day, index) => ({ label: dayMenuLabel(day, index, t, locale), onClick: () => onPick(day, index) }))+ const assignments = useTripStore(state => state.assignments ?? {})+ const assigned = (dayId: number) => placeId != null && (assignments[String(dayId)] ?? []).some(assignment => assignment.place_id === placeId)+ const items = days.map((day, index) => ({+ label: dayMenuLabel(day, index, t, locale),+ disabled: assigned(day.id),+ onClick: () => onPick(day, index),+ }))+ const hasAvailableDay = items.some(item => !item.disabled)const open = (event: React.MouseEvent<HTMLButtonElement>) => {- if (disabled || items.length === 0) return+ if (disabled || !hasAvailableDay) returnif (menu.menu) { event.stopPropagation(); menu.close(); return }menu.open(event, items, true)}@@ -93,13 +102,13 @@ export function TourDayMenu({ days, onPick, disabled = false, label, variant = '<>{variant === 'round' ? (<Tooltip label={label} disabled={!!menu.menu}>- <button type="button" onClick={open} disabled={disabled || items.length === 0} aria-label={label} aria-haspopup="menu" aria-expanded={!!menu.menu}+ <button type="button" onClick={open} disabled={disabled || !hasAvailableDay} aria-label={label} aria-haspopup="menu" aria-expanded={!!menu.menu}className={`grid h-[26px] w-[26px] flex-none place-items-center rounded-full shadow-sm ring-1 transition-colors disabled:cursor-default disabled:opacity-40 ${menu.menu ? 'bg-accent text-accent-text ring-transparent' : 'bg-surface-card text-content-muted ring-edge-faint enabled:hover:bg-accent enabled:hover:text-accent-text enabled:hover:ring-transparent'}`}><Plus size={13} strokeWidth={2.4} /></button></Tooltip>) : (- <DialogButton variant={primary ? 'primary' : 'secondary'} onClick={open} disabled={disabled || items.length === 0}+ <DialogButton variant={primary ? 'primary' : 'secondary'} onClick={open} disabled={disabled || !hasAvailableDay}aria-haspopup="menu" aria-expanded={!!menu.menu} icon={<Plus size={14} strokeWidth={2} />}>{label}<ChevronDown size={13} strokeWidth={2.2} className={`transition-transform ${menu.menu ? 'rotate-180' : ''}`} />diff --git a/client/src/components/shared/ContextMenu.test.tsx b/client/src/components/shared/ContextMenu.test.tsxindex 5f00397f6..4838ac09a 100644--- a/client/src/components/shared/ContextMenu.test.tsx+++ b/client/src/components/shared/ContextMenu.test.tsx@@ -79,4 +79,13 @@ describe('ContextMenu', () => {});expect(onClose).toHaveBeenCalledOnce();});++ it('does not activate a disabled menu item', () => {+ const onClick = vi.fn()+ render(<ContextMenu menu={makeMenu(100, 200, [{ label: 'Already assigned', onClick, disabled: true }])} onClose={onClose} />)+ const item = screen.getByRole('button', { name: 'Already assigned' })+ expect(item).toBeDisabled()+ fireEvent.click(item)+ expect(onClick).not.toHaveBeenCalled()+ })});diff --git a/client/src/components/shared/ContextMenu.tsx b/client/src/components/shared/ContextMenu.tsxindex 3558a9398..6cdb6a22f 100644--- a/client/src/components/shared/ContextMenu.tsx+++ b/client/src/components/shared/ContextMenu.tsx@@ -6,6 +6,7 @@ interface MenuItem {label?: stringicon?: LucideIcononClick?: () => void+ disabled?: booleandanger?: booleandivider?: boolean}@@ -84,15 +85,15 @@ export function ContextMenu({ menu, onClose }: ContextMenuProps) {if (item.divider) return <div key={i} style={{ height: 1, background: 'var(--border-faint)', margin: '3px 6px' }} />const Icon = item.iconreturn (- <button type="button" key={i} onClick={() => { item.onClick?.(); onClose() }} style={{+ <button type="button" key={i} disabled={item.disabled} onClick={() => { if (item.disabled) return; item.onClick?.(); onClose() }} style={{display: 'flex', alignItems: 'center', gap: 8, width: '100%',padding: '7px 10px', borderRadius: 7, border: 'none',- background: 'none', cursor: 'pointer', fontFamily: 'inherit',+ background: 'none', cursor: item.disabled ? 'default' : 'pointer', fontFamily: 'inherit',fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500, textAlign: 'left',- color: item.danger ? '#ef4444' : 'var(--text-primary)',+ color: item.danger ? '#ef4444' : 'var(--text-primary)', opacity: item.disabled ? 0.45 : 1,transition: 'background 0.1s',}}- onMouseEnter={e => e.currentTarget.style.background = item.danger ? 'rgba(239,68,68,0.08)' : 'var(--bg-hover)'}+ onMouseEnter={e => { if (!item.disabled) e.currentTarget.style.background = item.danger ? 'rgba(239,68,68,0.08)' : 'var(--bg-hover)' }}onMouseLeave={e => e.currentTarget.style.background = 'none'}>{Icon && <Icon size={13} style={{ flexShrink: 0, color: item.danger ? '#ef4444' : 'var(--text-faint)' }} />}diff --git a/client/src/mobile/screens/trip/sheets/MBrowseActionsSheet.tsx b/client/src/mobile/screens/trip/sheets/MBrowseActionsSheet.tsxindex f4d2317a6..18d5fae13 100644--- a/client/src/mobile/screens/trip/sheets/MBrowseActionsSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MBrowseActionsSheet.tsx@@ -31,6 +31,7 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsPropsconst openSavePicker = useSaveToCollectionStore(s => s.open)const [daysOpen, setDaysOpen] = useState(false)+ const pendingTourDayIds = useRef(new Set<string>())useEffect(() => { setDaysOpen(open && Boolean(payload.dayPicker)) }, [open, payload.dayPicker])// Hold the last place so the card content survives the exit animation.@@ -57,9 +58,20 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsPropsopenSavePicker(collectionTargetFromPlace(place))}+ const tourAlreadyAssignedToDay = (dayId: number) => isTourPlace(place.id)+ && (planner.assignments[String(dayId)] ?? []).some(assignment => assignment.place_id === place.id)+const assignToDay = async (dayId: number) => {- const assigned = await planner.handleAssignToDay(place.id, dayId)- if (assigned !== false) shell.closeSheet()+ const isTour = isTourPlace(place.id)+ const pendingKey = `${place.id}:${dayId}`+ if (isTour && (tourAlreadyAssignedToDay(dayId) || pendingTourDayIds.current.has(pendingKey))) return+ if (isTour) pendingTourDayIds.current.add(pendingKey)+ try {+ const assigned = await planner.handleAssignToDay(place.id, dayId)+ if (assigned !== false) shell.closeSheet()+ } finally {+ if (isTour) pendingTourDayIds.current.delete(pendingKey)+ }}const deletePlace = () => {@@ -112,8 +124,9 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps<buttonkey={d.id}type="button"+ disabled={tourAlreadyAssignedToDay(d.id) || (isTourPlace(place.id) && pendingTourDayIds.current.has(`${place.id}:${d.id}`))}onClick={() => { void assignToDay(d.id) }}- className={`flex w-full items-center gap-2 px-3 py-[10px] text-left ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}+ className={`flex w-full items-center gap-2 px-3 py-[10px] text-left disabled:cursor-default disabled:opacity-40 ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}><span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">{/* A day_number of 0 is as unusable as a missing one — both take the row position. */}diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsxindex a8a4854e6..55e510c89 100644--- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx@@ -1567,6 +1567,37 @@ describe('useTripPlanner — place CRUD', () => {})describe('useTripPlanner — day plan CRUD', () => {+ it('does not write a Tour assignment twice to one day, but allows another day and preserves Place writes', async () => {+ const tour: TourListItem = {+ place_id: 1, name: 'Ridge walk', tour_type: 'hike', distance: 4, elevation_gain: 100,+ elevation_loss: 80, duration: null, difficulty: null, wanderer_ref: null, match_confidence: 1,+ tour_group_id: null, max_hiking_difficulty: 2, planned: false, caution: false,+ }+ const tourPlace = buildPlace({ id: 1, name: 'Ridge walk', tour_place_id: 1 })+ const ordinaryPlace = buildPlace({ id: 2, name: 'Ordinary place' })+ useAddonStore.setState({ addons: [{ id: 'tours', enabled: true } as never], loaded: true })+ vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'tours' }] })+ vi.spyOn(toursApi, 'list').mockResolvedValue({ tours: [tour] })+ seedTrip({+ places: [tourPlace, ordinaryPlace],+ assignments: { '7': [buildAssignment({ id: 70, day_id: 7, place: tourPlace })] },+ })++ const { result } = await renderPlanner()+ await waitFor(() => expect(result.current.tours).toEqual([tour]))+ actions.assignPlaceToDay.mockClear()++ let repeated!: boolean+ await act(async () => { repeated = await result.current.handleAssignToDay(tourPlace.id, 7) })+ expect(repeated).toBe(false)+ expect(actions.assignPlaceToDay).not.toHaveBeenCalled()++ await act(async () => { await result.current.handleAssignToDay(tourPlace.id, 8) })+ await act(async () => { await result.current.handleAssignToDay(ordinaryPlace.id, 7) })+ expect(actions.assignPlaceToDay).toHaveBeenNthCalledWith(1, 42, 8, tourPlace.id, undefined)+ expect(actions.assignPlaceToDay).toHaveBeenNthCalledWith(2, 42, 7, ordinaryPlace.id, undefined)+ })+it('refreshes Tours only after a successful Tour assignment write', async () => {const unplanned: TourListItem = {place_id: 1, name: 'Ridge walk', tour_type: 'hike', distance: 4, elevation_gain: 100,diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.tsindex 993ee1055..4dfd4e831 100644--- a/client/src/pages/tripPlanner/useTripPlanner.ts+++ b/client/src/pages/tripPlanner/useTripPlanner.ts@@ -2527,6 +2527,7 @@ export function useTripPlanner() {const handleAssignToDay = useCallback(async (placeId: number, dayId?: number, position?: number) => {const target = dayId || selectedDayIdif (!target) { toast.error(t('trip.toast.selectDay')); return false }+ if (isTourPlace(placeId) && (storedAssignments[String(target)] ?? []).some(assignment => assignment.place_id === placeId)) return falseconst place = places.find(p => p.id === placeId)// A place with a start of its own is drawn by it, so it is stored there too, the// way a stop moved over from another day is. Without one it goes where it was put.diff --git a/client/tests/unit/mobile/trip/MBrowseActionsSheet.tours.test.tsx b/client/tests/unit/mobile/trip/MBrowseActionsSheet.tours.test.tsxnew file mode 100644index 000000000..7c20fea12--- /dev/null+++ b/client/tests/unit/mobile/trip/MBrowseActionsSheet.tours.test.tsx@@ -0,0 +1,109 @@+import { describe, expect, it, vi } from 'vitest';+import type { TripPlanner } from '../../../../src/mobile/screens/trip/MTripShell';+import MBrowseActionsSheet from '../../../../src/mobile/screens/trip/sheets/MBrowseActionsSheet';+import type { Place } from '../../../../src/types';+import { buildPlanner, buildShell } from '../../../helpers/mobileTrip';+import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render';+import { resetAllStores } from '../../../helpers/store';++function tourPlace(): Place {+ return {+ id: 42,+ trip_id: 1,+ name: 'Ridge walk',+ address: null,+ description: null,+ category_id: null,+ lat: 48,+ lng: 11,+ image_url: null,+ google_place_id: null,+ osm_id: null,+ route_geometry: '[[48,11],[49,12]]',+ route_color: null,+ tour_place_id: 42,+ } as unknown as Place;+}++const days = [+ { id: 7, trip_id: 1, day_number: 1, title: 'Day one', date: null },+ { id: 8, trip_id: 1, day_number: 2, title: 'Day two', date: null },+ { id: 9, trip_id: 1, day_number: 3, title: 'Day three', date: null },+] as never;++function mobilePlanner(overrides: Partial<TripPlanner> = {}) {+ const place = tourPlace();+ return buildPlanner({+ places: [place],+ days,+ assignments: { '7': [{ id: 70, day_id: 7, place_id: place.id }] } as never,+ isTourPlace: vi.fn((placeId: number) => placeId === place.id),+ ...overrides,+ } as Partial<TripPlanner>);+}++function renderDayPicker(planner = mobilePlanner()) {+ const shell = buildShell({ sheet: { id: 'bract', payload: { placeId: 42, dayPicker: true } } });+ const view = render(<MBrowseActionsSheet planner={planner} shell={shell} />);+ return { ...view, planner, shell };+}++describe('MBrowseActionsSheet Tour assignment picker', () => {+ it('disables assigned Tour days, blocks repeat clicks, and refreshes on reopen', async () => {+ resetAllStores();+ let finishAssignment!: (assigned: boolean) => void;+ const handleAssignToDay = vi.fn(+ () =>+ new Promise<boolean>((resolve) => {+ finishAssignment = resolve;+ })+ );+ const planner = mobilePlanner({ handleAssignToDay });+ const { rerender, shell } = renderDayPicker(planner);++ const dayOne = screen.getByRole('button', { name: /Day one/ });+ const dayTwo = screen.getByRole('button', { name: /Day two/ });+ expect(dayOne).toBeDisabled();+ expect(dayTwo).toBeEnabled();+ fireEvent.click(dayOne);+ expect(handleAssignToDay).not.toHaveBeenCalled();++ fireEvent.click(dayTwo);+ fireEvent.click(dayTwo);+ expect(handleAssignToDay).toHaveBeenCalledTimes(1);+ expect(handleAssignToDay).toHaveBeenCalledWith(42, 8);++ await act(async () => {+ finishAssignment(true);+ });+ await waitFor(() => expect(shell.closeSheet).toHaveBeenCalledOnce());++ const reopened = mobilePlanner({+ assignments: {+ '7': [{ id: 70, day_id: 7, place_id: 42 }],+ '8': [{ id: 80, day_id: 8, place_id: 42 }],+ } as never,+ });+ rerender(<MBrowseActionsSheet planner={reopened} shell={shell} />);+ expect(screen.getByRole('button', { name: /Day one/ })).toBeDisabled();+ expect(screen.getByRole('button', { name: /Day two/ })).toBeDisabled();+ expect(screen.getByRole('button', { name: /Day three/ })).toBeEnabled();+ });++ it('leaves ordinary Place day choices enabled and preserves their assignment write behavior', () => {+ resetAllStores();+ const place = { ...tourPlace(), tour_place_id: undefined };+ const handleAssignToDay = vi.fn().mockResolvedValue(true);+ const planner = mobilePlanner({+ places: [place],+ isTourPlace: vi.fn(() => false),+ assignments: { '7': [{ id: 70, day_id: 7, place_id: place.id }] } as never,+ handleAssignToDay,+ });+ renderDayPicker(planner);+ const dayOne = screen.getByRole('button', { name: /Day one/ });+ expect(dayOne).toBeEnabled();+ fireEvent.click(dayOne);+ expect(handleAssignToDay).toHaveBeenCalledWith(place.id, 7);+ });+});diff --git a/server/src/nest/assignments/assignments.service.ts b/server/src/nest/assignments/assignments.service.tsindex 3cf70583a..e8fbb13d9 100644--- a/server/src/nest/assignments/assignments.service.ts+++ b/server/src/nest/assignments/assignments.service.ts@@ -1,4 +1,4 @@-import { Injectable } from '@nestjs/common';+import { ConflictException, Injectable } from '@nestjs/common';import { chronoOrder, type RoadtripVia, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';import { isEmptyReanchoring, reanchorByStopOrder, type AnchoredVia } from '@trek/shared/roadtrip';import { RealtimeService } from '../realtime/realtime.service';@@ -176,6 +176,15 @@ export class AssignmentsService {*/createAssignment(dayId: string | number, placeId: unknown, notes?: string | null, opts: { accommodationId?: number; orderIndex?: number } = {}) {const result = this.dbs.transaction(() => {+ const duplicateTourAssignment = this.dbs.get<{ id: number }>(+ `SELECT da.id FROM day_assignments da+ JOIN tours t ON t.place_id = da.place_id+ WHERE da.day_id = ? AND da.place_id = ?+ LIMIT 1`,+ dayId, placeId,+ );+ if (duplicateTourAssignment) throw new ConflictException('Tour is already assigned to this day');+const maxOrder = this.dbs.get<{ max: number | null }>('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?', dayId)!;const end = (maxOrder.max !== null ? maxOrder.max : -1) + 1;// Somewhere in the middle when the caller says so, which means everything fromdiff --git a/server/tests/e2e/assignments.e2e.test.ts b/server/tests/e2e/assignments.e2e.test.tsindex ada4ee0cb..902768d3c 100644--- a/server/tests/e2e/assignments.e2e.test.ts+++ b/server/tests/e2e/assignments.e2e.test.ts@@ -204,6 +204,38 @@ describe('Assignments e2e (real auth guard + temp SQLite)', () => {expect(miss.body).toEqual({ error: 'Place not found' });});+ it('prevents duplicate Tour/day assignments through concurrent REST requests', async () => {+ const tourPlaceId = 20;+ db.prepare('INSERT INTO places (id, trip_id, name) VALUES (?, 5, ?)').run(tourPlaceId, 'Ridge walk');+ db.prepare('INSERT INTO tours (place_id) VALUES (?)').run(tourPlaceId);+ try {+ const createTourAssignment = () => request(server)+ .post('/api/trips/5/days/3/assignments')+ .set('Cookie', sessionCookie(1))+ .send({ place_id: tourPlaceId });+ const results = await Promise.all([createTourAssignment(), createTourAssignment()]);++ expect(results.map(result => result.status).sort()).toEqual([201, 409]);+ expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = 3 AND place_id = ?').get(tourPlaceId)).toEqual({ n: 1 });++ const otherDay = await request(server).post('/api/trips/5/days/4/assignments')+ .set('Cookie', sessionCookie(1)).send({ place_id: tourPlaceId });+ expect(otherDay.status).toBe(201);+ expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(tourPlaceId)).toEqual({ n: 2 });++ const firstOrdinary = await request(server).post('/api/trips/5/days/3/assignments')+ .set('Cookie', sessionCookie(1)).send({ place_id: 2 });+ const secondOrdinary = await request(server).post('/api/trips/5/days/3/assignments')+ .set('Cookie', sessionCookie(1)).send({ place_id: 2 });+ expect(firstOrdinary.status).toBe(201);+ expect(secondOrdinary.status).toBe(201);+ } finally {+ db.prepare('DELETE FROM day_assignments WHERE place_id = ?').run(tourPlaceId);+ db.prepare('DELETE FROM tours WHERE place_id = ?').run(tourPlaceId);+ db.prepare('DELETE FROM places WHERE id = ?').run(tourPlaceId);+ }+ });+it('200 delete assignment reconciles journey skeletons', async () => {reconcileTripSkeletons.mockClear();const id = seedAssignment();diff --git a/server/tests/unit/nest/assignments.controller.test.ts b/server/tests/unit/nest/assignments.controller.test.tsindex d868e7720..fd88a2f54 100644--- a/server/tests/unit/nest/assignments.controller.test.ts+++ b/server/tests/unit/nest/assignments.controller.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi } from 'vitest';-import { HttpException } from '@nestjs/common';+import { ConflictException, HttpException } from '@nestjs/common';import { DayAssignmentsController, AssignmentOpsController } from '../../../src/nest/assignments/assignments.controller';import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';import type { User } from '../../../src/types';@@ -47,6 +47,18 @@ describe('DayAssignmentsController (parity with the legacy day-assignments routeexpect(broadcast).toHaveBeenCalledWith('5', 'assignment:created', { assignment: { id: 9 } }, 'sock');expect(reconcile).toHaveBeenCalledWith('5', 'sock');});++ it('409 duplicate Tour assignment propagates without announcing a new assignment', () => {+ const broadcast = vi.fn();+ const reconcile = vi.fn();+ const createAssignment = vi.fn(() => { throw new ConflictException('Tour is already assigned to this day') });+ const controller = new DayAssignmentsController(svc({ createAssignment, broadcast, reconcile } as Partial<AssignmentsService>));++ expect(thrown(() => controller.create(user, '5', '3', { place_id: 42 }))).toMatchObject({ status: 409 });+ expect(createAssignment).toHaveBeenCalledWith('3', 42, undefined);+ expect(broadcast).not.toHaveBeenCalled();+ expect(reconcile).not.toHaveBeenCalled();+ });});it('PUT /reorder 404 day, else reorders + broadcasts', () => {diff --git a/server/tests/unit/nest/assignments.service.test.ts b/server/tests/unit/nest/assignments.service.test.tsindex dbea060d5..f25f9b28a 100644--- a/server/tests/unit/nest/assignments.service.test.ts+++ b/server/tests/unit/nest/assignments.service.test.ts@@ -10,6 +10,7 @@* logic is exercised faithfully.*/import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';+import { ConflictException } from '@nestjs/common';// ── DB setup ──────────────────────────────────────────────────────────────────@@ -99,6 +100,11 @@ function fixture() {return { user, trip, day, place };}+function addTourFacet(placeId: number) {+ testDb.prepare("INSERT OR IGNORE INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'hike', 'Mountain', '#000000')").run();+ testDb.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(placeId);+}+// ── verifyTripAccess / canEdit ────────────────────────────────────────────────describe('verifyTripAccess', () => {@@ -193,6 +199,40 @@ describe('createAssignment', () => {expect(a!.place.tags).toEqual([{ id: tag.id, name: 'museum', color: '#10b981', created_at: (tag as { created_at?: string }).created_at }]);void trip;});++ it('ASG-SVC-031: rejects a duplicate Tour assignment on the same day but allows another day and ordinary Place duplicates', () => {+ const { trip, day, place: tourPlace } = fixture();+ const secondDay = createDay(testDb, trip.id);+ const ordinaryPlace = createPlace(testDb, trip.id, { name: 'Ordinary place' });+ addTourFacet(tourPlace.id);++ const firstTourAssignment = svc.createAssignment(day.id, tourPlace.id);+ expect(() => svc.createAssignment(day.id, tourPlace.id)).toThrow(ConflictException);+ const otherDayTourAssignment = svc.createAssignment(secondDay.id, tourPlace.id);+ expect(firstTourAssignment?.day_id).toBe(day.id);+ expect(otherDayTourAssignment?.day_id).toBe(secondDay.id);+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(tourPlace.id)).toEqual({ n: 2 });++ svc.createAssignment(day.id, ordinaryPlace.id);+ svc.createAssignment(day.id, ordinaryPlace.id);+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(ordinaryPlace.id)).toEqual({ n: 2 });+ });++ it('ASG-SVC-032: near-concurrent Tour assignments serialize to one row and one conflict', async () => {+ const { day, place } = fixture();+ addTourFacet(place.id);++ const results = await Promise.allSettled([+ Promise.resolve().then(() => svc.createAssignment(day.id, place.id)),+ Promise.resolve().then(() => svc.createAssignment(day.id, place.id)),+ ]);++ expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1);+ const rejected = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');+ expect(rejected).toHaveLength(1);+ expect(rejected[0].reason).toBeInstanceOf(ConflictException);+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ? AND place_id = ?').get(day.id, place.id)).toEqual({ n: 1 });+ });});// ── listDayAssignments ────────────────────────────────────────────────────────