import { useCallback, useMemo, type CSSProperties } from 'react' import { Download, Plane, Plus, SearchX } from 'lucide-react' import { useTripStore } from '../../store/tripStore' import { useCanDo } from '../../store/permissionsStore' import { useSettingsStore } from '../../store/settingsStore' import { useTranslation } from '../../i18n' import type { Reservation, Day, TripFile, AssignmentsMap, BudgetItem } from '../../types' import { usePluginViewContributions } from '../Plugins/PluginContributions' import EmptyState from '../shared/EmptyState' import type { TripMember } from '../Budget/BudgetPanelMemberChips' import { applyFilters, buildAssignmentLookup, costsFor, groupReservations, sortReservations, TYPE_ORDER, typeInfo, type BookingsKind, } from './bookings/bookingsModel' import { bookingFacts, formatDay, type BookingFacts } from './bookings/bookingFacts' import { SectionHead, fs } from './bookings/bookingParts' import { filesFor } from '../../utils/reservationFiles' import { useBookingsView } from './bookings/useBookingsView' import BookingsHeader from './bookings/BookingsHeader' import BookingCard from './bookings/BookingCard' import BookingsList from './bookings/BookingsList' import BookingsTimeline from './bookings/BookingsTimeline' import BookingDetailHost from './bookings/BookingDetailHost' import { useReservationDetailPlugins } from './bookings/useReservationDetailPlugins' import { useBookingActions } from './bookings/useBookingActions' import { bookingsCsv, bookingsFileName } from './bookings/bookingsExport' import { downloadBlob } from '../../utils/fileDownload' interface ReservationsPanelProps { tripId: number reservations: Reservation[] days: Day[] assignments: AssignmentsMap files?: TripFile[] onAdd: () => void onImport?: () => void bookingImportAvailable?: boolean onAirTrailImport?: () => void airTrailAvailable?: boolean onEdit: (reservation: Reservation) => void onDelete: (id: number) => void onNavigateToFiles: () => void titleKey?: string addManualKey?: string /** Which plugin view this panel represents — the transports tab is its own * contribution view, the bookings tab stays 'reservations'. */ contributionView?: 'reservations' | 'transports' /** Trip members + guests, for the traveller filter (#1517). */ tripMembers?: TripMember[] /** The other tab's bookings, shown dimmed on the timeline for orientation. */ contextReservations?: Reservation[] /** Shows a booking on the plan map: its route for a transport, its place otherwise. */ onShowOnMap?: (reservation: Reservation) => void isOnMap?: (reservation: Reservation) => boolean /** Opens the expense editor for an expense linked to a booking. */ onEditExpense?: (item: BudgetItem) => void /** Re-enters the transit search for a public-transit journey, seeded with its route. * Passed only to someone who may do that (day_edit, as on the plan); the tab adds no gate of its own. */ onChangeRoute?: (reservation: Reservation) => void } // Cards take a quarter of the row at most, so a wide screen shows four and a narrow one fewer. const CARD_GRID = 'grid gap-3.5 [grid-template-columns:repeat(auto-fill,minmax(max(300px,calc((100%_-_42px)/4)),1fr))]' /** The empty state's call-to-action buttons — same shape as the toolbar's. */ const CTA_STYLE: CSSProperties = { appearance: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 6, padding: '9px 14px', borderRadius: 10, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, } export default function ReservationsPanel({ tripId, reservations, days, assignments, files = [], onAdd, onImport, bookingImportAvailable, onAirTrailImport, airTrailAvailable, onEdit, onDelete, onNavigateToFiles, titleKey = 'reservations.title', addManualKey = 'reservations.addManual', contributionView = 'reservations', tripMembers = [], contextReservations = [], onShowOnMap, isOnMap, onEditExpense, onChangeRoute, }: ReservationsPanelProps) { const { t, locale } = useTranslation() const can = useCanDo() const trip = useTripStore(s => s.trip) const budgetItems = useTripStore(s => s.budgetItems) const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h' const canEdit = can('reservation_edit', trip) const kind: BookingsKind = contributionView === 'transports' ? 'transports' : 'bookings' const v = useBookingsView(kind, tripId) const contribFor = usePluginViewContributions(contributionView, tripId) const detailPlugins = useReservationDetailPlugins() // The cards' and rows' own status switch and delete question; the detail brings its own. const actions = useBookingActions(tripId, onDelete, r => { if (v.selectedId === r.id) v.setSelectedId(null) }) const labelOf = useCallback((type: string) => t(typeInfo(type).labelKey), [t]) const assignmentLookup = useMemo(() => buildAssignmentLookup(days, assignments), [days, assignments]) const tripCurrency = trip?.currency || 'EUR' const filtered = useMemo( () => applyFilters(reservations, { types: v.types, status: v.status, travelers: v.travelers, query: v.query }, labelOf), [reservations, v.types, v.status, v.travelers, v.query, labelOf], ) const sorted = useMemo(() => sortReservations(filtered, days, v.sort.by, v.sort.dir, labelOf, v.transitApart), [filtered, days, v.sort.by, v.sort.dir, labelOf, v.transitApart]) // What is on screen, in its order, as a spreadsheet (#1360). const exportCsv = () => { const csv = bookingsCsv(sorted, { type: labelOf, status: s => (s === 'confirmed' ? t('reservations.confirmed') : s === 'pending' ? t('reservations.pending') : s), headers: { type: t('reservations.export.type'), title: t('reservations.export.title'), status: t('reservations.status'), start: t('reservations.export.start'), end: t('reservations.export.end'), from: t('reservations.export.from'), to: t('reservations.export.to'), location: t('reservations.export.location'), confirmation: t('reservations.export.confirmation'), notes: t('reservations.export.notes'), }, }) downloadBlob(new Blob([csv], { type: 'text/csv;charset=utf-8' }), bookingsFileName(trip?.title, kind)) } const groups = useMemo(() => groupReservations(sorted, v.group, days, trip?.start_date, trip?.end_date, { confirmed: t('reservations.confirmed'), pending: t('reservations.pending'), transit: t('transit.sectionTitle'), before: t('reservations.group.before'), after: t('reservations.group.after'), undated: t('reservations.group.undated'), dayN: n => t('dayplan.dayN', { n }), typeLabel: labelOf, dayDate: d => formatDay(d, locale), }, v.transitApart), [sorted, v.group, days, trip?.start_date, trip?.end_date, locale, t, labelOf, v.transitApart]) const costsOf = useCallback((r: Reservation) => costsFor(r.id, budgetItems, tripCurrency), [budgetItems, tripCurrency]) // Formatted once per booking object and setting; a changed booking is a new object and formats again. const factsOf = useMemo(() => { const cache = new WeakMap() return (r: Reservation) => { let f = cache.get(r) if (!f) { f = bookingFacts(r, { t, locale, timeFormat, days, assignmentLookup, tripCurrency, hasLinkedCost: costsOf(r).length > 0 }) cache.set(r, f) } return f } }, [t, locale, timeFormat, days, assignmentLookup, tripCurrency, costsOf]) const typeCounts = useMemo(() => { const counts = new Map() for (const r of reservations) counts.set(r.type, (counts.get(r.type) ?? 0) + 1) for (const type of v.types) if (!counts.has(type)) counts.set(type, 0) return [...counts.entries()].sort((a, b) => TYPE_ORDER.indexOf(a[0]) - TYPE_ORDER.indexOf(b[0])).map(([type, count]) => ({ type, count })) }, [reservations, v.types]) const selected = v.selectedId != null ? reservations.find(r => r.id === v.selectedId) ?? null : null const select = (r: Reservation) => v.setSelectedId(v.selectedId === r.id ? null : r.id) // Whatever leaves the tab's own view closes the detail first: an editor, the map, an expense. const closeDetail = () => v.setSelectedId(null) const edit = (r: Reservation) => { closeDetail() onEdit(r) } const { toggleStatus, requestDelete } = actions const importAction = onImport && bookingImportAvailable ? onImport : undefined const airTrailAction = onAirTrailImport && airTrailAvailable ? onAirTrailImport : undefined const detail = selected && ( ) const content = (() => { if (reservations.length === 0) { return ( {importAction && } {airTrailAction && } ) : undefined} /> ) } if (sorted.length === 0) { return (
{t('reservations.noMatches')}
) } if (v.view === 'timeline') { return ( ) } if (v.view === 'list') { return ( filesFor(r, files).length} costsOf={costsOf} selectedId={v.selectedId} canEdit={canEdit} collapsed={v.collapsed} onToggleGroup={v.toggleGroup} onSelect={select} onEdit={edit} onDelete={requestDelete} onToggleStatus={toggleStatus} /> ) } return (
{groups.map(g => { const open = !v.collapsed(g.id) return (
{g.label && v.toggleGroup(g.id)} />} {open && (
{g.items.map(r => ( select(r)} onEdit={() => edit(r)} onDelete={() => requestDelete(r)} onToggleStatus={() => toggleStatus(r)} contributions={contribFor(r.id)} detailPlugins={detailPlugins} showFrames={v.selectedId !== r.id} /> ))}
)}
) })}
) })() return (
1 && reservations.some(r => (r.travelers || []).length > 0)} activeTravelers={v.travelers} onToggleTraveler={v.toggleTraveler} onClearTravelers={v.clearTravelers} group={v.group} onGroup={v.setGroup} sort={v.sort.by} sortDir={v.sort.dir} onSort={v.setSort} onSortDir={v.flipSort} byType={v.timeline.byType} onByType={v.toggleByType} showContext={v.timeline.context} onShowContext={v.toggleContext} transitApart={v.transitApart} onTransitApart={v.view === 'cards' && v.group === 'status' && reservations.some(r => r.type === 'transit') ? v.toggleTransitApart : undefined} viewIsDefault={v.viewIsDefault} onResetView={v.resetView} onExport={exportCsv} />
{content}
{detail} {actions.confirmDialog}
) }