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:
1751
backend/package-lock.json
generated
Normal file
1751
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@
|
|||||||
"@fastify/helmet": "^11.1.1",
|
"@fastify/helmet": "^11.1.1",
|
||||||
"@fastify/jwt": "^8.0.1",
|
"@fastify/jwt": "^8.0.1",
|
||||||
"@fastify/rate-limit": "^9.1.0",
|
"@fastify/rate-limit": "^9.1.0",
|
||||||
|
"@fastify/websocket": "^11.2.0",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"fastify": "^4.28.1",
|
"fastify": "^4.28.1",
|
||||||
"ioredis": "^5.3.2",
|
"ioredis": "^5.3.2",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import rateLimit from '@fastify/rate-limit'
|
|||||||
import { config } from './config'
|
import { config } from './config'
|
||||||
import './types' // side-effect: augments fastify types
|
import './types' // side-effect: augments fastify types
|
||||||
|
|
||||||
|
import wsRoutes from './routes/ws'
|
||||||
import authRoutes from './routes/auth'
|
import authRoutes from './routes/auth'
|
||||||
import hotelsRoutes from './routes/hotels'
|
import hotelsRoutes from './routes/hotels'
|
||||||
import roomsRoutes from './routes/rooms'
|
import roomsRoutes from './routes/rooms'
|
||||||
@@ -62,6 +63,7 @@ export async function buildApp() {
|
|||||||
fastify.get('/health', async () => ({ status: 'ok', ts: new Date().toISOString() }))
|
fastify.get('/health', async () => ({ status: 'ok', ts: new Date().toISOString() }))
|
||||||
|
|
||||||
// ── Routes ─────────────────────────────────────────────────────────────────
|
// ── Routes ─────────────────────────────────────────────────────────────────
|
||||||
|
await fastify.register(wsRoutes)
|
||||||
await fastify.register(authRoutes)
|
await fastify.register(authRoutes)
|
||||||
await fastify.register(hotelsRoutes)
|
await fastify.register(hotelsRoutes)
|
||||||
await fastify.register(roomsRoutes)
|
await fastify.register(roomsRoutes)
|
||||||
|
|||||||
40
backend/src/routes/ws.ts
Normal file
40
backend/src/routes/ws.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { FastifyPluginAsync } from 'fastify'
|
||||||
|
import fastifyWebsocket from '@fastify/websocket'
|
||||||
|
import type { WebSocket } from 'ws'
|
||||||
|
|
||||||
|
// hotel slug → set of connected clients
|
||||||
|
const hotelRooms = new Map<string, Set<WebSocket>>()
|
||||||
|
|
||||||
|
const ws: FastifyPluginAsync = async (fastify) => {
|
||||||
|
await fastify.register(fastifyWebsocket)
|
||||||
|
|
||||||
|
fastify.get<{ Querystring: { hotel?: string; token?: string } }>(
|
||||||
|
'/ws',
|
||||||
|
{ websocket: true },
|
||||||
|
(socket, request) => {
|
||||||
|
const hotel = request.query.hotel ?? ''
|
||||||
|
if (!hotel) { socket.close(4001, 'hotel required'); return }
|
||||||
|
|
||||||
|
if (!hotelRooms.has(hotel)) hotelRooms.set(hotel, new Set())
|
||||||
|
hotelRooms.get(hotel)!.add(socket)
|
||||||
|
|
||||||
|
socket.on('message', (raw) => {
|
||||||
|
const data = raw.toString()
|
||||||
|
const peers = hotelRooms.get(hotel)
|
||||||
|
if (!peers) return
|
||||||
|
peers.forEach(client => {
|
||||||
|
if (client !== socket && client.readyState === 1) {
|
||||||
|
client.send(data)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on('close', () => {
|
||||||
|
hotelRooms.get(hotel)?.delete(socket)
|
||||||
|
if (hotelRooms.get(hotel)?.size === 0) hotelRooms.delete(hotel)
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ws
|
||||||
@@ -16,6 +16,8 @@ const ROW_HEIGHT_COMPACT = 34
|
|||||||
const LABEL_WIDTH = 160
|
const LABEL_WIDTH = 160
|
||||||
const DAYS_VISIBLE = 30
|
const DAYS_VISIBLE = 30
|
||||||
|
|
||||||
|
export type BookingLock = { checkIn: string; checkOut: string; lockedBy: string }
|
||||||
|
|
||||||
interface BookingCalendarProps {
|
interface BookingCalendarProps {
|
||||||
rooms: Room[]
|
rooms: Room[]
|
||||||
bookings: Booking[]
|
bookings: Booking[]
|
||||||
@@ -26,6 +28,9 @@ interface BookingCalendarProps {
|
|||||||
rentalObjects?: RentalObject[]
|
rentalObjects?: RentalObject[]
|
||||||
rentalBookings?: RentalBooking[]
|
rentalBookings?: RentalBooking[]
|
||||||
onRentalBookingCreate?: (b: RentalBooking) => void
|
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> = {
|
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'
|
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 [startDate, setStartDate] = useState(() => startOfDay(new Date()))
|
||||||
const [visibleDays, setVisibleDays] = useState(DAYS_VISIBLE)
|
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 checkIn = format(addDays(startDate, minDay), 'yyyy-MM-dd')
|
||||||
const checkOut = format(addDays(startDate, maxDay + 1), 'yyyy-MM-dd')
|
const checkOut = format(addDays(startDate, maxDay + 1), 'yyyy-MM-dd')
|
||||||
setBookingModalDraft({ roomId: dragStart.roomId, checkIn, checkOut })
|
setBookingModalDraft({ roomId: dragStart.roomId, checkIn, checkOut })
|
||||||
|
onDraftStart?.(dragStart.roomId, checkIn, checkOut)
|
||||||
setDragStart(null)
|
setDragStart(null)
|
||||||
setDragEnd(null)
|
setDragEnd(null)
|
||||||
setDraft(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) => {
|
const getDraftStyle = (roomId: string) => {
|
||||||
if (!dragStart || dragEnd === null || dragStart.roomId !== roomId) return null
|
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 }}
|
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>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -600,7 +636,10 @@ export function BookingCalendar({ rooms, bookings, onBookingCreate, onBookingUpd
|
|||||||
open={true}
|
open={true}
|
||||||
draft={bookingModalDraft}
|
draft={bookingModalDraft}
|
||||||
rooms={rooms}
|
rooms={rooms}
|
||||||
onClose={() => setBookingModalDraft(null)}
|
onClose={() => {
|
||||||
|
if (bookingModalDraft) onDraftCancel?.(bookingModalDraft.roomId)
|
||||||
|
setBookingModalDraft(null)
|
||||||
|
}}
|
||||||
onSave={(data) => {
|
onSave={(data) => {
|
||||||
onBookingCreate(data)
|
onBookingCreate(data)
|
||||||
setBookingModalDraft(null)
|
setBookingModalDraft(null)
|
||||||
|
|||||||
44
src/hooks/useHotelSocket.ts
Normal file
44
src/hooks/useHotelSocket.ts
Normal 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 }
|
||||||
|
}
|
||||||
@@ -1,14 +1,18 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect, useCallback } from 'react'
|
||||||
import { BookingCalendar } from '../components/calendar/BookingCalendar'
|
import { BookingCalendar } from '../components/calendar/BookingCalendar'
|
||||||
import { RENTAL_OBJECTS, MOCK_RENTAL_BOOKINGS } from '../data/rentalData'
|
import { RENTAL_OBJECTS, MOCK_RENTAL_BOOKINGS } from '../data/rentalData'
|
||||||
import { useModules } from '../contexts/ModulesContext'
|
import { useModules } from '../contexts/ModulesContext'
|
||||||
import { useAuth } from '../contexts/AuthContext'
|
import { useAuth } from '../contexts/AuthContext'
|
||||||
import { api } from '../lib/api'
|
import { api } from '../lib/api'
|
||||||
|
import { useHotelSocket } from '../hooks/useHotelSocket'
|
||||||
|
import type { WsMessage } from '../hooks/useHotelSocket'
|
||||||
import type { Room, Booking } from '../types'
|
import type { Room, Booking } from '../types'
|
||||||
import type { RentalBooking } from '../data/rentalData'
|
import type { RentalBooking } from '../data/rentalData'
|
||||||
|
|
||||||
|
export type BookingLock = { checkIn: string; checkOut: string; lockedBy: string }
|
||||||
|
|
||||||
export function CalendarPage() {
|
export function CalendarPage() {
|
||||||
const { user } = useAuth()
|
const { user, session } = useAuth()
|
||||||
const slug = user?.hotelSlug ?? ''
|
const slug = user?.hotelSlug ?? ''
|
||||||
const { statuses } = useModules()
|
const { statuses } = useModules()
|
||||||
const isRentalActive = statuses['rental'] === 'active' || statuses['rental'] === 'trial'
|
const isRentalActive = statuses['rental'] === 'active' || statuses['rental'] === 'trial'
|
||||||
@@ -17,6 +21,7 @@ export function CalendarPage() {
|
|||||||
const [bookings, setBookings] = useState<Booking[]>([])
|
const [bookings, setBookings] = useState<Booking[]>([])
|
||||||
const [fadingBookings, setFadingBookings] = useState<Set<string>>(new Set())
|
const [fadingBookings, setFadingBookings] = useState<Set<string>>(new Set())
|
||||||
const [rentalBookings, setRentalBookings] = useState<RentalBooking[]>(MOCK_RENTAL_BOOKINGS)
|
const [rentalBookings, setRentalBookings] = useState<RentalBooking[]>(MOCK_RENTAL_BOOKINGS)
|
||||||
|
const [locks, setLocks] = useState<Map<string, BookingLock>>(new Map())
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!slug) return
|
if (!slug) return
|
||||||
@@ -29,6 +34,23 @@ export function CalendarPage() {
|
|||||||
}).catch(console.error)
|
}).catch(console.error)
|
||||||
}, [slug])
|
}, [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>) => {
|
const handleCreate = async (data: Partial<Booking>) => {
|
||||||
try {
|
try {
|
||||||
const created = await api.bookings.create(slug, {
|
const created = await api.bookings.create(slug, {
|
||||||
@@ -39,6 +61,8 @@ export function CalendarPage() {
|
|||||||
totalAmount: data.totalAmount, notes: data.notes,
|
totalAmount: data.totalAmount, notes: data.notes,
|
||||||
})
|
})
|
||||||
setBookings(prev => [...prev, created])
|
setBookings(prev => [...prev, created])
|
||||||
|
send({ type: 'booking:created', booking: created })
|
||||||
|
if (data.roomId) send({ type: 'unlock', roomId: data.roomId })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to create booking:', err)
|
console.error('Failed to create booking:', err)
|
||||||
}
|
}
|
||||||
@@ -54,6 +78,7 @@ export function CalendarPage() {
|
|||||||
totalAmount: data.totalAmount, notes: data.notes,
|
totalAmount: data.totalAmount, notes: data.notes,
|
||||||
})
|
})
|
||||||
setBookings(prev => prev.map(b => b.id === id ? updated : b))
|
setBookings(prev => prev.map(b => b.id === id ? updated : b))
|
||||||
|
send({ type: 'booking:updated', booking: updated })
|
||||||
if (data.status === 'cancelled') {
|
if (data.status === 'cancelled') {
|
||||||
setFadingBookings(prev => new Set([...prev, id]))
|
setFadingBookings(prev => new Set([...prev, id]))
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -79,14 +104,19 @@ export function CalendarPage() {
|
|||||||
results.forEach(r => { next = next.map(b => b.id === r.id ? r : b) })
|
results.forEach(r => { next = next.map(b => b.id === r.id ? r : b) })
|
||||||
return next
|
return next
|
||||||
})
|
})
|
||||||
|
results.forEach(r => send({ type: 'booking:updated', booking: r }))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to bulk update bookings:', err)
|
console.error('Failed to bulk update bookings:', err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleRentalCreate = (b: RentalBooking) => {
|
const handleDraftStart = useCallback((roomId: string, checkIn: string, checkOut: string) => {
|
||||||
setRentalBookings(prev => [...prev, b])
|
send({ type: 'lock', roomId, checkIn, checkOut, lockedBy: user?.name ?? 'Менеджер' })
|
||||||
}
|
}, [send, user?.name])
|
||||||
|
|
||||||
|
const handleDraftCancel = useCallback((roomId: string) => {
|
||||||
|
send({ type: 'unlock', roomId })
|
||||||
|
}, [send])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full">
|
<div className="flex flex-col h-full">
|
||||||
@@ -100,7 +130,10 @@ export function CalendarPage() {
|
|||||||
fadingBookingIds={fadingBookings}
|
fadingBookingIds={fadingBookings}
|
||||||
rentalObjects={isRentalActive ? RENTAL_OBJECTS : undefined}
|
rentalObjects={isRentalActive ? RENTAL_OBJECTS : undefined}
|
||||||
rentalBookings={isRentalActive ? rentalBookings : 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>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user