298 lines
11 KiB
JavaScript
298 lines
11 KiB
JavaScript
// DmsContainer updated
|
|
import { useQuery } from "@apollo/client";
|
|
import { Button, Card, Col, Result, Row, Select, Space } from "antd";
|
|
import queryString from "query-string";
|
|
import { useEffect, useMemo, useRef, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { connect } from "react-redux";
|
|
import { Link, useLocation, useNavigate } from "react-router-dom";
|
|
import { createStructuredSelector } from "reselect";
|
|
import SocketIO from "socket.io-client";
|
|
import AlertComponent from "../../components/alert/alert.component";
|
|
import DmsAllocationsSummary from "../../components/dms-allocations-summary/dms-allocations-summary.component";
|
|
import DmsCustomerSelector from "../../components/dms-customer-selector/dms-customer-selector.component";
|
|
import DmsLogEvents from "../../components/dms-log-events/dms-log-events.component";
|
|
import DmsPostForm from "../../components/dms-post-form/dms-post-form.component";
|
|
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
|
|
import { OwnerNameDisplayFunction } from "../../components/owner-name-display/owner-name-display.component";
|
|
import { auth } from "../../firebase/firebase.utils";
|
|
import { QUERY_JOB_EXPORT_DMS } from "../../graphql/jobs.queries";
|
|
import { insertAuditTrail, setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
|
|
import { selectBodyshop } from "../../redux/user/user.selectors";
|
|
import InstanceRenderManager from "../../utils/instanceRenderMgr";
|
|
import AuditTrailMapping from "../../utils/AuditTrailMappings";
|
|
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
|
|
import { useSplitTreatments } from "@splitsoftware/splitio-react";
|
|
import { useSocket } from "../../contexts/SocketIO/useSocket.js";
|
|
import { determineDmsType } from "../../utils/determineDmsType";
|
|
|
|
const mapStateToProps = createStructuredSelector({
|
|
bodyshop: selectBodyshop
|
|
});
|
|
|
|
const mapDispatchToProps = (dispatch) => ({
|
|
setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
|
|
setSelectedHeader: (key) => dispatch(setSelectedHeader(key)),
|
|
insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
|
|
});
|
|
|
|
export default connect(mapStateToProps, mapDispatchToProps)(DmsContainer);
|
|
|
|
// Legacy /ws socket (CDK/PBS)
|
|
export const socket = SocketIO(import.meta.env.PROD ? import.meta.env.VITE_APP_AXIOS_BASE_API_URL : "", {
|
|
path: "/ws",
|
|
withCredentials: true,
|
|
auth: async (callback) => {
|
|
const token = auth.currentUser && (await auth.currentUser.getIdToken());
|
|
callback({ token });
|
|
}
|
|
});
|
|
|
|
export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, insertAuditTrail }) {
|
|
const { t } = useTranslation();
|
|
const dms = determineDmsType(bodyshop);
|
|
const [logLevel, setLogLevel] = useState(dms === "pbs" ? "INFO" : "DEBUG");
|
|
const history = useNavigate();
|
|
const [logs, setLogs] = useState([]);
|
|
const search = queryString.parse(useLocation().search);
|
|
const { jobId } = search;
|
|
const notification = useNotification();
|
|
const {
|
|
treatments: { Fortellis }
|
|
} = useSplitTreatments({
|
|
attributes: {},
|
|
names: ["Fortellis"],
|
|
splitKey: bodyshop.imexshopid
|
|
});
|
|
// New unified wss socket (Fortellis, RR)
|
|
const { socket: wsssocket } = useSocket();
|
|
|
|
const activeSocket = useMemo(() => {
|
|
return dms === "rr" || (dms === "cdk" && Fortellis.treatment === "on") ? wsssocket : socket;
|
|
}, [dms, Fortellis.treatment, wsssocket, socket]);
|
|
|
|
const { loading, error, data } = useQuery(QUERY_JOB_EXPORT_DMS, {
|
|
variables: { id: jobId },
|
|
skip: !jobId,
|
|
fetchPolicy: "network-only",
|
|
nextFetchPolicy: "network-only"
|
|
});
|
|
const logsRef = useRef(null);
|
|
|
|
useEffect(() => {
|
|
document.title = t("titles.dms", {
|
|
app: InstanceRenderManager({
|
|
imex: "$t(titles.imexonline)",
|
|
rome: "$t(titles.romeonline)"
|
|
})
|
|
});
|
|
setSelectedHeader("dms");
|
|
setBreadcrumbs([
|
|
{
|
|
link: "/manage/accounting/receivables",
|
|
label: t("titles.bc.accounting-receivables")
|
|
},
|
|
{
|
|
link: "/manage/dms",
|
|
label: t("titles.bc.dms")
|
|
}
|
|
]);
|
|
}, [t, setBreadcrumbs, setSelectedHeader]);
|
|
|
|
useEffect(() => {
|
|
// ✅ RR uses the new wss socket and takes precedence over Fortellis flag
|
|
if (dms === "rr") {
|
|
// set log level on connect and immediately
|
|
wsssocket.emit("set-log-level", logLevel);
|
|
const handleConnect = () => wsssocket.emit("set-log-level", logLevel);
|
|
const handleReconnect = () =>
|
|
setLogs((prev) => [
|
|
...prev,
|
|
{ timestamp: new Date(), level: "warn", message: "Reconnected to RR Export Service" }
|
|
]);
|
|
const handleConnectError = (err) => {
|
|
console.log(`connect_error due to ${err}`, err);
|
|
notification.error({ message: err.message });
|
|
};
|
|
|
|
const handleLogEvent = (payload) => setLogs((prev) => [...prev, payload]);
|
|
|
|
const handleExportSuccess = (payload) => {
|
|
const jobId = payload?.jobId ?? payload; // RR sends object; legacy sends raw id notification.success({ message: t("jobs.successes.exported") });
|
|
insertAuditTrail({
|
|
jobid: jobId,
|
|
operation: AuditTrailMapping.jobexported(),
|
|
type: "jobexported"
|
|
});
|
|
history("/manage/accounting/receivables");
|
|
};
|
|
const handleRrExportResult = (payload) => handleExportSuccess(payload);
|
|
|
|
wsssocket.on("connect", handleConnect);
|
|
wsssocket.on("reconnect", handleReconnect);
|
|
wsssocket.on("connect_error", handleConnectError);
|
|
|
|
// RR channels (over wss)
|
|
wsssocket.on("rr-log-event", handleLogEvent);
|
|
wsssocket.on("RR:LOG", handleLogEvent);
|
|
wsssocket.on("export-success", handleExportSuccess);
|
|
wsssocket.on("rr-export-job:result", handleRrExportResult);
|
|
|
|
return () => {
|
|
wsssocket.off("connect", handleConnect);
|
|
wsssocket.off("reconnect", handleReconnect);
|
|
wsssocket.off("connect_error", handleConnectError);
|
|
wsssocket.off("rr-log-event", handleLogEvent);
|
|
wsssocket.off("export-success", handleExportSuccess);
|
|
wsssocket.off("rr-export-job:result", handleRrExportResult);
|
|
};
|
|
}
|
|
|
|
// Fortellis / CDK behavior (when not RR)
|
|
if (Fortellis.treatment === "on") {
|
|
wsssocket.emit("set-log-level", logLevel);
|
|
|
|
const handleLogEvent = (payload) => setLogs((prev) => [...prev, payload]);
|
|
const handleExportSuccess = (payload) => {
|
|
notification.success({ message: t("jobs.successes.exported") });
|
|
insertAuditTrail({
|
|
jobid: payload,
|
|
operation: AuditTrailMapping.jobexported(),
|
|
type: "jobexported"
|
|
});
|
|
history("/manage/accounting/receivables");
|
|
};
|
|
|
|
// Fortellis logs (wss)
|
|
wsssocket.on("fortellis-log-event", handleLogEvent);
|
|
wsssocket.on("export-success", handleExportSuccess);
|
|
|
|
return () => {
|
|
wsssocket.off("fortellis-log-event", handleLogEvent);
|
|
wsssocket.off("export-success", handleExportSuccess);
|
|
};
|
|
} else {
|
|
// CDK/PBS via legacy /ws socket
|
|
socket.on("connect", () => socket.emit("set-log-level", logLevel));
|
|
socket.on("reconnect", () => {
|
|
setLogs((prev) => [
|
|
...prev,
|
|
{ timestamp: new Date(), level: "warn", message: "Reconnected to CDK Export Service" }
|
|
]);
|
|
});
|
|
socket.on("connect_error", (err) => {
|
|
console.log(`connect_error due to ${err}`, err);
|
|
notification.error({ message: err.message });
|
|
});
|
|
socket.on("log-event", (payload) => setLogs((prev) => [...prev, payload]));
|
|
socket.on("export-success", (payload) => {
|
|
notification.success({ message: t("jobs.successes.exported") });
|
|
insertAuditTrail({
|
|
jobid: payload,
|
|
operation: AuditTrailMapping.jobexported(),
|
|
type: "jobexported"
|
|
});
|
|
history("/manage/accounting/receivables");
|
|
});
|
|
|
|
if (socket.disconnected) socket.connect();
|
|
return () => {
|
|
socket.removeAllListeners();
|
|
socket.disconnect();
|
|
};
|
|
}
|
|
}, [dms, Fortellis?.treatment, logLevel, history, insertAuditTrail, notification, t, wsssocket]);
|
|
|
|
if (loading) return <LoadingSpinner />;
|
|
if (error) return <AlertComponent message={error.message} type="error" />;
|
|
|
|
if (!jobId || !(bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber || bodyshop.rr_dealerid) || !data?.jobs_by_pk)
|
|
return <Result status="404" title={t("general.errors.notfound")} />;
|
|
|
|
if (data.jobs_by_pk?.date_exported) return <Result status="warning" title={t("dms.errors.alreadyexported")} />;
|
|
|
|
return (
|
|
<div>
|
|
<AlertComponent
|
|
style={{ marginBottom: 10 }}
|
|
message={`Posting to ${determineDmsType(bodyshop)}`}
|
|
type="warning"
|
|
showIcon
|
|
closable
|
|
/>
|
|
|
|
<Row gutter={[16, 16]}>
|
|
<Col md={24} lg={10}>
|
|
<DmsAllocationsSummary
|
|
title={
|
|
<span>
|
|
<Link to={`/manage/jobs/${data && data.jobs_by_pk.id}`}>{`${
|
|
data?.jobs_by_pk && data.jobs_by_pk.ro_number
|
|
}`}</Link>
|
|
{` | ${OwnerNameDisplayFunction(data.jobs_by_pk)} | ${
|
|
data.jobs_by_pk.v_model_yr || ""
|
|
} ${data.jobs_by_pk.v_make_desc || ""} ${data.jobs_by_pk.v_model_desc || ""}`}
|
|
</span>
|
|
}
|
|
socket={activeSocket}
|
|
jobId={jobId}
|
|
/>
|
|
</Col>
|
|
<Col md={24} lg={14}>
|
|
<DmsPostForm socket={activeSocket} jobId={jobId} job={data?.jobs_by_pk} logsRef={logsRef} />
|
|
</Col>
|
|
|
|
<DmsCustomerSelector jobid={jobId} />
|
|
|
|
<Col span={24}>
|
|
<div ref={logsRef}>
|
|
<Card
|
|
title={t("jobs.labels.dms.logs")}
|
|
extra={
|
|
<Space wrap>
|
|
<Select
|
|
placeholder="Log Level"
|
|
value={logLevel}
|
|
onChange={(value) => {
|
|
setLogLevel(value);
|
|
// Send to the active socket type
|
|
if (dms === "rr" || Fortellis.treatment === "on") {
|
|
wsssocket.emit("set-log-level", value);
|
|
} else {
|
|
socket.emit("set-log-level", value);
|
|
}
|
|
}}
|
|
>
|
|
<Select.Option key="DEBUG">DEBUG</Select.Option>
|
|
<Select.Option key="INFO">INFO</Select.Option>
|
|
<Select.Option key="WARN">WARN</Select.Option>
|
|
<Select.Option key="ERROR">ERROR</Select.Option>
|
|
</Select>
|
|
<Button onClick={() => setLogs([])}>Clear Logs</Button>
|
|
<Button
|
|
onClick={() => {
|
|
setLogs([]);
|
|
// Reconnect appropriate socket
|
|
if (dms === "rr" || Fortellis.treatment === "on") {
|
|
// wsssocket is managed by provider; emit a ping
|
|
wsssocket.emit("set-log-level", logLevel);
|
|
} else {
|
|
socket.disconnect();
|
|
socket.connect();
|
|
}
|
|
}}
|
|
>
|
|
Reconnect
|
|
</Button>
|
|
</Space>
|
|
}
|
|
>
|
|
<DmsLogEvents socket={socket} logs={logs} />
|
|
</Card>
|
|
</div>
|
|
</Col>
|
|
</Row>
|
|
</div>
|
|
);
|
|
}
|