mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-09-30 12:43:13 +00:00
- Verify & Close button at bottom of dispatch modal - Disabled with tooltip showing missing items (checklist, signoffs) - Green verified banner after verification with verifier name + timestamp - Verified status badge (dark green) - Added Verified to DISPATCH_STATUSES constant - verifyDispatch API function
1060 lines
43 KiB
JavaScript
1060 lines
43 KiB
JavaScript
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 (
|
|
<>
|
|
<button ref={btnRef} className="woAssignBtn" onClick={handleOpen}>
|
|
{value || "Unassigned"} <span className="woStatusCaret">▾</span>
|
|
</button>
|
|
{open && ReactDOM.createPortal(
|
|
<div ref={menuRef} className="woAssignMenu" style={{ top: menuPos.top, left: menuPos.left }}>
|
|
<button className={`woAssignOption ${!value ? "active" : ""}`} onClick={() => handleSelect("", "")}>
|
|
Unassigned
|
|
</button>
|
|
{users.map((u) => (
|
|
<button key={u.id} className={`woAssignOption ${value === u.name ? "active" : ""}`} onClick={() => handleSelect(u.id, u.name)}>
|
|
{u.name}
|
|
</button>
|
|
))}
|
|
</div>,
|
|
document.body
|
|
)}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function CollapsibleSection({ title, defaultOpen = false, children }) {
|
|
const [open, setOpen] = useState(defaultOpen);
|
|
return (
|
|
<div className="woViewSection">
|
|
<h4 className="woSectionToggle" onClick={() => setOpen(!open)}>
|
|
<span className={`woSectionArrow ${open ? "open" : ""}`}>▸</span>
|
|
{title}
|
|
</h4>
|
|
{open && children}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 <div className="woTabScroll"><p className="woNoComments">No comments yet.</p></div>;
|
|
}
|
|
|
|
return (
|
|
<div className="woTabScroll">
|
|
<div className="woTimeline">
|
|
{sorted.map((c) => (
|
|
<div key={c.id} className="woTimelineItem">
|
|
<div className="woTimelineHeader">
|
|
<span className="woTimelineAuthor">{c.userName || c.commenter || "System"}</span>
|
|
<span className="woTimelineDate">
|
|
{c.createdDate ? formatDateTime(c.createdDate) : ""}
|
|
</span>
|
|
</div>
|
|
<div className="woTimelineBody">{c.commenttext}</div>
|
|
</div>
|
|
))}
|
|
<div ref={bottomRef} />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 <div className="woTabScroll"><p className="woNoComments">No changes recorded.</p></div>;
|
|
}
|
|
|
|
return (
|
|
<div className="woTabScroll">
|
|
<div className="woTimeline">
|
|
{sorted.map((e) => (
|
|
<div key={e.id} className="woTimelineItem woAuditItem">
|
|
<div className="woTimelineHeader">
|
|
<span className="woTimelineAuthor">{e.userName || "System"}</span>
|
|
<span className="woTimelineDate">
|
|
{e.createdAt ? formatDateTime(e.createdAt) : ""}
|
|
</span>
|
|
</div>
|
|
<div className="woTimelineBody">
|
|
<span className="woAuditField">{e.fieldName}</span>
|
|
{e.oldValue && <span className="woAuditOld">{e.oldValue}</span>}
|
|
<span className="woAuditArrow">→</span>
|
|
<span className="woAuditNew">{e.newValue}</span>
|
|
</div>
|
|
</div>
|
|
))}
|
|
<div ref={bottomRef} />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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(
|
|
<div className="woDispatchOverlay"><div className="woDispatchModal"><div className="woDispatchLoading">Loading...</div></div></div>,
|
|
document.body
|
|
);
|
|
}
|
|
|
|
if (!dispatch) return null;
|
|
|
|
return ReactDOM.createPortal(
|
|
<div className="woDispatchOverlay" onClick={onClose}>
|
|
<div className="dispatchDetailModal" onClick={(e) => e.stopPropagation()}>
|
|
<div className="woDispatchHeader">
|
|
<div>
|
|
<h3>{dispatch.dispatchNumber || dispatch.poNumber} · {dispatch.vendorName}</h3>
|
|
<span className="dispatchDetailSub">
|
|
PO: {dispatch.poNumber} · {dispatch.workOrders?.length > 0 ? `${dispatch.workOrders.length} WO(s): ${dispatch.workOrders.map(w => w.woNumber).join(", ")}` : `WO: ${dispatch.woNumber}`} · {dispatch.vendorEmail}
|
|
</span>
|
|
</div>
|
|
<button className="woDispatchClose" onClick={onClose}>×</button>
|
|
</div>
|
|
|
|
<div className="dispatchDetailBody">
|
|
<div className="dispatchDetailSection">
|
|
<div className="dispatchDetailGrid">
|
|
{editing ? (
|
|
<>
|
|
<div className="dispatchDetailField">
|
|
<label>Status</label>
|
|
<select className="form-control" value={form.status} onChange={(e) => setForm(f => ({ ...f, status: e.target.value }))}>
|
|
{DISPATCH_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
|
|
</select>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>NTE Amount</label>
|
|
<input className="form-control" type="number" value={form.nteAmount} onChange={(e) => setForm(f => ({ ...f, nteAmount: e.target.value }))} step="0.01" />
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Scheduled Date</label>
|
|
<input className="form-control" type="date" value={form.scheduledDate} onChange={(e) => setForm(f => ({ ...f, scheduledDate: e.target.value }))} />
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Completed Date</label>
|
|
<input className="form-control" type="date" value={form.completedDate} onChange={(e) => setForm(f => ({ ...f, completedDate: e.target.value }))} />
|
|
</div>
|
|
<div className="dispatchDetailField dispatchDetailFieldFull">
|
|
<label>Description</label>
|
|
<textarea className="form-control" value={form.description} onChange={(e) => setForm(f => ({ ...f, description: e.target.value }))} rows="3" style={{ resize: "none" }} />
|
|
</div>
|
|
<div className="dispatchDetailActions">
|
|
<button className="btn btn-primary" onClick={handleSave} disabled={saving}>{saving ? "Saving..." : "Save"}</button>
|
|
<button className="btn btn-default" onClick={() => setEditing(false)}>Cancel</button>
|
|
</div>
|
|
</>
|
|
) : (
|
|
<>
|
|
<div className="dispatchDetailField">
|
|
<label>Status</label>
|
|
<span className={`woDispatchStatus ${(dispatch.status || "").toLowerCase()}`}>{dispatch.status}</span>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>NTE</label>
|
|
<span>{dispatch.nteAmount != null ? `$${parseFloat(dispatch.nteAmount).toFixed(2)}` : "—"}</span>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Scheduled</label>
|
|
<span>{dispatch.scheduledDate ? dispatch.scheduledDate.split("T")[0] : "—"}</span>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Completed</label>
|
|
<span>{dispatch.completedDate ? dispatch.completedDate.split("T")[0] : "—"}</span>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Dispatched</label>
|
|
<span>{dispatch.dispatchedAt ? formatDateTime(dispatch.dispatchedAt) : "—"}</span>
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Accepted</label>
|
|
{dispatch.acknowledgedAt ? (
|
|
<span style={{ color: "#28a745" }}>{formatDateTime(dispatch.acknowledgedAt)} (after {timeBetween(dispatch.dispatchedAt, dispatch.acknowledgedAt)})</span>
|
|
) : dispatch.status === "Sent" ? (
|
|
<span className={`dispatchWaiting dispatchWait-${waitTimeColor(dispatch.dispatchedAt)}`}>Awaiting acceptance · {timeSince(dispatch.dispatchedAt)}</span>
|
|
) : (
|
|
<span>—</span>
|
|
)}
|
|
</div>
|
|
<div className="dispatchDetailField">
|
|
<label>Vendor Email</label>
|
|
<span>{dispatch.vendorEmail}</span>
|
|
</div>
|
|
{dispatch.description && (
|
|
<div className="dispatchDetailField dispatchDetailFieldFull">
|
|
<label>Description</label>
|
|
<span>{dispatch.description}</span>
|
|
</div>
|
|
)}
|
|
<div className="dispatchDetailActions">
|
|
<button className="btn btn-primary" onClick={() => setEditing(true)}>Edit</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="dispatchDetailSection">
|
|
{dispatch.checklistItems && dispatch.checklistItems.length > 0 && (
|
|
<>
|
|
<h4>Checklist ({dispatch.checklistItems.filter(i => i.isCompleted).length}/{dispatch.checklistItems.length})</h4>
|
|
<div className="dispatchChecklist">
|
|
{dispatch.checklistItems.map((item) => (
|
|
<div key={item.id} className={`dispatchChecklistItem ${item.isCompleted ? "completed" : ""}`}>
|
|
<input
|
|
type="checkbox"
|
|
checked={item.isCompleted}
|
|
onChange={async () => {
|
|
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
|
|
),
|
|
}));
|
|
}}
|
|
/>
|
|
<span className="dispatchChecklistText">{item.itemText}</span>
|
|
{item.isCompleted && (
|
|
<span className="dispatchChecklistDone">
|
|
{item.completedBy}{item.completedAt ? ` · ${formatDateTime(item.completedAt)}` : ""}
|
|
</span>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
</>
|
|
)}
|
|
<h4>Sign-offs</h4>
|
|
<div className="dispatchSignoffs">
|
|
{["Customer", "Vendor"].map((type) => {
|
|
const signoff = (dispatch.signoffs || []).find((s) => s.signoffType === type);
|
|
return (
|
|
<div key={type} className={`dispatchSignoffSlot ${signoff ? "signed" : ""}`}>
|
|
<div className="dispatchSignoffLabel">{type}</div>
|
|
{signoff ? (
|
|
<div className="dispatchSignoffDone">
|
|
{signoff.signatureMethod === "drawn" && signoff.signature && (
|
|
<img src={signoff.signature} alt="Signature" className="dispatchSignoffImg" />
|
|
)}
|
|
{signoff.signatureMethod === "typed" && (
|
|
<span className="dispatchSignoffTyped">{signoff.signature}</span>
|
|
)}
|
|
<span className="dispatchSignoffMeta">{signoff.name} · {signoff.signedAt ? formatDateTime(signoff.signedAt) : ""}</span>
|
|
</div>
|
|
) : (
|
|
<button className="btn btn-default dispatchSignoffBtn" onClick={() => setSigCapture(type)}>
|
|
Collect Signature
|
|
</button>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
{(dispatch.signoffs || []).length >= 2 && <div className="dispatchSignoffBadge">All Signed ✓</div>}
|
|
</div>
|
|
|
|
{sigCapture && (
|
|
<SignatureCapture
|
|
title={`${sigCapture} Sign-off`}
|
|
onClose={() => 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");
|
|
}
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
<h4>Vendor Communication</h4>
|
|
<div className="dispatchThreadContainer">
|
|
<div className="dispatchThreadScroll">
|
|
{(!dispatch.comments || dispatch.comments.length === 0) ? (
|
|
<p className="woNoComments">No messages yet.</p>
|
|
) : (
|
|
<div className="woTimeline">
|
|
{dispatch.comments.map((c) => (
|
|
<div key={c.id} className={`woTimelineItem ${c.commenter ? "woTimelineInbound" : ""}`}>
|
|
<div className="woTimelineHeader">
|
|
<span className="woTimelineAuthor">{c.userName || c.commenter || "System"}</span>
|
|
<span className="woTimelineDate">{c.createdDate ? formatDateTime(c.createdDate) : ""}</span>
|
|
</div>
|
|
<div className="woTimelineBody">{c.commenttext}</div>
|
|
</div>
|
|
))}
|
|
<div ref={bottomRef} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
<form className="dispatchThreadInput" onSubmit={handleComment}>
|
|
<textarea
|
|
className="woCommentTextarea"
|
|
value={commentText}
|
|
onChange={(e) => setCommentText(e.target.value)}
|
|
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleComment(e); } }}
|
|
placeholder="Message vendor..."
|
|
rows={2}
|
|
disabled={sendingComment}
|
|
/>
|
|
<div className="dispatchThreadControls">
|
|
<label className="dispatchEmailToggle">
|
|
<input type="checkbox" checked={sendEmail} onChange={(e) => setSendEmail(e.target.checked)} />
|
|
Send email
|
|
</label>
|
|
<button className="btn btn-primary woCommentSend" type="submit" disabled={sendingComment || !commentText.trim()}>
|
|
{sendingComment ? "Sending..." : "Send"}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
|
|
{dispatch.verifiedAt ? (
|
|
<div className="dispatchVerifiedBanner">
|
|
✓ Verified by {dispatch.verifiedBy} on {formatDateTime(dispatch.verifiedAt)}
|
|
</div>
|
|
) : (
|
|
<div className="dispatchVerifyFooter">
|
|
{(() => {
|
|
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 && <span className="dispatchVerifyMissing">Missing: {missing.join(", ")}</span>}
|
|
<button
|
|
className="btn btn-success"
|
|
disabled={!canVerify}
|
|
onClick={async () => {
|
|
try {
|
|
const result = await verifyDispatch(dispatchId);
|
|
toast.success("Dispatch verified");
|
|
loadDispatch();
|
|
onUpdated();
|
|
} catch (err) {
|
|
toast.error(err.message || "Failed to verify");
|
|
}
|
|
}}
|
|
>
|
|
Verify & Close
|
|
</button>
|
|
</>
|
|
);
|
|
})()}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>,
|
|
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(
|
|
<div className="woDispatchOverlay" onClick={onClose}>
|
|
<div className="woDispatchModal" onClick={(e) => e.stopPropagation()}>
|
|
<div className="woDispatchHeader">
|
|
<h3>Dispatch Work Order {wo.internalWONumber}</h3>
|
|
<button className="woDispatchClose" onClick={onClose}>×</button>
|
|
</div>
|
|
<div className="woDispatchBody">
|
|
<div className="woDispatchField">
|
|
<label>Select Vendors</label>
|
|
<input
|
|
className="woDispatchSearch"
|
|
type="text"
|
|
value={vendorSearch}
|
|
onChange={(e) => setVendorSearch(e.target.value)}
|
|
placeholder="Search vendors..."
|
|
/>
|
|
{!loaded ? <div className="woDispatchLoading">Loading vendors...</div> : filteredVendors.length === 0 ? <div className="woDispatchLoading">No vendors found</div> : (
|
|
<div className="woDispatchVendorList">
|
|
{filteredVendors.map((v) => (
|
|
<div key={v.id} className={`woDispatchVendorItem ${selectedId === v.id ? "selected" : ""}`} onClick={() => selectVendor(v.id)}>
|
|
<input type="radio" name="vendorSelect" checked={selectedId === v.id} readOnly />
|
|
<div className="woDispatchVendorInfo">
|
|
<span className="woDispatchVendorName">{v.companyName}</span>
|
|
{v.tradeSpecialties && <span className="woDispatchVendorTrades">{v.tradeSpecialties}</span>}
|
|
{v.address && <span className="woDispatchVendorAddr">{v.address}</span>}
|
|
</div>
|
|
{v.distanceMiles != null && (
|
|
<div className="woDispatchVendorDistBadge">
|
|
<span className="woDispatchDistNum">{v.distanceMiles}</span>
|
|
<span className="woDispatchDistLabel">miles</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
{selectedId && (
|
|
<div className="woDispatchSelected">
|
|
<span className="woDispatchSelectedChip">
|
|
{vendors.find((x) => x.id === selectedId)?.companyName}
|
|
<button onClick={() => setSelectedId(null)}>×</button>
|
|
</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="woDispatchFieldRow">
|
|
<div className="woDispatchField woDispatchFieldHalf">
|
|
<label>NTE Amount</label>
|
|
<input type="number" className="form-control" value={nteAmount} onChange={(e) => setNteAmount(e.target.value)} placeholder="0.00" step="0.01" min="0" />
|
|
</div>
|
|
<div className="woDispatchField woDispatchFieldHalf">
|
|
<label>Vendor Scheduled Date</label>
|
|
<input type="date" className="form-control" value={scheduledDate} onChange={(e) => setScheduledDate(e.target.value)} />
|
|
</div>
|
|
</div>
|
|
<div className="woDispatchField">
|
|
<label>Task List Template</label>
|
|
<select className="form-control" value={selectedTemplateId} onChange={(e) => setSelectedTemplateId(e.target.value)}>
|
|
<option value="">No checklist</option>
|
|
{taskTemplates.map((t) => (
|
|
<option key={t.id} value={t.id}>{t.name} ({t.items?.length || 0} items)</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div className="woDispatchField">
|
|
<label>Description</label>
|
|
<textarea className="form-control" value={description} onChange={(e) => setDescription(e.target.value)} rows="4" style={{ resize: "none" }} />
|
|
</div>
|
|
</div>
|
|
<div className="woDispatchFooter">
|
|
<button className="btn btn-default" onClick={onClose} disabled={sending}>Cancel</button>
|
|
<button className="btn btn-primary" onClick={handleSubmit} disabled={sending || !selectedId}>
|
|
{sending ? "Dispatching..." : "Dispatch"}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>,
|
|
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 (
|
|
<form className="woCommentInput" onSubmit={handleSubmit}>
|
|
<textarea
|
|
className="woCommentTextarea"
|
|
value={text}
|
|
onChange={(e) => setText(e.target.value)}
|
|
onKeyDown={handleKeyDown}
|
|
placeholder="Type a comment... (Enter to send, Shift+Enter for new line)"
|
|
rows={2}
|
|
disabled={sending}
|
|
/>
|
|
<button className="btn btn-primary woCommentSend" type="submit" disabled={sending || !text.trim()}>
|
|
{sending ? "Sending..." : "Send"}
|
|
</button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<>
|
|
<button
|
|
ref={btnRef}
|
|
className={`woStatusBadge ${statusClass} woStatusClickable`}
|
|
onClick={handleOpen}
|
|
>
|
|
{status} <span className="woStatusCaret">▾</span>
|
|
</button>
|
|
{open && ReactDOM.createPortal(
|
|
<div
|
|
ref={menuRef}
|
|
className="woStatusMenu"
|
|
style={{ top: menuPos.top, left: menuPos.left }}
|
|
>
|
|
{STATUS_OPTIONS.map((s) => (
|
|
<button
|
|
key={s}
|
|
className={`woStatusOption ${s === status ? "active" : ""}`}
|
|
onClick={() => { onStatusChange(s); setOpen(false); }}
|
|
>
|
|
<span className={`woStatusDot ${s.toLowerCase().replace(/\s+/g, "-")}`} />
|
|
{s}
|
|
</button>
|
|
))}
|
|
</div>,
|
|
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 <div className="woViewPage"><div className="loading">Loading...</div></div>;
|
|
if (!wo) return <div className="woViewPage"><div className="loading">Work order not found.</div></div>;
|
|
|
|
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 (
|
|
<div className="woViewPage">
|
|
<div className="panel panel-default panel-connected">
|
|
<div className="panel-body">
|
|
<ol className="breadcrumb breadcrumb-alt">
|
|
<li>
|
|
<a href="#" onClick={(e) => { e.preventDefault(); navigate("/workorders"); }}>
|
|
Work Orders
|
|
</a>
|
|
</li>
|
|
<li className="active">{wo.internalWONumber}</li>
|
|
</ol>
|
|
|
|
<div className="woViewHeader">
|
|
<div className="woViewTitle">
|
|
<h2>{wo.title}</h2>
|
|
<StatusDropdown status={wo.status} onStatusChange={handleStatusChange} />
|
|
</div>
|
|
<div className="woViewActions">
|
|
<button className="btn btn-success" onClick={() => setDispatchOpen(true)}>
|
|
Dispatch
|
|
</button>
|
|
<button className="btn btn-primary" onClick={() => navigate(`/workorders/edit/${id}`)}>
|
|
Edit
|
|
</button>
|
|
<button className="btn btn-default" onClick={() => navigate("/workorders")}>
|
|
Back to List
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="woViewGrid">
|
|
<div className="woViewSection">
|
|
<h4>Details</h4>
|
|
<div className="woFieldGrid">
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Internal WO</span>
|
|
<span className="woFieldValue">{wo.internalWONumber}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Customer WO</span>
|
|
<span className="woFieldValue">{wo.workOrderNumber || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Priority</span>
|
|
<span className="woFieldValue">{wo.priority || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Location</span>
|
|
<span className="woFieldValue">{wo.location || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Assigned To</span>
|
|
<span className="woFieldValue">
|
|
<AssignDropdown
|
|
value={wo.assignedTo}
|
|
onAssign={async (userId, userName) => {
|
|
try {
|
|
await changeWorkOrderAssignment(wo.id, userId);
|
|
setWo((prev) => ({ ...prev, assignedTo: userName }));
|
|
toast.success(`Assigned to ${userName || "Unassigned"}`);
|
|
} catch { toast.error("Failed to update assignment"); }
|
|
}}
|
|
/>
|
|
</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Source</span>
|
|
<span className="woFieldValue">{wo.source || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">TT</span>
|
|
<span className="woFieldValue">{wo.tt || "—"}</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<CollapsibleSection title="Classification">
|
|
<div className="woFieldGrid">
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Problem</span>
|
|
<span className="woFieldValue">{wo.problem || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Trade</span>
|
|
<span className="woFieldValue">{wo.trade || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Sub-Trade</span>
|
|
<span className="woFieldValue">{wo.subTrade || "—"}</span>
|
|
</div>
|
|
</div>
|
|
</CollapsibleSection>
|
|
|
|
<CollapsibleSection title="Schedule">
|
|
<div className="woFieldGrid">
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Created</span>
|
|
<span className="woFieldValue">
|
|
{wo.createdDateFull ? formatDateTime(wo.createdDateFull) : "—"}
|
|
</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Due Date</span>
|
|
<span className="woFieldValue">{wo.dueDate || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Scheduled</span>
|
|
<span className="woFieldValue">{wo.scheduledDate || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Completed</span>
|
|
<span className="woFieldValue">{wo.completedDate || "—"}</span>
|
|
</div>
|
|
</div>
|
|
</CollapsibleSection>
|
|
|
|
<CollapsibleSection title="Financial">
|
|
<div className="woFieldGrid">
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Vendor NTE</span>
|
|
<span className="woFieldValue">{wo.vendorNTE ? `$${parseFloat(wo.vendorNTE).toFixed(2)}` : "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Customer PO</span>
|
|
<span className="woFieldValue">{wo.po || "—"}</span>
|
|
</div>
|
|
<div className="woField">
|
|
<span className="woFieldLabel">Customer NTE</span>
|
|
<span className="woFieldValue woFieldPlaceholder">Not connected</span>
|
|
</div>
|
|
</div>
|
|
</CollapsibleSection>
|
|
|
|
<CollapsibleSection title={`Dispatches (${(wo.dispatches || []).length})`}>
|
|
{wo.dispatches?.length ? (
|
|
<table className="woDispatchTable">
|
|
<thead>
|
|
<tr><th>Dispatch #</th><th>Vendor</th><th>NTE</th><th>Status</th><th>Date</th><th>Wait</th></tr>
|
|
</thead>
|
|
<tbody>
|
|
{wo.dispatches.map(d => (
|
|
<tr key={d.id} className="dispatchClickRow" onClick={() => setDispatchDetailId(d.id)}>
|
|
<td>{d.dispatchNumber || d.poNumber}</td>
|
|
<td>{d.vendorName}</td>
|
|
<td>{d.nteAmount != null ? `$${parseFloat(d.nteAmount).toFixed(2)}` : "—"}</td>
|
|
<td><span className={`woDispatchStatus ${(d.status || "").toLowerCase()}`}>{d.status}</span></td>
|
|
<td>{d.dispatchedAt ? formatDateTime(d.dispatchedAt) : "—"}</td>
|
|
<td>{d.status === "Sent" ? <span className={`dispatchWaitDot dispatchWait-${waitTimeColor(d.dispatchedAt)}`}>{timeSince(d.dispatchedAt)}</span> : "—"}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
) : (
|
|
<p className="woNoComments">No dispatches yet.</p>
|
|
)}
|
|
</CollapsibleSection>
|
|
|
|
<CollapsibleSection title="Description">
|
|
<p className="woDescription">{wo.description || "No description provided."}</p>
|
|
</CollapsibleSection>
|
|
|
|
<div className="woViewSection">
|
|
<h4>Activity</h4>
|
|
<div className="woCommentTabs">
|
|
{tabs.map((tab) => (
|
|
<button
|
|
key={tab.key}
|
|
className={`woCommentTab ${activeTab === tab.key ? "active" : ""}`}
|
|
onClick={() => setActiveTab(tab.key)}
|
|
>
|
|
{tab.label} ({tab.count})
|
|
</button>
|
|
))}
|
|
</div>
|
|
<div className="woTabContainer">
|
|
{activeTab === "customer" && <CommentTimeline comments={customerComments} />}
|
|
{activeTab === "internal" && <CommentTimeline comments={internalComments} />}
|
|
{activeTab === "audit" && <AuditTimeline entries={auditLog} />}
|
|
{showInput && (
|
|
<CommentInput
|
|
workOrderId={parseInt(id)}
|
|
commentType={activeTab}
|
|
onCommentAdded={handleCommentAdded}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{dispatchOpen && (
|
|
<DispatchModal
|
|
wo={wo}
|
|
onClose={() => setDispatchOpen(false)}
|
|
onDispatched={async () => {
|
|
const data = await getWorkOrderById(id);
|
|
setWo(data);
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
{dispatchDetailId && (
|
|
<DispatchDetailModal
|
|
dispatchId={dispatchDetailId}
|
|
onClose={() => setDispatchDetailId(null)}
|
|
onUpdated={async () => {
|
|
const data = await getWorkOrderById(id);
|
|
setWo(data);
|
|
}}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|