phosphat-report-app/app/routes/equipment.tsx

662 lines
30 KiB
TypeScript

import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation } from "@remix-run/react";
import { requireAuthLevel } from "~/utils/auth.server";
import DashboardLayout from "~/components/DashboardLayout";
import FormModal from "~/components/FormModal";
import Toast from "~/components/Toast";
import { useState, useEffect } from "react";
import { prisma } from "~/utils/db.server";
export const meta: MetaFunction = () => [{ title: "Equipment Management - Phosphat Report" }];
export const loader = async ({ request }: LoaderFunctionArgs) => {
const user = await requireAuthLevel(request, 2);
const equipment = await prisma.equipment.findMany({
orderBy: [{ category: 'asc' }, { model: 'asc' }]
});
return json({ user, equipment });
};
export const action = async ({ request }: ActionFunctionArgs) => {
await requireAuthLevel(request, 2);
const formData = await request.formData();
const intent = formData.get("intent");
const id = formData.get("id");
const category = formData.get("category");
const model = formData.get("model");
const number = formData.get("number");
if (intent === "create") {
if (typeof category !== "string" || category.length === 0) {
return json({ errors: { category: "Category is required" } }, { status: 400 });
}
if (typeof model !== "string" || model.length === 0) {
return json({ errors: { model: "Model is required" } }, { status: 400 });
}
if (typeof number !== "string" || isNaN(parseInt(number)) || parseInt(number) < 1) {
return json({ errors: { number: "Valid number is required" } }, { status: 400 });
}
try {
await prisma.equipment.create({
data: {
category,
model,
number: parseInt(number)
}
});
return json({ success: "Equipment created successfully!" });
} catch (error) {
return json({ errors: { form: "Failed to create equipment" } }, { status: 400 });
}
}
if (intent === "update") {
if (typeof category !== "string" || category.length === 0) {
return json({ errors: { category: "Category is required" } }, { status: 400 });
}
if (typeof model !== "string" || model.length === 0) {
return json({ errors: { model: "Model is required" } }, { status: 400 });
}
if (typeof number !== "string" || isNaN(parseInt(number)) || parseInt(number) < 1) {
return json({ errors: { number: "Valid number is required" } }, { status: 400 });
}
if (typeof id !== "string") {
return json({ errors: { form: "Invalid equipment ID" } }, { status: 400 });
}
try {
await prisma.equipment.update({
where: { id: parseInt(id) },
data: {
category,
model,
number: parseInt(number)
}
});
return json({ success: "Equipment updated successfully!" });
} catch (error) {
return json({ errors: { form: "Failed to update equipment" } }, { status: 400 });
}
}
if (intent === "delete") {
if (typeof id !== "string") {
return json({ errors: { form: "Invalid equipment ID" } }, { status: 400 });
}
try {
await prisma.equipment.delete({
where: { id: parseInt(id) }
});
return json({ success: "Equipment deleted successfully!" });
} catch (error) {
return json({ errors: { form: "Failed to delete equipment" } }, { status: 400 });
}
}
return json({ errors: { form: "Invalid action" } }, { status: 400 });
};
export default function Equipment() {
const { user, equipment } = useLoaderData<typeof loader>();
const actionData = useActionData<typeof action>();
const navigation = useNavigation();
const [editingEquipment, setEditingEquipment] = useState<{ id: number; category: string; model: string; number: number } | null>(null);
const [showModal, setShowModal] = useState(false);
const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);
const [showUsageModal, setShowUsageModal] = useState(false);
const [selectedEquipment, setSelectedEquipment] = useState<any>(null);
const [equipmentUsage, setEquipmentUsage] = useState<any[]>([]);
const [totalHours, setTotalHours] = useState({ hours: 0, minutes: 0 });
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
const [isLoadingUsage, setIsLoadingUsage] = useState(false);
const isSubmitting = navigation.state === "submitting";
const isEditing = editingEquipment !== null;
// Handle success/error messages
useEffect(() => {
if (actionData?.success) {
setToast({ message: actionData.success, type: "success" });
setShowModal(false);
setEditingEquipment(null);
} else if (actionData?.errors?.form) {
setToast({ message: actionData.errors.form, type: "error" });
}
}, [actionData]);
const handleEdit = (item: { id: number; category: string; model: string; number: number }) => {
setEditingEquipment(item);
setShowModal(true);
};
const handleAdd = () => {
setEditingEquipment(null);
setShowModal(true);
};
const handleCloseModal = () => {
setShowModal(false);
setEditingEquipment(null);
};
const handleViewUsage = (item: any) => {
setSelectedEquipment(item);
setShowUsageModal(true);
setDateFrom('');
setDateTo('');
setEquipmentUsage([]);
setTotalHours({ hours: 0, minutes: 0 });
};
const handleCloseUsageModal = () => {
setShowUsageModal(false);
setSelectedEquipment(null);
setEquipmentUsage([]);
setDateFrom('');
setDateTo('');
setTotalHours({ hours: 0, minutes: 0 });
};
const calculateTotalHours = (usage: any[]) => {
let totalMinutes = 0;
usage.forEach((entry: any) => {
const [hours, minutes] = entry.totalHours.split(':').map(Number);
totalMinutes += hours * 60 + minutes;
});
return {
hours: Math.floor(totalMinutes / 60),
minutes: totalMinutes % 60
};
};
const handleFilterUsage = async () => {
if (!selectedEquipment) return;
setIsLoadingUsage(true);
try {
const params = new URLSearchParams({
category: selectedEquipment.category,
model: selectedEquipment.model,
number: selectedEquipment.number.toString()
});
if (dateFrom) params.append('dateFrom', dateFrom);
if (dateTo) params.append('dateTo', dateTo);
const response = await fetch(`/api/equipment-usage?${params.toString()}`);
const data = await response.json();
if (data.usage) {
setEquipmentUsage(data.usage);
setTotalHours(calculateTotalHours(data.usage));
}
} catch (error) {
setToast({ message: "Failed to load equipment usage", type: "error" });
} finally {
setIsLoadingUsage(false);
}
};
const getCategoryBadge = (category: string) => {
const colors = {
Dozer: "bg-yellow-100 text-yellow-800",
Excavator: "bg-blue-100 text-blue-800",
Loader: "bg-green-100 text-green-800",
Truck: "bg-red-100 text-red-800"
};
return colors[category as keyof typeof colors] || "bg-gray-100 text-gray-800";
};
const getCategoryIcon = (category: string) => {
// Using the same heavy equipment SVG icon with different colors based on category
const color = {
"Dozer": "#f59e0b", // yellow-500
"Excavator": "#3b82f6", // blue-500
"Loader": "#10b981", // green-500
"Truck": "#ef4444", // red-500
}[category] || "#6b7280"; // gray-500 default
return (
<svg className="h-5 w-5" fill="none" stroke={color} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
);
};
return (
<DashboardLayout user={user}>
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:justify-between sm:items-center space-y-4 sm:space-y-0">
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900">Equipment Management</h1>
<p className="mt-1 text-sm text-gray-600">Manage your fleet equipment and machinery</p>
</div>
<button
onClick={handleAdd}
className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200"
>
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
Add New Equipment
</button>
</div>
{/* Equipment Table - Desktop */}
<div className="bg-white shadow-sm rounded-lg overflow-hidden">
<div className="hidden sm:block">
<div className="overflow-x-auto">
<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">
Equipment
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Category
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Number
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{equipment.map((item) => (
<tr key={item.id} className="hover:bg-gray-50 transition-colors duration-150">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="flex-shrink-0 h-10 w-10">
<div className={`h-10 w-10 rounded-full flex items-center justify-center ${getCategoryBadge(item.category)}`}>
{getCategoryIcon(item.category)}
</div>
</div>
<div className="ml-4">
<div className="text-sm font-medium text-gray-900">{item.model}</div>
{/* <div className="text-sm text-gray-500">ID #{item.id}</div> */}
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getCategoryBadge(item.category)}`}>
{item.category}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
<span className="font-mono">{item.number}</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div className="flex justify-end space-x-2">
<button
onClick={() => handleViewUsage(item)}
className="text-teal-600 hover:text-teal-900 transition-colors duration-150"
>
View Usage
</button>
<button
onClick={() => handleEdit(item)}
className="text-indigo-600 hover:text-indigo-900 transition-colors duration-150"
>
Edit
</button>
<Form method="post" className="inline">
<input type="hidden" name="intent" value="delete" />
<input type="hidden" name="id" value={item.id} />
<button
type="submit"
onClick={(e) => {
if (!confirm("Are you sure you want to delete this equipment?")) {
e.preventDefault();
}
}}
className="text-red-600 hover:text-red-900 transition-colors duration-150"
>
Delete
</button>
</Form>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Equipment Cards - Mobile */}
<div className="sm:hidden">
<div className="space-y-4 p-4">
{equipment.map((item) => (
<div key={item.id} className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center">
<div className={`h-10 w-10 rounded-full flex items-center justify-center ${getCategoryBadge(item.category)}`}>
{getCategoryIcon(item.category)}
</div>
<div className="ml-3">
<div className="text-sm font-medium text-gray-900">{item.model}</div>
<div className="text-xs text-gray-500 font-mono">#{item.number}</div>
</div>
</div>
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getCategoryBadge(item.category)}`}>
{item.category}
</span>
</div>
<div className="flex flex-col space-y-2">
<button
onClick={() => handleViewUsage(item)}
className="w-full text-center px-3 py-2 text-sm text-teal-600 bg-teal-50 rounded-md hover:bg-teal-100 transition-colors duration-150"
>
View Usage
</button>
<button
onClick={() => handleEdit(item)}
className="w-full text-center px-3 py-2 text-sm text-indigo-600 bg-indigo-50 rounded-md hover:bg-indigo-100 transition-colors duration-150"
>
Edit Equipment
</button>
<Form method="post" className="w-full">
<input type="hidden" name="intent" value="delete" />
<input type="hidden" name="id" value={item.id} />
<button
type="submit"
onClick={(e) => {
if (!confirm("Are you sure you want to delete this equipment?")) {
e.preventDefault();
}
}}
className="w-full text-center px-3 py-2 text-sm text-red-600 bg-red-50 rounded-md hover:bg-red-100 transition-colors duration-150"
>
Delete Equipment
</button>
</Form>
</div>
</div>
))}
</div>
</div>
{equipment.length === 0 && (
<div className="text-center py-12">
<svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z" />
</svg>
<h3 className="mt-2 text-sm font-medium text-gray-900">No equipment</h3>
<p className="mt-1 text-sm text-gray-500">Get started by adding your first equipment.</p>
<div className="mt-6">
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
>
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
Add Equipment
</button>
</div>
</div>
)}
</div>
{/* Equipment Usage Modal */}
{showUsageModal && selectedEquipment && (
<div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
<div className="relative top-20 mx-auto p-5 border w-full max-w-5xl shadow-lg rounded-md bg-white">
<div className="flex justify-between items-center mb-4">
<div>
<h3 className="text-lg font-medium text-gray-900">
Equipment Usage - {selectedEquipment.model}
</h3>
<p className="text-sm text-gray-500">
{selectedEquipment.category} #{selectedEquipment.number}
</p>
</div>
<button
onClick={handleCloseUsageModal}
className="text-gray-400 hover:text-gray-600"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Date Filters */}
<div className="bg-gray-50 p-4 rounded-lg mb-4">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div>
<label htmlFor="usageDateFrom" className="block text-sm font-medium text-gray-700 mb-1">
From Date
</label>
<input
type="date"
id="usageDateFrom"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
max={new Date().toISOString().split('T')[0]}
className="block w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
/>
</div>
<div>
<label htmlFor="usageDateTo" className="block text-sm font-medium text-gray-700 mb-1">
To Date
</label>
<input
type="date"
id="usageDateTo"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
max={new Date().toISOString().split('T')[0]}
className="block w-full text-sm border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
/>
</div>
<div className="flex items-end">
<button
onClick={handleFilterUsage}
disabled={isLoadingUsage}
className="w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
>
{isLoadingUsage ? 'Loading...' : 'Filter Usage'}
</button>
</div>
</div>
</div>
{/* Total Hours Summary */}
{equipmentUsage.length > 0 && (
<div className="bg-indigo-50 border border-indigo-200 rounded-lg p-4 mb-4">
<div className="flex items-center justify-between">
<div className="flex items-center">
<svg className="h-8 w-8 text-indigo-600 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div>
<p className="text-sm font-medium text-indigo-900">Total Working Hours</p>
<p className="text-xs text-indigo-700">Across {equipmentUsage.length} shift{equipmentUsage.length !== 1 ? 's' : ''}</p>
</div>
</div>
<div className="text-right">
<p className="text-3xl font-bold text-indigo-900">
{totalHours.hours}h {totalHours.minutes}m
</p>
<p className="text-xs text-indigo-700">
({totalHours.hours * 60 + totalHours.minutes} minutes)
</p>
</div>
</div>
</div>
)}
{/* Usage List */}
<div className="max-h-96 overflow-y-auto">
{equipmentUsage.length > 0 ? (
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Date
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Shift
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Area
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Employee
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Working Hours
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Reason
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{equipmentUsage.map((entry: any, index: number) => (
<tr key={index} className="hover:bg-gray-50">
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
{new Date(entry.createdDate).toLocaleDateString('en-GB')}
</td>
<td className="px-4 py-3 whitespace-nowrap">
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${entry.shift === 'day' ? 'bg-yellow-100 text-yellow-800' : 'bg-blue-100 text-blue-800'}`}>
{entry.shift.charAt(0).toUpperCase() + entry.shift.slice(1)}
</span>
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
{entry.area.name}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm text-gray-900">
{entry.employee.name}
</td>
<td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-indigo-600">
{entry.totalHours}
</td>
<td className="px-4 py-3 text-sm text-gray-500">
{entry.reason || '-'}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="text-center py-12 bg-gray-50 rounded-lg">
<svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<p className="mt-2 text-sm text-gray-500">
{isLoadingUsage ? 'Loading usage data...' : 'Click "Filter Usage" to view equipment usage history'}
</p>
</div>
)}
</div>
<div className="flex justify-end mt-4 pt-4 border-t border-gray-200">
<button
onClick={handleCloseUsageModal}
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
Close
</button>
</div>
</div>
</div>
)}
{/* Form Modal */}
<FormModal
isOpen={showModal}
onClose={handleCloseModal}
title={isEditing ? "Edit Equipment" : "Add New Equipment"}
isSubmitting={isSubmitting}
submitText={isEditing ? "Update Equipment" : "Create Equipment"}
>
<Form method="post" id="modal-form" className="space-y-4">
<input type="hidden" name="intent" value={isEditing ? "update" : "create"} />
{isEditing && <input type="hidden" name="id" value={editingEquipment?.id} />}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-2">
Category
</label>
<select
name="category"
id="category"
required
defaultValue={editingEquipment?.category || ""}
className="block w-full border-gray-300 h-9 p-2 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
>
<option value="">Select category</option>
<option value="Dozer">Dozer</option>
<option value="Excavator">Excavator</option>
<option value="Loader">Loader</option>
<option value="Truck">Truck</option>
</select>
{actionData?.errors?.category && (
<p className="mt-1 text-sm text-red-600">{actionData.errors.category}</p>
)}
</div>
<div>
<label htmlFor="number" className="block text-sm font-medium text-gray-700 mb-2">
Number
</label>
<input
type="number"
name="number"
id="number"
min="1"
required
defaultValue={editingEquipment?.number || ""}
className="block w-full border-gray-300 h-9 p-2 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="Enter number"
/>
{actionData?.errors?.number && (
<p className="mt-1 text-sm text-red-600">{actionData.errors.number}</p>
)}
</div>
</div>
<div>
<label htmlFor="model" className="block text-sm font-medium text-gray-700 mb-2">
Model
</label>
<input
type="text"
name="model"
id="model"
required
defaultValue={editingEquipment?.model || ""}
className="block w-full border-gray-300 h-9 p-2 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
placeholder="Enter model name"
/>
{actionData?.errors?.model && (
<p className="mt-1 text-sm text-red-600">{actionData.errors.model}</p>
)}
</div>
</Form>
</FormModal>
{/* Toast Notifications */}
{toast && (
<Toast
message={toast.message}
type={toast.type}
onClose={() => setToast(null)}
/>
)}
</div>
</DashboardLayout>
);
}