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 } from "../api";
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}
))}
);
}
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 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 vendorComments = allComments.filter((c) => c.commentType === "vendor");
const internalComments = allComments.filter((c) => c.commentType === "internal");
const auditLog = wo.auditLog || [];
const tabs = [
{ key: "customer", label: "Customer", count: customerComments.length },
{ key: "vendor", label: "Vendor", count: vendorComments.length },
{ key: "internal", label: "Internal", count: internalComments.length },
{ key: "audit", label: "Audit Log", count: auditLog.length },
];
const showInput = activeTab === "internal" || activeTab === "vendor";
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.description || "No description provided."}
Activity
{tabs.map((tab) => (
))}
{activeTab === "customer" &&
}
{activeTab === "vendor" &&
}
{activeTab === "internal" &&
}
{activeTab === "audit" &&
}
{showInput && (
)}
);
}