Files
Hotel-Booking/Frontend/src/components/shared/InspectionManagement.tsx
Iliyan Angelov 627959f52b updates
2025-11-23 18:59:18 +02:00

769 lines
32 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import {
ClipboardCheck,
Plus,
Edit,
Eye,
Search,
X,
CheckCircle,
XCircle,
AlertTriangle,
Star,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../common/Loading';
import Pagination from '../common/Pagination';
import advancedRoomService, {
RoomInspection,
InspectionChecklistItem,
Issue,
} from '../../services/api/advancedRoomService';
import { roomService, Room } from '../../services/api';
import { userService, User as UserType } from '../../services/api';
import useAuthStore from '../../store/useAuthStore';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
const InspectionManagement: React.FC = () => {
const { userInfo } = useAuthStore();
const isAdmin = userInfo?.role === 'admin';
const [loading, setLoading] = useState(true);
const [inspections, setInspections] = useState<RoomInspection[]>([]);
const [rooms, setRooms] = useState<Room[]>([]);
const [staff, setStaff] = useState<UserType[]>([]);
const [showModal, setShowModal] = useState(false);
const [editingInspection, setEditingInspection] = useState<RoomInspection | null>(null);
const [viewingInspection, setViewingInspection] = useState<RoomInspection | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [filters, setFilters] = useState({
room_id: '',
inspection_type: '',
status: '',
});
const defaultChecklistCategories = [
{
category: 'Bathroom',
items: ['Toilet', 'Shower', 'Sink', 'Mirror', 'Tiles', 'Ventilation'],
},
{
category: 'Bedroom',
items: ['Bed', 'Linens', 'Pillows', 'Furniture', 'Closet', 'Lighting'],
},
{
category: 'Electronics',
items: ['TV', 'Remote', 'AC', 'WiFi', 'Safe', 'Charging ports'],
},
{
category: 'Amenities',
items: ['Towels', 'Toiletries', 'Coffee/Tea', 'Mini bar', 'Hangers', 'Iron'],
},
{
category: 'General',
items: ['Floor', 'Walls', 'Windows', 'Doors', 'Curtains', 'Smoke detector'],
},
];
const [formData, setFormData] = useState({
room_id: '',
booking_id: '',
inspection_type: 'routine' as 'pre_checkin' | 'post_checkout' | 'routine' | 'maintenance' | 'damage',
scheduled_at: new Date(),
inspected_by: '',
checklist_items: [] as InspectionChecklistItem[],
overall_score: '',
overall_notes: '',
issues_found: [] as Issue[],
requires_followup: false,
});
useEffect(() => {
fetchInspections();
fetchRooms();
fetchStaff();
}, [currentPage, filters]);
const fetchInspections = async () => {
try {
setLoading(true);
const params: any = { page: currentPage, limit: 10 };
if (filters.room_id) params.room_id = parseInt(filters.room_id);
if (filters.inspection_type) params.inspection_type = filters.inspection_type;
if (filters.status) params.status = filters.status;
const response = await advancedRoomService.getRoomInspections(params);
if (response.status === 'success') {
setInspections(response.data.inspections);
setTotalPages(response.data.pagination?.total_pages || 1);
}
} catch (error: any) {
toast.error(error.response?.data?.detail || 'Failed to fetch inspections');
} finally {
setLoading(false);
}
};
const fetchRooms = async () => {
try {
const response = await roomService.getRooms({ limit: 1000, page: 1 });
if (response.data?.rooms) {
setRooms(response.data.rooms);
}
} catch (error) {
console.error('Failed to fetch rooms:', error);
}
};
const fetchStaff = async () => {
try {
const response = await userService.getUsers({ role: 'staff', limit: 100 });
if (response.data?.users) {
setStaff(response.data.users);
}
} catch (error) {
console.error('Failed to fetch staff:', error);
}
};
const initializeChecklist = () => {
const items: InspectionChecklistItem[] = [];
defaultChecklistCategories.forEach((category) => {
category.items.forEach((item) => {
items.push({
category: category.category,
item: item,
status: 'not_applicable',
notes: '',
photos: [],
});
});
});
setFormData({ ...formData, checklist_items: items });
};
const handleCreate = () => {
setEditingInspection(null);
setFormData({
room_id: '',
booking_id: '',
inspection_type: 'routine',
scheduled_at: new Date(),
inspected_by: '',
checklist_items: [],
overall_score: '',
overall_notes: '',
issues_found: [],
requires_followup: false,
});
initializeChecklist();
setShowModal(true);
};
const handleMarkAsDone = async (inspection: RoomInspection) => {
// Double check that the inspection is assigned to the current user
if (!inspection.inspected_by) {
toast.error('Inspection must be assigned before it can be marked as done');
return;
}
if (inspection.inspected_by !== userInfo?.id) {
toast.error('Only the assigned inspector can mark this inspection as done');
return;
}
try {
await advancedRoomService.updateRoomInspection(inspection.id, {
status: 'completed',
completed_at: new Date().toISOString(),
});
toast.success('Inspection marked as completed successfully');
fetchInspections();
} catch (error: any) {
toast.error(error.response?.data?.detail || 'Failed to mark inspection as done');
}
};
const handleEdit = (inspection: RoomInspection) => {
setEditingInspection(inspection);
setFormData({
room_id: inspection.room_id.toString(),
booking_id: inspection.booking_id?.toString() || '',
inspection_type: inspection.inspection_type,
scheduled_at: new Date(inspection.scheduled_at),
inspected_by: inspection.inspected_by?.toString() || '',
checklist_items: inspection.checklist_items || [],
overall_score: inspection.overall_score?.toString() || '',
overall_notes: inspection.overall_notes || '',
issues_found: inspection.issues_found || [],
requires_followup: inspection.requires_followup,
});
setShowModal(true);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const data = {
room_id: parseInt(formData.room_id),
booking_id: formData.booking_id ? parseInt(formData.booking_id) : undefined,
inspection_type: formData.inspection_type,
scheduled_at: formData.scheduled_at.toISOString(),
inspected_by: formData.inspected_by ? parseInt(formData.inspected_by) : undefined,
checklist_items: formData.checklist_items,
overall_score: formData.overall_score ? parseFloat(formData.overall_score) : undefined,
overall_notes: formData.overall_notes,
issues_found: formData.issues_found,
requires_followup: formData.requires_followup,
};
if (editingInspection) {
await advancedRoomService.updateRoomInspection(editingInspection.id, {
status: editingInspection.status,
...data,
});
toast.success('Inspection updated successfully');
} else {
await advancedRoomService.createRoomInspection(data);
toast.success('Inspection created successfully');
}
setShowModal(false);
fetchInspections();
} catch (error: any) {
toast.error(error.response?.data?.detail || 'Failed to save inspection');
}
};
const updateChecklistItem = (index: number, field: 'status' | 'notes', value: any) => {
const updated = [...formData.checklist_items];
updated[index] = { ...updated[index], [field]: value };
setFormData({ ...formData, checklist_items: updated });
};
const addIssue = () => {
setFormData({
...formData,
issues_found: [
...formData.issues_found,
{ severity: 'minor', description: '', photo: '' },
],
});
};
const updateIssue = (index: number, field: 'severity' | 'description' | 'photo', value: any) => {
const updated = [...formData.issues_found];
updated[index] = { ...updated[index], [field]: value };
setFormData({ ...formData, issues_found: updated });
};
const removeIssue = (index: number) => {
setFormData({
...formData,
issues_found: formData.issues_found.filter((_, i) => i !== index),
});
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800';
case 'in_progress':
return 'bg-blue-100 text-blue-800';
case 'pending':
return 'bg-yellow-100 text-yellow-800';
case 'failed':
return 'bg-red-100 text-red-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'pass':
return <CheckCircle className="w-4 h-4 text-green-500" />;
case 'fail':
return <XCircle className="w-4 h-4 text-red-500" />;
case 'needs_attention':
return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
default:
return null;
}
};
if (loading && inspections.length === 0) {
return <Loading />;
}
return (
<div>
<div className="mb-6 flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<Search className="w-5 h-5 text-gray-500" />
<input
type="text"
placeholder="Search by room..."
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
onChange={(e) => setFilters({ ...filters, room_id: e.target.value })}
/>
</div>
<select
value={filters.status}
onChange={(e) => setFilters({ ...filters, status: e.target.value })}
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Statuses</option>
<option value="pending">Pending</option>
<option value="in_progress">In Progress</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
<select
value={filters.inspection_type}
onChange={(e) => setFilters({ ...filters, inspection_type: e.target.value })}
className="border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Types</option>
<option value="pre_checkin">Pre Check-in</option>
<option value="post_checkout">Post Check-out</option>
<option value="routine">Routine</option>
<option value="maintenance">Maintenance</option>
<option value="damage">Damage</option>
</select>
</div>
{isAdmin && (
<button
onClick={handleCreate}
className="flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
>
<Plus className="w-4 h-4" />
<span>New Inspection</span>
</button>
)}
</div>
<div className="bg-white rounded-lg shadow overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Room</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Scheduled</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Score</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Inspector</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{inspections.map((inspection) => (
<tr key={inspection.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900">
{inspection.room_number || `Room ${inspection.room_id}`}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-500 capitalize">
{inspection.inspection_type.replace('_', ' ')}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(inspection.status)}`}>
{inspection.status.replace('_', ' ')}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{new Date(inspection.scheduled_at).toLocaleDateString()}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{inspection.overall_score ? (
<div className="flex items-center space-x-1">
<Star className="w-4 h-4 text-yellow-500 fill-current" />
<span className="text-sm text-gray-900">{inspection.overall_score.toFixed(1)}</span>
</div>
) : (
<span className="text-sm text-gray-400">N/A</span>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{inspection.inspector_name || 'Unassigned'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
<div className="flex items-center space-x-2">
<button
onClick={() => setViewingInspection(inspection)}
className="text-blue-600 hover:text-blue-900"
title="View inspection"
>
<Eye className="w-4 h-4" />
</button>
{isAdmin ? (
<button
onClick={() => handleEdit(inspection)}
className="text-indigo-600 hover:text-indigo-900"
title="Edit inspection"
>
<Edit className="w-4 h-4" />
</button>
) : (
// Staff can mark their own assigned inspections as done
inspection.inspected_by === userInfo?.id && inspection.status !== 'completed' && (
<button
onClick={() => handleMarkAsDone(inspection)}
className="text-green-600 hover:text-green-900"
title="Mark as done"
>
<CheckCircle className="w-4 h-4" />
</button>
)
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{totalPages > 1 && (
<div className="mt-4">
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={setCurrentPage}
/>
</div>
)}
{/* Create/Edit Modal - Simplified for space, full version would be similar to others */}
{showModal && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
<div className="p-6 border-b border-gray-200">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-bold text-gray-900">
{editingInspection ? 'Edit Inspection' : 'New Inspection'}
</h2>
<button
onClick={() => setShowModal(false)}
className="text-gray-400 hover:text-gray-600"
>
<X className="w-6 h-6" />
</button>
</div>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Room *</label>
<select
required
value={formData.room_id}
onChange={(e) => setFormData({ ...formData, room_id: e.target.value })}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">Select Room</option>
{rooms.map((room) => (
<option key={room.id} value={room.id}>
{room.room_number} - Floor {room.floor}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Inspection Type *</label>
<select
required
value={formData.inspection_type}
onChange={(e) => setFormData({ ...formData, inspection_type: e.target.value as any })}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="pre_checkin">Pre Check-in</option>
<option value="post_checkout">Post Check-out</option>
<option value="routine">Routine</option>
<option value="maintenance">Maintenance</option>
<option value="damage">Damage</option>
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Scheduled At *</label>
<DatePicker
selected={formData.scheduled_at}
onChange={(date: Date | null) => date && setFormData({ ...formData, scheduled_at: date })}
showTimeSelect
dateFormat="yyyy-MM-dd HH:mm"
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Inspector</label>
<select
value={formData.inspected_by}
onChange={(e) => setFormData({ ...formData, inspected_by: e.target.value })}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">Unassigned</option>
{staff.map((s) => (
<option key={s.id} value={s.id}>
{s.full_name}
</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Checklist</label>
<div className="space-y-4 border border-gray-200 rounded-md p-4 max-h-96 overflow-y-auto">
{defaultChecklistCategories.map((category, catIndex) => (
<div key={catIndex} className="border-b border-gray-100 pb-3 last:border-0">
<h4 className="font-semibold text-sm text-gray-700 mb-2">{category.category}</h4>
<div className="space-y-2">
{category.items.map((item, itemIndex) => {
const checklistIndex = formData.checklist_items.findIndex(
(ci) => ci.category === category.category && ci.item === item
);
if (checklistIndex === -1) return null;
return (
<div key={itemIndex} className="flex items-center space-x-3">
<select
value={formData.checklist_items[checklistIndex].status}
onChange={(e) => updateChecklistItem(checklistIndex, 'status', e.target.value)}
className="border border-gray-300 rounded-md px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
>
<option value="not_applicable">N/A</option>
<option value="pass">Pass</option>
<option value="fail">Fail</option>
<option value="needs_attention">Needs Attention</option>
</select>
<span className="text-sm text-gray-700 flex-1">{item}</span>
{getStatusIcon(formData.checklist_items[checklistIndex].status)}
</div>
);
})}
</div>
</div>
))}
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Overall Score (0-5)</label>
<input
type="number"
min="0"
max="5"
step="0.1"
value={formData.overall_score}
onChange={(e) => setFormData({ ...formData, overall_score: e.target.value })}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Overall Notes</label>
<textarea
value={formData.overall_notes}
onChange={(e) => setFormData({ ...formData, overall_notes: e.target.value })}
rows={3}
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Issues Found</label>
<div className="space-y-2">
{formData.issues_found.map((issue, index) => (
<div key={index} className="flex items-start space-x-2 border border-gray-200 rounded-md p-3">
<select
value={issue.severity}
onChange={(e) => updateIssue(index, 'severity', e.target.value)}
className="border border-gray-300 rounded-md px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
>
<option value="cosmetic">Cosmetic</option>
<option value="minor">Minor</option>
<option value="major">Major</option>
<option value="critical">Critical</option>
</select>
<input
type="text"
placeholder="Description"
value={issue.description}
onChange={(e) => updateIssue(index, 'description', e.target.value)}
className="flex-1 border border-gray-300 rounded-md px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
<button
type="button"
onClick={() => removeIssue(index)}
className="text-red-600 hover:text-red-800"
>
<X className="w-4 h-4" />
</button>
</div>
))}
<button
type="button"
onClick={addIssue}
className="text-sm text-blue-600 hover:text-blue-800"
>
+ Add Issue
</button>
</div>
</div>
<div className="flex items-center">
<input
type="checkbox"
id="requires_followup"
checked={formData.requires_followup}
onChange={(e) => setFormData({ ...formData, requires_followup: e.target.checked })}
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
/>
<label htmlFor="requires_followup" className="ml-2 block text-sm text-gray-700">
Requires Follow-up
</label>
</div>
<div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
<button
type="button"
onClick={() => setShowModal(false)}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"
>
{editingInspection ? 'Update' : 'Create'}
</button>
</div>
</form>
</div>
</div>
)}
{/* View Modal - Similar structure to others, showing full inspection details */}
{viewingInspection && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
<div className="p-6 border-b border-gray-200">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-bold text-gray-900">Inspection Details</h2>
<button
onClick={() => setViewingInspection(null)}
className="text-gray-400 hover:text-gray-600"
>
<X className="w-6 h-6" />
</button>
</div>
</div>
<div className="p-6 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-500">Room</label>
<p className="mt-1 text-sm text-gray-900">
{viewingInspection.room_number || `Room ${viewingInspection.room_id}`}
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-500">Status</label>
<p className="mt-1">
<span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(viewingInspection.status)}`}>
{viewingInspection.status.replace('_', ' ')}
</span>
</p>
</div>
</div>
{viewingInspection.overall_score && (
<div>
<label className="block text-sm font-medium text-gray-500">Overall Score</label>
<div className="mt-1 flex items-center space-x-1">
<Star className="w-5 h-5 text-yellow-500 fill-current" />
<span className="text-lg font-semibold text-gray-900">{viewingInspection.overall_score.toFixed(1)} / 5.0</span>
</div>
</div>
)}
{viewingInspection.checklist_items && viewingInspection.checklist_items.length > 0 && (
<div>
<label className="block text-sm font-medium text-gray-500 mb-2">Checklist</label>
<div className="space-y-3">
{defaultChecklistCategories.map((category) => {
const categoryItems = viewingInspection.checklist_items.filter(
(item) => item.category === category.category
);
if (categoryItems.length === 0) return null;
return (
<div key={category.category} className="border border-gray-200 rounded-md p-3">
<h4 className="font-semibold text-sm text-gray-700 mb-2">{category.category}</h4>
<div className="space-y-1">
{categoryItems.map((item, index) => (
<div key={index} className="flex items-center space-x-2">
{getStatusIcon(item.status)}
<span className="text-sm text-gray-700">{item.item}</span>
<span className="text-xs text-gray-500 capitalize">({item.status.replace('_', ' ')})</span>
</div>
))}
</div>
</div>
);
})}
</div>
</div>
)}
{viewingInspection.issues_found && viewingInspection.issues_found.length > 0 && (
<div>
<label className="block text-sm font-medium text-gray-500 mb-2">Issues Found</label>
<div className="space-y-2">
{viewingInspection.issues_found.map((issue, index) => (
<div key={index} className="border border-red-200 bg-red-50 rounded-md p-3">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold text-red-800 capitalize">{issue.severity}</span>
</div>
<p className="text-sm text-gray-900 mt-1">{issue.description}</p>
</div>
))}
</div>
</div>
)}
{isAdmin && (
<div className="flex justify-end pt-4 border-t border-gray-200">
<button
onClick={() => {
setViewingInspection(null);
handleEdit(viewingInspection);
}}
className="px-4 py-2 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"
>
Edit
</button>
</div>
)}
</div>
</div>
</div>
)}
</div>
);
};
export default InspectionManagement;