diff --git a/client/src/components/Trips/TripFormModal.test.tsx b/client/src/components/Trips/TripFormModal.test.tsx index f5955dbf8..880515cf4 100644 --- a/client/src/components/Trips/TripFormModal.test.tsx +++ b/client/src/components/Trips/TripFormModal.test.tsx @@ -368,6 +368,79 @@ describe('TripFormModal', () => { expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ currency: 'EUR' })); }); + // Changing the start of a dated trip must go through the date-shift choice step (#1288). + const changeStartDate = async (user: ReturnType, iso: string) => { + await user.click(screen.getAllByRole('button', { name: 'Enter date manually' })[0]); + const input = screen.getByPlaceholderText('DD.MM.YYYY'); + fireEvent.change(input, { target: { value: iso } }); + fireEvent.keyDown(input, { key: 'Enter' }); + }; + + it('FE-COMP-TRIPFORM-035: changing the start date shows the choice step and saves with keep_bookings by default', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue({}); + const trip = buildTrip({ id: 1, title: 'Dated Trip', start_date: '2025-06-01', end_date: '2025-06-05' }); + render(); + + await changeStartDate(user, '2025-05-31'); + await user.click(screen.getByRole('button', { name: /Update/i })); + + // The choice step appears instead of saving right away. + await screen.findByText('Keep bookings on their dates'); + expect(onSave).not.toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: /Update/i })); + await waitFor(() => expect(onSave).toHaveBeenCalled()); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ + start_date: '2025-05-31', + date_shift_mode: 'keep_bookings', + })); + }); + + it('FE-COMP-TRIPFORM-036: picking "Shift everything" sends shift_all', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue({}); + const trip = buildTrip({ id: 1, title: 'Dated Trip', start_date: '2025-06-01', end_date: '2025-06-05' }); + render(); + + await changeStartDate(user, '2025-06-02'); + await user.click(screen.getByRole('button', { name: /Update/i })); + await user.click(await screen.findByRole('radio', { name: /Shift everything/i })); + await user.click(screen.getByRole('button', { name: /Update/i })); + + await waitFor(() => expect(onSave).toHaveBeenCalled()); + expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ date_shift_mode: 'shift_all' })); + }); + + it('FE-COMP-TRIPFORM-037: Back returns to the form without saving', async () => { + const user = userEvent.setup(); + const onSave = vi.fn(); + const trip = buildTrip({ id: 1, title: 'Dated Trip', start_date: '2025-06-01', end_date: '2025-06-05' }); + render(); + + await changeStartDate(user, '2025-05-30'); + await user.click(screen.getByRole('button', { name: /Update/i })); + await screen.findByText('Keep bookings on their dates'); + + await user.click(screen.getByRole('button', { name: /Back/i })); + await waitFor(() => expect(screen.queryByText('Keep bookings on their dates')).not.toBeInTheDocument()); + expect(screen.getByDisplayValue('Dated Trip')).toBeInTheDocument(); + expect(onSave).not.toHaveBeenCalled(); + }); + + it('FE-COMP-TRIPFORM-038: an edit that keeps the dates saves directly without the choice step', async () => { + const user = userEvent.setup(); + const onSave = vi.fn().mockResolvedValue({}); + const trip = buildTrip({ id: 1, title: 'Dated Trip', start_date: '2025-06-01', end_date: '2025-06-05' }); + render(); + + await user.click(screen.getByRole('button', { name: /Update/i })); + + await waitFor(() => expect(onSave).toHaveBeenCalled()); + expect(screen.queryByText('Keep bookings on their dates')).not.toBeInTheDocument(); + expect(onSave).toHaveBeenCalledWith(expect.not.objectContaining({ date_shift_mode: expect.anything() })); + }); + it('FE-COMP-TRIPFORM-034: picking a currency sends the new one on save', async () => { const user = userEvent.setup(); const onSave = vi.fn().mockResolvedValue({}); diff --git a/client/src/components/Trips/TripFormModal.tsx b/client/src/components/Trips/TripFormModal.tsx index 3862267e1..641df712b 100644 --- a/client/src/components/Trips/TripFormModal.tsx +++ b/client/src/components/Trips/TripFormModal.tsx @@ -14,12 +14,14 @@ import type { TripCreateRequest } from '@trek/shared' import { NumericInput } from '../shared/NumericInput' import { currenciesWith, SYMBOLS } from '../Budget/BudgetPanel.constants' +type DateShiftMode = 'keep_bookings' | 'shift_all' + interface TripFormModalProps { isOpen: boolean onClose: () => void // Create returns the new trip (so we can attach members / upload the cover); // update resolves without a payload. - onSave: (data: TripCreateRequest) => Promise<{ trip?: Trip } | void> | void + onSave: (data: TripCreateRequest & { date_shift_mode?: DateShiftMode }) => Promise<{ trip?: Trip } | void> | void trip: Trip | null onCoverUpdate?: (tripId: number, coverUrl: string | null) => void } @@ -70,6 +72,10 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp const [selectedMembers, setSelectedMembers] = useState([]) const [existingMembers, setExistingMembers] = useState<{ id: number; username: string }[]>([]) const [memberSelectValue, setMemberSelectValue] = useState('') + // Set when a start-date change on a dated trip needs the user to pick how the + // itinerary follows the new dates (#1288); holds the payload awaiting that choice. + const [pendingDateShift, setPendingDateShift] = useState<(TripCreateRequest & { date_shift_mode?: DateShiftMode }) | null>(null) + const [dateShiftMode, setDateShiftMode] = useState('keep_bookings') useEffect(() => { if (trip) { @@ -97,6 +103,8 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp setCoverSearchResults([]) setCoverSearchError('') setSelectedMembers([]) + setPendingDateShift(null) + setDateShiftMode('keep_bookings') setError('') if (isOpen) { authApi.getAppConfig().then((c: { trip_reminders_enabled?: boolean }) => { @@ -130,17 +138,31 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp setError(t('dashboard.dayCountRequired')); return } } + const payload: TripCreateRequest & { date_shift_mode?: DateShiftMode } = { + title: formData.title.trim(), + description: formData.description.trim() || null, + start_date: formData.start_date || null, + end_date: formData.end_date || null, + currency: formData.currency, + reminder_days: formData.reminder_days, + ...(!formData.start_date && !formData.end_date ? { day_count: Number(formData.day_count) } : {}), + } + // Moving the start of a dated trip shifts the whole day grid, so let the user + // choose how bookings follow before anything is saved (#1288). End-date-only + // changes don't shift days and dateless transitions have nothing to shift. + if (isEditing && trip?.start_date && trip?.end_date + && payload.start_date && payload.end_date && payload.start_date !== trip.start_date) { + setDateShiftMode('keep_bookings') + setPendingDateShift(payload) + return + } + await performSave(payload) + } + + const performSave = async (payload: TripCreateRequest & { date_shift_mode?: DateShiftMode }) => { setIsLoading(true) try { - const result = await onSave({ - title: formData.title.trim(), - description: formData.description.trim() || null, - start_date: formData.start_date || null, - end_date: formData.end_date || null, - currency: formData.currency, - reminder_days: formData.reminder_days, - ...(!formData.start_date && !formData.end_date ? { day_count: Number(formData.day_count) } : {}), - }) + const result = await onSave(payload) const createdTrip = result ? result.trip : undefined // Add selected members for newly created trips if (selectedMembers.length > 0 && createdTrip?.id) { @@ -317,24 +339,64 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp - - + {pendingDateShift ? ( + <> + + + + ) : ( + <> + + + + )} } > -
+ {pendingDateShift && ( +
+ {error && ( +
{error}
+ )} +

{t('dashboard.dateShiftIntro')}

+ {([ + { mode: 'keep_bookings' as DateShiftMode, label: t('dashboard.dateShiftKeepBookings'), desc: t('dashboard.dateShiftKeepBookingsDesc') }, + { mode: 'shift_all' as DateShiftMode, label: t('dashboard.dateShiftAll'), desc: t('dashboard.dateShiftAllDesc') }, + ]).map(({ mode, label, desc }) => ( + + ))} +

{t('dashboard.dateShiftHint')}

+
+ )} + {error && (
{error}
)} diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx index ad56bcf74..ada1934d5 100644 --- a/client/src/pages/TripPlannerPage.tsx +++ b/client/src/pages/TripPlannerPage.tsx @@ -744,7 +744,7 @@ export default function TripPlannerPage(): React.ReactElement | null { setShowTripForm(false)} - onSave={async (data) => { await tripActions.updateTrip(tripId, data); toast.success(t('trip.toast.tripUpdated')) }} + onSave={async (data) => { await tripActions.updateTrip(tripId, data); loadAccommodations(); toast.success(t('trip.toast.tripUpdated')) }} trip={trip} onCoverUpdate={(_, coverUrl) => useTripStore.setState(state => ({ trip: state.trip ? { ...state.trip, cover_image: coverUrl } : state.trip }))} /> diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts index 8d4514442..965f2042e 100644 --- a/client/src/pages/tripPlanner/useTripPlanner.ts +++ b/client/src/pages/tripPlanner/useTripPlanner.ts @@ -307,6 +307,14 @@ export function useTripPlanner() { } }, [tripId]) + // Accommodations live in this hook's local state, so store-level refreshes + // (remote trip date change, reconnect hydration) nudge us via this event (#1288). + useEffect(() => { + const onRefresh = () => loadAccommodations() + window.addEventListener('accommodations:refresh', onRefresh) + return () => window.removeEventListener('accommodations:refresh', onRefresh) + }, [loadAccommodations]) + useTripWebSocket(tripId) // Same filter the places sidebar renders — shared via the store so tab diff --git a/client/src/store/slices/remoteEventHandler.ts b/client/src/store/slices/remoteEventHandler.ts index 5487c2d33..6b9fa005d 100644 --- a/client/src/store/slices/remoteEventHandler.ts +++ b/client/src/store/slices/remoteEventHandler.ts @@ -164,6 +164,10 @@ async function _writeDayToDb(dayId: number, state: TripStoreState): Promise { switch (type) { // Places @@ -470,6 +474,20 @@ export function handleRemoteEvent(set: SetState, get: GetState, event: WebSocket } } + // A trip date-range change re-dates day rows and re-anchors bookings and + // accommodations server-side (#1288), so pull the authoritative days + + // reservations and tell the planner to reload accommodations (they live in + // page-local state, not this store). + if (type === 'trip:updated') { + const updated = payload.trip as Trip + if (prevTrip && updated.id === prevTrip.id + && (updated.start_date !== prevTrip.start_date || updated.end_date !== prevTrip.end_date)) { + get().refreshDays(updated.id) + get().loadReservations(updated.id) + window.dispatchEvent(new CustomEvent('accommodations:refresh')) + } + } + // Write the change through to IndexedDB using the post-update state writeToDexie(type, payload as Record, get()) } diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.ts index b5fcf6e87..c7cfed79c 100644 --- a/client/src/store/tripStore.ts +++ b/client/src/store/tripStore.ts @@ -76,7 +76,7 @@ export interface TripStoreState loadTrip: (tripId: number | string) => Promise hydrateActiveTrip: (tripId: number | string) => Promise refreshDays: (tripId: number | string) => Promise - updateTrip: (tripId: number | string, data: Partial) => Promise + updateTrip: (tripId: number | string, data: Partial & { date_shift_mode?: 'keep_bookings' | 'shift_all' }) => Promise addTag: (data: Partial & { name: string }) => Promise addCategory: (data: Partial & { name: string }) => Promise } @@ -193,6 +193,9 @@ export const useTripStore = create((set, get) => ({ get().loadReservations(tripId), get().loadFiles(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). + window.dispatchEvent(new CustomEvent('accommodations:refresh')) }, refreshDays: async (tripId: number | string) => { @@ -210,7 +213,7 @@ export const useTripStore = create((set, get) => ({ } }, - updateTrip: async (tripId: number | string, data: Partial) => { + updateTrip: async (tripId: number | string, data: Partial & { date_shift_mode?: 'keep_bookings' | 'shift_all' }) => { try { const result = await tripsApi.update(tripId, data) set({ trip: result.trip }) @@ -222,6 +225,9 @@ export const useTripStore = create((set, get) => ({ dayNotesMap[String(day.id)] = day.notes_items || [] } set({ days: daysData.days, assignments: assignmentsMap, dayNotes: dayNotesMap }) + // A date change re-anchors bookings server-side (#1288); the socket echo is + // suppressed for this client, so pull the fresh reservations here. + await get().loadReservations(tripId) return result.trip } catch (err: unknown) { throw new Error(getApiErrorMessage(err, 'Error updating trip')) diff --git a/client/tests/unit/remoteEventHandler/trip.test.ts b/client/tests/unit/remoteEventHandler/trip.test.ts index 992c260b5..cf7496abc 100644 --- a/client/tests/unit/remoteEventHandler/trip.test.ts +++ b/client/tests/unit/remoteEventHandler/trip.test.ts @@ -1,10 +1,11 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { useTripStore } from '../../../src/store/tripStore'; import { resetAllStores } from '../../helpers/store'; import { buildTrip, buildPlace } from '../../helpers/factories'; beforeEach(() => { resetAllStores(); + vi.restoreAllMocks(); }); describe('remoteEventHandler > trip', () => { @@ -29,4 +30,47 @@ describe('remoteEventHandler > trip', () => { expect(places).toHaveLength(1); expect(places[0].id).toBe(55); }); + + // A remote date-range change re-anchors bookings/accommodations server-side, so the + // handler must pull authoritative days + reservations and nudge the planner (#1288). + describe('date-range change refresh (#1288)', () => { + const stubRefresh = () => { + const refreshDays = vi.fn().mockResolvedValue(undefined); + const loadReservations = vi.fn().mockResolvedValue(undefined); + useTripStore.setState({ refreshDays, loadReservations }); + const dispatchSpy = vi.spyOn(window, 'dispatchEvent'); + return { refreshDays, loadReservations, dispatchSpy }; + }; + const firedAccommodationsRefresh = (spy: ReturnType) => + spy.mock.calls.some(([e]) => (e as Event).type === 'accommodations:refresh'); + + it('FE-WSEVT-TRIP-003: trip:updated with a changed start_date refetches days + reservations and fires accommodations:refresh', () => { + useTripStore.setState({ trip: buildTrip({ id: 1, start_date: '2025-06-01', end_date: '2025-06-05' }) }); + const { refreshDays, loadReservations, dispatchSpy } = stubRefresh(); + const updatedTrip = buildTrip({ id: 1, start_date: '2025-05-31', end_date: '2025-06-05' }); + useTripStore.getState().handleRemoteEvent({ type: 'trip:updated', trip: updatedTrip }); + expect(refreshDays).toHaveBeenCalledWith(1); + expect(loadReservations).toHaveBeenCalledWith(1); + expect(firedAccommodationsRefresh(dispatchSpy)).toBe(true); + }); + + it('FE-WSEVT-TRIP-004: a title-only trip:updated does not trigger any refetch', () => { + useTripStore.setState({ trip: buildTrip({ id: 1, title: 'Old', start_date: '2025-06-01', end_date: '2025-06-05' }) }); + const { refreshDays, loadReservations, dispatchSpy } = stubRefresh(); + const updatedTrip = buildTrip({ id: 1, title: 'New', start_date: '2025-06-01', end_date: '2025-06-05' }); + useTripStore.getState().handleRemoteEvent({ type: 'trip:updated', trip: updatedTrip }); + expect(refreshDays).not.toHaveBeenCalled(); + expect(loadReservations).not.toHaveBeenCalled(); + expect(firedAccommodationsRefresh(dispatchSpy)).toBe(false); + }); + + it('FE-WSEVT-TRIP-005: a trip:updated for a different trip id does not trigger a refetch', () => { + useTripStore.setState({ trip: buildTrip({ id: 1, start_date: '2025-06-01', end_date: '2025-06-05' }) }); + const { refreshDays, loadReservations } = stubRefresh(); + const updatedTrip = buildTrip({ id: 2, start_date: '2025-07-01', end_date: '2025-07-05' }); + useTripStore.getState().handleRemoteEvent({ type: 'trip:updated', trip: updatedTrip }); + expect(refreshDays).not.toHaveBeenCalled(); + expect(loadReservations).not.toHaveBeenCalled(); + }); + }); }); diff --git a/client/tests/unit/tripStore.test.ts b/client/tests/unit/tripStore.test.ts index 8f8259a26..e89b1cd96 100644 --- a/client/tests/unit/tripStore.test.ts +++ b/client/tests/unit/tripStore.test.ts @@ -326,6 +326,21 @@ describe('tripStore', () => { expect(result).toEqual(updatedTrip); expect(useTripStore.getState().trip).toEqual(updatedTrip); }); + + it('FE-TRIP-011: updateTrip reloads reservations (re-anchored server-side on date changes, #1288)', async () => { + const updatedTrip = buildTrip({ id: 1, start_date: '2025-05-31', end_date: '2025-06-05' }); + const reservation = buildReservation({ id: 7, trip_id: 1, day_id: 21 }); + + server.use( + http.put('/api/trips/1', () => HttpResponse.json({ trip: updatedTrip })), + http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })), + http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [reservation] })), + ); + + await useTripStore.getState().updateTrip(1, { start_date: '2025-05-31' }); + + expect(useTripStore.getState().reservations).toEqual([reservation]); + }); }); describe('setSelectedDay', () => { diff --git a/server/src/mcp/tools/trips.ts b/server/src/mcp/tools/trips.ts index 4db8905f6..e6037df8e 100644 --- a/server/src/mcp/tools/trips.ts +++ b/server/src/mcp/tools/trips.ts @@ -81,10 +81,12 @@ export function registerTripTools(server: McpServer, userId: number, scopes: str currency: z.string().length(3).optional(), is_archived: z.boolean().optional().describe('Archive (true) or unarchive (false) the trip'), cover_image: z.string().optional().describe('Cover image path, e.g. /uploads/covers/abc.jpg'), + date_shift_mode: z.enum(['keep_bookings', 'shift_all']).optional().describe( + 'When changing dates: keep_bookings (default) keeps dated reservations/accommodations on their dates while day plans move; shift_all moves the whole itinerary, bookings included'), }, annotations: TOOL_ANNOTATIONS_WRITE, }, - async ({ tripId, title, description, start_date, end_date, currency, is_archived, cover_image }) => { + async ({ tripId, title, description, start_date, end_date, currency, is_archived, cover_image, date_shift_mode }) => { if (isDemoUser(userId)) return demoDenied(); if (!canAccessTrip(tripId, userId)) return noAccess(); if (!hasTripPermission('trip_edit', tripId, userId)) return permissionDenied(); @@ -100,7 +102,7 @@ export function registerTripTools(server: McpServer, userId: number, scopes: str } // Re-anchor the budget before the trip row moves off the old currency (#1543). await rebaseTripCurrency(tripId, currency); - const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image }, 'user'); + const { updatedTrip } = updateTrip(tripId, userId, { title, description, start_date, end_date, currency, is_archived, cover_image, date_shift_mode }, 'user'); safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip }); return ok({ trip: updatedTrip }); } diff --git a/server/src/services/dayService.ts b/server/src/services/dayService.ts index 5bc6da92f..d73e99c92 100644 --- a/server/src/services/dayService.ts +++ b/server/src/services/dayService.ts @@ -207,7 +207,7 @@ function withDatePart(timestamp: string, date: string): string { * date (time-of-day preserved). Transport endpoints (flight legs) shift by the * same per-booking day delta so multi-leg timing stays internally consistent. */ -function restampReservationDates( +export function restampReservationDates( tripId: string | number, oldDateById: Map, newDateById: Map, @@ -265,6 +265,56 @@ function assertNoInvertedAccommodation(tripId: string | number): void { } } +/** + * After a trip's date range changes, generateDays positionally re-dates the day rows + * (keeping their ids), so an accommodation — which has no absolute date, only + * start_day_id/end_day_id — visually shifts with the range (#1288). Re-anchor each + * stay to the days now holding its pre-change dates (from the snapshot taken before + * generateDays ran). A stay whose dates fall outside the new range is left glued to + * its day rows, mirroring resyncReservationDays' out-of-range semantics, so moving a + * whole trip still shifts everything together. The linked hotel reservation follows + * its accommodation's start day in both branches. + */ +export function resyncAccommodationDays( + tripId: string | number, + prevDateByDayId: Map, +): void { + const stays = db.prepare( + 'SELECT id, start_day_id, end_day_id FROM day_accommodations WHERE trip_id = ?' + ).all(tripId) as { id: number; start_day_id: number; end_day_id: number }[]; + if (stays.length === 0) return; + + const dayByDate = db.prepare('SELECT id, day_number FROM days WHERE trip_id = ? AND date = ? LIMIT 1'); + const updateStay = db.prepare('UPDATE day_accommodations SET start_day_id = ?, end_day_id = ? WHERE id = ?'); + const restampLinkedRes = db.prepare(` + UPDATE reservations SET day_id = :dayId, + reservation_time = CASE WHEN reservation_time IS NULL THEN :date + ELSE :date || SUBSTR(reservation_time, 11) END + WHERE accommodation_id = :accId AND type = 'hotel' + `); + + for (const stay of stays) { + const oldStartDate = prevDateByDayId.get(stay.start_day_id); + const oldEndDate = prevDateByDayId.get(stay.end_day_id); + if (oldStartDate && oldEndDate) { + const newStart = dayByDate.get(tripId, oldStartDate) as { id: number; day_number: number } | undefined; + const newEnd = dayByDate.get(tripId, oldEndDate) as { id: number; day_number: number } | undefined; + if (newStart && newEnd && newStart.day_number <= newEnd.day_number + && (newStart.id !== stay.start_day_id || newEnd.id !== stay.end_day_id)) { + updateStay.run(newStart.id, newEnd.id, stay.id); + stay.start_day_id = newStart.id; + } + } + // Keep the linked reservation on the stay's (possibly re-dated) start day — its + // reservation_time is a snapshot of that day's date, stale after any range change. + const startDayDate = (db.prepare('SELECT date FROM days WHERE id = ?') + .get(stay.start_day_id) as { date: string | null } | undefined)?.date; + if (startDayDate) { + restampLinkedRes.run({ dayId: stay.start_day_id, date: startDayDate, accId: stay.id }); + } + } +} + /** Thrown for invalid reorder/insert requests; mapped to HTTP 400 by the controller. */ export class DayReorderError extends Error {} diff --git a/server/src/services/reservationService.ts b/server/src/services/reservationService.ts index de90348c8..a9a552a1b 100644 --- a/server/src/services/reservationService.ts +++ b/server/src/services/reservationService.ts @@ -106,12 +106,14 @@ function resolveDayIdFromTime( // the booking visually shifts by the offset (#1288). Re-anchor non-hotel bookings to the // day matching their absolute reservation_time — the same derivation create/updateReservation // use. Only updates when a matching day exists, so a booking whose date now falls outside -// the new range is left untouched. Hotels keep their range on the linked day_accommodation. +// the new range is left untouched. Hotels linked to a day_accommodation are excluded here — +// resyncAccommodationDays re-anchors the accommodation span and its linked reservation; +// unlinked dated hotels (e.g. imported ones) re-anchor like any other booking. export function resyncReservationDays(tripId: string | number): void { const rows = db.prepare( `SELECT id, reservation_time, reservation_end_time, day_id, end_day_id FROM reservations - WHERE trip_id = ? AND type != 'hotel' AND reservation_time IS NOT NULL`, + WHERE trip_id = ? AND (type != 'hotel' OR accommodation_id IS NULL) AND reservation_time IS NOT NULL`, ).all(tripId) as { id: number; reservation_time: string | null; reservation_end_time: string | null; day_id: number | null; end_day_id: number | null; diff --git a/server/src/services/tripService.ts b/server/src/services/tripService.ts index ff1c1f808..8278fbede 100644 --- a/server/src/services/tripService.ts +++ b/server/src/services/tripService.ts @@ -6,7 +6,7 @@ import { db, isOwner } from '../db/database'; import { erasePluginUserData } from './userCleanupService'; import { emitUserDeleted } from '../plugin-user-lifecycle'; import { Trip, User } from '../types'; -import { listDays, listAccommodations, addDays } from './dayService'; +import { listDays, listAccommodations, addDays, resyncAccommodationDays, restampReservationDates } from './dayService'; import { listBudgetItems, removeUserFromBudgetItems } from './budgetService'; import { listItems as listPackingItems } from './packingService'; import { listReservations, loadEndpointsByTrip, resyncReservationDays } from './reservationService'; @@ -218,6 +218,7 @@ interface UpdateTripData { cover_image?: string; reminder_days?: number; day_count?: number; + date_shift_mode?: 'keep_bookings' | 'shift_all'; } export interface UpdateTripResult { @@ -262,10 +263,30 @@ export function updateTrip(tripId: string | number, userId: number, data: Update const dayCount = data.day_count ? Math.min(Math.max(Number(data.day_count) || 7, 1), MAX_TRIP_DAYS) : undefined; if (newStart !== trip.start_date || newEnd !== trip.end_date || dayCount) { - generateDays(tripId, newStart || null, newEnd || null, undefined, dayCount); - // generateDays re-dates day rows positionally; re-anchor dated bookings to the day - // matching their absolute reservation_time so they don't shift with it (#1288). - resyncReservationDays(tripId); + db.transaction(() => { + // Accommodations have no absolute date columns, so their pre-change dates must be + // snapshotted before generateDays re-dates the day rows in place. + const prevDateByDayId = new Map( + (db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[]) + .map(d => [d.id, d.date]), + ); + generateDays(tripId, newStart || null, newEnd || null, undefined, dayCount); + if (data.date_shift_mode === 'shift_all') { + // Explicit "shift everything": bookings stay glued to their (re-dated) day rows, + // so re-stamp reservation_time to follow — same rules as reorderDays/insertDay. + const newDateByDayId = new Map( + (db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[]) + .map(d => [d.id, d.date]), + ); + restampReservationDates(tripId, prevDateByDayId, newDateByDayId); + } else { + // Default: generateDays re-dates day rows positionally; re-anchor dated bookings to + // the day matching their absolute reservation_time, and accommodations (+ their + // linked hotel reservations) to the days now holding their pre-change dates (#1288). + resyncReservationDays(tripId); + resyncAccommodationDays(tripId, prevDateByDayId); + } + })(); } const changes: Record = {}; diff --git a/server/tests/unit/services/tripService.test.ts b/server/tests/unit/services/tripService.test.ts index b09834b8a..88d27150f 100644 --- a/server/tests/unit/services/tripService.test.ts +++ b/server/tests/unit/services/tripService.test.ts @@ -35,6 +35,7 @@ import { runMigrations } from '../../../src/db/migrations'; import { resetTestDb } from '../../helpers/test-db'; import { createUser, createTrip, createReservation, createPlace, createDay, createDayAssignment, createDayNote, addTripMember } from '../../helpers/factories'; import { exportICS, generateDays, deleteOldCover, updateTrip, transferOwnership, createGuest, renameGuest, deleteGuest, listMembers, addMember } from '../../../src/services/tripService'; +import { createAccommodation } from '../../../src/services/dayService'; import fs from 'fs'; beforeAll(() => { @@ -597,6 +598,89 @@ describe('resyncReservationDays (#1288)', () => { }); }); +describe('resyncAccommodationDays (#1288)', () => { + const dayFor = (tripId: number, date: string) => + (testDb.prepare('SELECT id FROM days WHERE trip_id = ? AND date = ?').get(tripId, date) as { id: number }).id; + + const insertAccommodation = (tripId: number, startDayId: number, endDayId: number) => { + const place = createPlace(testDb, tripId, { name: 'Grand Hotel' }); + const acc = createAccommodation(tripId, { + place_id: place.id, start_day_id: startDayId, end_day_id: endDayId, + }) as { id: number }; + const linkedRes = testDb.prepare( + 'SELECT id FROM reservations WHERE accommodation_id = ?', + ).get(acc.id) as { id: number }; + return { accId: acc.id, linkedResId: linkedRes.id }; + }; + + const getAcc = (id: number) => + testDb.prepare('SELECT start_day_id, end_day_id FROM day_accommodations WHERE id = ?').get(id) as + { start_day_id: number; end_day_id: number }; + const getRes = (id: number) => + testDb.prepare('SELECT day_id, reservation_time FROM reservations WHERE id = ?').get(id) as + { day_id: number | null; reservation_time: string | null }; + + it('TRIP-SVC-035: extending the start keeps an accommodation on its absolute dates', () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2025-06-10', end_date: '2025-06-14' }); + const { accId, linkedResId } = insertAccommodation(trip.id, dayFor(trip.id, '2025-06-11'), dayFor(trip.id, '2025-06-13')); + // Add a day at the start: days re-date positionally (old 06-11 row becomes 06-10, …). + updateTrip(trip.id, user.id, { start_date: '2025-06-09', end_date: '2025-06-14' }, 'user'); + const acc = getAcc(accId); + expect(acc.start_day_id).toBe(dayFor(trip.id, '2025-06-11')); + expect(acc.end_day_id).toBe(dayFor(trip.id, '2025-06-13')); + const res = getRes(linkedResId); + expect(res.day_id).toBe(acc.start_day_id); + expect(res.reservation_time?.slice(0, 10)).toBe('2025-06-11'); + }); + + it('TRIP-SVC-036: moving the whole trip out of the old range keeps the accommodation glued to its days', () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' }); + const startDayId = dayFor(trip.id, '2025-06-02'); + const endDayId = dayFor(trip.id, '2025-06-03'); + const { accId, linkedResId } = insertAccommodation(trip.id, startDayId, endDayId); + updateTrip(trip.id, user.id, { start_date: '2025-07-01', end_date: '2025-07-05' }, 'user'); + const acc = getAcc(accId); + expect(acc.start_day_id).toBe(startDayId); + expect(acc.end_day_id).toBe(endDayId); + // The linked reservation follows the (re-dated) start day instead of keeping a stale date snapshot. + const res = getRes(linkedResId); + expect(res.day_id).toBe(startDayId); + expect(res.reservation_time?.slice(0, 10)).toBe('2025-07-02'); + }); + + it("TRIP-SVC-038: date_shift_mode 'shift_all' glues bookings to their days and restamps their times", () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' }); + const origDayId = dayFor(trip.id, '2025-06-02'); + const resId = Number(testDb.prepare( + "INSERT INTO reservations (trip_id, day_id, title, reservation_time, type, status) VALUES (?, ?, 'Dinner', '2025-06-02T19:00:00', 'restaurant', 'pending')", + ).run(trip.id, origDayId).lastInsertRowid); + const { accId } = insertAccommodation(trip.id, origDayId, dayFor(trip.id, '2025-06-03')); + updateTrip(trip.id, user.id, { start_date: '2025-06-03', end_date: '2025-06-07', date_shift_mode: 'shift_all' }, 'user'); + // The booking stays on its day row (now 2025-06-04) and its time follows. + const res = testDb.prepare('SELECT day_id, reservation_time FROM reservations WHERE id = ?').get(resId) as + { day_id: number; reservation_time: string }; + expect(res.day_id).toBe(origDayId); + expect(res.reservation_time).toBe('2025-06-04T19:00:00'); + // The accommodation stays glued to its (re-dated) day rows too. + const acc = getAcc(accId); + expect(acc.start_day_id).toBe(origDayId); + }); + + it('TRIP-SVC-037: a dated hotel reservation without a linked accommodation is re-anchored like other bookings', () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2025-06-01', end_date: '2025-06-05' }); + const resId = Number(testDb.prepare( + "INSERT INTO reservations (trip_id, day_id, title, reservation_time, type, status) VALUES (?, ?, 'Imported hotel', ?, 'hotel', 'pending')", + ).run(trip.id, dayFor(trip.id, '2025-06-02'), '2025-06-02T15:00:00').lastInsertRowid); + updateTrip(trip.id, user.id, { start_date: '2025-06-02', end_date: '2025-06-06' }, 'user'); + const res = testDb.prepare('SELECT day_id FROM reservations WHERE id = ?').get(resId) as { day_id: number }; + expect(res.day_id).toBe(dayFor(trip.id, '2025-06-02')); + }); +}); + describe('transferOwnership (#973)', () => { it('TRIP-SVC-020: hands the trip to a member and demotes the former owner to a member', () => { const { user: owner } = createUser(testDb); diff --git a/shared/src/i18n/ar/dashboard.ts b/shared/src/i18n/ar/dashboard.ts index 15a907f5c..1a978b5a1 100644 --- a/shared/src/i18n/ar/dashboard.ts +++ b/shared/src/i18n/ar/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'استخدم صورة من Unsplash بواسطة {photographer}', 'dashboard.titleRequired': 'العنوان مطلوب', 'dashboard.endDateError': 'يجب أن يكون تاريخ النهاية بعد البداية', + 'dashboard.dateShiftTitle': 'تاريخ بداية جديد', + 'dashboard.dateShiftIntro': 'لقد غيّرت موعد بداية هذه الرحلة. كيف تريد أن تتبع خططك التواريخ الجديدة؟', + 'dashboard.dateShiftKeepBookings': 'إبقاء الحجوزات في تواريخها', + 'dashboard.dateShiftKeepBookingsDesc': 'تنتقل خطط الأيام مع التواريخ الجديدة، بينما تبقى الحجوزات وأماكن الإقامة في تواريخها الأصلية ما دامت تلك التواريخ لا تزال ضمن الرحلة.', + 'dashboard.dateShiftAll': 'نقل كل شيء', + 'dashboard.dateShiftAllDesc': 'ينتقل خط سير الرحلة بالكامل مع التواريخ الجديدة، بما في ذلك الحجوزات وأماكن الإقامة.', + 'dashboard.dateShiftHint': 'نصيحة: لنقل جزء من خط سير الرحلة فقط، استخدم "إضافة يوم" في مخطط الرحلة بدلاً من ذلك.', 'dashboard.filter.planned': 'مخطط لها', 'dashboard.hero.badgeLive': 'مباشر الآن', 'dashboard.hero.badgeToday': 'تبدأ اليوم', diff --git a/shared/src/i18n/br/dashboard.ts b/shared/src/i18n/br/dashboard.ts index 7401aa980..1291303f6 100644 --- a/shared/src/i18n/br/dashboard.ts +++ b/shared/src/i18n/br/dashboard.ts @@ -84,6 +84,14 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Usar foto do Unsplash por {photographer}', 'dashboard.titleRequired': 'O título é obrigatório', 'dashboard.endDateError': 'A data final deve ser depois da inicial', + 'dashboard.dateShiftTitle': 'Nova data de início', + 'dashboard.dateShiftIntro': 'Você alterou o início desta viagem. Como seus planos devem acompanhar as novas datas?', + 'dashboard.dateShiftKeepBookings': 'Manter reservas em suas datas', + 'dashboard.dateShiftKeepBookingsDesc': + 'Os planos diários acompanham as novas datas, enquanto reservas e hospedagens permanecem nas datas originais, desde que ainda façam parte da viagem.', + 'dashboard.dateShiftAll': 'Mover tudo', + 'dashboard.dateShiftAllDesc': 'Todo o itinerário acompanha as novas datas, incluindo reservas e hospedagens.', + 'dashboard.dateShiftHint': 'Dica: para mover apenas parte do itinerário, use "Adicionar dia" no planejador.', 'dashboard.greeting.morning': 'Bom dia,', 'dashboard.greeting.afternoon': 'Boa tarde,', 'dashboard.greeting.evening': 'Boa noite,', diff --git a/shared/src/i18n/cs/dashboard.ts b/shared/src/i18n/cs/dashboard.ts index 2e2582ce0..0e57a6fcb 100644 --- a/shared/src/i18n/cs/dashboard.ts +++ b/shared/src/i18n/cs/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Použít fotku z Unsplash od {photographer}', 'dashboard.titleRequired': 'Název je povinný', 'dashboard.endDateError': 'Datum konce musí být po datu začátku', + 'dashboard.dateShiftTitle': 'Nové datum začátku', + 'dashboard.dateShiftIntro': 'Změnili jste začátek této cesty. Jak se mají vaše plány přizpůsobit novým termínům?', + 'dashboard.dateShiftKeepBookings': 'Ponechat rezervace v původních termínech', + 'dashboard.dateShiftKeepBookingsDesc': 'Denní plány se posunou podle nových termínů, zatímco rezervace a ubytování zůstanou v původních termínech, pokud jsou stále součástí cesty.', + 'dashboard.dateShiftAll': 'Posunout vše', + 'dashboard.dateShiftAllDesc': 'Celý itinerář se posune podle nových termínů, včetně rezervací a ubytování.', + 'dashboard.dateShiftHint': 'Tip: pokud chcete posunout jen část itineráře, použijte místo toho „Přidat den” v plánovači.', 'dashboard.greeting.morning': 'Dobré ráno,', 'dashboard.greeting.afternoon': 'Dobré odpoledne,', 'dashboard.greeting.evening': 'Dobrý večer,', diff --git a/shared/src/i18n/de/dashboard.ts b/shared/src/i18n/de/dashboard.ts index 0ed5d4aa7..8ff854537 100644 --- a/shared/src/i18n/de/dashboard.ts +++ b/shared/src/i18n/de/dashboard.ts @@ -85,6 +85,16 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Unsplash-Foto von {photographer} verwenden', 'dashboard.titleRequired': 'Titel ist erforderlich', 'dashboard.endDateError': 'Enddatum muss nach dem Startdatum liegen', + 'dashboard.dateShiftTitle': 'Neues Startdatum', + 'dashboard.dateShiftIntro': + 'Du hast den Beginn dieser Reise geändert. Wie sollen deine Pläne den neuen Daten folgen?', + 'dashboard.dateShiftKeepBookings': 'Buchungen auf ihren Terminen belassen', + 'dashboard.dateShiftKeepBookingsDesc': + 'Tagespläne wandern mit den neuen Daten, während Reservierungen und Unterkünfte auf ihren ursprünglichen Terminen bleiben, solange diese noch Teil der Reise sind.', + 'dashboard.dateShiftAll': 'Alles verschieben', + 'dashboard.dateShiftAllDesc': + 'Der gesamte Reiseplan wandert mit den neuen Daten, einschließlich Reservierungen und Unterkünften.', + 'dashboard.dateShiftHint': 'Tipp: Um nur einen Teil deines Reiseplans zu verschieben, nutze stattdessen "Tag hinzufügen" im Planer.', 'dashboard.greeting.morning': 'Guten Morgen,', 'dashboard.greeting.afternoon': 'Guten Tag,', 'dashboard.greeting.evening': 'Guten Abend,', diff --git a/shared/src/i18n/en/dashboard.ts b/shared/src/i18n/en/dashboard.ts index 30d915621..9d2dd9eeb 100644 --- a/shared/src/i18n/en/dashboard.ts +++ b/shared/src/i18n/en/dashboard.ts @@ -98,6 +98,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Use Unsplash photo by {photographer}', 'dashboard.titleRequired': 'Title is required', 'dashboard.endDateError': 'End date must be after start date', + 'dashboard.dateShiftTitle': 'New start date', + 'dashboard.dateShiftIntro': 'You changed when this trip starts. How should your plans follow the new dates?', + 'dashboard.dateShiftKeepBookings': 'Keep bookings on their dates', + 'dashboard.dateShiftKeepBookingsDesc': 'Day plans move with the new dates, while reservations and accommodations stay on their original dates as long as those are still part of the trip.', + 'dashboard.dateShiftAll': 'Shift everything', + 'dashboard.dateShiftAllDesc': 'The entire itinerary moves with the new dates, including reservations and accommodations.', + 'dashboard.dateShiftHint': 'Tip: to shift only part of your itinerary, use "Add day" in the planner instead.', 'dashboard.greeting.morning': 'Good morning,', 'dashboard.greeting.afternoon': 'Good afternoon,', 'dashboard.greeting.evening': 'Good evening,', diff --git a/shared/src/i18n/es/dashboard.ts b/shared/src/i18n/es/dashboard.ts index b58499e1e..a17d27b1f 100644 --- a/shared/src/i18n/es/dashboard.ts +++ b/shared/src/i18n/es/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Usar foto de Unsplash de {photographer}', 'dashboard.titleRequired': 'El título es obligatorio', 'dashboard.endDateError': 'La fecha de fin debe ser posterior a la de inicio', + 'dashboard.dateShiftTitle': 'Nueva fecha de inicio', + 'dashboard.dateShiftIntro': 'Has cambiado cuándo empieza este viaje. ¿Cómo deben seguir tus planes las nuevas fechas?', + 'dashboard.dateShiftKeepBookings': 'Mantener las reservas en sus fechas', + 'dashboard.dateShiftKeepBookingsDesc': 'Los planes de cada día se mueven con las nuevas fechas, mientras que las reservas y los alojamientos permanecen en sus fechas originales siempre que sigan formando parte del viaje.', + 'dashboard.dateShiftAll': 'Mover todo', + 'dashboard.dateShiftAllDesc': 'Todo el itinerario se mueve con las nuevas fechas, incluidas las reservas y los alojamientos.', + 'dashboard.dateShiftHint': 'Consejo: para mover solo una parte del itinerario, usa "Añadir día" en el planificador.', 'dashboard.greeting.morning': 'Buenos días,', 'dashboard.greeting.afternoon': 'Buenas tardes,', 'dashboard.greeting.evening': 'Buenas noches,', diff --git a/shared/src/i18n/fr/dashboard.ts b/shared/src/i18n/fr/dashboard.ts index 432e99033..6bf68a9b4 100644 --- a/shared/src/i18n/fr/dashboard.ts +++ b/shared/src/i18n/fr/dashboard.ts @@ -86,6 +86,17 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Utiliser la photo Unsplash de {photographer}', 'dashboard.titleRequired': 'Le titre est obligatoire', 'dashboard.endDateError': 'La date de fin doit être postérieure à la date de début', + 'dashboard.dateShiftTitle': 'Nouvelle date de début', + 'dashboard.dateShiftIntro': + 'Vous avez modifié la date de début de ce voyage. Comment vos plans doivent-ils suivre les nouvelles dates ?', + 'dashboard.dateShiftKeepBookings': 'Conserver les réservations à leurs dates', + 'dashboard.dateShiftKeepBookingsDesc': + "Les plans journaliers suivent les nouvelles dates, tandis que les réservations et hébergements restent à leurs dates d'origine tant que celles-ci font toujours partie du voyage.", + 'dashboard.dateShiftAll': 'Tout décaler', + 'dashboard.dateShiftAllDesc': + "L'itinéraire entier suit les nouvelles dates, y compris les réservations et hébergements.", + 'dashboard.dateShiftHint': + "Astuce : pour ne décaler qu'une partie de votre itinéraire, utilisez plutôt « Ajouter un jour » dans le planificateur.", 'dashboard.greeting.morning': 'Bonjour,', 'dashboard.greeting.afternoon': 'Bon après-midi,', 'dashboard.greeting.evening': 'Bonsoir,', diff --git a/shared/src/i18n/gr/dashboard.ts b/shared/src/i18n/gr/dashboard.ts index 85a4adba0..a71979a26 100644 --- a/shared/src/i18n/gr/dashboard.ts +++ b/shared/src/i18n/gr/dashboard.ts @@ -99,6 +99,17 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Χρήση φωτογραφίας Unsplash από {photographer}', 'dashboard.titleRequired': 'Ο τίτλος είναι υποχρεωτικός', 'dashboard.endDateError': 'Η ημερομηνία λήξης πρέπει να είναι μετά την ημερομηνία έναρξης', + 'dashboard.dateShiftTitle': 'Νέα ημερομηνία έναρξης', + 'dashboard.dateShiftIntro': + 'Αλλάξατε την ημερομηνία έναρξης αυτού του ταξιδιού. Πώς θέλετε να ακολουθήσουν τα σχέδιά σας τις νέες ημερομηνίες;', + 'dashboard.dateShiftKeepBookings': 'Διατήρηση κρατήσεων στις ημερομηνίες τους', + 'dashboard.dateShiftKeepBookingsDesc': + 'Τα σχέδια ημέρας μετακινούνται με τις νέες ημερομηνίες, ενώ οι κρατήσεις και τα καταλύματα παραμένουν στις αρχικές τους ημερομηνίες, εφόσον αυτές εξακολουθούν να ανήκουν στο ταξίδι.', + 'dashboard.dateShiftAll': 'Μετατόπιση όλων', + 'dashboard.dateShiftAllDesc': + 'Ολόκληρο το δρομολόγιο μετακινείται με τις νέες ημερομηνίες, συμπεριλαμβανομένων των κρατήσεων και των καταλυμάτων.', + 'dashboard.dateShiftHint': + 'Συμβουλή: για να μετατοπίσετε μόνο ένα μέρος του δρομολογίου σας, χρησιμοποιήστε την επιλογή "Προσθήκη ημέρας" στο ημερήσιο πλάνο.', 'dashboard.greeting.morning': 'Καλημέρα,', 'dashboard.greeting.afternoon': 'Καλό απόγευμα,', 'dashboard.greeting.evening': 'Καλησπέρα,', diff --git a/shared/src/i18n/hu/dashboard.ts b/shared/src/i18n/hu/dashboard.ts index 5ba0bef1f..2ebe575b1 100644 --- a/shared/src/i18n/hu/dashboard.ts +++ b/shared/src/i18n/hu/dashboard.ts @@ -86,6 +86,16 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '{photographer} Unsplash-fotójának használata', 'dashboard.titleRequired': 'A cím megadása kötelező', 'dashboard.endDateError': 'A záró dátumnak a kezdő dátum után kell lennie', + 'dashboard.dateShiftTitle': 'Új kezdő dátum', + 'dashboard.dateShiftIntro': 'Megváltoztattad az út kezdetét. Hogyan kövessék a terveid az új dátumokat?', + 'dashboard.dateShiftKeepBookings': 'A foglalások maradjanak a saját dátumaikon', + 'dashboard.dateShiftKeepBookingsDesc': + 'A napi tervek az új dátumokkal együtt mozognak, míg a foglalások és szállások az eredeti dátumaikon maradnak, amíg azok még az út részei.', + 'dashboard.dateShiftAll': 'Minden eltolása', + 'dashboard.dateShiftAllDesc': + 'A teljes útiterv az új dátumokkal együtt mozog, beleértve a foglalásokat és a szállásokat is.', + 'dashboard.dateShiftHint': + 'Tipp: ha csak az útiterv egy részét szeretnéd eltolni, használd inkább a "Nap hozzáadása" funkciót a tervezőben.', 'dashboard.greeting.morning': 'Jó reggelt,', 'dashboard.greeting.afternoon': 'Jó napot,', 'dashboard.greeting.evening': 'Jó estét,', diff --git a/shared/src/i18n/id/dashboard.ts b/shared/src/i18n/id/dashboard.ts index b1de591de..1cc8299de 100644 --- a/shared/src/i18n/id/dashboard.ts +++ b/shared/src/i18n/id/dashboard.ts @@ -84,6 +84,17 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Gunakan foto Unsplash oleh {photographer}', 'dashboard.titleRequired': 'Judul wajib diisi', 'dashboard.endDateError': 'Tanggal selesai harus setelah tanggal mulai', + 'dashboard.dateShiftTitle': 'Tanggal mulai baru', + 'dashboard.dateShiftIntro': + 'Kamu mengubah tanggal mulai perjalanan ini. Bagaimana rencanamu harus mengikuti tanggal baru?', + 'dashboard.dateShiftKeepBookings': 'Pertahankan pesanan pada tanggalnya', + 'dashboard.dateShiftKeepBookingsDesc': + 'Rencana harian ikut berpindah ke tanggal baru, sementara reservasi dan akomodasi tetap pada tanggal aslinya selama tanggal tersebut masih termasuk dalam perjalanan.', + 'dashboard.dateShiftAll': 'Geser semuanya', + 'dashboard.dateShiftAllDesc': + 'Seluruh rencana perjalanan berpindah ke tanggal baru, termasuk reservasi dan akomodasi.', + 'dashboard.dateShiftHint': + 'Tip: untuk menggeser sebagian rencana perjalanan saja, gunakan "Tambah hari" di perencana.', 'dashboard.greeting.morning': 'Selamat pagi,', 'dashboard.greeting.afternoon': 'Selamat siang,', 'dashboard.greeting.evening': 'Selamat malam,', diff --git a/shared/src/i18n/it/dashboard.ts b/shared/src/i18n/it/dashboard.ts index 428d78862..5de571050 100644 --- a/shared/src/i18n/it/dashboard.ts +++ b/shared/src/i18n/it/dashboard.ts @@ -86,6 +86,16 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Usa foto Unsplash di {photographer}', 'dashboard.titleRequired': 'Il titolo è obbligatorio', 'dashboard.endDateError': 'La data di fine deve essere successiva alla data di inizio', + 'dashboard.dateShiftTitle': 'Nuova data di inizio', + 'dashboard.dateShiftIntro': + 'Hai modificato la data di inizio di questo viaggio. Come devono adattarsi i tuoi piani alle nuove date?', + 'dashboard.dateShiftKeepBookings': 'Mantieni le prenotazioni alle loro date', + 'dashboard.dateShiftKeepBookingsDesc': + 'I programmi giornalieri si spostano con le nuove date, mentre prenotazioni e alloggi restano alle date originali, purché queste facciano ancora parte del viaggio.', + 'dashboard.dateShiftAll': 'Sposta tutto', + 'dashboard.dateShiftAllDesc': "L'intero itinerario si sposta con le nuove date, incluse prenotazioni e alloggi.", + 'dashboard.dateShiftHint': + 'Suggerimento: per spostare solo una parte dell\'itinerario, usa "Aggiungi giorno" nel planner.', 'dashboard.greeting.morning': 'Buongiorno,', 'dashboard.greeting.afternoon': 'Buon pomeriggio,', 'dashboard.greeting.evening': 'Buonasera,', diff --git a/shared/src/i18n/ja/dashboard.ts b/shared/src/i18n/ja/dashboard.ts index 410dc1bd4..1f01f187c 100644 --- a/shared/src/i18n/ja/dashboard.ts +++ b/shared/src/i18n/ja/dashboard.ts @@ -99,6 +99,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '{photographer}さんのUnsplash写真を使用', 'dashboard.titleRequired': 'タイトルは必須です', 'dashboard.endDateError': '終了日は開始日より後にしてください', + 'dashboard.dateShiftTitle': '新しい開始日', + 'dashboard.dateShiftIntro': '旅行の開始日が変更されました。予定を新しい日程にどのように合わせますか?', + 'dashboard.dateShiftKeepBookings': '予約を元の日付のままにする', + 'dashboard.dateShiftKeepBookingsDesc': '日別計画は新しい日程に合わせて移動しますが、予約と宿泊先は旅行期間内にある限り元の日付のままになります。', + 'dashboard.dateShiftAll': 'すべてを移動する', + 'dashboard.dateShiftAllDesc': '予約や宿泊先を含む旅程全体が新しい日程に合わせて移動します。', + 'dashboard.dateShiftHint': 'ヒント:旅程の一部だけを移動したい場合は、プランナーの「日付を追加」を使用してください。', 'dashboard.greeting.morning': 'おはようございます、', 'dashboard.greeting.afternoon': 'こんにちは、', 'dashboard.greeting.evening': 'こんばんは、', diff --git a/shared/src/i18n/ko/dashboard.ts b/shared/src/i18n/ko/dashboard.ts index 793a28435..86f04a480 100644 --- a/shared/src/i18n/ko/dashboard.ts +++ b/shared/src/i18n/ko/dashboard.ts @@ -99,6 +99,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '{photographer}님의 Unsplash 사진 사용', 'dashboard.titleRequired': '제목을 입력하세요', 'dashboard.endDateError': '종료일은 시작일 이후여야 합니다', + 'dashboard.dateShiftTitle': '새 시작일', + 'dashboard.dateShiftIntro': '여행 시작일이 변경되었습니다. 계획을 새 날짜에 어떻게 맞출까요?', + 'dashboard.dateShiftKeepBookings': '예약은 원래 날짜에 유지', + 'dashboard.dateShiftKeepBookingsDesc': '일별 계획은 새 날짜로 이동하고, 예약과 숙박은 여행 기간에 포함되어 있는 한 원래 날짜에 그대로 유지됩니다.', + 'dashboard.dateShiftAll': '모두 이동', + 'dashboard.dateShiftAllDesc': '예약과 숙박을 포함한 전체 일정이 새 날짜로 이동합니다.', + 'dashboard.dateShiftHint': '팁: 일정의 일부만 이동하려면 플래너의 "날짜 추가" 기능을 사용하세요.', 'dashboard.greeting.morning': '좋은 아침이에요,', 'dashboard.greeting.afternoon': '안녕하세요,', 'dashboard.greeting.evening': '좋은 저녁이에요,', diff --git a/shared/src/i18n/nl/dashboard.ts b/shared/src/i18n/nl/dashboard.ts index 62e7cab37..58ff96504 100644 --- a/shared/src/i18n/nl/dashboard.ts +++ b/shared/src/i18n/nl/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Unsplash-foto van {photographer} gebruiken', 'dashboard.titleRequired': 'Titel is verplicht', 'dashboard.endDateError': 'Einddatum moet na de startdatum liggen', + 'dashboard.dateShiftTitle': 'Nieuwe startdatum', + 'dashboard.dateShiftIntro': 'Je hebt gewijzigd wanneer deze reis begint. Hoe moeten je plannen de nieuwe datums volgen?', + 'dashboard.dateShiftKeepBookings': 'Boekingen op hun datums houden', + 'dashboard.dateShiftKeepBookingsDesc': 'Dagplannen verschuiven mee met de nieuwe datums, terwijl reserveringen en accommodaties op hun oorspronkelijke datums blijven zolang die nog binnen de reis vallen.', + 'dashboard.dateShiftAll': 'Alles verschuiven', + 'dashboard.dateShiftAllDesc': 'De volledige reisplanning verschuift mee met de nieuwe datums, inclusief reserveringen en accommodaties.', + 'dashboard.dateShiftHint': 'Tip: om slechts een deel van je reisplanning te verschuiven, gebruik je "Dag toevoegen" in de planner.', 'dashboard.greeting.morning': 'Goedemorgen,', 'dashboard.greeting.afternoon': 'Goedemiddag,', 'dashboard.greeting.evening': 'Goedenavond,', diff --git a/shared/src/i18n/pl/dashboard.ts b/shared/src/i18n/pl/dashboard.ts index 7659b347f..14886e8d6 100644 --- a/shared/src/i18n/pl/dashboard.ts +++ b/shared/src/i18n/pl/dashboard.ts @@ -80,6 +80,17 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Użyj zdjęcia z Unsplash autorstwa {photographer}', 'dashboard.titleRequired': 'Nazwa podróży jest wymagana', 'dashboard.endDateError': 'Data zakończenia musi być po dacie rozpoczęcia', + 'dashboard.dateShiftTitle': 'Nowa data rozpoczęcia', + 'dashboard.dateShiftIntro': + 'Data rozpoczęcia podróży została zmieniona. Jak plany mają dostosować się do nowych dat?', + 'dashboard.dateShiftKeepBookings': 'Zachowaj rezerwacje w ich terminach', + 'dashboard.dateShiftKeepBookingsDesc': + 'Plany dnia przesuną się wraz z nowymi datami, a rezerwacje i noclegi pozostaną w swoich pierwotnych terminach, o ile nadal mieszczą się one w ramach podróży.', + 'dashboard.dateShiftAll': 'Przesuń wszystko', + 'dashboard.dateShiftAllDesc': + 'Cały plan podróży przesunie się wraz z nowymi datami, w tym rezerwacje i noclegi.', + 'dashboard.dateShiftHint': + 'Wskazówka: aby przesunąć tylko część planu podróży, użyj opcji "Dodaj dzień" w planerze.', 'dashboard.members': 'Współpodróżnicy', 'dashboard.copyTrip': 'Kopiuj', 'dashboard.copySuffix': 'kopia', diff --git a/shared/src/i18n/ru/dashboard.ts b/shared/src/i18n/ru/dashboard.ts index 05c13cd68..4a3530168 100644 --- a/shared/src/i18n/ru/dashboard.ts +++ b/shared/src/i18n/ru/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Использовать фото Unsplash от {photographer}', 'dashboard.titleRequired': 'Название обязательно', 'dashboard.endDateError': 'Дата окончания должна быть позже даты начала', + 'dashboard.dateShiftTitle': 'Новая дата начала', + 'dashboard.dateShiftIntro': 'Вы изменили дату начала поездки. Как перенести ваши планы на новые даты?', + 'dashboard.dateShiftKeepBookings': 'Оставить бронирования на своих датах', + 'dashboard.dateShiftKeepBookingsDesc': 'Планы дней переносятся на новые даты, а бронирования и жильё остаются на исходных датах, пока те входят в поездку.', + 'dashboard.dateShiftAll': 'Перенести всё', + 'dashboard.dateShiftAllDesc': 'Весь маршрут переносится на новые даты, включая бронирования и жильё.', + 'dashboard.dateShiftHint': 'Совет: чтобы перенести только часть маршрута, используйте «Добавить день» в планировщике.', 'dashboard.greeting.morning': 'Доброе утро,', 'dashboard.greeting.afternoon': 'Добрый день,', 'dashboard.greeting.evening': 'Добрый вечер,', diff --git a/shared/src/i18n/sv/dashboard.ts b/shared/src/i18n/sv/dashboard.ts index 209e066dc..3d835dae6 100644 --- a/shared/src/i18n/sv/dashboard.ts +++ b/shared/src/i18n/sv/dashboard.ts @@ -98,6 +98,17 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Använd Unsplash-foto av {photographer}', 'dashboard.titleRequired': 'Titel är obligatoriskt', 'dashboard.endDateError': 'Slutdatumet måste ligga efter startdatumet', + 'dashboard.dateShiftTitle': 'Nytt startdatum', + 'dashboard.dateShiftIntro': + 'Du har ändrat när resan börjar. Hur ska dina planer följa de nya datumen?', + 'dashboard.dateShiftKeepBookings': 'Behåll bokningar på sina datum', + 'dashboard.dateShiftKeepBookingsDesc': + 'Dagsplanerna flyttas med de nya datumen, medan bokningar och boenden ligger kvar på sina ursprungliga datum så länge dessa fortfarande ingår i resan.', + 'dashboard.dateShiftAll': 'Flytta allt', + 'dashboard.dateShiftAllDesc': + 'Hela resplanen flyttas med de nya datumen, inklusive bokningar och boenden.', + 'dashboard.dateShiftHint': + 'Tips: om du bara vill flytta en del av resplanen kan du använda "Lägg till dag" i planeraren istället.', 'dashboard.greeting.morning': 'God morgon,', 'dashboard.greeting.afternoon': 'God eftermiddag,', 'dashboard.greeting.evening': 'God kväll,', diff --git a/shared/src/i18n/tr/dashboard.ts b/shared/src/i18n/tr/dashboard.ts index 24d8cdf9b..ed157aaba 100644 --- a/shared/src/i18n/tr/dashboard.ts +++ b/shared/src/i18n/tr/dashboard.ts @@ -98,6 +98,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '{photographer} tarafından çekilen Unsplash fotoğrafını kullan', 'dashboard.titleRequired': 'Başlık gerekli', 'dashboard.endDateError': 'Bitiş tarihi başlangıçtan sonra olmalı', + 'dashboard.dateShiftTitle': 'Yeni başlangıç tarihi', + 'dashboard.dateShiftIntro': 'Bu seyahatin başlangıç tarihini değiştirdiniz. Planlarınız yeni tarihlere nasıl uyum sağlasın?', + 'dashboard.dateShiftKeepBookings': 'Rezervasyonları kendi tarihlerinde tut', + 'dashboard.dateShiftKeepBookingsDesc': 'Gün planları yeni tarihlerle birlikte taşınır; rezervasyonlar ve konaklamalar ise seyahatin kapsamında kaldıkları sürece orijinal tarihlerinde kalır.', + 'dashboard.dateShiftAll': 'Her şeyi kaydır', + 'dashboard.dateShiftAllDesc': 'Rezervasyonlar ve konaklamalar dahil tüm plan yeni tarihlerle birlikte taşınır.', + 'dashboard.dateShiftHint': 'İpucu: planın yalnızca bir kısmını kaydırmak için planlayıcıdaki "Gün ekle" özelliğini kullanın.', 'dashboard.greeting.morning': 'Günaydın,', 'dashboard.greeting.afternoon': 'İyi günler,', 'dashboard.greeting.evening': 'İyi akşamlar,', diff --git a/shared/src/i18n/uk/dashboard.ts b/shared/src/i18n/uk/dashboard.ts index 368e438e3..64dc70394 100644 --- a/shared/src/i18n/uk/dashboard.ts +++ b/shared/src/i18n/uk/dashboard.ts @@ -100,6 +100,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': 'Використати фото Unsplash від {photographer}', 'dashboard.titleRequired': "Назва обов'язкова", 'dashboard.endDateError': 'Дата закінчення повинна бути пізніше дати початку', + 'dashboard.dateShiftTitle': 'Нова дата початку', + 'dashboard.dateShiftIntro': 'Ви змінили дату початку поїздки. Як ваші плани мають перейти на нові дати?', + 'dashboard.dateShiftKeepBookings': 'Залишити бронювання на своїх датах', + 'dashboard.dateShiftKeepBookingsDesc': 'Плани днів переміщуються разом із новими датами, а бронювання та проживання залишаються на своїх початкових датах, поки ті все ще входять до поїздки.', + 'dashboard.dateShiftAll': 'Перемістити все', + 'dashboard.dateShiftAllDesc': 'Весь маршрут переміщується на нові дати, включно з бронюваннями та проживанням.', + 'dashboard.dateShiftHint': 'Порада: щоб зсунути лише частину маршруту, скористайтеся «Додати день» у планувальнику.', 'dashboard.greeting.morning': 'Доброго ранку,', 'dashboard.greeting.afternoon': 'Доброго дня,', 'dashboard.greeting.evening': 'Доброго вечора,', diff --git a/shared/src/i18n/vi/dashboard.ts b/shared/src/i18n/vi/dashboard.ts index 2416f75b1..eef00611c 100644 --- a/shared/src/i18n/vi/dashboard.ts +++ b/shared/src/i18n/vi/dashboard.ts @@ -92,6 +92,15 @@ const dashboard: TranslationStrings = { 'dashboard.coverRemoveError': 'Không thể xóa', 'dashboard.titleRequired': 'Tiêu đề là bắt buộc', 'dashboard.endDateError': 'Ngày kết thúc phải sau ngày bắt đầu', + 'dashboard.dateShiftTitle': 'Ngày bắt đầu mới', + 'dashboard.dateShiftIntro': + 'Bạn đã thay đổi thời điểm bắt đầu chuyến đi. Các kế hoạch của bạn nên theo ngày mới như thế nào?', + 'dashboard.dateShiftKeepBookings': 'Giữ đặt chỗ theo ngày ban đầu', + 'dashboard.dateShiftKeepBookingsDesc': + 'Kế hoạch theo ngày sẽ dời theo ngày mới, trong khi đặt chỗ và chỗ ở vẫn giữ nguyên ngày ban đầu miễn là những ngày đó vẫn nằm trong chuyến đi.', + 'dashboard.dateShiftAll': 'Dời tất cả', + 'dashboard.dateShiftAllDesc': 'Toàn bộ lịch trình sẽ dời theo ngày mới, bao gồm cả đặt chỗ và chỗ ở.', + 'dashboard.dateShiftHint': 'Mẹo: để chỉ dời một phần lịch trình, hãy dùng "Thêm ngày" trong trình lập kế hoạch.', 'dashboard.greeting.morning': 'Chào buổi sáng,', 'dashboard.greeting.afternoon': 'Chào buổi chiều,', 'dashboard.greeting.evening': 'Buổi tối vui vẻ,', diff --git a/shared/src/i18n/zh-TW/dashboard.ts b/shared/src/i18n/zh-TW/dashboard.ts index cbcfe1475..2303f35bf 100644 --- a/shared/src/i18n/zh-TW/dashboard.ts +++ b/shared/src/i18n/zh-TW/dashboard.ts @@ -84,6 +84,13 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '使用 {photographer} 的 Unsplash 照片', 'dashboard.titleRequired': '標題為必填項', 'dashboard.endDateError': '結束日期必須晚於開始日期', + 'dashboard.dateShiftTitle': '新的開始日期', + 'dashboard.dateShiftIntro': '你變更了旅行的開始時間。你的計劃要如何配合新日期?', + 'dashboard.dateShiftKeepBookings': '預訂保留在原日期', + 'dashboard.dateShiftKeepBookingsDesc': '每日計劃會隨新日期移動,而預訂和住宿只要仍在旅行期間內,就會保留在原本的日期。', + 'dashboard.dateShiftAll': '全部移動', + 'dashboard.dateShiftAllDesc': '整個行程都會隨新日期移動,包括預訂和住宿。', + 'dashboard.dateShiftHint': '提示:若只想移動部分行程,請改用規劃頁面中的「新增日期」。', 'dashboard.greeting.morning': '早安,', 'dashboard.greeting.afternoon': '午安,', 'dashboard.greeting.evening': '晚安,', diff --git a/shared/src/i18n/zh/dashboard.ts b/shared/src/i18n/zh/dashboard.ts index f758870df..66eb7b2ce 100644 --- a/shared/src/i18n/zh/dashboard.ts +++ b/shared/src/i18n/zh/dashboard.ts @@ -84,6 +84,14 @@ const dashboard: TranslationStrings = { 'dashboard.useUnsplashPhoto': '使用 {photographer} 的 Unsplash 照片', 'dashboard.titleRequired': '标题为必填项', 'dashboard.endDateError': '结束日期必须晚于开始日期', + 'dashboard.dateShiftTitle': '新的开始日期', + 'dashboard.dateShiftIntro': '您更改了旅行的开始时间。您的计划应如何适应新的日期?', + 'dashboard.dateShiftKeepBookings': '保留预订的原定日期', + 'dashboard.dateShiftKeepBookingsDesc': + '日程计划将随新日期移动,而预订和住宿只要仍在旅行日期范围内,就保留其原定日期。', + 'dashboard.dateShiftAll': '全部顺移', + 'dashboard.dateShiftAllDesc': '整个行程将随新日期移动,包括预订和住宿。', + 'dashboard.dateShiftHint': '提示:如需仅移动部分行程,请改用行程规划中的「添加一天」。', 'dashboard.greeting.morning': '早上好,', 'dashboard.greeting.afternoon': '下午好,', 'dashboard.greeting.evening': '晚上好,', diff --git a/shared/src/trip/trip.schema.ts b/shared/src/trip/trip.schema.ts index 8abd0a57e..36d94828a 100644 --- a/shared/src/trip/trip.schema.ts +++ b/shared/src/trip/trip.schema.ts @@ -88,6 +88,13 @@ export const tripUpdateRequestSchema = z.object({ description: z.string().nullable().optional(), start_date: z.string().nullable().optional(), end_date: z.string().nullable().optional(), + /** + * How day-attached content follows a date-range change (#1288): + * 'keep_bookings' (default) — day plans move with the days; dated reservations and + * accommodations stay on their absolute dates while those remain inside the trip. + * 'shift_all' — the whole itinerary, bookings included, moves with the range. + */ + date_shift_mode: z.enum(['keep_bookings', 'shift_all']).optional(), currency: z.string().optional(), reminder_days: z.number().optional(), day_count: z.number().optional(),