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 => { 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 } = request.query if (status) { conditions.push(`t.status = $${idx}`); values.push(status); idx++ } if (date) { conditions.push(`t.due_date = $${idx}`); values.push(date); 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, t.created_at`, 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', assignee_id, notes, due_date } = request.body const { rows } = await db.query( `INSERT INTO housekeeping_tasks (hotel_id, room_id, type, priority, assignee_id, notes, due_date) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`, [hotelId, room_id ?? null, type, priority, assignee_id ?? null, notes ?? null, due_date ?? null], ) 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'] 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 completed_at when marking done 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 } = await db.query( `UPDATE housekeeping_tasks SET ${updates.join(', ')} WHERE id = $${idx} AND hotel_id = $${idx + 1} RETURNING *`, values, ) if (!rows[0]) return reply.code(404).send({ error: 'Task not found' }) const task = rows[0] // 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