Files
hotelsync/backend/src/routes/rooms.ts
HotelSync 63da3d21cc feat: maintenance/blocked date ranges with booking overlap warning
- DB migration 020: add maintenance_from, maintenance_to to rooms
- Room type + RoomPayload: maintenanceFrom, maintenanceTo fields
- Context menu: clicking "На ремонт"/"Закрыт" expands inline date picker
  (С / По + "Без срока" checkbox), confirms with "Применить" button
- Calendar: stripe overlay covers only the maintenance date range
  (full row if no dates set, partial if date range specified)
- Booking creation: if drag-selected dates overlap with maintenance period,
  shows warning dialog with "Отмена" / "Всё равно забронировать"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 14:49:19 +03:00

203 lines
8.2 KiB
TypeScript

import { FastifyPluginAsync } from 'fastify'
import { db } from '../db'
type SlugParam = { Params: { slug: string } }
type SlugIdParam = { Params: { slug: string; id: string } }
const rooms: FastifyPluginAsync = async (fastify) => {
const getHotelId = async (slug: string): Promise<string | null> => {
const { rows } = await db.query('SELECT id FROM hotels WHERE slug = $1', [slug])
return rows[0]?.id ?? null
}
const canAccess = (userSlug: string | null, role: string, slug: string) =>
role === 'super_admin' || userSlug === slug
// ── GET /api/hotels/:slug/rooms ────────────────────────────────────────────
fastify.get<SlugParam>(
'/api/hotels/:slug/rooms',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
const { slug } = request.params
if (!canAccess(request.user.hotelSlug, request.user.role, slug)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const hotelId = await getHotelId(slug)
if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' })
const { rows } = await db.query(
`SELECT r.*,
(SELECT json_build_object(
'guest_name', b.guest_name,
'check_in', b.check_in,
'check_out', b.check_out,
'status', b.status
)
FROM bookings b
WHERE b.room_id = r.id
AND b.status = 'checked_in'
LIMIT 1
) AS current_booking
FROM rooms r
WHERE r.hotel_id = $1
ORDER BY r.floor, r.number`,
[hotelId],
)
return rows
},
)
// ── POST /api/hotels/:slug/rooms ───────────────────────────────────────────
fastify.post<SlugParam & { Body: {
number: string; type: string; floor?: number
max_guests?: number; base_rate: number; amenities?: string[]
name?: string; category_id?: string; bed_type?: string
beds?: unknown; housekeeping_status?: string; sort_order?: number
allow_hourly?: boolean; hourly_rate?: number; extra_place?: unknown
child_policy?: unknown; description?: string; photos?: string[]
early_checkin_fee?: number; late_checkout_fee?: number
} }>(
'/api/hotels/:slug/rooms',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (!['manager', 'super_admin'].includes(request.user.role)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const { slug } = request.params
if (!canAccess(request.user.hotelSlug, request.user.role, slug)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const hotelId = await getHotelId(slug)
if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' })
const {
number, type, floor = 1, max_guests = 2, base_rate,
amenities = [], name, category_id, bed_type = 'double',
beds, housekeeping_status = 'clean', sort_order = 99,
allow_hourly = false, hourly_rate, extra_place, child_policy,
description, photos = [], early_checkin_fee, late_checkout_fee,
} = request.body
const { rows } = await db.query(
`INSERT INTO rooms
(hotel_id, number, type, floor, max_guests, base_rate, amenities, name,
category_id, bed_type, beds, housekeeping_status, sort_order,
allow_hourly, hourly_rate, extra_place, child_policy, description, photos,
early_checkin_fee, late_checkout_fee)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21)
RETURNING *`,
[
hotelId, number, type, floor, max_guests, base_rate,
amenities, name ?? null, category_id ?? null, bed_type,
beds ? JSON.stringify(beds) : null, housekeeping_status, sort_order,
allow_hourly, hourly_rate ?? null,
extra_place ? JSON.stringify(extra_place) : null,
child_policy ? JSON.stringify(child_policy) : null,
description ?? null, photos,
early_checkin_fee ?? null, late_checkout_fee ?? null,
],
)
return reply.code(201).send(rows[0])
},
)
// ── GET /api/hotels/:slug/rooms/:id ───────────────────────────────────────
fastify.get<SlugIdParam>(
'/api/hotels/:slug/rooms/:id',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
const { slug, id } = request.params
if (!canAccess(request.user.hotelSlug, request.user.role, slug)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const hotelId = await getHotelId(slug)
if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' })
const { rows } = await db.query(
'SELECT * FROM rooms WHERE id = $1 AND hotel_id = $2',
[id, hotelId],
)
if (!rows[0]) return reply.code(404).send({ error: 'Room not found' })
return rows[0]
},
)
// ── PATCH /api/hotels/:slug/rooms/:id ─────────────────────────────────────
fastify.patch<SlugIdParam & { Body: Record<string, unknown> }>(
'/api/hotels/:slug/rooms/:id',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (!['manager', 'super_admin'].includes(request.user.role)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const { slug, id } = request.params
if (!canAccess(request.user.hotelSlug, request.user.role, slug)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const hotelId = await getHotelId(slug)
if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' })
const allowed = [
'number', 'type', 'floor', 'max_guests', 'base_rate', 'status',
'amenities', 'name', 'category_id', 'bed_type', 'beds',
'housekeeping_status', 'sort_order', 'allow_hourly', 'hourly_rate',
'extra_place', 'child_policy', 'description', 'photos',
'early_checkin_fee', 'late_checkout_fee',
'maintenance_from', 'maintenance_to',
]
const updates: string[] = []
const values: unknown[] = []
let idx = 1
for (const key of allowed) {
if (request.body[key] !== undefined) {
updates.push(`${key} = $${idx}`)
const val = request.body[key]
values.push(
(key === 'beds' || key === 'extra_place' || key === 'child_policy') && val && typeof val === 'object'
? JSON.stringify(val)
: val,
)
idx++
}
}
if (updates.length === 0) return reply.code(400).send({ error: 'Nothing to update' })
updates.push(`updated_at = NOW()`)
values.push(id, hotelId)
const { rows } = await db.query(
`UPDATE rooms SET ${updates.join(', ')} WHERE id = $${idx} AND hotel_id = $${idx + 1} RETURNING *`,
values,
)
if (!rows[0]) return reply.code(404).send({ error: 'Room not found' })
return rows[0]
},
)
// ── DELETE /api/hotels/:slug/rooms/:id ────────────────────────────────────
fastify.delete<SlugIdParam>(
'/api/hotels/:slug/rooms/:id',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (!['manager', 'super_admin'].includes(request.user.role)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const { slug, id } = request.params
if (!canAccess(request.user.hotelSlug, request.user.role, slug)) {
return reply.code(403).send({ error: 'Forbidden' })
}
const hotelId = await getHotelId(slug)
if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' })
const { rowCount } = await db.query(
'DELETE FROM rooms WHERE id = $1 AND hotel_id = $2',
[id, hotelId],
)
if (!rowCount) return reply.code(404).send({ error: 'Room not found' })
return reply.code(204).send()
},
)
}
export default rooms