fix(reservations): restrict all booking dates to the trip span

This commit is contained in:
Konstantinos Thermos
2026-07-24 16:48:44 +03:00
committed by Maurice
parent 8769ed084e
commit c61203e607
4 changed files with 87 additions and 4 deletions
@@ -112,6 +112,14 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
[days, assignments, t, locale]
)
// Restrict non-hotel booking dates to the trip's span (#1662). Hotels already
// constrain to trip days via their day dropdowns. Falls back to no limit when
// the trip has no dated days.
const tripDateRange = useMemo(() => {
const dates = (days || []).map(d => d.date).filter((d): d is string => !!d).sort()
return { min: dates[0], max: dates[dates.length - 1] }
}, [days])
useEffect(() => {
// Match an existing place by name (exact, then loose contains) for hotels.
const matchPlaceId = (name: string | undefined): string | number => {
@@ -473,6 +481,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
const [, tm] = (form.reservation_time || '').split('T')
set('reservation_time', d ? (tm ? `${d}T${tm}` : d) : '')
}}
min={tripDateRange.min}
max={tripDateRange.max}
/>
</div>
<div style={{ flex: 1, minWidth: 0 }}>
@@ -494,6 +504,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
<CustomDatePicker
value={form.end_date}
onChange={d => set('end_date', d || '')}
min={tripDateRange.min}
max={tripDateRange.max}
/>
</div>
<div style={{ flex: 1, minWidth: 0 }}>
@@ -135,6 +135,45 @@ describe('CustomDatePicker', () => {
expect(screen.queryByPlaceholderText('DD.MM.YYYY')).toBeNull();
expect(screen.getAllByRole('button').length).toBeGreaterThan(0);
});
// ── min/max range restriction (#1662) ──────────────────────────────────────
it('FE-COMP-DATEPICKER-027: days outside [min,max] are disabled and not clickable', async () => {
const user = userEvent.setup();
render(<CustomDatePicker value="2026-03-15" onChange={onChange} min="2026-03-10" max="2026-03-20" />);
await user.click(screen.getAllByRole('button')[0]); // open March 2026
const day5 = screen.getAllByRole('button').find((b) => b.textContent?.trim() === '5');
expect((day5 as HTMLButtonElement).disabled).toBe(true);
await user.click(day5!);
expect(onChange).not.toHaveBeenCalled();
});
it('FE-COMP-DATEPICKER-028: days within [min,max] stay selectable', async () => {
const user = userEvent.setup();
render(<CustomDatePicker value="2026-03-15" onChange={onChange} min="2026-03-10" max="2026-03-20" />);
await user.click(screen.getAllByRole('button')[0]); // open March 2026
const day12 = screen.getAllByRole('button').find((b) => b.textContent?.trim() === '12');
expect((day12 as HTMLButtonElement).disabled).toBe(false);
await user.click(day12!);
expect(onChange).toHaveBeenCalledWith('2026-03-12');
});
it('FE-COMP-DATEPICKER-029: manual entry of an out-of-range date is rejected', async () => {
const user = userEvent.setup();
render(<CustomDatePicker value="" onChange={onChange} min="2026-03-10" max="2026-03-20" />);
await user.click(screen.getByRole('button', { name: /enter date manually/i }));
const input = screen.getByPlaceholderText('DD.MM.YYYY');
fireEvent.change(input, { target: { value: '2026-03-25' } });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onChange).not.toHaveBeenCalled();
});
it('FE-COMP-DATEPICKER-030: empty value opens the calendar on the first in-range month', async () => {
const user = userEvent.setup();
render(<CustomDatePicker value="" onChange={onChange} min="2026-03-10" max="2026-03-20" />);
await user.click(screen.getAllByRole('button')[0]); // open — should land on March 2026
expect(screen.getByText(/march 2026/i)).toBeTruthy();
});
});
// ─── CustomDateTimePicker ─────────────────────────────────────────────────────
@@ -19,6 +19,10 @@ interface CustomDatePickerProps {
style?: React.CSSProperties;
compact?: boolean;
borderless?: boolean;
// Optional inclusive ISO (YYYY-MM-DD) bounds. Dates outside the range are
// disabled in the calendar and rejected on manual entry.
min?: string;
max?: string;
}
export function CustomDatePicker({
@@ -28,6 +32,8 @@ export function CustomDatePicker({
style = {},
compact = false,
borderless = false,
min,
max,
}: CustomDatePickerProps) {
const { locale, t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -55,6 +61,12 @@ export function CustomDatePicker({
if (parsed) {
setViewYear(parsed.getUTCFullYear());
setViewMonth(parsed.getUTCMonth());
} else if (min || max) {
// No value yet: open on the first in-range month so the user isn't
// greeted by an all-disabled calendar.
const anchor = new Date((min || max) + 'T00:00:00Z');
setViewYear(anchor.getUTCFullYear());
setViewMonth(anchor.getUTCMonth());
}
setView('days');
}
@@ -149,11 +161,17 @@ export function CustomDatePicker({
})
: '';
// Inclusive range check on ISO (YYYY-MM-DD) strings — lexicographic order
// matches chronological order for this format.
const isOutOfRange = (iso: string) => (!!min && iso < min) || (!!max && iso > max);
const selectDay = (day: number) => {
const y = String(viewYear);
const m = String(viewMonth + 1).padStart(2, '0');
const d = String(day).padStart(2, '0');
onChange(`${y}-${m}-${d}`);
const iso = `${y}-${m}-${d}`;
if (isOutOfRange(iso)) return;
onChange(iso);
setOpen(false);
};
@@ -183,6 +201,7 @@ export function CustomDatePicker({
// Try ISO first — always works
if (/^\d{4}-\d{2}-\d{2}$/.test(input)) {
if (isOutOfRange(input)) return;
onChange(input);
return;
}
@@ -218,7 +237,9 @@ export function CustomDatePicker({
}
const year = y < 100 ? 2000 + y : y;
if (m < 1 || m > 12 || d < 1 || d > 31) return;
onChange(`${year}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`);
const iso = `${year}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
if (isOutOfRange(iso)) return;
onChange(iso);
};
const gridCellStyle = (selected: boolean, current: boolean): React.CSSProperties => ({
@@ -465,6 +486,7 @@ export function CustomDatePicker({
const sel = d === selectedDay;
const td = isToday(d);
const isoDate = `${viewYear}-${String(viewMonth + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
const disabled = isOutOfRange(isoDate);
const ariaLabel = new Date(isoDate + 'T00:00:00Z').toLocaleDateString(locale, {
day: 'numeric',
month: 'long',
@@ -476,6 +498,7 @@ export function CustomDatePicker({
key={d}
type="button"
onClick={() => selectDay(d)}
disabled={disabled}
aria-label={ariaLabel}
aria-pressed={sel}
style={{
@@ -486,9 +509,10 @@ export function CustomDatePicker({
alignItems: 'center',
justifyContent: 'center',
...gridCellStyle(sel, td),
...(disabled ? { opacity: 0.3, cursor: 'not-allowed' } : {}),
}}
onMouseEnter={(e) => {
if (!sel) e.currentTarget.style.background = 'var(--bg-hover)';
if (!sel && !disabled) e.currentTarget.style.background = 'var(--bg-hover)';
}}
onMouseLeave={(e) => {
if (!sel) e.currentTarget.style.background = 'transparent';
@@ -174,6 +174,12 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
badge: fmtDate(d.date),
}))
// Restrict non-hotel booking dates to the trip's span (#1662); hotels already
// constrain to trip days via their day dropdowns.
const tripDates = days.map(d => d.date).filter((d): d is string => !!d).sort()
const tripMinDate = tripDates[0]
const tripMaxDate = tripDates[tripDates.length - 1]
const handleClose = () => {
if (importReviewActive) { advanceImportReview(); return }
setShowReservationModal(false)
@@ -309,6 +315,8 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
<CustomDatePicker
value={startDate}
onChange={d => set('reservation_time', d ? (startTime ? `${d}T${startTime}` : d) : '')}
min={tripMinDate}
max={tripMaxDate}
/>
</div>
<div className="min-w-0 flex-1">
@@ -325,7 +333,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
<div className="mt-2 flex gap-2">
<div className="min-w-0 flex-[1.2]">
<Eyebrow className="mb-[5px] uppercase">{t('reservations.endDate')}</Eyebrow>
<CustomDatePicker value={form.end_date} onChange={d => set('end_date', d || '')} />
<CustomDatePicker value={form.end_date} onChange={d => set('end_date', d || '')} min={tripMinDate} max={tripMaxDate} />
</div>
<div className="min-w-0 flex-1">
<Eyebrow className="mb-[5px] uppercase">{t('reservations.endTime')}</Eyebrow>