feat(dayplan): a day can be deleted from the reorder dialog, after a warning that says what goes with it

Every row of the reorder dialog, and of the days sheet on a phone, now has a delete button. It first asks, and the question lists what goes with the day: planned places stay in the place list, notes and day texts are deleted, bookings stay without a day, a stay that checks in or out on the day is cancelled with its booking and expense (shown in the danger tone), and on a dated trip the later days and their bookings move one date earlier or the trip ends a day earlier.

The server side moved from a bare DELETE into DayRemovalService, which REST, the delete_day tool and the plugin RPC all use. It closes the numbering, keeps the dates on their positions like a reorder, re-stamps the moved bookings, shifts the road trip boundaries, cancels touching stays through the accommodations domain, refuses the last day of a trip, and fans out day:deleted, day:reordered and trip:updated so collaborators renumber and see the new day count and end date. The trip query moved into a leaf file so the days domain can read it without a module cycle.

On the client the delete is online only, runs optimistically through the days slice with the same reducer collaborators apply, and the ConfirmDialog gained a slot for extra content, an Escape that only closes itself, and the danger and accent tokens.
This commit is contained in:
Maurice
2026-09-23 18:42:02 +02:00
parent 436f0740fb
commit 2f6f921aef
78 changed files with 3086 additions and 170 deletions
+5 -2
View File
@@ -1,7 +1,7 @@
import { isEffectivelyOffline } from '../sync/networkMode'
import axios, { AxiosInstance } from 'axios'
import type { z } from 'zod'
import type { Place } from '../types'
import type { Place, Trip } from '../types'
import type { TransitProvider } from '@trek/shared'
import { randomId } from '../utils/randomId'
import {
@@ -438,7 +438,10 @@ export const daysApi = {
update: (tripId: number | string, dayId: number | string, data: DayUpdateRequest) => apiClient.put(`/trips/${tripId}/days/${dayId}`, data).then(r => r.data),
// Whole-day default route mode (#1281); per-segment leg modes override it.
updateTransport: (tripId: number | string, dayId: number | string, mode: string | null) => apiClient.put(`/trips/${tripId}/days/${dayId}/transport`, { transport_mode: mode }).then(r => r.data),
delete: (tripId: number | string, dayId: number | string) => apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
// Answers with the trip in list shape: its day count changed, and its end
// date when the day took the last date along.
delete: (tripId: number | string, dayId: number | string): Promise<{ success: boolean; trip?: Trip }> =>
apiClient.delete(`/trips/${tripId}/days/${dayId}`).then(r => r.data),
reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/days/reorder`, { orderedIds } satisfies DayReorderRequest).then(r => r.data),
}
@@ -76,6 +76,8 @@ interface DayPlanSidebarProps {
onReorder: (dayId: number, orderedIds: number[]) => void
onReorderDays?: (orderedIds: number[]) => void
onAddDay?: (position?: number) => void
/** Asks to delete a day from the reorder dialog; the planner owns the question. */
onDeleteDay?: (dayId: number) => void
/** Renaming lives in the day-detail panel (#1065); the sidebar only forwards the prop. */
onUpdateDayTitle: (dayId: number, title: string) => void
/** The day route is computed by the planner page itself; kept for the existing call sites. */
@@ -146,7 +148,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
trip, days, places, categories, assignments,
selectedDayId, selectedPlaceId, selectedAssignmentId,
onSelectDay, onPlaceClick, onDayDetail, accommodations = [],
onReorder, onReorderDays, onAddDay,
onReorder, onReorderDays, onAddDay, onDeleteDay,
onAssignToDay, onMoveToDay, onRemoveAssignment, onEditPlace, onDeletePlace,
reservations = [],
visibleConnectionIds = [],
@@ -1129,6 +1131,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
onReorder,
onReorderDays,
onAddDay,
onDeleteDay,
onAssignToDay,
onRemoveAssignment,
onEditPlace,
@@ -1331,6 +1334,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
onReorder,
onReorderDays,
onAddDay,
onDeleteDay,
onAssignToDay,
onRemoveAssignment,
onEditPlace,
@@ -1590,6 +1594,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
canManageShare={canManageShare}
onReorderDays={onReorderDays}
onAddDay={onAddDay}
onDeleteDay={onDeleteDay}
/>
{/* Tagesliste */}
@@ -1,4 +1,4 @@
// FE-PLANNER-DPTOOLBAR-001 to FE-PLANNER-DPTOOLBAR-023
// FE-PLANNER-DPTOOLBAR-001 to FE-PLANNER-DPTOOLBAR-024
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { downloadTripPDF } from '../PDF/TripPDF'
@@ -233,6 +233,16 @@ describe('DayPlanSidebarToolbar', () => {
expect(onAddDay).toHaveBeenCalledWith()
})
it('FE-PLANNER-DPTOOLBAR-024: the popup hands a delete request for its day to the planner', async () => {
const user = userEvent.setup()
const days = [buildDay({ id: 10, title: 'Day 1', day_number: 1 }), buildDay({ id: 11, title: 'Day 2', day_number: 2 })]
const onDeleteDay = vi.fn((_id: number) => {})
render(<DayPlanSidebarToolbar {...makeProps({ days, canEditDays: true, onReorderDays: vi.fn(), onAddDay: vi.fn(), onDeleteDay })} />)
await user.click(screen.getByRole('button', { name: 'dayplan.reorderDays' }))
await user.click(screen.getAllByRole('button', { name: 'dayplan.deleteDay' })[1])
expect(onDeleteDay).toHaveBeenCalledWith(11)
})
it('FE-PLANNER-DPTOOLBAR-021: the reorder button is hidden without edit rights or without days', () => {
const days = [buildDay({ id: 10 })]
const { rerender } = render(<DayPlanSidebarToolbar {...makeProps({ days, canEditDays: false, onReorderDays: vi.fn(), onAddDay: vi.fn() })} />)
@@ -37,6 +37,8 @@ interface DayPlanSidebarToolbarProps {
canManageShare?: boolean
onReorderDays?: (orderedIds: number[]) => void
onAddDay?: (position?: number) => void
/** Asks to delete a day from the reorder dialog; without it the dialog has no delete buttons. */
onDeleteDay?: (dayId: number) => void
}
export function DayPlanSidebarToolbar({
@@ -44,7 +46,7 @@ export function DayPlanSidebarToolbar({
allConnectionsShown = false, onToggleAllConnections,
t, locale, toast,
expandedDays, setExpandedDays, onUndo, canUndo, undoHover, setUndoHover, lastActionLabel,
canEditDays, canManageShare = true, onReorderDays, onAddDay,
canEditDays, canManageShare = true, onReorderDays, onAddDay, onDeleteDay,
}: DayPlanSidebarToolbarProps) {
const [reorderOpen, setReorderOpen] = useState(false)
const [exportOpen, setExportOpen] = useState(false)
@@ -197,6 +199,7 @@ export function DayPlanSidebarToolbar({
locale={locale}
onReorder={onReorderDays}
onAddDay={() => onAddDay()}
onDeleteDay={onDeleteDay}
onClose={() => setReorderOpen(false)}
/>
</div>
@@ -1,8 +1,9 @@
// FE-PLANNER-DAYREORDER-001 to FE-PLANNER-DAYREORDER-012
// FE-PLANNER-DAYREORDER-001 to FE-PLANNER-DAYREORDER-016
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { buildDay } from '../../../tests/helpers/factories'
import { DayReorderPopup } from './DayReorderPopup'
import { setForcedOffline } from '../../sync/networkMode'
import type { Day } from '../../types'
// The component takes `t` as a prop, so returning the key keeps assertions exact.
@@ -137,4 +138,47 @@ describe('DayReorderPopup', () => {
await user.click(screen.getByText('common.close'))
expect(onClose).toHaveBeenCalled()
})
describe('deleting a day', () => {
afterEach(() => setForcedOffline(false))
it('FE-PLANNER-DAYREORDER-013: each row asks to delete its own day, and only asks', async () => {
const user = userEvent.setup()
const onDeleteDay = vi.fn()
const onReorder = vi.fn()
render(<DayReorderPopup {...makeProps({ days: threeDays(), onDeleteDay, onReorder })} />)
const buttons = screen.getAllByRole('button', { name: 'dayplan.deleteDay' })
expect(buttons).toHaveLength(3)
await user.click(buttons[1])
expect(onDeleteDay).toHaveBeenCalledWith(7)
expect(onReorder).not.toHaveBeenCalled()
})
it('FE-PLANNER-DAYREORDER-014: without a delete handler the rows carry no delete button', () => {
render(<DayReorderPopup {...makeProps({ days: threeDays() })} />)
expect(screen.queryByRole('button', { name: 'dayplan.deleteDay' })).not.toBeInTheDocument()
// The label is still the row's second span, next to its position badge.
expect(rows()[0].querySelectorAll('span')[1].textContent).toBe('Paris')
})
it('FE-PLANNER-DAYREORDER-015: the only day of a trip cannot be deleted', async () => {
const user = userEvent.setup()
const onDeleteDay = vi.fn()
render(<DayReorderPopup {...makeProps({ days: [buildDay({ id: 3, title: 'Paris', day_number: 1 })], onDeleteDay })} />)
const button = screen.getByRole('button', { name: 'dayplan.deleteDay' })
expect(button).toBeDisabled()
await user.click(button)
expect(onDeleteDay).not.toHaveBeenCalled()
})
it('FE-PLANNER-DAYREORDER-016: offline every delete button is off, and hovering says why', async () => {
setForcedOffline(true)
const user = userEvent.setup()
render(<DayReorderPopup {...makeProps({ days: threeDays(), onDeleteDay: vi.fn() })} />)
const buttons = screen.getAllByRole('button', { name: 'dayplan.deleteDay' })
expect(buttons.every(b => (b as HTMLButtonElement).disabled)).toBe(true)
await user.hover(buttons[0].parentElement as HTMLElement)
expect(await screen.findByText('dayplan.daysOffline')).toBeInTheDocument()
})
})
})
@@ -1,6 +1,10 @@
import { useState } from 'react'
import { GripVertical, ArrowUp, ArrowDown, Plus } from 'lucide-react'
import { GripVertical, ArrowUp, ArrowDown, Plus, Trash2 } from 'lucide-react'
import Modal from '../shared/Modal'
import Tooltip from '../shared/Tooltip'
import { useNetworkMode } from '../../hooks/useNetworkMode'
import { dayLabel } from '../../utils/dayLabel'
import { deleteDayBlockedReason } from '../../utils/dayDeleteImpact'
import type { Day } from '../../types'
interface DayReorderPopupProps {
@@ -10,29 +14,25 @@ interface DayReorderPopupProps {
locale: string
onReorder: (orderedIds: number[]) => void
onAddDay: () => void
/** Asks to delete a day; the planner opens the question. Without it rows have no delete button. */
onDeleteDay?: (dayId: number) => void
onClose: () => void
}
/**
* Modal for moving whole days around: drag a row by its grip or use the up/down
* arrows, and add a day at the end. Day headers stay untouched — this is the
* single surface for ordering. Reorders are applied optimistically by the store,
* so the list reflects each move immediately.
* arrows, add a day at the end, or delete one. Day headers stay untouched, so
* this is the single surface for ordering. Reorders are applied optimistically
* by the store, so the list reflects each move immediately. A delete only asks:
* the planner shows what goes with the day before anything happens.
*/
export function DayReorderPopup({ isOpen, days, t, locale, onReorder, onAddDay, onClose }: DayReorderPopupProps) {
export function DayReorderPopup({ isOpen, days, t, locale, onReorder, onAddDay, onDeleteDay, onClose }: DayReorderPopupProps) {
const [dragIndex, setDragIndex] = useState<number | null>(null)
const [overIndex, setOverIndex] = useState<number | null>(null)
const { offline } = useNetworkMode()
const ordered = [...days].sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0))
const label = (day: Day, index: number) => {
if (day.title) return day.title
if (day.date) {
const d = new Date(day.date + 'T00:00:00')
return d.toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' })
}
return t('dayplan.dayN', { n: index + 1 })
}
const deleteBlocked = deleteDayBlockedReason(ordered.length, offline, t)
const move = (from: number, to: number) => {
if (to < 0 || to >= ordered.length || from === to) return
@@ -120,7 +120,7 @@ export function DayReorderPopup({ isOpen, days, t, locale, onReorder, onAddDay,
{index + 1}
</span>
<span style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{label(day, index)}
{dayLabel(day, index, t, locale)}
</span>
<button
type="button"
@@ -140,6 +140,24 @@ export function DayReorderPopup({ isOpen, days, t, locale, onReorder, onAddDay,
>
<ArrowDown size={14} strokeWidth={2} />
</button>
{onDeleteDay && (
<>
<span aria-hidden="true" className="mx-0.5 h-5 w-px flex-shrink-0 bg-edge-faint" />
<Tooltip label={deleteBlocked ?? t('dayplan.deleteDay')} placement="left">
<span className="inline-flex flex-shrink-0">
<button
type="button"
onClick={() => onDeleteDay(day.id)}
disabled={!!deleteBlocked}
aria-label={t('dayplan.deleteDay')}
className="grid h-7 w-7 place-items-center rounded-[7px] border border-edge-faint text-content-muted transition-colors hover:bg-danger-soft hover:text-danger focus-visible:bg-danger-soft focus-visible:text-danger disabled:cursor-default disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-content-muted"
>
<Trash2 size={14} strokeWidth={2} />
</button>
</span>
</Tooltip>
</>
)}
</div>
))}
</div>
@@ -1,6 +1,7 @@
import { render, screen, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import ConfirmDialog from './ConfirmDialog';
import Modal from './Modal';
describe('ConfirmDialog', () => {
const onClose = vi.fn();
@@ -91,6 +92,44 @@ describe('ConfirmDialog', () => {
process.off('unhandledRejection', unhandled);
});
it('FE-COMP-CONFIRM-010: extra content renders under the message, and the card widens for it', () => {
render(
<ConfirmDialog isOpen={true} onClose={onClose} onConfirm={onConfirm} message="Delete it?">
<ul aria-label="consequences"><li>Stay at Harbour Hotel</li></ul>
</ConfirmDialog>
);
const list = screen.getByRole('list', { name: 'consequences' });
expect(list).toHaveTextContent('Stay at Harbour Hotel');
expect(screen.getByText('Delete it?').compareDocumentPosition(list) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(document.querySelector('.max-w-md')).not.toBeNull();
});
it('FE-COMP-CONFIRM-011: Escape takes back the question only, not the dialog it was asked from', () => {
const closeModal = vi.fn();
render(
<>
<Modal isOpen={true} onClose={closeModal} title="Reorder days">rows</Modal>
<ConfirmDialog isOpen={true} onClose={onClose} onConfirm={onConfirm} message="Delete it?" />
</>
);
fireEvent.keyDown(document.body, { key: 'Escape' });
expect(onClose).toHaveBeenCalledOnce();
expect(closeModal).not.toHaveBeenCalled();
// Other keys pass through untouched.
fireEvent.keyDown(document.body, { key: 'Enter' });
expect(onClose).toHaveBeenCalledOnce();
});
it('FE-COMP-CONFIRM-012: the danger look comes from the danger tokens, the plain one from the accent', () => {
const { unmount } = render(<ConfirmDialog isOpen={true} onClose={onClose} onConfirm={onConfirm} />);
expect(screen.getByRole('button', { name: /delete/i })).toHaveClass('bg-danger');
expect(document.querySelector('.bg-danger-soft')).not.toBeNull();
unmount();
render(<ConfirmDialog isOpen={true} onClose={onClose} onConfirm={onConfirm} danger={false} confirmLabel="Keep" />);
expect(screen.getByRole('button', { name: 'Keep' })).toHaveClass('bg-accent', 'text-accent-text');
expect(document.querySelector('.bg-danger-soft')).toBeNull();
});
it('FE-COMP-CONFIRM-008: clicking backdrop calls onClose', async () => {
const user = userEvent.setup();
render(<ConfirmDialog isOpen={true} onClose={onClose} onConfirm={onConfirm} message="msg" />);
+20 -12
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useCallback } from 'react'
import React, { useEffect, useCallback, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n'
@@ -12,6 +12,8 @@ interface ConfirmDialogProps {
confirmLabel?: string
cancelLabel?: string
danger?: boolean
/** Extra content under the message, such as a list of what the action takes with it. */
children?: ReactNode
}
// Callers commonly pass an async handler that reports its own failure and then
@@ -33,18 +35,23 @@ export default function ConfirmDialog({
confirmLabel,
cancelLabel,
danger = true,
children,
}: ConfirmDialogProps) {
const { t } = useTranslation()
// Captured and stopped here: the question often opens over another dialog
// (a Modal) that closes on Escape too, and one key press should only take
// back the question, not the dialog it was asked from.
const handleEsc = useCallback((e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
if (e.key !== 'Escape') return
e.stopPropagation()
onClose()
}, [onClose])
useEffect(() => {
if (isOpen) {
document.addEventListener('keydown', handleEsc)
}
return () => document.removeEventListener('keydown', handleEsc)
if (!isOpen) return
document.addEventListener('keydown', handleEsc, true)
return () => document.removeEventListener('keydown', handleEsc, true)
}, [isOpen, handleEsc])
if (!isOpen) return null
@@ -60,22 +67,23 @@ export default function ConfirmDialog({
>
<div
role="presentation"
className="trek-modal-enter rounded-2xl shadow-2xl w-full max-w-sm p-6 bg-surface-card"
className={`trek-modal-enter rounded-2xl shadow-2xl w-full ${children ? 'max-w-md' : 'max-w-sm'} p-6 bg-surface-card`}
onClick={e => e.stopPropagation()}
>
<div className="flex items-start gap-4">
{danger && (
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
<AlertTriangle className="w-5 h-5 text-red-600" />
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-danger-soft flex items-center justify-center">
<AlertTriangle className="w-5 h-5 text-danger" />
</div>
)}
<div className="flex-1">
<div className="flex-1 min-w-0">
<h3 className="text-base font-semibold text-content">
{title || t('common.confirm')}
</h3>
<p className="mt-1 text-sm text-content-secondary">
{message}
</p>
{children}
</div>
</div>
@@ -88,8 +96,8 @@ export default function ConfirmDialog({
</button>
<button type="button"
onClick={() => { runConfirm(onConfirm); onClose() }}
className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors text-white ${
danger ? 'bg-red-600 hover:bg-red-700' : 'bg-blue-600 hover:bg-blue-700'
className={`px-4 py-2 text-sm font-medium rounded-lg transition-opacity hover:opacity-90 ${
danger ? 'bg-danger text-white' : 'bg-accent text-accent-text'
}`}
>
{confirmLabel || t('common.delete')}
@@ -0,0 +1,49 @@
// FE-COMP-DAYIMPACT-001 to FE-COMP-DAYIMPACT-003
import { describe, it, expect } from 'vitest'
import { BedDouble, MapPin } from 'lucide-react'
import { render, screen } from '../../../tests/helpers/render'
import DayImpactList from './DayImpactList'
import MDayImpactList from '../../mobile/components/MDayImpactList'
import type { ImpactLine } from '../../utils/dayImpactLines'
const lines: ImpactLine[] = [
{ key: 'stay-9', icon: BedDouble, tone: 'danger', text: 'Stay at Harbour Hotel', hint: 'Cancelled with its booking.' },
{ key: 'places', icon: MapPin, tone: 'neutral', text: 'Planned places: 3' },
]
describe('DayImpactList', () => {
it('FE-COMP-DAYIMPACT-001: one row per line, text and hint, named for assistive tech', () => {
render(<DayImpactList lines={lines} label="Delete Tue, Oct 13?" />)
const list = screen.getByRole('list', { name: 'Delete Tue, Oct 13?' })
const rows = screen.getAllByRole('listitem')
expect(list).toContainElement(rows[0])
expect(rows).toHaveLength(2)
expect(rows[0]).toHaveTextContent('Stay at Harbour Hotel')
expect(rows[0]).toHaveTextContent('Cancelled with its booking.')
expect(rows[1]).toHaveTextContent('Planned places: 3')
})
it('FE-COMP-DAYIMPACT-002: the tone reaches the row: money in the danger tokens, the rest in the content tokens', () => {
render(<DayImpactList lines={lines} />)
const [stay, places] = screen.getAllByRole('listitem')
expect(stay).toHaveAttribute('data-tone', 'danger')
expect(screen.getByText('Stay at Harbour Hotel')).toHaveClass('text-danger')
expect(stay.querySelector('span')).toHaveClass('bg-danger-soft')
expect(screen.getByText('Planned places: 3')).toHaveClass('text-content')
expect(places.querySelectorAll('p')).toHaveLength(1)
})
it('FE-COMP-DAYIMPACT-003: renders nothing without lines, and the phone skin draws the same rows in its own tokens', () => {
const { container } = render(<DayImpactList lines={[]} />)
expect(container).toBeEmptyDOMElement()
render(<MDayImpactList lines={lines} label="phone" />)
const phone = screen.getByRole('list', { name: 'phone' })
expect(phone.className).toContain('var(--m-inner)')
const rows = phone.querySelectorAll('li')
expect(rows).toHaveLength(2)
// Hairlines between rows, not above the first.
expect(rows[0].className).not.toContain('border-t')
expect(rows[1].className).toContain('border-t')
})
})
@@ -0,0 +1,66 @@
import type { ImpactLine, ImpactTone } from '../../utils/dayImpactLines'
/** The class names one shell draws the list with. */
export interface ImpactListSkin {
list: string
row: string
/** Between two rows; the desktop card divides them itself. */
divider: string
chip: string
iconSize: number
text: string
hint: string
chipTone: Record<ImpactTone, string>
textTone: Record<ImpactTone, string>
}
const DESKTOP: ImpactListSkin = {
list: 'mt-4 overflow-hidden rounded-xl border border-edge-faint bg-surface-secondary divide-y divide-edge-faint',
row: 'flex items-start gap-3 px-3 py-2.5',
divider: '',
chip: 'mt-0.5 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-lg',
iconSize: 15,
text: 'text-body font-medium leading-snug',
hint: 'mt-0.5 text-caption text-content-muted',
chipTone: {
neutral: 'bg-surface text-content-muted',
muted: 'bg-surface text-content-faint',
warning: 'bg-warning-soft text-warning',
danger: 'bg-danger-soft text-danger',
},
textTone: { neutral: 'text-content', muted: 'text-content-muted', warning: 'text-content', danger: 'text-danger' },
}
interface DayImpactListProps {
lines: ImpactLine[]
/** Names the list for assistive tech; the dialog title usually says it already. */
label?: string
/** The phone passes its own; the default is the desktop card. */
skin?: ImpactListSkin
}
/**
* What goes with the days being removed, one row per kind of content: an icon
* chip in the row's tone, the count, and a caption saying what happens to it.
* The rows come ready made from utils/dayImpactLines, and the look comes from a
* skin, so the desktop dialog and the phone sheet share this markup and differ
* only in their tokens.
*/
export default function DayImpactList({ lines, label, skin = DESKTOP }: DayImpactListProps) {
if (lines.length === 0) return null
return (
<ul aria-label={label} className={skin.list}>
{lines.map(({ key, icon: Icon, text, hint, tone }, i) => (
<li key={key} data-tone={tone} className={`${skin.row} ${i > 0 ? skin.divider : ''}`.trim()}>
<span className={`${skin.chip} ${skin.chipTone[tone]}`}>
<Icon size={skin.iconSize} strokeWidth={2} aria-hidden="true" />
</span>
<div className="min-w-0 flex-1">
<p className={`${skin.text} ${skin.textTone[tone]}`}>{text}</p>
{hint && <p className={skin.hint}>{hint}</p>}
</div>
</li>
))}
</ul>
)
}
@@ -0,0 +1,30 @@
import DayImpactList, { type ImpactListSkin } from '../../components/shared/DayImpactList'
import type { ImpactLine } from '../../utils/dayImpactLines'
/** The mobile tokens for the same rows: an inset card with hairlines between rows. */
const PHONE: ImpactListSkin = {
list: 'mt-3 overflow-hidden rounded-[13px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)]',
row: 'flex items-start gap-[10px] px-[11px] py-[9px]',
divider: 'border-t border-[color:var(--m-rowbr)]',
chip: 'mt-[1px] flex h-[26px] w-[26px] flex-none items-center justify-center rounded-full',
iconSize: 13,
text: 'text-[0.78125rem] font-semibold leading-snug',
hint: 'mt-[2px] text-[0.6875rem] leading-snug text-m-muted',
chipTone: {
neutral: 'bg-[color:var(--m-ic)] text-m-muted',
muted: 'bg-[color:var(--m-ic)] text-m-faint',
warning: 'bg-[color:color-mix(in_srgb,var(--m-st-pending)_14%,transparent)] text-[color:var(--m-st-pending)]',
danger: 'bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]',
},
textTone: {
neutral: 'text-m-ink',
muted: 'text-m-muted',
warning: 'text-m-ink',
danger: 'text-[color:var(--m-st-danger)]',
},
}
/** The phone's day impact list: DayImpactList drawn in the mobile tokens. */
export default function MDayImpactList({ lines, label }: { lines: ImpactLine[]; label?: string }) {
return <DayImpactList lines={lines} label={label} skin={PHONE} />
}
@@ -1,33 +1,24 @@
import { CalendarRange, Plus } from 'lucide-react'
import { CalendarRange, Plus, Trash2 } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import { ReorderStack } from '../plan/MPlanTimelineRows'
import { INNER_CLS, TileHeader } from './MTripSheetUi'
import { useTranslation } from '../../../../i18n'
import { dayLabel } from '../../../../utils/dayLabel'
import type { MTripSheetsProps } from '../MTripShell'
import type { Day } from '../../../../types'
/**
* Day management sheet ('days'): move whole days up/down and append a new day —
* the mobile counterpart of the desktop DayReorderPopup, button-based like the
* rest of the touch reordering (#1432). A day's places, notes and bookings
* move with it (store handles that optimistically).
* Day management sheet ('days'): move whole days up/down, append a new day or
* delete one, the mobile counterpart of the desktop DayReorderPopup and
* button-based like the rest of the touch reordering (#1432). A day's places,
* notes and bookings move with it (store handles that optimistically). Delete
* only asks; the confirm sheet with what goes with the day is MTripSheets'.
*/
export default function MDaysSheet({ planner, shell }: MTripSheetsProps) {
const { t, locale } = useTranslation()
const open = shell.sheet?.id === 'days'
const canEditDays = planner.can('day_edit', planner.trip)
const ordered = [...planner.days].sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0))
const label = (day: Day, index: number): string => {
if (day.title) return day.title
if (day.date) {
const d = new Date(`${day.date.slice(0, 10)}T00:00:00`)
if (!Number.isNaN(d.getTime())) {
return d.toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' })
}
}
return t('planner.dayN', { n: day.day_number ?? index + 1 })
}
const deleteBlocked = planner.deleteDayBlocked
const move = (from: number, to: number) => {
if (to < 0 || to >= ordered.length || from === to) return
@@ -57,7 +48,7 @@ export default function MDaysSheet({ planner, shell }: MTripSheetsProps) {
<span className="flex h-6 w-6 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] font-geist text-[0.65625rem] font-bold text-m-muted">
{i + 1}
</span>
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold">{label(day, i)}</span>
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold">{dayLabel(day, i, t, locale)}</span>
{canEditDays && (
<ReorderStack
onUp={() => move(i, i - 1)}
@@ -67,6 +58,18 @@ export default function MDaysSheet({ planner, shell }: MTripSheetsProps) {
t={t}
/>
)}
{canEditDays && (
<button
type="button"
onClick={() => planner.handleDeleteDay(day.id)}
disabled={!!deleteBlocked}
aria-label={t('dayplan.deleteDay')}
title={deleteBlocked ?? undefined}
className="flex h-[30px] w-[30px] flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)] disabled:text-m-faint disabled:opacity-40"
>
<Trash2 size={13} strokeWidth={2.2} />
</button>
)}
</div>
))}
</div>
@@ -80,6 +83,9 @@ export default function MDaysSheet({ planner, shell }: MTripSheetsProps) {
{t('dayplan.addDay')}
</button>
)}
{canEditDays && deleteBlocked && (
<p className="mt-[10px] text-center text-[0.6875rem] text-m-muted">{deleteBlocked}</p>
)}
</div>
</MSheet>
)
@@ -9,6 +9,7 @@ import { useAuthStore } from '../../../../store/authStore'
import { useSettingsStore } from '../../../../store/settingsStore'
import { useTripStore } from '../../../../store/tripStore'
import MConfirmSheet from '../../settings/MConfirmSheet'
import MDayImpactList from '../../../components/MDayImpactList'
import MDaySheet from './MDaySheet'
import MDaysSheet from './MDaysSheet'
import MAccommodationSheet from './MAccommodationSheet'
@@ -201,6 +202,22 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
planner.setDeletePlaceId(null)
}}
/>
{/* Delete-day confirm behind the days sheet's delete buttons. Mounted
last, so it opens over that sheet; the list of what goes with the day
comes ready made from the planner, the same one the desktop shows. */}
<MConfirmSheet
open={planner.deleteDayId != null}
onClose={() => planner.setDeleteDayId(null)}
title={planner.deleteDayTitle}
message={t('dayplan.deleteDayBody')}
confirmLabel={t('dayplan.deleteDay')}
cancelLabel={t('common.cancel')}
danger
onConfirm={() => { void planner.confirmDeleteDay() }}
>
<MDayImpactList lines={planner.deleteDayLines} label={planner.deleteDayTitle} />
</MConfirmSheet>
</>
)
}
+54 -1
View File
@@ -150,10 +150,21 @@ vi.mock('../components/Planner/ReservationModal', () => ({
}));
const capturedConfirmDialogProps: { current: Record<string, any> } = { current: {} };
// Every dialog the page renders, by title: the page holds several, and the last
// one rendered is not always the one a case is about. An open one draws its
// extra content, so a case can read the list it carries.
interface ConfirmDialogStub {
isOpen?: boolean
message?: string
confirmLabel?: string
onConfirm?: () => unknown
}
const capturedConfirmDialogsByTitle: { current: Record<string, ConfirmDialogStub> } = { current: {} };
vi.mock('../components/shared/ConfirmDialog', () => ({
default: (props: Record<string, any>) => {
capturedConfirmDialogProps.current = props;
return null;
capturedConfirmDialogsByTitle.current[String(props.title)] = props as ConfirmDialogStub;
return props.isOpen ? React.createElement('div', { 'data-testid': 'confirm-dialog' }, props.children) : null;
},
}));
@@ -276,6 +287,7 @@ beforeEach(() => {
capturedPlaceFormModalProps.current = {};
capturedReservationModalProps.current = {};
capturedConfirmDialogProps.current = {};
capturedConfirmDialogsByTitle.current = {};
capturedDayDetailPanelProps.current = {};
capturedTripFormModalProps.current = {};
capturedTripMembersModalProps.current = {};
@@ -1740,6 +1752,47 @@ describe('TripPlannerPage', () => {
});
});
describe('FE-PAGE-PLANNER-053: Deleting a day from the reorder dialog', () => {
it('asks with the list of what goes with the day, then deletes through the store', async () => {
vi.useFakeTimers();
seedTripStore({ id: 42 });
const deleteDay = vi.fn().mockResolvedValue(undefined);
const harbour = buildDay({ id: 902, trip_id: 42, day_number: 2, date: null, title: 'Harbour day' });
useTripStore.setState({
days: [buildDay({ id: 901, trip_id: 42, day_number: 1, date: null }), harbour],
dayNotes: {},
deleteDay,
});
renderPlannerPage(42);
act(() => { vi.runAllTimers(); });
vi.useRealTimers();
await waitFor(() => {
expect(screen.getByTestId('day-plan-sidebar')).toBeInTheDocument();
});
// The sidebar hands the reorder dialog its delete action; nothing opens until it is used.
expect(typeof capturedDayPlanSidebarProps.current.onDeleteDay).toBe('function');
expect(screen.queryByTestId('confirm-dialog')).not.toBeInTheDocument();
await act(async () => { capturedDayPlanSidebarProps.current.onDeleteDay(harbour.id); });
await waitFor(() => {
expect(capturedConfirmDialogsByTitle.current['Delete Harbour day?']?.isOpen).toBe(true);
});
const dialog = capturedConfirmDialogsByTitle.current['Delete Harbour day?'];
expect(dialog.message).toBe('The day is removed from the trip. This cannot be undone.');
expect(dialog.confirmLabel).toBe('Delete day');
expect(screen.getByRole('list', { name: 'Delete Harbour day?' })).toHaveTextContent('Day titles and descriptions: 1');
await act(async () => { await dialog.onConfirm?.(); });
expect(deleteDay).toHaveBeenCalledWith(42, harbour.id);
await waitFor(() => {
expect(screen.queryByTestId('confirm-dialog')).not.toBeInTheDocument();
});
});
});
describe('FE-PAGE-PLANNER-052: Road trip mode opens a booking the way the day plan does (#2428)', () => {
// The rail is mounted only with the addon on and the mode on for this trip; the
// road-trip hooks then read their own endpoints, answered empty here.
+16 -1
View File
@@ -42,6 +42,7 @@ import { addonsApi, accommodationsApi, authApi, tripsApi, assignmentsApi, mapsAp
import { accommodationRepo } from '../repo/accommodationRepo'
import { useAuthStore } from '../store/authStore'
import ConfirmDialog from '../components/shared/ConfirmDialog'
import DayImpactList from '../components/shared/DayImpactList'
import { useTripWebSocket } from '../hooks/useTripWebSocket'
import { useRouteCalculation } from '../hooks/useRouteCalculation'
import { usePlaceSelection } from '../hooks/usePlaceSelection'
@@ -304,6 +305,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
handleSelectDay, handlePlaceClick, handleMarkerClick, handleMapClick, handleMapContextMenu, handlePoiClick,
handleSavePlace, openPlaceEditor, handleDeletePlace, confirmDeletePlace, confirmDeletePlaces, confirmChangeCategory,
handleAssignToDay, handleMoveToDay, handleRemoveAssignment, handleReorder, handleReorderDays, handleAddDay, handleUpdateDayTitle,
deleteDayId, setDeleteDayId, deleteDayTitle, deleteDayLines, handleDeleteDay, confirmDeleteDay,
handleSaveReservation, handleSaveTransport, handleDeleteReservation,
selectedPlace, dayOrderMap, dayPlaces,
mapTileUrl, fontStyle, splashDone,
@@ -656,6 +658,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
onReorder={handleReorder}
onReorderDays={handleReorderDays}
onAddDay={handleAddDay}
onDeleteDay={handleDeleteDay}
onUpdateDayTitle={handleUpdateDayTitle}
onAssignToDay={handleAssignToDay}
onMoveToDay={handleMoveToDay}
@@ -948,7 +951,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
</div>
<div style={{ flex: 1, overflow: 'auto', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
{mobileSidebarOpen === 'left'
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, from, to, time }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill({ from, to, time }); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} onDeleteDay={handleDeleteDay} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, from, to, time }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill({ from, to, time }); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
: <PlacesSidebar tripId={tripId} places={places} categories={categories} assignments={assignments} accommodations={tripAccommodations} selectedDayId={selectedDayId} onClearSelectedDay={() => handleSelectDay(null)} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { openPlaceEditor(place); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} onBulkChangeCategory={(ids, catId) => confirmChangeCategory(ids, catId)} days={days} isMobile pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
}
</div>
@@ -1176,6 +1179,18 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
? `${t('trip.confirm.deletePlaces', { count: deletePlaceIds?.length ?? 0 })} ${deletePlacesNote}`
: t('trip.confirm.deletePlaces', { count: deletePlaceIds?.length ?? 0 })}
/>
{/* Deleting a day from the reorder dialog: the question lists what goes
with the day, and a booked stay in it shows in the danger tone. */}
<ConfirmDialog
isOpen={deleteDayId != null}
onClose={() => setDeleteDayId(null)}
onConfirm={confirmDeleteDay}
title={deleteDayTitle}
message={t('dayplan.deleteDayBody')}
confirmLabel={t('dayplan.deleteDay')}
>
<DayImpactList lines={deleteDayLines} label={deleteDayTitle} />
</ConfirmDialog>
<ConfirmDialog
isOpen={!!stayRelease}
onClose={() => setStayRelease(null)}
@@ -0,0 +1,99 @@
import { useCallback, useMemo, useState } from 'react'
import { useTripStore } from '../../store/tripStore'
import { useNetworkMode } from '../../hooks/useNetworkMode'
import { dayDeleteImpact, deleteDayBlockedReason } from '../../utils/dayDeleteImpact'
import { deleteDayLines as buildDeleteDayLines, type ImpactLine } from '../../utils/dayImpactLines'
import { dayLabel } from '../../utils/dayLabel'
import { formatDate } from '../../utils/formatters'
import type { Accommodation, Day, Place, Reservation, Trip } from '../../types'
type Translate = (key: string, params?: Record<string, string | number>) => string
interface DayDeleteOptions {
tripId: number
trip: Trip | null
days: Day[]
places: Place[]
reservations: Reservation[]
accommodations: Accommodation[]
canEditDays: boolean
t: Translate
locale: string
toast: { success: (message: string) => unknown; error: (message: string) => unknown }
/** After a delete went through: the stays and the route of the selected day are the planner's to reload. */
onDeleted: () => void
}
export interface DayDelete {
/** The day the question is asked about, or null while no question is open. */
deleteDayId: number | null
setDeleteDayId: (dayId: number | null) => void
/** "Delete Tue, Oct 13?", the day named the way the reorder list names it. */
deleteDayTitle: string
/** What goes with the day, ready for DayImpactList and its phone skin. */
deleteDayLines: ImpactLine[]
/** Why no day can be deleted right now (the last day, offline), or null. */
deleteDayBlocked: string | null
handleDeleteDay: (dayId: number) => void
confirmDeleteDay: () => Promise<void>
}
const byNumber = (a: Day, b: Day): number => (a.day_number ?? 0) - (b.day_number ?? 0)
/**
* Deleting a day from the reorder dialog, for both shells: which day is asked
* about, the question's title and the list of what goes with the day, and the
* delete itself. The desktop dialog and the phone sheet only render what this
* returns, which keeps the logic in one place for the duplication gate.
*
* There is no undo: the server cancels stays and moves dates in one go, and
* nothing puts all of that back. The question says so instead.
*/
export function useDayDelete(options: DayDeleteOptions): DayDelete {
const { tripId, trip, days, places, reservations, accommodations, canEditDays, t, locale, toast, onDeleted } = options
const { offline } = useNetworkMode()
const assignments = useTripStore(s => s.assignments)
const dayNotes = useTripStore(s => s.dayNotes)
const [deleteDayId, setDeleteDayId] = useState<number | null>(null)
const deleteDayBlocked = deleteDayBlockedReason(days.length, offline, t)
const ordered = useMemo(() => [...days].sort(byNumber), [days])
const index = deleteDayId == null ? -1 : ordered.findIndex(d => d.id === deleteDayId)
const target = index < 0 ? null : ordered[index]
const deleteDayTitle = useMemo(
() => (target ? t('dayplan.deleteDayTitle', { day: dayLabel(target, index, t, locale) }) : ''),
[target, index, t, locale],
)
const deleteDayLines = useMemo(() => {
if (!target) return []
const impact = dayDeleteImpact(target, days, { assignments, dayNotes, reservations, accommodations, places }, trip)
return buildDeleteDayLines(impact, t, iso => formatDate(iso, locale) ?? iso)
}, [target, days, assignments, dayNotes, reservations, accommodations, places, trip, t, locale])
const handleDeleteDay = useCallback((dayId: number) => {
if (!canEditDays || deleteDayBlocked) return
setDeleteDayId(dayId)
}, [canEditDays, deleteDayBlocked])
const confirmDeleteDay = useCallback(async () => {
if (deleteDayId == null) return
const dayId = deleteDayId
setDeleteDayId(null)
try {
await useTripStore.getState().deleteDay(tripId, dayId)
} catch (err: unknown) {
// The store has put the day back already; the server's own sentence is
// English, so the toast says it in the traveller's language instead.
console.error('Failed to delete day:', err)
toast.error(t('dayplan.deleteDayError'))
return
}
onDeleted()
toast.success(t('dayplan.deleteDaySuccess'))
}, [deleteDayId, tripId, toast, t, onDeleted])
return { deleteDayId, setDeleteDayId, deleteDayTitle, deleteDayLines, deleteDayBlocked, handleDeleteDay, confirmDeleteDay }
}
@@ -1,4 +1,4 @@
// FE-TP-HOOK-001 to FE-TP-HOOK-119
// FE-TP-HOOK-001 to FE-TP-HOOK-125
import React from 'react'
import { renderHook, act, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n/TranslationContext'
@@ -102,6 +102,7 @@ interface PlannerActions {
reorderAssignments: ReturnType<typeof vi.fn>
reorderDays: ReturnType<typeof vi.fn>
insertDay: ReturnType<typeof vi.fn>
deleteDay: ReturnType<typeof vi.fn>
updateDayTitle: ReturnType<typeof vi.fn>
addReservation: ReturnType<typeof vi.fn>
updateReservation: ReturnType<typeof vi.fn>
@@ -129,6 +130,7 @@ function makeActions(): PlannerActions {
reorderAssignments: vi.fn(async () => undefined),
reorderDays: vi.fn(async () => undefined),
insertDay: vi.fn(async () => undefined),
deleteDay: vi.fn(async () => undefined),
updateDayTitle: vi.fn(async () => undefined),
addReservation: vi.fn(async () => ({ id: 77 })),
updateReservation: vi.fn(async () => ({ id: 77 })),
@@ -2270,3 +2272,107 @@ describe('useTripPlanner — dropping a hit on the drive', () => {
expect(result.current.stopDraft).toBeNull()
})
})
describe('useTripPlanner: deleting a day', () => {
// Dated 1 to 3 June on a trip running 1 to 3 June, with a place on the middle day.
function seedDays(extra: Partial<TripStoreState> = {}) {
const place = buildPlace({ id: 70 })
return seedTrip({
trip: buildTrip({ id: 42, title: 'Kyoto', start_date: '2026-06-01', end_date: '2026-06-03' }),
days: [
buildDay({ id: 1, day_number: 1, date: '2026-06-01', title: null }),
buildDay({ id: 2, day_number: 2, date: '2026-06-02', title: 'Harbour day' }),
buildDay({ id: 3, day_number: 3, date: '2026-06-03', title: null }),
],
assignments: { '1': [], '2': [buildAssignment({ id: 20, day_id: 2, place })], '3': [] },
dayNotes: { '1': [], '2': [], '3': [] },
...extra,
} as Partial<TripStoreState>)
}
it('FE-TP-HOOK-122: asking needs day_edit; with it the question names the day and lists what goes with it', async () => {
seedStore(useAuthStore, { user: buildUser({ id: 2, role: 'user' }) })
usePermissionsStore.setState({ permissions: { day_edit: 'admin' } })
seedDays()
const denied = await renderPlanner()
act(() => { denied.result.current.handleDeleteDay(2) })
expect(denied.result.current.deleteDayId).toBeNull()
denied.unmount()
seedStore(useAuthStore, { user: buildUser({ id: 1 }) })
usePermissionsStore.setState({ permissions: {} })
const { result } = await renderPlanner()
act(() => { result.current.handleDeleteDay(2) })
expect(result.current.deleteDayId).toBe(2)
expect(result.current.deleteDayTitle).toBe('Delete Harbour day?')
expect(result.current.deleteDayLines.map(l => l.key)).toEqual(['places', 'texts', 'shift', 'shrink'])
expect(result.current.deleteDayLines.find(l => l.key === 'places')?.text).toBe('Planned places: 1')
})
it('FE-TP-HOOK-123: confirming deletes through the store, closes the question and reloads the stays', async () => {
seedDays()
const { result } = await renderPlanner()
act(() => { result.current.handleDeleteDay(2) })
vi.mocked(accommodationRepo.list).mockClear()
await act(async () => { await result.current.confirmDeleteDay() })
expect(actions.deleteDay).toHaveBeenCalledWith(42, 2)
expect(result.current.deleteDayId).toBeNull()
expect(accommodationRepo.list).toHaveBeenCalledWith(42)
expect(updateRouteForDay).toHaveBeenCalled()
expect(toasts).toContainEqual(expect.objectContaining({ type: 'success', message: 'Day deleted' }))
// A refusal is said in the traveller's language, and nothing is reloaded.
actions.deleteDay.mockRejectedValueOnce(new Error('A trip needs at least one day.'))
vi.mocked(accommodationRepo.list).mockClear()
act(() => { result.current.handleDeleteDay(3) })
await act(async () => { await result.current.confirmDeleteDay() })
expect(toasts).toContainEqual(expect.objectContaining({ type: 'error', message: 'Failed to delete day' }))
expect(accommodationRepo.list).not.toHaveBeenCalled()
// Without an open question there is nothing to confirm.
actions.deleteDay.mockClear()
await act(async () => { await result.current.confirmDeleteDay() })
expect(actions.deleteDay).not.toHaveBeenCalled()
})
it('FE-TP-HOOK-124: the last day and a missing connection block the question, and say why', async () => {
seedDays({ days: [buildDay({ id: 1, day_number: 1, date: '2026-06-01' })] } as Partial<TripStoreState>)
const single = await renderPlanner()
expect(single.result.current.deleteDayBlocked).toBe('A trip needs at least one day')
act(() => { single.result.current.handleDeleteDay(1) })
expect(single.result.current.deleteDayId).toBeNull()
single.unmount()
env.forcedOffline = true
seedDays()
const { result } = await renderPlanner()
expect(result.current.deleteDayBlocked).toBe('Changing days needs a connection')
act(() => { result.current.handleDeleteDay(2) })
expect(result.current.deleteDayId).toBeNull()
})
it('FE-TP-HOOK-125: undoing a day reorder skips the days deleted since, and steps aside once a day was added', async () => {
seedDays()
const { result } = await renderPlanner()
await act(async () => { result.current.handleReorderDays([3, 1, 2]) })
await waitFor(() => expect(result.current.canUndo).toBe(true))
// Day 2 went in the meantime: the old order without it is still one the server takes.
useTripStore.setState({ days: [buildDay({ id: 3, day_number: 1 }), buildDay({ id: 1, day_number: 2 })] })
await act(async () => { await result.current.undo() })
expect(actions.reorderDays).toHaveBeenLastCalledWith(42, [1, 3])
// A day added since leaves the old order short of one, so the undo does nothing.
await act(async () => { result.current.handleReorderDays([1, 3]) })
await waitFor(() => expect(result.current.canUndo).toBe(true))
useTripStore.setState({
days: [buildDay({ id: 1, day_number: 1 }), buildDay({ id: 3, day_number: 2 }), buildDay({ id: 9, day_number: 3 })],
})
actions.reorderDays.mockClear()
await act(async () => { await result.current.undo() })
expect(actions.reorderDays).not.toHaveBeenCalled()
})
})
+20 -1
View File
@@ -76,6 +76,7 @@ import {
type StoredConnections,
} from '../../utils/connectionsVisibility'
import { plannedPlaceIds, plannedPlaceIdsForDay } from '../../utils/plannedPlaces'
import { useDayDelete } from './useDayDelete'
/** Stable empty list so the road trip hook stays inert while its mode is off. */
const EMPTY_DAYS: Day[] = []
@@ -2508,7 +2509,13 @@ export function useTripPlanner() {
tripActions.reorderDays(tripId, orderedIds)
.then(() => {
pushUndo(t('dayplan.reorderUndo'), async () => {
await tripActions.reorderDays(tripId, prevIds)
// A day deleted since then drops out of the old order. When the list no
// longer matches the days there are (one was added), the old order is
// not one the server could take, so the undo steps aside.
const live = new Set(useTripStore.getState().days.map(d => d.id))
const restorable = prevIds.filter(id => live.has(id))
if (restorable.length !== live.size) return
await tripActions.reorderDays(tripId, restorable)
})
})
.catch(err => toast.error(err instanceof Error ? err.message : t('dayplan.reorderError')))
@@ -2519,6 +2526,17 @@ export function useTripPlanner() {
.catch(err => toast.error(err instanceof Error ? err.message : t('dayplan.addDayError')))
}, [tripId, toast])
// A deleted day can take a stay along, and the selected day's route may have
// lost its day or its stops.
const afterDayDeleted = useCallback(() => {
loadAccommodations()
updateRouteForDay(useTripStore.getState().selectedDayId)
}, [loadAccommodations, updateRouteForDay])
const dayDelete = useDayDelete({
tripId, trip, days, places: allPlaces, reservations, accommodations: tripAccommodations,
canEditDays: can('day_edit', trip), t, locale, toast, onDeleted: afterDayDeleted,
})
const handleSaveReservation = async (data: Record<string, string | number | null> & { title: string }) => {
try {
// Imported hotel with a reviewed address but no existing place picked: match
@@ -2844,6 +2862,7 @@ export function useTripPlanner() {
handleSelectDay, handlePlaceClick, handleMarkerClick, handleMapClick, handleMapContextMenu, openAddPlaceFromPoi, handlePoiClick,
handleSavePlace, openPlaceEditor, handleDeletePlace, confirmDeletePlace, confirmDeletePlaces, confirmChangeCategory,
handleAssignToDay, handleMoveToDay, handleRemoveAssignment, handleReorder, handleReorderDays, handleAddDay, handleUpdateDayTitle,
...dayDelete,
handleSaveReservation, handleSaveTransport, handleDeleteReservation,
selectedPlace, dayOrderMap, dayPlaces,
mapTileUrl, fontStyle, splashDone,
+33 -2
View File
@@ -1,11 +1,11 @@
// FE-REPO-DAY-001 to FE-REPO-DAY-004
// FE-REPO-DAY-001 to FE-REPO-DAY-006
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { dayRepo } from './dayRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildDay } from '../../tests/helpers/factories'
import { buildDay, buildTrip } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
@@ -57,3 +57,34 @@ describe('dayRepo.list', () => {
await expect(dayRepo.list(5)).rejects.toThrow()
})
})
describe('dayRepo.remove', () => {
it('FE-REPO-DAY-005: online, deletes through the API, drops the cached row and caches the trip it answers with', async () => {
await offlineDb.days.bulkPut([buildDay({ id: 41, trip_id: 5 }), buildDay({ id: 42, trip_id: 5 })])
const trip = buildTrip({ id: 5, end_date: '2026-06-02' })
let deleted = ''
server.use(http.delete('/api/trips/5/days/41', ({ request }) => {
deleted = new URL(request.url).pathname
return HttpResponse.json({ success: true, trip })
}))
const result = await dayRepo.remove(5, 41)
expect(deleted).toBe('/api/trips/5/days/41')
expect(result.trip).toMatchObject({ id: 5, end_date: '2026-06-02' })
expect(await offlineDb.days.get(41)).toBeUndefined()
expect(await offlineDb.days.get(42)).toBeDefined()
expect(await offlineDb.trips.get(5)).toMatchObject({ end_date: '2026-06-02' })
})
it('FE-REPO-DAY-006: offline, refuses without a request and keeps the cached row', async () => {
await offlineDb.days.put(buildDay({ id: 51, trip_id: 5 }))
const hit = vi.fn()
server.use(http.delete('/api/trips/5/days/51', () => { hit(); return HttpResponse.json({ success: true }) }))
setOnline(false)
await expect(dayRepo.remove(5, 51)).rejects.toThrow('Deleting a day needs a connection')
expect(hit).not.toHaveBeenCalled()
expect(await offlineDb.days.get(51)).toBeDefined()
})
})
+18 -2
View File
@@ -1,7 +1,8 @@
import { daysApi } from '../api/client'
import { offlineDb, upsertDays } from '../db/offlineDb'
import { offlineDb, upsertDays, upsertTrip } from '../db/offlineDb'
import { isEffectivelyOffline } from '../sync/networkMode'
import { onlineThenCache } from './withOfflineFallback'
import type { Day } from '../types'
import type { Day, Trip } from '../types'
export const dayRepo = {
async list(tripId: number | string): Promise<{ days: Day[] }> {
@@ -19,4 +20,19 @@ export const dayRepo = {
}),
)
},
/**
* Delete a day. Online only, deliberately: the server cancels the stays on the
* day, lets go of its bookings and moves the dates of the days after it, and a
* queued offline write could not replay that faithfully. The cached row goes
* right away, since this tab never hears its own day:deleted, and the trip the
* server answers with (new day count, maybe a new end date) replaces the cached one.
*/
async remove(tripId: number | string, dayId: number): Promise<{ trip?: Trip }> {
if (isEffectivelyOffline()) throw new Error('Deleting a day needs a connection')
const result = await daysApi.delete(tripId, dayId)
await offlineDb.days.delete(dayId)
if (result.trip) await upsertTrip(result.trip)
return { trip: result.trip }
},
}
+72 -2
View File
@@ -1,8 +1,8 @@
// FE-TSLICE-DAYS-001 to FE-TSLICE-DAYS-008 (whole-day reorder + insert, #589)
// FE-TSLICE-DAYS-001 to FE-TSLICE-DAYS-011 (whole-day reorder + insert, #589; delete)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildDay, buildReservation } from '../../../tests/helpers/factories';
import { buildAssignment, buildDay, buildDayNote, buildReservation, buildTrip } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
import type { Day } from '../../types';
@@ -178,4 +178,74 @@ describe('daysSlice', () => {
expect(useTripStore.getState().days.map(d => d.id)).toEqual([1, 2, 3]);
});
});
describe('deleteDay', () => {
const seedDayContent = () => seedStore(useTripStore, {
trip: buildTrip({ id: 1, start_date: '2025-06-01', end_date: '2025-06-03' }),
days: datedDays(),
assignments: { '1': [], '2': [buildAssignment({ day_id: 2 })], '3': [] },
dayNotes: { '1': [], '2': [buildDayNote({ day_id: 2 })], '3': [] },
selectedDayId: 2,
});
it('FE-TSLICE-DAYS-009: closes the gap at once, keeps the dates on their slots and takes the trip it is answered with', async () => {
seedDayContent();
const serverDays = [
buildDay({ id: 1, trip_id: 1, day_number: 1, date: '2025-06-01', title: 'Arrival' }),
buildDay({ id: 3, trip_id: 1, day_number: 2, date: '2025-06-02', title: 'Departure' }),
];
let optimistic: ReturnType<typeof useTripStore.getState> | null = null;
server.use(
http.delete('/api/trips/1/days/2', () => {
optimistic = useTripStore.getState();
return HttpResponse.json({ success: true, trip: buildTrip({ id: 1, start_date: '2025-06-01', end_date: '2025-06-02' }) });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays })),
http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [buildReservation({ id: 5, trip_id: 1, title: 'Let go' })] })),
);
await useTripStore.getState().deleteDay(1, 2);
const during = optimistic as unknown as ReturnType<typeof useTripStore.getState>;
expect(during.days.map(d => [d.id, d.day_number, d.date])).toEqual([[1, 1, '2025-06-01'], [3, 2, '2025-06-02']]);
expect('2' in during.assignments).toBe(false);
expect('2' in during.dayNotes).toBe(false);
const after = useTripStore.getState();
expect(after.trip?.end_date).toBe('2025-06-02');
expect(after.days.map(d => d.id)).toEqual([1, 3]);
expect(after.reservations.map(r => r.title)).toEqual(['Let go']);
});
it('FE-TSLICE-DAYS-010: a refusal puts every field back and throws the server sentence', async () => {
seedDayContent();
server.use(http.delete('/api/trips/1/days/2', () => HttpResponse.json({ error: 'A trip needs at least one day.' }, { status: 400 })));
await expect(useTripStore.getState().deleteDay(1, 2)).rejects.toThrow('A trip needs at least one day.');
const state = useTripStore.getState();
expect(state.days.map(d => d.id)).toEqual([1, 2, 3]);
expect(state.assignments['2']).toHaveLength(1);
expect(state.dayNotes['2']).toHaveLength(1);
expect(state.selectedDayId).toBe(2);
expect(state.trip?.end_date).toBe('2025-06-03');
});
it('FE-TSLICE-DAYS-011: a selection on the deleted day clears, one on another day stays', async () => {
seedDayContent();
server.use(
http.delete('/api/trips/1/days/:id', () => HttpResponse.json({ success: true })),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: datedDays() })),
http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [] })),
);
await useTripStore.getState().deleteDay(1, 2);
expect(useTripStore.getState().selectedDayId).toBeNull();
seedDayContent();
await useTripStore.getState().deleteDay(1, 3);
expect(useTripStore.getState().selectedDayId).toBe(2);
// Answered without a trip, the store keeps the one it has.
expect(useTripStore.getState().trip?.end_date).toBe('2025-06-03');
});
});
});
+48
View File
@@ -1,4 +1,5 @@
import { daysApi } from '../../api/client'
import { dayRepo } from '../../repo/dayRepo'
import type { StoreApi } from 'zustand'
import type { TripStoreState } from '../tripStore'
import type { Day } from '../../types'
@@ -10,6 +11,31 @@ type GetState = StoreApi<TripStoreState>['getState']
export interface DaysSlice {
reorderDays: (tripId: number | string, orderedIds: number[]) => Promise<void>
insertDay: (tripId: number | string, position?: number) => Promise<Day | undefined>
deleteDay: (tripId: number | string, dayId: number) => Promise<void>
}
type DayState = Pick<TripStoreState, 'days' | 'assignments' | 'dayNotes' | 'selectedDayId'>
/**
* The day state without one day, the way the server leaves it: the days after it
* move up one place, and on a dated trip the dates stay on their positions, so
* every later day takes the date one slot earlier. The day's assignments and
* notes go with it, and a selection on it is cleared.
*
* Both the optimistic delete below and a collaborator's day:deleted apply this,
* so the two ends of the same delete cannot drift apart field by field.
*/
export function withoutDay(state: DayState, dayId: number): DayState {
const ordered = [...state.days].sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0))
const dates = ordered.map(d => d.date).filter((d): d is string => !!d).sort()
const days = ordered
.filter(d => d.id !== dayId)
.map((d, i) => ({ ...d, day_number: i + 1, date: dates.length ? (dates[i] ?? null) : d.date }))
const assignments = { ...state.assignments }
delete assignments[String(dayId)]
const dayNotes = { ...state.dayNotes }
delete dayNotes[String(dayId)]
return { days, assignments, dayNotes, selectedDayId: state.selectedDayId === dayId ? null : state.selectedDayId }
}
export const createDaysSlice = (set: SetState, get: GetState): DaysSlice => ({
@@ -53,4 +79,26 @@ export const createDaysSlice = (set: SetState, get: GetState): DaysSlice => ({
throw new Error(getApiErrorMessage(err, 'Error adding day'))
}
},
// Delete a day. The list closes up at once; a refusal (the last day, no
// connection, a server error) puts every field back. Afterwards the store pulls
// the re-dated days and the bookings, which were re-stamped or let go of, and
// takes the trip the server answered with for its day count and end date.
deleteDay: async (tripId, dayId) => {
const { days, assignments, dayNotes, selectedDayId } = get()
const previous: DayState = { days, assignments, dayNotes, selectedDayId }
set(withoutDay(previous, dayId))
const outcome = await dayRepo.remove(tripId, dayId).then(
answer => ({ trip: answer.trip }),
(failure: unknown) => ({ failure }),
)
if ('failure' in outcome) {
set(previous)
throw new Error(getApiErrorMessage(outcome.failure, 'Error deleting day'))
}
if (outcome.trip) set({ trip: outcome.trip })
await get().refreshDays(tripId)
await get().loadReservations(tripId)
},
})
+8 -12
View File
@@ -5,6 +5,7 @@ import type { Assignment, Place, Day, DayNote, PackingItem, TodoItem, BudgetItem
import { offlineDb } from '../../db/offlineDb'
import { useAuthStore } from '../authStore'
import { mergeAssignmentPlace } from './placesSlice'
import { withoutDay } from './daysSlice'
type SetState = StoreApi<TripStoreState>['setState']
type GetState = StoreApi<TripStoreState>['getState']
@@ -330,18 +331,9 @@ export const STATE_APPLIERS: Partial<Record<TrekWsTripEventName, StateApplier>>
'day:updated': (payload, state) => ({
days: state.days.map(d => d.id === (payload.day as Day).id ? payload.day as Day : d),
}),
'day:deleted': (payload, state) => {
const removedDayId = String(payload.dayId)
const newAssignments = { ...state.assignments }
delete newAssignments[removedDayId]
const newDayNotes = { ...state.dayNotes }
delete newDayNotes[removedDayId]
return {
days: state.days.filter(d => d.id !== payload.dayId),
assignments: newAssignments,
dayNotes: newDayNotes,
}
},
// The same reducer the deleting tab ran optimistically: the later days move up
// one place, the dates stay on their positions, a selection on the day clears.
'day:deleted': (payload, state) => withoutDay(state, Number(payload.dayId)),
'day:reordered': (payload, state) => {
// Apply the new order instantly when we know all ids; the authoritative
// dates + re-stamped booking times are pulled by the refresh below.
@@ -564,6 +556,10 @@ export function handleRemoteEvent(set: SetState, get: GetState, event: WebSocket
if (tripId) get().loadReservations(tripId)
}
// A deleted day cancels a stay that checked in or out on it, and the stays
// live in page-local planner state rather than this store.
if (type === 'day:deleted') window.dispatchEvent(new CustomEvent('accommodations:refresh'))
// A reorder/insert re-pins dates and re-stamps booking times server-side, so
// pull the authoritative days + reservations for collaborators.
if (type === 'day:reordered') {
+124
View File
@@ -0,0 +1,124 @@
// FE-UTIL-DAYDEL-001 to FE-UTIL-DAYDEL-008
import { describe, it, expect } from 'vitest'
import { buildAssignment, buildDay, buildDayNote, buildPlace, buildReservation } from '../../tests/helpers/factories'
import { contentOnDays, dayDeleteImpact, deleteDayBlockedReason, type DayContentData } from './dayDeleteImpact'
import type { Accommodation, Day } from '../types'
const stay = (overrides: Partial<Accommodation>): Accommodation =>
({ id: 1, trip_id: 1, place_id: null, start_day_id: 0, end_day_id: 0, ...overrides }) as Accommodation
const empty = (): DayContentData => ({ assignments: {}, dayNotes: {}, reservations: [], accommodations: [] })
/** Three dated days, 1 to 3 June, and optionally a spare day without a date at the end. */
function datedDays(spare = false): Day[] {
const days = [
buildDay({ id: 1, day_number: 1, date: '2026-06-01' }),
buildDay({ id: 2, day_number: 2, date: '2026-06-02' }),
buildDay({ id: 3, day_number: 3, date: '2026-06-03' }),
]
return spare ? [...days, buildDay({ id: 4, day_number: 4, date: null })] : days
}
const range = { start_date: '2026-06-01', end_date: '2026-06-03' }
describe('contentOnDays', () => {
it('FE-UTIL-DAYDEL-001: an empty day holds nothing', () => {
const day = buildDay({ id: 7 })
expect(contentOnDays([day], empty())).toEqual({ places: 0, notes: 0, texts: 0, bookings: 0, stays: [] })
})
it('FE-UTIL-DAYDEL-002: places count once each, and the stop a stay wrote is the stay, not a place', () => {
const museum = buildPlace({ id: 50 })
const cafe = buildPlace({ id: 51 })
const hotel = buildPlace({ id: 52 })
const data = {
...empty(),
assignments: {
'7': [
buildAssignment({ day_id: 7, place: museum }),
buildAssignment({ day_id: 7, place: museum }),
buildAssignment({ day_id: 7, place: cafe }),
buildAssignment({ day_id: 7, place: hotel, accommodation_id: 9 }),
],
'8': [buildAssignment({ day_id: 8, place: buildPlace({ id: 53 }) })],
},
}
expect(contentOnDays([buildDay({ id: 7 })], data).places).toBe(2)
})
it('FE-UTIL-DAYDEL-003: notes count one by one, a day title and a day description one each', () => {
const data = { ...empty(), dayNotes: { '7': [buildDayNote({ day_id: 7 }), buildDayNote({ day_id: 7 })] } }
expect(contentOnDays([buildDay({ id: 7, title: 'Harbour day', notes: 'Ferry at nine' })], data)).toMatchObject({ notes: 2, texts: 2 })
expect(contentOnDays([buildDay({ id: 7, title: 'Harbour day', notes: null })], empty()).texts).toBe(1)
})
it('FE-UTIL-DAYDEL-004: bookings starting or ending on the day count, a cancelled stay\'s own booking does not', () => {
const data = {
...empty(),
accommodations: [stay({ id: 9, start_day_id: 7, end_day_id: 8 })],
reservations: [
buildReservation({ id: 1, day_id: 7 }),
buildReservation({ id: 2, day_id: 6, end_day_id: 7 }),
buildReservation({ id: 3, day_id: 8 }),
buildReservation({ id: 4, day_id: 7, type: 'hotel', accommodation_id: '9' }),
],
}
expect(contentOnDays([buildDay({ id: 7 })], data).bookings).toBe(2)
})
it('FE-UTIL-DAYDEL-005: a stay checking in or out on the day goes, named by its place, with its booking', () => {
const data: DayContentData = {
...empty(),
places: [buildPlace({ id: 60, name: 'Pension Alma' })],
accommodations: [
stay({ id: 1, start_day_id: 7, end_day_id: 8, place_name: 'Harbour Hotel' }),
stay({ id: 2, start_day_id: 5, end_day_id: 7, place_id: 60, reservation_title: 'Alma, two nights' }),
stay({ id: 3, start_day_id: 5, end_day_id: 7 }),
stay({ id: 4, start_day_id: 6, end_day_id: 8 }),
],
reservations: [buildReservation({ id: 30, title: 'Harbour Hotel, 1 night', accommodation_id: 1 })],
}
expect(contentOnDays([buildDay({ id: 7 })], data).stays).toEqual([
{ id: 1, name: 'Harbour Hotel', booking: 'Harbour Hotel, 1 night' },
{ id: 2, name: 'Pension Alma', booking: 'Alma, two nights' },
{ id: 3, name: '', booking: null },
])
})
})
describe('dayDeleteImpact', () => {
it('FE-UTIL-DAYDEL-006: with a spare day left, the later dated days move one date and their bookings go along', () => {
const days = datedDays(true)
const data = {
...empty(),
reservations: [
buildReservation({ id: 1, day_id: 3, reservation_time: '2026-06-03T10:00' }),
buildReservation({ id: 2, day_id: 1, end_day_id: 3, reservation_end_time: '2026-06-03T09:00' }),
buildReservation({ id: 3, day_id: 3, reservation_time: null }),
buildReservation({ id: 4, day_id: 1, reservation_time: '2026-06-01T08:00' }),
],
}
expect(dayDeleteImpact(days[1], days, data, range)).toMatchObject({ shiftedDays: 1, shiftedBookings: 2, newEndDate: null, isLastDay: false })
})
it('FE-UTIL-DAYDEL-007: with no spare day the last date goes, and a dated trip ends on the one before', () => {
const days = datedDays()
expect(dayDeleteImpact(days[0], days, empty(), range)).toMatchObject({ shiftedDays: 2, newEndDate: '2026-06-02' })
// A trip without a range keeps it; only its days move.
expect(dayDeleteImpact(days[0], days, empty(), { start_date: null, end_date: null }).newEndDate).toBeNull()
// The last day of the list moves nothing.
expect(dayDeleteImpact(days[2], days, empty(), range)).toMatchObject({ shiftedDays: 0, newEndDate: '2026-06-02' })
})
it('FE-UTIL-DAYDEL-008: a spare day moves no date, and the only day of a trip is the last one', () => {
const days = datedDays(true)
expect(dayDeleteImpact(days[3], days, empty(), range)).toMatchObject({ shiftedDays: 0, shiftedBookings: 0, newEndDate: null })
const only = [buildDay({ id: 1, day_number: 1 })]
expect(dayDeleteImpact(only[0], only, empty(), null).isLastDay).toBe(true)
const t = (key: string) => key
expect(deleteDayBlockedReason(1, true, t)).toBe('dayplan.deleteDayLast')
expect(deleteDayBlockedReason(3, true, t)).toBe('dayplan.daysOffline')
expect(deleteDayBlockedReason(3, false, t)).toBeNull()
})
})
+136
View File
@@ -0,0 +1,136 @@
import type { Accommodation, AssignmentsMap, Day, DayNotesMap, Place, Reservation, Trip } from '../types'
/** What the trip holds on its days, as the store and the planner have it. */
export interface DayContentData {
assignments: AssignmentsMap
dayNotes: DayNotesMap
reservations: Reservation[]
accommodations: Accommodation[]
places?: Place[]
}
/** A stay that goes with the days: checked in or out on one of them. */
export interface StayImpact {
id: number
name: string
/** Title of the booking that goes with it, or null when none is linked. */
booking: string | null
}
/** What sits on a set of days and would go with them. */
export interface DayContent {
/** Distinct places planned there. The places themselves stay on the trip. */
places: number
notes: number
/** Day titles and day descriptions. */
texts: number
/** Bookings on the days, the ones a cancelled stay takes along left out. */
bookings: number
stays: StayImpact[]
}
/** Deleting one day: its content, and what the dates of the other days do. */
export interface DayDeleteImpact extends DayContent {
/** Later dated days that take another date. */
shiftedDays: number
/** Bookings on those days whose date is re-stamped with them. */
shiftedBookings: number
/** The trip's new last date when the delete takes the last date along. */
newEndDate: string | null
isLastDay: boolean
}
const byNumber = (a: Day, b: Day): number => (a.day_number ?? 0) - (b.day_number ?? 0)
/** A reservation's link to a stay, which the wire carries as a number or a string. */
const stayOf = (r: Reservation): number | null => (r.accommodation_id == null ? null : Number(r.accommodation_id))
/**
* Count what sits on the given days, the way the server treats it when they go.
*
* A stop a stay wrote is the stay, not a place of its own, so it is not counted
* as one; a stay touching two of the days counts once, and the booking that came
* with it is part of the stay rather than one of the bookings. Shared by the day
* delete question and the warning before a trip is shortened.
*/
export function contentOnDays(days: Pick<Day, 'id' | 'title' | 'notes'>[], data: DayContentData): DayContent {
const ids = new Set(days.map(d => d.id))
const stays = data.accommodations.filter(stay => ids.has(stay.start_day_id) || ids.has(stay.end_day_id))
const stayIds = new Set(stays.map(stay => stay.id))
const placeIds = new Set<number>()
let notes = 0
let texts = 0
for (const day of days) {
for (const assignment of data.assignments[String(day.id)] ?? []) {
if (assignment.accommodation_id == null) placeIds.add(assignment.place.id)
}
notes += (data.dayNotes[String(day.id)] ?? []).length
if (day.title) texts += 1
if (day.notes) texts += 1
}
const onDays = (r: Reservation) => (r.day_id != null && ids.has(r.day_id)) || (r.end_day_id != null && ids.has(r.end_day_id))
const bookings = data.reservations.filter(r => onDays(r) && !stayIds.has(stayOf(r) ?? -1)).length
return {
places: placeIds.size,
notes,
texts,
bookings,
stays: stays.map(stay => {
const booking = data.reservations.find(r => stayOf(r) === stay.id)?.title ?? stay.reservation_title ?? null
const name = stay.place_name ?? data.places?.find(p => p.id === stay.place_id)?.name ?? booking ?? ''
return { id: stay.id, name, booking }
}),
}
}
/**
* What deleting one day does, as the server will do it (DayRemovalService): the
* dates stay on their positions, so every later dated day takes the date one slot
* earlier and the bookings on it are re-stamped along. When no day without a date
* is left to take the last date, the last date goes and a dated trip ends a day
* earlier.
*/
export function dayDeleteImpact(
day: Day,
days: Day[],
data: DayContentData,
trip: Pick<Trip, 'start_date' | 'end_date'> | null,
): DayDeleteImpact {
const content = contentOnDays([day], data)
const ordered = [...days].sort(byNumber)
const remaining = ordered.filter(d => d.id !== day.id)
const dates = ordered.map(d => d.date).filter((d): d is string => !!d).sort()
const moved = new Set<number>()
remaining.forEach((d, i) => {
const next = dates[i]
if (d.date && next && next !== d.date) moved.add(d.id)
})
const cancelled = new Set(content.stays.map(stay => stay.id))
const shiftedBookings = data.reservations.filter(r => {
if (cancelled.has(stayOf(r) ?? -1)) return false
const start = r.day_id != null && moved.has(r.day_id) && !!r.reservation_time
const end = r.end_day_id != null && moved.has(r.end_day_id) && !!r.reservation_end_time
return start || end
}).length
const dropsDate = remaining.length < dates.length
const newEndDate = dropsDate && trip?.start_date && trip.end_date ? (dates[remaining.length - 1] ?? null) : null
return { ...content, shiftedDays: moved.size, shiftedBookings, newEndDate, isLastDay: days.length <= 1 }
}
/**
* Why a day cannot be deleted right now, or null when it can. A trip keeps at
* least one day, and the delete runs on the server only: the cascade behind it
* (stays cancelled, bookings let go of, dates moved) is not something a queued
* offline write could replay faithfully.
*/
export function deleteDayBlockedReason(dayCount: number, offline: boolean, t: (key: string) => string): string | null {
if (dayCount <= 1) return t('dayplan.deleteDayLast')
if (offline) return t('dayplan.daysOffline')
return null
}
+56
View File
@@ -0,0 +1,56 @@
// FE-UTIL-DAYLINES-001 to FE-UTIL-DAYLINES-004
import { describe, it, expect } from 'vitest'
import { BedDouble, CalendarCheck } from 'lucide-react'
import { deleteDayLines, impactLines } from './dayImpactLines'
import type { DayDeleteImpact } from './dayDeleteImpact'
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}(${Object.entries(params).map(([k, v]) => `${k}=${v}`).join(',')})` : key
const nothing: DayDeleteImpact = {
places: 0, notes: 0, texts: 0, bookings: 0, stays: [],
shiftedDays: 0, shiftedBookings: 0, newEndDate: null, isLastDay: false,
}
describe('impactLines', () => {
it('FE-UTIL-DAYLINES-001: stays come first in the danger tone, then every kind that has something in it', () => {
const lines = impactLines({
places: 3, notes: 2, texts: 1, bookings: 4,
stays: [{ id: 9, name: 'Harbour Hotel', booking: 'HH 1 night' }, { id: 10, name: 'Pension Alma', booking: null }],
}, t, 'deleteDay')
expect(lines.map(l => [l.key, l.tone, l.text, l.hint])).toEqual([
['stay-9', 'danger', 'dayplan.impactStay(name=Harbour Hotel)', 'dayplan.deleteDayStayBookedHint(booking=HH 1 night)'],
['stay-10', 'danger', 'dayplan.impactStay(name=Pension Alma)', 'dayplan.deleteDayStayHint'],
['places', 'neutral', 'dayplan.impactPlaces(count=3)', 'dayplan.impactPlacesHint'],
['notes', 'neutral', 'dayplan.impactNotes(count=2)', 'dayplan.impactDeletedHint'],
['texts', 'neutral', 'dayplan.impactTexts(count=1)', 'dayplan.impactDeletedHint'],
['bookings', 'neutral', 'dayplan.impactBookings(count=4)', 'dayplan.deleteDayBookingsHint'],
])
expect(lines[0].icon).toBe(BedDouble)
})
it('FE-UTIL-DAYLINES-002: kinds with nothing in them are left out', () => {
expect(impactLines({ ...nothing, notes: 1 }, t, 'deleteDay').map(l => l.key)).toEqual(['notes'])
expect(impactLines(nothing, t, 'deleteDay')).toEqual([])
})
})
describe('deleteDayLines', () => {
const formatDate = (iso: string) => `<${iso}>`
it('FE-UTIL-DAYLINES-003: moved dates follow the content, with the bookings that move along and the new end', () => {
const lines = deleteDayLines({ ...nothing, places: 1, shiftedDays: 2, shiftedBookings: 3, newEndDate: '2026-06-02' }, t, formatDate)
expect(lines.map(l => [l.key, l.tone, l.text, l.hint])).toEqual([
['places', 'neutral', 'dayplan.impactPlaces(count=1)', 'dayplan.impactPlacesHint'],
['shift', 'warning', 'dayplan.deleteDayShift(count=2)', 'dayplan.deleteDayShiftBookingsHint(count=3)'],
['shrink', 'warning', 'dayplan.deleteDayShrink(date=<2026-06-02>)', 'dayplan.deleteDayShrinkHint'],
])
expect(deleteDayLines({ ...nothing, shiftedDays: 1 }, t, formatDate)[0].hint).toBe('dayplan.deleteDayShiftHint')
})
it('FE-UTIL-DAYLINES-004: a day with nothing on it and no dates to move gets one quiet row', () => {
const lines = deleteDayLines(nothing, t, formatDate)
expect(lines).toEqual([{ key: 'empty', icon: CalendarCheck, tone: 'muted', text: 'dayplan.deleteDayEmpty' }])
})
})
+97
View File
@@ -0,0 +1,97 @@
import { BedDouble, CalendarCheck, CalendarClock, CalendarMinus, MapPin, StickyNote, Ticket, Type } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import type { DayContent, DayDeleteImpact } from './dayDeleteImpact'
type Translate = (key: string, params?: Record<string, string | number>) => string
/**
* How loud a line is. `danger` is money: a stay cancelled with its booking and
* expense. `warning` is dates that move. `muted` is the reassurance that nothing
* is lost at all.
*/
export type ImpactTone = 'neutral' | 'muted' | 'warning' | 'danger'
/** One row of a warning list, ready for either shell to render. */
export interface ImpactLine {
key: string
icon: LucideIcon
text: string
hint?: string
tone: ImpactTone
}
/**
* The question the list answers. Deleting a day cancels a stay cleanly and lets
* go of its bookings; other ways of losing days treat both differently, so the
* hints are looked up per variant while the rows themselves stay the same.
*/
export type ImpactVariant = 'deleteDay'
const HINTS: Record<ImpactVariant, { bookings: string; stay: string; stayBooked: string }> = {
deleteDay: {
bookings: 'dayplan.deleteDayBookingsHint',
stay: 'dayplan.deleteDayStayHint',
stayBooked: 'dayplan.deleteDayStayBookedHint',
},
}
/**
* The rows for what sits on the days that go: stays first, because they cost
* money, then places, notes, day texts and bookings. Kinds with nothing in them
* are left out.
*/
export function impactLines(content: DayContent, t: Translate, variant: ImpactVariant): ImpactLine[] {
const hints = HINTS[variant]
const lines: ImpactLine[] = content.stays.map(stay => ({
key: `stay-${stay.id}`,
icon: BedDouble,
tone: 'danger',
text: t('dayplan.impactStay', { name: stay.name }),
hint: stay.booking ? t(hints.stayBooked, { booking: stay.booking }) : t(hints.stay),
}))
if (content.places > 0) {
lines.push({ key: 'places', icon: MapPin, tone: 'neutral', text: t('dayplan.impactPlaces', { count: content.places }), hint: t('dayplan.impactPlacesHint') })
}
if (content.notes > 0) {
lines.push({ key: 'notes', icon: StickyNote, tone: 'neutral', text: t('dayplan.impactNotes', { count: content.notes }), hint: t('dayplan.impactDeletedHint') })
}
if (content.texts > 0) {
lines.push({ key: 'texts', icon: Type, tone: 'neutral', text: t('dayplan.impactTexts', { count: content.texts }), hint: t('dayplan.impactDeletedHint') })
}
if (content.bookings > 0) {
lines.push({ key: 'bookings', icon: Ticket, tone: 'neutral', text: t('dayplan.impactBookings', { count: content.bookings }), hint: t(hints.bookings) })
}
return lines
}
/**
* The full list for the delete question: the content rows, then what happens to
* the dates, and a single quiet row for a day with nothing on it.
*/
export function deleteDayLines(impact: DayDeleteImpact, t: Translate, formatDate: (iso: string) => string): ImpactLine[] {
const lines = impactLines(impact, t, 'deleteDay')
if (impact.shiftedDays > 0) {
lines.push({
key: 'shift',
icon: CalendarClock,
tone: 'warning',
text: t('dayplan.deleteDayShift', { count: impact.shiftedDays }),
hint: impact.shiftedBookings > 0
? t('dayplan.deleteDayShiftBookingsHint', { count: impact.shiftedBookings })
: t('dayplan.deleteDayShiftHint'),
})
}
if (impact.newEndDate) {
lines.push({
key: 'shrink',
icon: CalendarMinus,
tone: 'warning',
text: t('dayplan.deleteDayShrink', { date: formatDate(impact.newEndDate) }),
hint: t('dayplan.deleteDayShrinkHint'),
})
}
if (lines.length === 0) {
lines.push({ key: 'empty', icon: CalendarCheck, tone: 'muted', text: t('dayplan.deleteDayEmpty') })
}
return lines
}
+22
View File
@@ -0,0 +1,22 @@
// FE-UTIL-DAYLABEL-001 to FE-UTIL-DAYLABEL-003
import { describe, it, expect } from 'vitest'
import { dayLabel } from './dayLabel'
const t = (key: string, params?: Record<string, string | number>) => `${key}:${params?.n}`
describe('dayLabel', () => {
it('FE-UTIL-DAYLABEL-001: a title wins over the date', () => {
expect(dayLabel({ title: 'Old Town', date: '2026-05-02' }, 1, t, 'en-US')).toBe('Old Town')
})
it('FE-UTIL-DAYLABEL-002: without a title the date reads as a short local weekday and day', () => {
expect(dayLabel({ title: null, date: '2026-05-01' }, 0, t, 'en-US')).toBe('Fri, May 1')
// A full timestamp names the same calendar day.
expect(dayLabel({ title: '', date: '2026-05-03T09:30:00' }, 2, t, 'en-US')).toBe('Sun, May 3')
})
it('FE-UTIL-DAYLABEL-003: no title and no usable date falls back to the position, counted from one', () => {
expect(dayLabel({ title: null, date: null }, 0, t, 'en-US')).toBe('dayplan.dayN:1')
expect(dayLabel({ title: null, date: 'not-a-date' }, 4, t, 'en-US')).toBe('dayplan.dayN:5')
})
})
+23
View File
@@ -0,0 +1,23 @@
import type { Day } from '../types'
type Translate = (key: string, params?: Record<string, string | number>) => string
/**
* How a day is named wherever days are listed as a whole: its title, else its
* date as a short weekday and day of the month, else "Day n" by its position.
*
* The reorder dialog, the phone's day sheet and the delete question all name a
* day, and they have to name it the same way, or the question asks about a day
* the list beside it calls something else. The date is read as a local calendar
* date, and a value that does not parse falls through to the position.
*/
export function dayLabel(day: Pick<Day, 'title' | 'date'>, index: number, t: Translate, locale: string): string {
if (day.title) return day.title
if (day.date) {
const date = new Date(`${day.date.slice(0, 10)}T00:00:00`)
if (!Number.isNaN(date.getTime())) {
return date.toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' })
}
}
return t('dayplan.dayN', { n: index + 1 })
}