import { FastifyPluginAsync } from 'fastify' import { db } from '../db' import { getHkSettings, autoAssignHousekeeper } 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 => { 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( '/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( '/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', notes, due_date, category = 'housekeeping', photos = [] } = request.body let { assignee_id } = request.body // Auto-assign if enabled and no assignee provided if (!assignee_id) { const settings = await getHkSettings(hotelId).catch(() => null) if (settings?.auto_assign) { // Urgent tasks always use first_free strategy; otherwise use configured strategy const strategy = priority === 'urgent' ? 'first_free' : (settings.auto_assign_strategy ?? 'least_loaded') assignee_id = await autoAssignHousekeeper(hotelId, strategy).catch(() => null) ?? undefined } } 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], ) // If priority=urgent and room_id → close the room for emergency_close_days if (priority === 'urgent' && room_id && category === 'maintenance') { const settings = await getHkSettings(hotelId).catch(() => null) const closeDays = settings?.emergency_close_days ?? 1 const from = new Date().toISOString().slice(0, 10) const toDate = new Date() toDate.setDate(toDate.getDate() + closeDays) const to = toDate.toISOString().slice(0, 10) await db.query( `UPDATE rooms SET status = 'maintenance', maintenance_from = $2, maintenance_to = $3 WHERE id = $1`, [room_id, from, to], ) broadcast(slug, { type: 'room_updated', room: { id: room_id, status: 'maintenance', maintenanceFrom: from, maintenanceTo: to }, }) } 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], ) broadcast(slug, { type: 'housekeeping_task_created', task: rows[0] }) return reply.code(201).send(rows[0]) }, ) // ── PATCH /api/hotels/:slug/housekeeping/:id ─────────────────────────────── fastify.patch }>( '/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`) } // Also allow updating minibar_checked flag if ((request.body as Record).minibar_checked !== undefined) { updates.push(`minibar_checked = $${idx}`) values.push((request.body as Record).minibar_checked) idx++ } if (updates.length === 0) return reply.code(400).send({ error: 'Nothing to update' }) // ── Validate completion requirements ────────────────────────────────── if (request.body.status === 'done') { // Get current task (need task_type, minibar_checked, room_id) const { rows: taskRows } = await db.query( `SELECT t.*, t.minibar_checked FROM housekeeping_tasks t WHERE t.id = $1 AND t.hotel_id = $2`, [id, hotelId], ) const currentTask = taskRows[0] if (!currentTask) return reply.code(404).send({ error: 'Task not found' }) // Merge minibar_checked from request body (may be set in same request) const minibarCheckedNow = (request.body as Record).minibar_checked ?? currentTask.minibar_checked const errors: string[] = [] // 1. Check checklist requirements const { rows: templates } = await db.query( `SELECT id, name FROM checklist_templates WHERE hotel_id = $1 AND is_active = true AND require_before_complete = true AND (task_type IS NULL OR task_type = $2)`, [hotelId, currentTask.type ?? null], ) for (const tpl of templates) { const { rows: items } = await db.query( `SELECT ci.id, ci.text, cc.id IS NOT NULL AS is_completed FROM checklist_items ci LEFT JOIN checklist_completions cc ON cc.item_id = ci.id AND cc.task_id = $1 WHERE ci.template_id = $2 ORDER BY ci.sort_order`, [id, tpl.id], ) const unchecked = items.filter((i: Record) => !i.is_completed) if (unchecked.length > 0) { errors.push(`Чек-лист «${tpl.name}»: не выполнено ${unchecked.length} из ${items.length} пунктов`) } } // 2. Check minibar requirement const { rows: rules } = await db.query( `SELECT require_minibar_check FROM hotel_housekeeping_rules WHERE hotel_id = $1`, [hotelId], ) if (rules[0]?.require_minibar_check && !minibarCheckedNow) { errors.push('Минибар не проверен') } if (errors.length > 0) { return reply.code(422).send({ error: errors.join('; '), errors }) } } 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( '/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