Files
hotelsync/backend/src/routes/bookings.ts
HotelSync 80e3b21827 Fix: drag ghost visual, check-in date auto-fill, backend room_id patch
- BookingCalendar: replace tiny ghost badge with full-size booking block
  (same color, correct width based on nights × cell width, centered on cursor)
- BookingModal: auto-set check-out to check-in+1 day when check-in changes
- Backend PATCH /bookings/🆔 add room_id to allowed fields so drag-to-move saves correctly

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

210 lines
8.5 KiB
TypeScript

import { FastifyPluginAsync } from 'fastify'
import { db } from '../db'
import { notifyNetupCheckin, notifyNetupCheckout } from './netup'
type SlugParam = { Params: { slug: string } }
type SlugIdParam = { Params: { slug: string; id: string } }
const bookings: 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/bookings ─────────────────────────────────────────
// Query params: ?start=YYYY-MM-DD&end=YYYY-MM-DD&room_id=&status=&source=
fastify.get<SlugParam & { Querystring: {
start?: string; end?: string; room_id?: string; status?: string; source?: string
} }>(
'/api/hotels/:slug/bookings',
{ 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 { start, end, room_id, status, source } = request.query
const conditions: string[] = ['b.hotel_id = $1']
const values: unknown[] = [hotelId]
let idx = 2
if (start && end) {
conditions.push(`b.check_out > $${idx} AND b.check_in < $${idx + 1}`)
values.push(start, end)
idx += 2
}
if (room_id) { conditions.push(`b.room_id = $${idx}`); values.push(room_id); idx++ }
if (status) { conditions.push(`b.status = $${idx}`); values.push(status); idx++ }
if (source) { conditions.push(`b.source = $${idx}`); values.push(source); idx++ }
const { rows } = await db.query(
`SELECT b.*, r.number AS room_number, r.type AS room_type
FROM bookings b
JOIN rooms r ON r.id = b.room_id
WHERE ${conditions.join(' AND ')}
ORDER BY b.check_in`,
values,
)
return rows
},
)
// ── POST /api/hotels/:slug/bookings ────────────────────────────────────────
fastify.post<SlugParam & { Body: {
room_id: string; guest_name: string; guest_email?: string; guest_phone?: string
check_in: string; check_out: string; adults?: number; children?: number
status?: string; source?: string; total_amount?: number; paid_amount?: number; notes?: string
} }>(
'/api/hotels/:slug/bookings',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (request.user.role === 'housekeeper') {
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 {
room_id, guest_name, guest_email, guest_phone,
check_in, check_out, adults = 1, children = 0,
status = 'confirmed', source = 'direct', total_amount, paid_amount = 0, notes,
} = request.body
// Check for conflicts
const { rows: conflicts } = await db.query(
`SELECT id FROM bookings
WHERE room_id = $1
AND status NOT IN ('cancelled','no_show')
AND check_in < $2 AND check_out > $3`,
[room_id, check_out, check_in],
)
if (conflicts.length > 0) {
return reply.code(409).send({ error: 'Номер уже занят на эти даты' })
}
const { rows } = await db.query(
`INSERT INTO bookings
(hotel_id, room_id, guest_name, guest_email, guest_phone, check_in, check_out,
adults, children, status, source, total_amount, paid_amount, notes)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14) RETURNING *`,
[hotelId, room_id, guest_name, guest_email ?? null, guest_phone ?? null,
check_in, check_out, adults, children, status, source,
total_amount ?? 0, paid_amount, notes ?? null],
)
return reply.code(201).send(rows[0])
},
)
// ── GET /api/hotels/:slug/bookings/:id ─────────────────────────────────────
fastify.get<SlugIdParam>(
'/api/hotels/:slug/bookings/: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 b.*, r.number AS room_number, r.type AS room_type, r.base_rate
FROM bookings b
JOIN rooms r ON r.id = b.room_id
WHERE b.id = $1 AND b.hotel_id = $2`,
[id, hotelId],
)
if (!rows[0]) return reply.code(404).send({ error: 'Booking not found' })
return rows[0]
},
)
// ── PATCH /api/hotels/:slug/bookings/:id ───────────────────────────────────
fastify.patch<SlugIdParam & { Body: Record<string, unknown> }>(
'/api/hotels/:slug/bookings/:id',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (request.user.role === 'housekeeper') {
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 = ['room_id','guest_name','guest_email','guest_phone','check_in','check_out',
'adults','children','status','source','total_amount','paid_amount','notes']
const updates: string[] = []
const values: unknown[] = []
let idx = 1
for (const key of allowed) {
if (request.body[key] !== undefined) {
updates.push(`${key} = $${idx}`)
values.push(request.body[key])
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 bookings SET ${updates.join(', ')}
WHERE id = $${idx} AND hotel_id = $${idx + 1} RETURNING *`,
values,
)
if (!rows[0]) return reply.code(404).send({ error: 'Booking not found' })
// NetUP IPTV: fire-and-forget при заселении/выселении
const updated = rows[0]
if (request.body.status === 'checked_in') {
notifyNetupCheckin(hotelId, updated.room_id, updated.guest_name, updated.id).catch(() => {})
} else if (request.body.status === 'checked_out') {
notifyNetupCheckout(hotelId, updated.room_id).catch(() => {})
}
return updated
},
)
// ── DELETE /api/hotels/:slug/bookings/:id ──────────────────────────────────
fastify.delete<SlugIdParam>(
'/api/hotels/:slug/bookings/:id',
{ onRequest: [fastify.authenticate] },
async (request, reply) => {
if (request.user.role === 'housekeeper') {
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 bookings WHERE id = $1 AND hotel_id = $2',
[id, hotelId],
)
if (!rowCount) return reply.code(404).send({ error: 'Booking not found' })
return reply.code(204).send()
},
)
}
export default bookings