import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { useParams, useNavigate } from "react-router";
import { toast } from "react-toastify";
import { getWorkOrderById, addComment, changeWorkOrderStatus, fetchUsers, changeWorkOrderAssignment, fetchVendorsDropdown, dispatchToVendor, getDispatchById, updateDispatch, addDispatchComment, fetchTaskTemplates, updateChecklistItem, addChecklistItem, addDispatchSignoff, verifyDispatch } from "../api";
import { getCurrentUser } from "../../../services/authService";
import { timeSince, timeBetween, waitTimeColor } from "../../../utils/timeSince";
import SignatureCapture from "../../../components/SignatureCapture";
import "../../../components/SignatureCapture.css";
import "./WorkOrderViewPage.css";
function AssignDropdown({ value, onAssign }) {
const [open, setOpen] = useState(false);
const [users, setUsers] = useState([]);
const [loaded, setLoaded] = useState(false);
const btnRef = useRef(null);
const menuRef = useRef(null);
const [menuPos, setMenuPos] = useState({ top: 0, left: 0 });
useEffect(() => {
const handleClick = (e) => {
if (btnRef.current?.contains(e.target)) return;
if (menuRef.current?.contains(e.target)) return;
setOpen(false);
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
const handleOpen = async () => {
if (!loaded) {
try {
const data = await fetchUsers();
setUsers(data);
setLoaded(true);
} catch { return; }
}
if (btnRef.current) {
const rect = btnRef.current.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.left });
}
setOpen(!open);
};
const handleSelect = async (userId, userName) => {
setOpen(false);
onAssign(userId, userName);
};
return (
<>
{open && ReactDOM.createPortal(
{users.map((u) => (
))}
,
document.body
)}
>
);
}
function CollapsibleSection({ title, defaultOpen = false, children }) {
const [open, setOpen] = useState(defaultOpen);
return (
setOpen(!open)}>
▸
{title}
{open && children}
);
}
function formatDateTime(value) {
const d = new Date(value.endsWith("Z") ? value : value + "Z");
if (isNaN(d)) return value;
const date = d.toLocaleDateString("en-CA");
const time = d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hour12: false });
const tz = d.toLocaleTimeString(undefined, { timeZoneName: "short" }).split(" ").pop();
return `${date} ${time} ${tz}`;
}
function CommentTimeline({ comments }) {
const bottomRef = useRef(null);
const sorted = [...(comments || [])].sort((a, b) =>
new Date(a.createdDate) - new Date(b.createdDate)
);
useEffect(() => {
bottomRef.current?.scrollIntoView();
}, [sorted.length]);
if (!sorted.length) {
return ;
}
return (
{sorted.map((c) => (
{c.userName || c.commenter || "System"}
{c.createdDate ? formatDateTime(c.createdDate) : ""}
{c.commenttext}
))}
);
}
function AuditTimeline({ entries }) {
const bottomRef = useRef(null);
const sorted = [...(entries || [])].sort((a, b) =>
new Date(a.createdAt) - new Date(b.createdAt)
);
useEffect(() => {
bottomRef.current?.scrollIntoView();
}, [sorted.length]);
if (!sorted.length) {
return ;
}
return (
{sorted.map((e) => (
{e.userName || "System"}
{e.createdAt ? formatDateTime(e.createdAt) : ""}
{e.fieldName}
{e.oldValue && {e.oldValue}}
→
{e.newValue}
))}
);
}
const DISPATCH_STATUSES = ["Sent", "Acknowledged", "In Progress", "Completed", "Verified", "Cancelled"];
function DispatchDetailModal({ dispatchId, onClose, onUpdated }) {
const [dispatch, setDispatch] = useState(null);
const [loading, setLoading] = useState(true);
const [editing, setEditing] = useState(false);
const [form, setForm] = useState({});
const [saving, setSaving] = useState(false);
const [commentText, setCommentText] = useState("");
const [sendEmail, setSendEmail] = useState(true);
const [sendingComment, setSendingComment] = useState(false);
const [sigCapture, setSigCapture] = useState(null);
const bottomRef = useRef(null);
const loadDispatch = async () => {
try {
const data = await getDispatchById(dispatchId);
setDispatch(data);
setForm({
status: data.status || "",
nteAmount: data.nteAmount != null ? String(data.nteAmount) : "",
scheduledDate: data.scheduledDate ? data.scheduledDate.split("T")[0] : "",
completedDate: data.completedDate ? data.completedDate.split("T")[0] : "",
description: data.description || "",
});
} catch {
toast.error("Failed to load dispatch");
} finally {
setLoading(false);
}
};
useEffect(() => { loadDispatch(); }, [dispatchId]);
useEffect(() => { bottomRef.current?.scrollIntoView(); }, [dispatch?.comments?.length]);
const handleSave = async () => {
setSaving(true);
try {
await updateDispatch({
Id: dispatchId,
Status: form.status,
NTEAmount: form.nteAmount ? parseFloat(form.nteAmount) : null,
ScheduledDate: form.scheduledDate || null,
CompletedDate: form.completedDate || null,
Description: form.description,
});
toast.success("Dispatch updated");
setEditing(false);
loadDispatch();
onUpdated();
} catch {
toast.error("Failed to update dispatch");
} finally {
setSaving(false);
}
};
const handleComment = async (e) => {
e.preventDefault();
if (!commentText.trim()) return;
setSendingComment(true);
try {
const newComment = await addDispatchComment(dispatchId, commentText.trim(), sendEmail);
setCommentText("");
setDispatch((prev) => ({
...prev,
comments: [...(prev.comments || []), newComment],
}));
} catch {
toast.error("Failed to send message");
} finally {
setSendingComment(false);
}
};
if (loading) {
return ReactDOM.createPortal(
,
document.body
);
}
if (!dispatch) return null;
return ReactDOM.createPortal(
e.stopPropagation()}>
{dispatch.dispatchNumber || dispatch.poNumber} · {dispatch.vendorName}
PO: {dispatch.poNumber} · {dispatch.workOrders?.length > 0 ? `${dispatch.workOrders.length} WO(s): ${dispatch.workOrders.map(w => w.woNumber).join(", ")}` : `WO: ${dispatch.woNumber}`} · {dispatch.vendorEmail}
{editing ? (
<>
setForm(f => ({ ...f, nteAmount: e.target.value }))} step="0.01" />
setForm(f => ({ ...f, scheduledDate: e.target.value }))} />
setForm(f => ({ ...f, completedDate: e.target.value }))} />
>
) : (
<>
{dispatch.status}
{dispatch.nteAmount != null ? `$${parseFloat(dispatch.nteAmount).toFixed(2)}` : "—"}
{dispatch.scheduledDate ? dispatch.scheduledDate.split("T")[0] : "—"}
{dispatch.completedDate ? dispatch.completedDate.split("T")[0] : "—"}
{dispatch.dispatchedAt ? formatDateTime(dispatch.dispatchedAt) : "—"}
{dispatch.acknowledgedAt ? (
{formatDateTime(dispatch.acknowledgedAt)} (after {timeBetween(dispatch.dispatchedAt, dispatch.acknowledgedAt)})
) : dispatch.status === "Sent" ? (
Awaiting acceptance · {timeSince(dispatch.dispatchedAt)}
) : (
—
)}
{dispatch.vendorEmail}
{dispatch.description && (
{dispatch.description}
)}
>
)}
{dispatch.checklistItems && dispatch.checklistItems.length > 0 && (
<>
Checklist ({dispatch.checklistItems.filter(i => i.isCompleted).length}/{dispatch.checklistItems.length})
{dispatch.checklistItems.map((item) => (
{
const currentUser = getCurrentUser();
const userName = currentUser?.fullname || "User";
await updateChecklistItem(item.id, !item.isCompleted, userName);
setDispatch((prev) => ({
...prev,
checklistItems: prev.checklistItems.map((ci) =>
ci.id === item.id ? { ...ci, isCompleted: !ci.isCompleted, completedBy: !ci.isCompleted ? userName : null, completedAt: !ci.isCompleted ? new Date().toISOString() : null } : ci
),
}));
}}
/>
{item.itemText}
{item.isCompleted && (
{item.completedBy}{item.completedAt ? ` · ${formatDateTime(item.completedAt)}` : ""}
)}
))}
>
)}
Sign-offs
{["Customer", "Vendor"].map((type) => {
const signoff = (dispatch.signoffs || []).find((s) => s.signoffType === type);
return (
{type}
{signoff ? (
{signoff.signatureMethod === "drawn" && signoff.signature && (

)}
{signoff.signatureMethod === "typed" && (
{signoff.signature}
)}
{signoff.name} · {signoff.signedAt ? formatDateTime(signoff.signedAt) : ""}
) : (
)}
);
})}
{(dispatch.signoffs || []).length >= 2 &&
All Signed ✓
}
{sigCapture && (
setSigCapture(null)}
onSave={async (signature, method) => {
const name = prompt(`Enter ${sigCapture.toLowerCase()} name:`);
if (!name) return;
try {
const result = await addDispatchSignoff(dispatchId, sigCapture, name, signature, method);
setDispatch((prev) => ({
...prev,
signoffs: [...(prev.signoffs || []), { ...result, signature, signatureMethod: method }],
}));
setSigCapture(null);
toast.success(`${sigCapture} sign-off collected`);
} catch {
toast.error("Failed to save sign-off");
}
}}
/>
)}
Vendor Communication
{(!dispatch.comments || dispatch.comments.length === 0) ? (
No messages yet.
) : (
{dispatch.comments.map((c) => (
{c.userName || c.commenter || "System"}
{c.createdDate ? formatDateTime(c.createdDate) : ""}
{c.commenttext}
))}
)}
{dispatch.verifiedAt ? (
✓ Verified by {dispatch.verifiedBy} on {formatDateTime(dispatch.verifiedAt)}
) : (
{(() => {
const checklistTotal = (dispatch.checklistItems || []).length;
const checklistDone = (dispatch.checklistItems || []).filter(i => i.isCompleted).length;
const signoffCount = (dispatch.signoffs || []).length;
const missing = [];
if (checklistTotal > 0 && checklistDone < checklistTotal) missing.push(`${checklistTotal - checklistDone} checklist item(s)`);
if (signoffCount < 2) {
const types = (dispatch.signoffs || []).map(s => s.signoffType);
if (!types.includes("Customer")) missing.push("Customer sign-off");
if (!types.includes("Vendor")) missing.push("Vendor sign-off");
}
const canVerify = missing.length === 0 && (checklistTotal > 0 || signoffCount >= 2);
return (
<>
{missing.length > 0 && Missing: {missing.join(", ")}}
>
);
})()}
)}
,
document.body
);
}
function DispatchModal({ wo, onClose, onDispatched }) {
const [vendors, setVendors] = useState([]);
const [selectedId, setSelectedId] = useState(null);
const [nteAmount, setNteAmount] = useState(wo.vendorNTE || "");
const [scheduledDate, setScheduledDate] = useState("");
const [description, setDescription] = useState(wo.description || "");
const [vendorSearch, setVendorSearch] = useState("");
const [sending, setSending] = useState(false);
const [taskTemplates, setTaskTemplates] = useState([]);
const [selectedTemplateId, setSelectedTemplateId] = useState("");
const [loaded, setLoaded] = useState(false);
useEffect(() => {
fetchVendorsDropdown(wo.trade, wo.locationZip).then((data) => {
setVendors(data);
setLoaded(true);
}).catch(() => setLoaded(true));
fetchTaskTemplates().then(setTaskTemplates).catch(() => {});
}, [wo.trade]);
const selectVendor = (id) => {
setSelectedId(prev => prev === id ? null : id);
};
const filteredVendors = vendors.filter((v) =>
(v.companyName || "").toLowerCase().includes(vendorSearch.toLowerCase()) ||
(v.tradeSpecialties || "").toLowerCase().includes(vendorSearch.toLowerCase())
);
const handleSubmit = async () => {
if (!selectedId) { toast.error("Select a vendor"); return; }
setSending(true);
try {
await dispatchToVendor({
WorkOrderIds: [wo.id],
VendorIds: [selectedId],
NTEAmount: nteAmount ? parseFloat(nteAmount) : null,
ScheduledDate: scheduledDate || null,
Description: description,
TaskListTemplateId: selectedTemplateId ? parseInt(selectedTemplateId) : null,
});
toast.success("Dispatched successfully");
onDispatched();
onClose();
} catch {
toast.error("Failed to dispatch");
} finally {
setSending(false);
}
};
return ReactDOM.createPortal(
e.stopPropagation()}>
Dispatch Work Order {wo.internalWONumber}
setVendorSearch(e.target.value)}
placeholder="Search vendors..."
/>
{!loaded ?
Loading vendors...
: filteredVendors.length === 0 ?
No vendors found
: (
{filteredVendors.map((v) => (
selectVendor(v.id)}>
{v.companyName}
{v.tradeSpecialties && {v.tradeSpecialties}}
{v.address && {v.address}}
{v.distanceMiles != null && (
{v.distanceMiles}
miles
)}
))}
)}
{selectedId && (
{vendors.find((x) => x.id === selectedId)?.companyName}
)}
,
document.body
);
}
function CommentInput({ workOrderId, commentType, onCommentAdded }) {
const [text, setText] = useState("");
const [sending, setSending] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!text.trim()) return;
setSending(true);
try {
const newComment = await addComment(workOrderId, text.trim(), commentType);
setText("");
if (onCommentAdded) onCommentAdded(newComment);
} catch (err) {
toast.error("Failed to add comment");
} finally {
setSending(false);
}
};
const handleKeyDown = (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
};
return (
);
}
const STATUS_OPTIONS = ["Open", "In Progress", "On Hold", "Done", "Cancelled"];
function StatusDropdown({ status, onStatusChange }) {
const [open, setOpen] = useState(false);
const btnRef = useRef(null);
const menuRef = useRef(null);
const [menuPos, setMenuPos] = useState({ top: 0, left: 0 });
const statusClass = (status || "").toLowerCase().replace(/\s+/g, "-");
useEffect(() => {
const handleClick = (e) => {
if (btnRef.current?.contains(e.target)) return;
if (menuRef.current?.contains(e.target)) return;
setOpen(false);
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
const handleOpen = () => {
if (btnRef.current) {
const rect = btnRef.current.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.left });
}
setOpen(!open);
};
return (
<>
{open && ReactDOM.createPortal(
{STATUS_OPTIONS.map((s) => (
))}
,
document.body
)}
>
);
}
export default function WorkOrderViewPage() {
const { id } = useParams();
const navigate = useNavigate();
const [wo, setWo] = useState(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState("customer");
const [statusUpdating, setStatusUpdating] = useState(false);
const [dispatchOpen, setDispatchOpen] = useState(false);
const [dispatchDetailId, setDispatchDetailId] = useState(null);
const handleStatusChange = async (newStatus) => {
if (newStatus === wo?.status) return;
setStatusUpdating(true);
try {
await changeWorkOrderStatus(id, newStatus);
const oldStatus = wo.status;
setWo((prev) => ({
...prev,
status: newStatus,
auditLog: [
{
id: Date.now(),
fieldName: "Status",
oldValue: oldStatus,
newValue: newStatus,
action: "status_change",
createdAt: new Date().toISOString(),
userName: "You",
},
...(prev.auditLog || []),
],
}));
toast.success(`Status changed to ${newStatus}`);
} catch (err) {
toast.error("Failed to update status");
} finally {
setStatusUpdating(false);
}
};
useEffect(() => {
const load = async () => {
try {
const data = await getWorkOrderById(id);
setWo(data);
} catch (err) {
toast.error("Failed to load work order");
} finally {
setLoading(false);
}
};
load();
}, [id]);
const handleCommentAdded = (newComment) => {
setWo((prev) => ({
...prev,
comments: [
...prev.comments,
{
id: newComment.id,
createdDate: newComment.createdDate,
commenttext: newComment.commenttext,
commentType: newComment.commentType,
userName: newComment.userName,
commenter: null,
recordType: null,
},
],
}));
};
if (loading) return ;
if (!wo) return ;
const allComments = wo.comments || [];
const customerComments = allComments.filter((c) => c.commentType === "customer");
const internalComments = allComments.filter((c) => c.commentType === "internal");
const auditLog = wo.auditLog || [];
const tabs = [
{ key: "customer", label: "Customer", count: customerComments.length },
{ key: "internal", label: "Internal", count: internalComments.length },
{ key: "audit", label: "Audit Log", count: auditLog.length },
];
const showInput = activeTab === "internal";
return (
-
{ e.preventDefault(); navigate("/workorders"); }}>
Work Orders
- {wo.internalWONumber}
{wo.title}
Details
Internal WO
{wo.internalWONumber}
Customer WO
{wo.workOrderNumber || "—"}
Priority
{wo.priority || "—"}
Location
{wo.location || "—"}
Assigned To
{
try {
await changeWorkOrderAssignment(wo.id, userId);
setWo((prev) => ({ ...prev, assignedTo: userName }));
toast.success(`Assigned to ${userName || "Unassigned"}`);
} catch { toast.error("Failed to update assignment"); }
}}
/>
Source
{wo.source || "—"}
TT
{wo.tt || "—"}
Problem
{wo.problem || "—"}
Trade
{wo.trade || "—"}
Sub-Trade
{wo.subTrade || "—"}
Created
{wo.createdDateFull ? formatDateTime(wo.createdDateFull) : "—"}
Due Date
{wo.dueDate || "—"}
Scheduled
{wo.scheduledDate || "—"}
Completed
{wo.completedDate || "—"}
Vendor NTE
{wo.vendorNTE ? `$${parseFloat(wo.vendorNTE).toFixed(2)}` : "—"}
Customer PO
{wo.po || "—"}
Customer NTE
Not connected
{wo.dispatches?.length ? (
| Dispatch # | Vendor | NTE | Status | Date | Wait |
{wo.dispatches.map(d => (
setDispatchDetailId(d.id)}>
| {d.dispatchNumber || d.poNumber} |
{d.vendorName} |
{d.nteAmount != null ? `$${parseFloat(d.nteAmount).toFixed(2)}` : "—"} |
{d.status} |
{d.dispatchedAt ? formatDateTime(d.dispatchedAt) : "—"} |
{d.status === "Sent" ? {timeSince(d.dispatchedAt)} : "—"} |
))}
) : (
No dispatches yet.
)}
{wo.description || "No description provided."}
Activity
{tabs.map((tab) => (
))}
{activeTab === "customer" &&
}
{activeTab === "internal" &&
}
{activeTab === "audit" &&
}
{showInput && (
)}
{dispatchOpen && (
setDispatchOpen(false)}
onDispatched={async () => {
const data = await getWorkOrderById(id);
setWo(data);
}}
/>
)}
{dispatchDetailId && (
setDispatchDetailId(null)}
onUpdated={async () => {
const data = await getWorkOrderById(id);
setWo(data);
}}
/>
)}
);
}