Files
hotelsync/backend/src/routes/housekeeping.ts
HotelSync c83a9ca714 feat: task problem/solution split + maintenance icons on rooms/calendar
- TechnicalPage: redesign task cards with separate "Задача" and "Решение" sections
  - "Задача": problem description + problem photos (editable before done)
  - "Решение": technician resolution comment + resolution photos (green section)
  - Resolution comment in CompletionModal now saves to resolution_notes field
  - Resolution photos save to resolution_photos (no longer mixed with problem photos)
- RoomModal history tab: maintenance entries show separate problem/resolution sections
- Backend: add resolution_notes, resolution_photos to PATCH allowed fields
- Migration 029: resolution_notes TEXT + resolution_photos TEXT[] columns
- RoomsPage: load active maintenance tasks, show 🔧 неисправность badge on room cards
- CalendarPage: load active maintenance tasks, show 🔧 неиспр. label in calendar row
- BookingCalendar: activeMaintenance prop, WS handler updates maintenance set on task changes
- CalendarPage WS: handle housekeeping_task_created to update activeMaintenance set

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 11:45:24 +03:00

202 lines
8.4 KiB
TypeScript

import { FastifyPluginAsync } from 'fastify'
import { db } from '../db'
import { getHkSettings } from './housekeeping-settings'
import { broadcast } from './ws'
type SlugParam = { Params: { slug: string } }
type SlugIdParam = { Params: { slug: string; id: string } }
const housekeeping: 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/housekeeping ─────────────────────────────────────
fastify.get<SlugParam & { Querystring: { status?: string; date?: string; category?: string; room_id?: string } }>(
'/api/hotels/:slug/housekeeping',
{ 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 conditions: string[] = ['t.hotel_id = $1']
const values: unknown[] = [hotelId]
let idx = 2
const { status, date, category, room_id } = request.query
if (status === 'active') {
conditions.push(`t.status IN ('pending', 'in_progress')`)
} else if (status) {
conditions.push(`t.status = $${idx}`); values.push(status); idx++
}
if (date) { conditions.push(`t.due_date = $${idx}`); values.push(date); idx++ }
if (category) { conditions.push(`t.category = $${idx}`); values.push(category); idx++ }
if (room_id) { conditions.push(`t.room_id = $${idx}`); values.push(room_id); idx++ }
const { rows } = await db.query(
`SELECT t.*,
r.number AS room_number, r.type AS room_type,
u.name AS assignee_name
FROM housekeeping_tasks t
LEFT JOIN rooms r ON r.id = t.room_id
LEFT JOIN users u ON u.id = t.assignee_id
WHERE ${conditions.join(' AND ')}
ORDER BY
CASE t.priority WHEN 'urgent' THEN 1 WHEN 'high' THEN 2 WHEN 'medium' THEN 3 ELSE 4 END,
COALESCE(t.completed_at, t.created_at) DESC`,
values,
)
return rows
},
)
// ── POST /api/hotels/:slug/housekeeping ────────────────────────────────────
fastify.post<SlugParam & { Body: {
room_id?: string; type: string; priority?: string
assignee_id?: string; notes?: string; due_date?: string; category?: string; photos?: string[]
} }>(
'/api/hotels/:slug/housekeeping',
{ 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 { room_id, type, priority = 'medium', assignee_id, notes, due_date, category = 'housekeeping', photos = [] } = request.body
const { rows: inserted } = await db.query(
`INSERT INTO housekeeping_tasks
(hotel_id, room_id, type, priority, assignee_id, notes, due_date, category, photos)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id`,
[hotelId, room_id ?? null, type, priority,
assignee_id ?? null, notes ?? null, due_date ?? null, category, photos],
)
const { rows } = await db.query(
`SELECT t.*, r.number AS room_number, r.type AS room_type, u.name AS assignee_name
FROM housekeeping_tasks t
LEFT JOIN rooms r ON r.id = t.room_id
LEFT JOIN users u ON u.id = t.assignee_id
WHERE t.id = $1`,
[inserted[0].id],
)
return reply.code(201).send(rows[0])
},
)
// ── PATCH /api/hotels/:slug/housekeeping/:id ───────────────────────────────
fastify.patch<SlugIdParam & { Body: Record<string, unknown> }>(
'/api/hotels/:slug/housekeeping/: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 allowed = ['room_id','type','status','priority','assignee_id','notes','due_date','category','photos','resolution_notes','resolution_photos']
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++
}
}
// Auto-set timestamps based on status transitions
if (request.body.status === 'in_progress') {
updates.push(`started_at = COALESCE(started_at, NOW())`)
}
if (request.body.status === 'done') {
updates.push(`completed_at = NOW()`)
} else if (request.body.status && request.body.status !== 'done') {
updates.push(`completed_at = NULL`)
}
if (updates.length === 0) return reply.code(400).send({ error: 'Nothing to update' })
values.push(id, hotelId)
const { rows: updated } = await db.query(
`UPDATE housekeeping_tasks SET ${updates.join(', ')}
WHERE id = $${idx} AND hotel_id = $${idx + 1} RETURNING id`,
values,
)
if (!updated[0]) return reply.code(404).send({ error: 'Task not found' })
const { rows } = await db.query(
`SELECT t.*, r.number AS room_number, r.type AS room_type, u.name AS assignee_name
FROM housekeeping_tasks t
LEFT JOIN rooms r ON r.id = t.room_id
LEFT JOIN users u ON u.id = t.assignee_id
WHERE t.id = $1`,
[updated[0].id],
)
const task = rows[0]
// When task is marked in_progress → room becomes 'cleaning'
if (request.body.status === 'in_progress' && task.room_id) {
await db.query(
`UPDATE rooms SET housekeeping_status = 'cleaning' WHERE id = $1`,
[task.room_id],
)
broadcast(slug, { type: 'housekeeping_done', taskId: task.id, roomId: task.room_id, roomStatus: 'cleaning' })
}
// When task is marked done → update room housekeeping status
if (request.body.status === 'done' && task.room_id) {
const settings = await getHkSettings(hotelId).catch(() => null)
const newRoomStatus = settings?.inspection_after_clean ? 'inspect' : 'clean'
await db.query(
`UPDATE rooms SET housekeeping_status = $1 WHERE id = $2`,
[newRoomStatus, task.room_id],
)
broadcast(slug, { type: 'housekeeping_done', taskId: task.id, roomId: task.room_id, roomStatus: newRoomStatus })
}
broadcast(slug, { type: 'housekeeping_updated', task })
return task
},
)
// ── DELETE /api/hotels/:slug/housekeeping/:id ──────────────────────────────
fastify.delete<SlugIdParam>(
'/api/hotels/:slug/housekeeping/: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 housekeeping_tasks WHERE id = $1 AND hotel_id = $2',
[id, hotelId],
)
if (!rowCount) return reply.code(404).send({ error: 'Task not found' })
return reply.code(204).send()
},
)
}
export default housekeeping