import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, useActionData, useLoaderData, useNavigation, Link } from "@remix-run/react"; import { requireAuthLevel } from "~/utils/auth.server"; import DashboardLayout from "~/components/DashboardLayout"; import { useState, useEffect } from "react"; import { prisma } from "~/utils/db.server"; export const meta: MetaFunction = () => [{ title: "Edit Report - Phosphat Report" }]; export const loader = async ({ request, params }: LoaderFunctionArgs) => { const user = await requireAuthLevel(request, 1); const reportId = params.id; if (!reportId) { throw new Response("Report ID is required", { status: 400 }); } // Get the report to edit const report = await prisma.report.findUnique({ where: { id: parseInt(reportId) }, include: { employee: { select: { name: true } }, area: { select: { name: true } }, dredgerLocation: { select: { name: true, class: true } }, reclamationLocation: { select: { name: true } }, shiftWorkers: { include: { worker: { select: { id: true, name: true, status: true } } } } } }); if (!report) { throw new Response("Report not found", { status: 404 }); } // Check permissions if (user.authLevel < 2 && report.employeeId !== user.id) { throw new Response("You can only edit your own reports", { status: 403 }); } // Get dropdown data for form const [foremen, equipment, workers] = await Promise.all([ prisma.foreman.findMany({ orderBy: { name: 'asc' } }), prisma.equipment.findMany({ orderBy: [{ category: 'asc' }, { model: 'asc' }, { number: 'asc' }] }), prisma.worker.findMany({ where: { status: 'active' }, orderBy: { name: 'asc' } }) ]); return json({ user, report, foremen, equipment, workers }); }; export const action = async ({ request, params }: ActionFunctionArgs) => { const user = await requireAuthLevel(request, 1); const reportId = params.id; if (!reportId) { return json({ errors: { form: "Report ID is required" } }, { status: 400 }); } const existingReport = await prisma.report.findUnique({ where: { id: parseInt(reportId) }, select: { employeeId: true, createdDate: true, shift: true, areaId: true, dredgerLocationId: true, reclamationLocationId: true } }); if (!existingReport) { return json({ errors: { form: "Report not found" } }, { status: 404 }); } if (user.authLevel < 2) { if (existingReport.employeeId !== user.id) { return json({ errors: { form: "You can only edit your own reports" } }, { status: 403 }); } const latestUserReport = await prisma.report.findFirst({ where: { employeeId: user.id }, orderBy: { createdDate: 'desc' }, select: { id: true } }); if (!latestUserReport || latestUserReport.id !== parseInt(reportId)) { return json({ errors: { form: "You can only edit your latest report" } }, { status: 403 }); } } const formData = await request.formData(); const dredgerLineLength = formData.get("dredgerLineLength"); const shoreConnection = formData.get("shoreConnection"); const notes = formData.get("notes"); const reclamationHeightBase = formData.get("reclamationHeightBase"); const reclamationHeightExtra = formData.get("reclamationHeightExtra"); const pipelineMain = formData.get("pipelineMain"); const pipelineExt1 = formData.get("pipelineExt1"); const pipelineReserve = formData.get("pipelineReserve"); const pipelineExt2 = formData.get("pipelineExt2"); const statsDozers = formData.get("statsDozers"); const statsExc = formData.get("statsExc"); const statsLoaders = formData.get("statsLoaders"); const statsForeman = formData.get("statsForeman"); const workersListData = formData.get("workersList"); const timeSheetData = formData.get("timeSheetData"); const stoppagesData = formData.get("stoppagesData"); if (typeof dredgerLineLength !== "string" || isNaN(parseInt(dredgerLineLength))) { return json({ errors: { dredgerLineLength: "Valid dredger line length is required" } }, { status: 400 }); } if (typeof shoreConnection !== "string" || isNaN(parseInt(shoreConnection))) { return json({ errors: { shoreConnection: "Valid shore connection is required" } }, { status: 400 }); } try { let timeSheet = []; let stoppages = []; let workersList = []; if (timeSheetData && typeof timeSheetData === "string") { try { timeSheet = JSON.parse(timeSheetData); } catch (e) { timeSheet = []; } } if (stoppagesData && typeof stoppagesData === "string") { try { stoppages = JSON.parse(stoppagesData); } catch (e) { stoppages = []; } } if (workersListData && typeof workersListData === "string") { try { workersList = JSON.parse(workersListData); } catch (e) { workersList = []; } } const ext1Value = parseInt(pipelineExt1 as string) || 0; const ext2Value = parseInt(pipelineExt2 as string) || 0; const shiftText = existingReport.shift === 'day' ? 'Day' : 'Night'; let automaticNotes = []; if (ext1Value > 0) automaticNotes.push(`Main Extension ${ext1Value}m ${shiftText}`); if (ext2Value > 0) automaticNotes.push(`Reserve Extension ${ext2Value}m ${shiftText}`); let finalNotes = typeof notes === "string" ? notes : ''; if (automaticNotes.length > 0) { const automaticNotesText = automaticNotes.join(', '); finalNotes = finalNotes.trim() ? `${automaticNotesText}. ${finalNotes}` : automaticNotesText; } await prisma.report.update({ where: { id: parseInt(reportId) }, data: { dredgerLineLength: parseInt(dredgerLineLength), shoreConnection: parseInt(shoreConnection), reclamationHeight: { base: parseInt(reclamationHeightBase as string) || 0, extra: parseInt(reclamationHeightExtra as string) || 0 }, pipelineLength: { main: parseInt(pipelineMain as string) || 0, ext1: ext1Value, reserve: parseInt(pipelineReserve as string) || 0, ext2: ext2Value }, stats: { Dozers: parseInt(statsDozers as string) || 0, Exc: parseInt(statsExc as string) || 0, Loaders: parseInt(statsLoaders as string) || 0, Foreman: statsForeman as string || "", Laborer: workersList.length }, timeSheet, stoppages, notes: finalNotes || null } }); // Update workers await prisma.shiftWorker.deleteMany({ where: { reportId: parseInt(reportId) } }); if (workersList.length > 0) { await prisma.shiftWorker.createMany({ data: workersList.map((workerId: number) => ({ reportId: parseInt(reportId), workerId: workerId })) }); } return redirect("/reports?success=Report updated successfully!"); } catch (error) { return json({ errors: { form: "Failed to update report. Please try again." } }, { status: 400 }); } }; export default function EditReport() { const { user, report, foremen, equipment, workers } = useLoaderData(); const actionData = useActionData(); const navigation = useNavigation(); const [formData, setFormData] = useState({ dredgerLineLength: report.dredgerLineLength.toString(), shoreConnection: report.shoreConnection.toString(), reclamationHeightBase: (report.reclamationHeight as any).base?.toString() || '0', reclamationHeightExtra: (report.reclamationHeight as any).extra?.toString() || '0', pipelineMain: (report.pipelineLength as any).main?.toString() || '0', pipelineExt1: (report.pipelineLength as any).ext1?.toString() || '0', pipelineReserve: (report.pipelineLength as any).reserve?.toString() || '0', pipelineExt2: (report.pipelineLength as any).ext2?.toString() || '0', statsDozers: (report.stats as any).Dozers?.toString() || '0', statsExc: (report.stats as any).Exc?.toString() || '0', statsLoaders: (report.stats as any).Loaders?.toString() || '0', statsForeman: (report.stats as any).Foreman || '', notes: report.notes || '' }); const [selectedWorkers, setSelectedWorkers] = useState( report.shiftWorkers?.map((sw: any) => sw.worker.id) || [] ); const [workerSearchTerm, setWorkerSearchTerm] = useState(''); const [timeSheetEntries, setTimeSheetEntries] = useState>(Array.isArray(report.timeSheet) ? (report.timeSheet as any[]).map((entry: any, index: number) => ({ ...entry, id: entry.id || `existing-${index}` })) : []); const [stoppageEntries, setStoppageEntries] = useState>(Array.isArray(report.stoppages) ? (report.stoppages as any[]).map((entry: any, index: number) => ({ ...entry, id: entry.id || `existing-${index}` })) : []); const [currentStep, setCurrentStep] = useState(1); const totalSteps = 3; const isSubmitting = navigation.state === "submitting"; const updateFormData = (field: string, value: string) => { setFormData(prev => ({ ...prev, [field]: value })); }; const handleSubmit = (event: React.FormEvent) => { if (currentStep !== totalSteps) { event.preventDefault(); event.stopPropagation(); return false; } const invalidStoppages = stoppageEntries.filter(entry => entry.responsible === 'reclamation' && !entry.note.trim() ); if (invalidStoppages.length > 0) { alert('Please add notes for all reclamation stoppages before submitting.'); event.preventDefault(); event.stopPropagation(); return false; } }; // Helper functions for time calculations const calculateTimeDifference = (from1: string, to1: string, from2: string, to2: string) => { if (!from1 || !to1) return "00:00"; const parseTime = (timeStr: string) => { const [hours, minutes] = timeStr.split(':').map(Number); return hours * 60 + minutes; }; const formatTime = (minutes: number) => { const hours = Math.floor(minutes / 60); const mins = minutes % 60; return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`; }; let totalMinutes = 0; if (from1 && to1) { const start1 = parseTime(from1); let end1 = parseTime(to1); if (end1 < start1) end1 += 24 * 60; totalMinutes += end1 - start1; } if (from2 && to2) { const start2 = parseTime(from2); let end2 = parseTime(to2); if (end2 < start2) end2 += 24 * 60; totalMinutes += end2 - start2; } return formatTime(Math.max(0, totalMinutes)); }; const calculateStoppageTime = (from: string, to: string) => { if (!from || !to) return "00:00"; const parseTime = (timeStr: string) => { const [hours, minutes] = timeStr.split(':').map(Number); return hours * 60 + minutes; }; const formatTime = (minutes: number) => { const hours = Math.floor(minutes / 60); const mins = minutes % 60; return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`; }; const startMinutes = parseTime(from); let endMinutes = parseTime(to); if (endMinutes < startMinutes) endMinutes += 24 * 60; const totalMinutes = Math.max(0, endMinutes - startMinutes); return formatTime(totalMinutes); }; // Time Sheet management const addTimeSheetEntry = () => { const newEntry = { id: Date.now().toString(), machine: '', from1: '', to1: '', from2: '', to2: '', total: '00:00', reason: '' }; setTimeSheetEntries([...timeSheetEntries, newEntry]); }; const removeTimeSheetEntry = (id: string) => { setTimeSheetEntries(timeSheetEntries.filter(entry => entry.id !== id)); }; const updateTimeSheetEntry = (id: string, field: string, value: string) => { setTimeSheetEntries(timeSheetEntries.map(entry => { if (entry.id === id) { const updatedEntry = { ...entry, [field]: value }; if (['from1', 'to1', 'from2', 'to2'].includes(field)) { updatedEntry.total = calculateTimeDifference( updatedEntry.from1, updatedEntry.to1, updatedEntry.from2, updatedEntry.to2 ); } return updatedEntry; } return entry; })); }; // Auto-calculate equipment counts based on time sheet entries useEffect(() => { const counts = { dozers: 0, excavators: 0, loaders: 0 }; timeSheetEntries.forEach(entry => { if (entry.machine) { const equipmentItem = equipment.find(item => `${item.model} (${item.number})` === entry.machine ); if (equipmentItem) { const category = equipmentItem.category.toLowerCase(); if (category.includes('dozer')) { counts.dozers++; } else if (category.includes('excavator')) { counts.excavators++; } else if (category.includes('loader')) { counts.loaders++; } } } }); setFormData(prev => ({ ...prev, statsDozers: counts.dozers.toString(), statsExc: counts.excavators.toString(), statsLoaders: counts.loaders.toString() })); }, [timeSheetEntries, equipment]); // Stoppage management const addStoppageEntry = () => { const newEntry = { id: Date.now().toString(), from: '', to: '', total: '00:00', reason: '', responsible: 'reclamation', note: '' }; setStoppageEntries([...stoppageEntries, newEntry]); }; const removeStoppageEntry = (id: string) => { setStoppageEntries(stoppageEntries.filter(entry => entry.id !== id)); }; const updateStoppageEntry = (id: string, field: string, value: string) => { setStoppageEntries(stoppageEntries.map(entry => { if (entry.id === id) { const updatedEntry = { ...entry, [field]: value }; if (['from', 'to'].includes(field)) { updatedEntry.total = calculateStoppageTime(updatedEntry.from, updatedEntry.to); } if (field === 'responsible') { if (value === 'reclamation') { updatedEntry.reason = ''; } } return updatedEntry; } return entry; })); }; const nextStep = (event?: React.MouseEvent) => { if (event) { event.preventDefault(); event.stopPropagation(); } if (currentStep < totalSteps) { setCurrentStep(currentStep + 1); } }; const prevStep = () => { if (currentStep > 1) { setCurrentStep(currentStep - 1); } }; const getStepTitle = (step: number) => { switch (step) { case 1: return "Pipeline Details"; case 2: return "Equipment & Time Sheet"; case 3: return "Stoppages & Notes"; default: return ""; } }; const isCurrentStepValid = () => { return true; // All steps are optional for editing }; // Worker selection functions const toggleWorker = (workerId: number) => { setSelectedWorkers(prev => prev.includes(workerId) ? prev.filter(id => id !== workerId) : [...prev, workerId] ); }; const filteredWorkers = workers.filter(worker => worker.name.toLowerCase().includes(workerSearchTerm.toLowerCase()) && !selectedWorkers.includes(worker.id) ); return (
{/* Header */}

Edit Report

Update shift details

Back to Reports
{/* Progress Steps */}
{[1, 2, 3].map((step) => (
{step < currentStep ? ( ) : ( {step} )}
{step < totalSteps && (
)}
))}

{getStepTitle(currentStep)}

Step {currentStep} of {totalSteps}

{/* Form */}
{/* Step 1: Locked Fields Display + Pipeline Details */} {currentStep === 1 && (
{/* Locked Fields Display */}

Report Information (Cannot be changed)

Date: {new Date(report.createdDate).toLocaleDateString('en-GB')}
Shift: {report.shift.charAt(0).toUpperCase() + report.shift.slice(1)}
Area: {report.area.name}
Dredger Location: {report.dredgerLocation.name}
Reclamation Location: {report.reclamationLocation.name}
{/* Editable Dredger Line Length and Shore Connection */}
updateFormData('dredgerLineLength', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateFormData('shoreConnection', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />

Reclamation Height

updateFormData('reclamationHeightBase', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateFormData('reclamationHeightExtra', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />

Pipeline Length

updateFormData('pipelineMain', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateFormData('pipelineExt1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateFormData('pipelineReserve', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateFormData('pipelineExt2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
)} {/* Step 2: Equipment & Time Sheet */} {currentStep === 2 && (

Equipment Statistics

Select Workers

setWorkerSearchTerm(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /> {workerSearchTerm && filteredWorkers.length > 0 && (
{filteredWorkers.map((worker) => ( ))}
)}
{selectedWorkers.length > 0 && (
{selectedWorkers.map((workerId) => { const worker = workers.find(w => w.id === workerId); return worker ? ( {worker.name} ) : null; })}
)}

Time Sheet

{timeSheetEntries.length > 0 ? (
{timeSheetEntries.map((entry) => (
updateTimeSheetEntry(entry.id, 'from1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateTimeSheetEntry(entry.id, 'to1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateTimeSheetEntry(entry.id, 'from2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateTimeSheetEntry(entry.id, 'to2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateTimeSheetEntry(entry.id, 'reason', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="Reason for downtime (if any)" />
))}
) : (

No time sheet entries yet. Click "Add Entry" to get started.

)}
)} {/* Step 3: Stoppages & Notes */} {currentStep === 3 && (

Dredger Stoppages

{stoppageEntries.length > 0 ? (
{stoppageEntries.map((entry) => (
updateStoppageEntry(entry.id, 'from', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateStoppageEntry(entry.id, 'to', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" />
updateStoppageEntry(entry.id, 'note', e.target.value)} className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 ${ entry.responsible === 'reclamation' && !entry.note.trim() ? 'border-red-300 bg-red-50' : 'border-gray-300' }`} placeholder={entry.responsible === 'reclamation' ? 'Notes required for reclamation stoppages' : 'Additional notes'} />
))}
) : (

No stoppages recorded. Click "Add Stoppage" if there were any.

)}