Add real-time booking collaboration via WebSocket

- Backend: /ws relay endpoint (@fastify/websocket)
- Frontend: useHotelSocket hook with lock/unlock/booking events
- Calendar: lock overlay with diagonal stripes shows other manager editing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 18:05:09 +03:00
parent 1d24e5a4c4
commit 3506105fc1
7 changed files with 1919 additions and 9 deletions

View File

@@ -16,6 +16,8 @@ const ROW_HEIGHT_COMPACT = 34
const LABEL_WIDTH = 160
const DAYS_VISIBLE = 30
export type BookingLock = { checkIn: string; checkOut: string; lockedBy: string }
interface BookingCalendarProps {
rooms: Room[]
bookings: Booking[]
@@ -26,6 +28,9 @@ interface BookingCalendarProps {
rentalObjects?: RentalObject[]
rentalBookings?: RentalBooking[]
onRentalBookingCreate?: (b: RentalBooking) => void
locks?: Map<string, BookingLock>
onDraftStart?: (roomId: string, checkIn: string, checkOut: string) => void
onDraftCancel?: (roomId: string) => void
}
const CATEGORY_ORDER: Record<string, number> = {
@@ -49,7 +54,7 @@ function getRoomTypeColor(type: string): string {
return map[type] ?? 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300'
}
export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpdate, onBookingBulkUpdate, fadingBookingIds, rentalObjects, rentalBookings, onRentalBookingCreate }: BookingCalendarProps) {
export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpdate, onBookingBulkUpdate, fadingBookingIds, rentalObjects, rentalBookings, onRentalBookingCreate, locks = new Map(), onDraftStart, onDraftCancel }: BookingCalendarProps) {
const [startDate, setStartDate] = useState(() => startOfDay(new Date()))
const [visibleDays, setVisibleDays] = useState(DAYS_VISIBLE)
@@ -141,10 +146,17 @@ export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpd
const checkIn = format(addDays(startDate, minDay), 'yyyy-MM-dd')
const checkOut = format(addDays(startDate, maxDay + 1), 'yyyy-MM-dd')
setBookingModalDraft({ roomId: dragStart.roomId, checkIn, checkOut })
onDraftStart?.(dragStart.roomId, checkIn, checkOut)
setDragStart(null)
setDragEnd(null)
setDraft(null)
}, [dragStart, dragEnd, startDate])
}, [dragStart, dragEnd, startDate, onDraftStart])
const getLockStyle = (roomId: string) => {
const lock = locks.get(roomId)
if (!lock) return null
return getBlockStyle({ checkIn: lock.checkIn, checkOut: lock.checkOut, roomId } as Booking)
}
const getDraftStyle = (roomId: string) => {
if (!dragStart || dragEnd === null || dragStart.roomId !== roomId) return null
@@ -466,6 +478,30 @@ export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpd
style={{ left: draftStyle.left + 2, width: draftStyle.width }}
/>
)}
{/* Lock overlay — another manager is editing this room */}
{(() => {
const lockStyle = getLockStyle(room.id)
if (!lockStyle) return null
const lock = locks.get(room.id)!
return (
<div
className="absolute top-1 bottom-1 rounded-md pointer-events-none z-10"
style={{
left: lockStyle.left + 2,
width: lockStyle.width,
background: 'repeating-linear-gradient(45deg, rgba(100,116,139,0.2) 0px, rgba(100,116,139,0.2) 4px, rgba(100,116,139,0.05) 4px, rgba(100,116,139,0.05) 10px)',
border: '1.5px dashed rgba(100,116,139,0.55)',
}}
>
{lockStyle.width > 60 && (
<span className="absolute inset-x-1 top-1/2 -translate-y-1/2 text-[9px] text-slate-500 dark:text-slate-400 font-medium truncate text-center leading-tight select-none">
{lock.lockedBy}
</span>
)}
</div>
)
})()}
</div>
</div>
)
@@ -600,7 +636,10 @@ export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpd
open={true}
draft={bookingModalDraft}
rooms={rooms}
onClose={() => setBookingModalDraft(null)}
onClose={() => {
if (bookingModalDraft) onDraftCancel?.(bookingModalDraft.roomId)
setBookingModalDraft(null)
}}
onSave={(data) => {
onBookingCreate(data)
setBookingModalDraft(null)

View File

@@ -0,0 +1,44 @@
import { useEffect, useRef, useCallback } from 'react'
import type { Booking } from '../types'
export type WsMessage =
| { type: 'lock'; roomId: string; checkIn: string; checkOut: string; lockedBy: string }
| { type: 'unlock'; roomId: string }
| { type: 'booking:created'; booking: Booking }
| { type: 'booking:updated'; booking: Booking }
| { type: 'booking:deleted'; bookingId: string }
interface Options {
slug: string
token: string | null
onMessage: (msg: WsMessage) => void
}
export function useHotelSocket({ slug, token, onMessage }: Options) {
const wsRef = useRef<WebSocket | null>(null)
const cbRef = useRef(onMessage)
cbRef.current = onMessage
useEffect(() => {
if (!slug || !token) return
const base = (import.meta.env.VITE_API_URL as string | undefined) ?? 'https://api.hotelsync.ru'
const wsBase = base.replace(/^https/, 'wss').replace(/^http(?!s)/, 'ws')
const ws = new WebSocket(`${wsBase}/ws?hotel=${encodeURIComponent(slug)}&token=${encodeURIComponent(token)}`)
wsRef.current = ws
ws.onmessage = (e) => {
try { cbRef.current(JSON.parse(e.data as string) as WsMessage) } catch { /* ignore */ }
}
ws.onerror = () => { /* silent */ }
return () => { ws.close(); wsRef.current = null }
}, [slug, token])
const send = useCallback((msg: WsMessage) => {
const ws = wsRef.current
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg))
}, [])
return { send }
}

View File

@@ -1,14 +1,18 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useCallback } from 'react'
import { BookingCalendar } from '../components/calendar/BookingCalendar'
import { RENTAL_OBJECTS, MOCK_RENTAL_BOOKINGS } from '../data/rentalData'
import { useModules } from '../contexts/ModulesContext'
import { useAuth } from '../contexts/AuthContext'
import { api } from '../lib/api'
import { useHotelSocket } from '../hooks/useHotelSocket'
import type { WsMessage } from '../hooks/useHotelSocket'
import type { Room, Booking } from '../types'
import type { RentalBooking } from '../data/rentalData'
export type BookingLock = { checkIn: string; checkOut: string; lockedBy: string }
export function CalendarPage() {
const { user } = useAuth()
const { user, session } = useAuth()
const slug = user?.hotelSlug ?? ''
const { statuses } = useModules()
const isRentalActive = statuses['rental'] === 'active' || statuses['rental'] === 'trial'
@@ -17,6 +21,7 @@ export function CalendarPage() {
const [bookings, setBookings] = useState<Booking[]>([])
const [fadingBookings, setFadingBookings] = useState<Set<string>>(new Set())
const [rentalBookings, setRentalBookings] = useState<RentalBooking[]>(MOCK_RENTAL_BOOKINGS)
const [locks, setLocks] = useState<Map<string, BookingLock>>(new Map())
useEffect(() => {
if (!slug) return
@@ -29,6 +34,23 @@ export function CalendarPage() {
}).catch(console.error)
}, [slug])
const handleWsMessage = useCallback((msg: WsMessage) => {
if (msg.type === 'lock') {
setLocks(prev => new Map(prev).set(msg.roomId, { checkIn: msg.checkIn, checkOut: msg.checkOut, lockedBy: msg.lockedBy }))
} else if (msg.type === 'unlock') {
setLocks(prev => { const n = new Map(prev); n.delete(msg.roomId); return n })
} else if (msg.type === 'booking:created') {
setBookings(prev => prev.find(b => b.id === msg.booking.id) ? prev : [...prev, msg.booking])
setLocks(prev => { const n = new Map(prev); n.delete(msg.booking.roomId); return n })
} else if (msg.type === 'booking:updated') {
setBookings(prev => prev.map(b => b.id === msg.booking.id ? msg.booking : b))
} else if (msg.type === 'booking:deleted') {
setBookings(prev => prev.filter(b => b.id !== msg.bookingId))
}
}, [])
const { send } = useHotelSocket({ slug, token: session?.token ?? null, onMessage: handleWsMessage })
const handleCreate = async (data: Partial<Booking>) => {
try {
const created = await api.bookings.create(slug, {
@@ -39,6 +61,8 @@ export function CalendarPage() {
totalAmount: data.totalAmount, notes: data.notes,
})
setBookings(prev => [...prev, created])
send({ type: 'booking:created', booking: created })
if (data.roomId) send({ type: 'unlock', roomId: data.roomId })
} catch (err) {
console.error('Failed to create booking:', err)
}
@@ -54,6 +78,7 @@ export function CalendarPage() {
totalAmount: data.totalAmount, notes: data.notes,
})
setBookings(prev => prev.map(b => b.id === id ? updated : b))
send({ type: 'booking:updated', booking: updated })
if (data.status === 'cancelled') {
setFadingBookings(prev => new Set([...prev, id]))
setTimeout(() => {
@@ -79,14 +104,19 @@ export function CalendarPage() {
results.forEach(r => { next = next.map(b => b.id === r.id ? r : b) })
return next
})
results.forEach(r => send({ type: 'booking:updated', booking: r }))
} catch (err) {
console.error('Failed to bulk update bookings:', err)
}
}
const handleRentalCreate = (b: RentalBooking) => {
setRentalBookings(prev => [...prev, b])
}
const handleDraftStart = useCallback((roomId: string, checkIn: string, checkOut: string) => {
send({ type: 'lock', roomId, checkIn, checkOut, lockedBy: user?.name ?? 'Менеджер' })
}, [send, user?.name])
const handleDraftCancel = useCallback((roomId: string) => {
send({ type: 'unlock', roomId })
}, [send])
return (
<div className="flex flex-col h-full">
@@ -100,7 +130,10 @@ export function CalendarPage() {
fadingBookingIds={fadingBookings}
rentalObjects={isRentalActive ? RENTAL_OBJECTS : undefined}
rentalBookings={isRentalActive ? rentalBookings : undefined}
onRentalBookingCreate={isRentalActive ? handleRentalCreate : undefined}
onRentalBookingCreate={isRentalActive ? (b: RentalBooking) => setRentalBookings(prev => [...prev, b]) : undefined}
locks={locks}
onDraftStart={handleDraftStart}
onDraftCancel={handleDraftCancel}
/>
</div>
</div>