feature/IO-3357-Reynolds-and-Reynolds-DMS-API-Integration - Checkpoint
This commit is contained in:
@@ -55,7 +55,7 @@ export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) {
|
||||
});
|
||||
}
|
||||
}, [socket, socket.connected, billids]);
|
||||
console.log(allocationsSummary);
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t("general.labels.status"),
|
||||
@@ -122,7 +122,7 @@ export function DmsAllocationsSummaryAp({ socket, bodyshop, billids, title }) {
|
||||
<Form.Item
|
||||
name="journal"
|
||||
label={t("jobs.fields.dms.journal")}
|
||||
initialValue={bodyshop.cdk_configuration && bodyshop.cdk_configuration.default_journal}
|
||||
initialValue={bodyshop.cdk_configuration?.default_journal}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useSplitTreatments } from "@splitsoftware/splitio-react";
|
||||
import { Button, Checkbox, Col, Form, Input, message, Modal, Table } from "antd";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { connect } from "react-redux";
|
||||
import { createStructuredSelector } from "reselect";
|
||||
@@ -16,6 +16,22 @@ const mapStateToProps = createStructuredSelector({
|
||||
const mapDispatchToProps = () => ({});
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(DmsCustomerSelector);
|
||||
|
||||
// ---------------- Helpers ----------------
|
||||
|
||||
function normalizeRrList(list) {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((row) => {
|
||||
const custNo = row.custNo || row.CustomerId || row.customerId || null;
|
||||
const name =
|
||||
row.name ||
|
||||
[row.CustomerName?.FirstName, row.CustomerName?.LastName].filter(Boolean).join(" ").trim() ||
|
||||
(custNo ? String(custNo) : "");
|
||||
return custNo ? { custNo: String(custNo), name } : null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
const { t } = useTranslation();
|
||||
const [customerList, setcustomerList] = useState([]);
|
||||
@@ -35,7 +51,7 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
|
||||
const { socket: wsssocket } = useSocket();
|
||||
|
||||
const dms = determineDmsType(bodyshop);
|
||||
const dms = useMemo(() => determineDmsType(bodyshop), [bodyshop]);
|
||||
const bodyshopId = bodyshop?.id || bodyshop?.bodyshopid || bodyshop?.uuid;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -44,28 +60,30 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
const handleRrSelectCustomer = (list) => {
|
||||
setOpen(true);
|
||||
setDmsType("rr");
|
||||
setcustomerList(Array.isArray(list) ? list : []);
|
||||
// Normalize to { custNo, name }
|
||||
setcustomerList(normalizeRrList(list));
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
|
||||
const handleRrCreateRequired = () => {
|
||||
// Open selector shell + creation form
|
||||
setOpen(true);
|
||||
setDmsType("rr");
|
||||
setcustomerList([]);
|
||||
setOpenCreate(true);
|
||||
};
|
||||
|
||||
const handleRrCustomerCreated = ({ custNo }) => {
|
||||
if (custNo) {
|
||||
message.success(t("dms.messages.customerCreated"));
|
||||
setSelectedCustomer(custNo);
|
||||
setSelectedCustomer(String(custNo));
|
||||
setOpenCreate(false);
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
wsssocket.on("rr-select-customer", handleRrSelectCustomer);
|
||||
wsssocket.on("rr-customer-create-required", handleRrCreateRequired);
|
||||
wsssocket.on("rr-customer-created", handleRrCustomerCreated);
|
||||
wsssocket.on("rr-select-customer", handleRrSelectCustomer);
|
||||
|
||||
return () => {
|
||||
wsssocket.off("rr-select-customer", handleRrSelectCustomer);
|
||||
@@ -79,6 +97,7 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
setOpen(true);
|
||||
setDmsType("cdk");
|
||||
setcustomerList(Array.isArray(list) ? list : []);
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
wsssocket.on("fortellis-select-customer", handleFortellisSelectCustomer);
|
||||
return () => {
|
||||
@@ -89,11 +108,13 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
setOpen(true);
|
||||
setDmsType("cdk");
|
||||
setcustomerList(Array.isArray(list) ? list : []);
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
const handlePbsSelectCustomer = (list) => {
|
||||
setOpen(true);
|
||||
setDmsType("pbs");
|
||||
setcustomerList(Array.isArray(list) ? list : []);
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
socket.on("cdk-select-customer", handleCdkSelectCustomer);
|
||||
socket.on("pbs-select-customer", handlePbsSelectCustomer);
|
||||
@@ -105,18 +126,25 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
}, [dms, Fortellis?.treatment, wsssocket]);
|
||||
|
||||
const onUseSelected = () => {
|
||||
if (dmsType === "rr") {
|
||||
// Stay open and show creation form
|
||||
setOpen(true);
|
||||
setOpenCreate(true);
|
||||
if (!selectedCustomer) {
|
||||
message.warning(t("general.actions.select"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (dmsType === "rr") {
|
||||
// ✅ RR now behaves like others: use the selected row and close
|
||||
wsssocket.emit("rr-selected-customer", { bodyshopId, custNo: String(selectedCustomer), jobId: jobid });
|
||||
setOpen(false);
|
||||
setSelectedCustomer(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Non-RR behavior unchanged:
|
||||
setOpen(false);
|
||||
if (Fortellis.treatment === "on") {
|
||||
wsssocket.emit("fortellis-selected-customer", { selectedCustomerId: null, jobid });
|
||||
wsssocket.emit("fortellis-selected-customer", { selectedCustomerId: selectedCustomer, jobid });
|
||||
} else {
|
||||
socket.emit(`${dmsType}-selected-customer`, null);
|
||||
socket.emit(`${dmsType}-selected-customer`, selectedCustomer);
|
||||
}
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
@@ -124,10 +152,9 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
const onUseGeneric = () => {
|
||||
setOpen(false);
|
||||
const generic = bodyshop.cdk_configuration?.generic_customer_number || null;
|
||||
console.dir({ bodyshop, generic });
|
||||
if (dmsType === "rr") {
|
||||
if (generic) {
|
||||
wsssocket.emit("rr-selected-customer", { bodyshopId, custNo: generic, jobId: jobid });
|
||||
wsssocket.emit("rr-selected-customer", { bodyshopId, custNo: String(generic), jobId: jobid });
|
||||
}
|
||||
} else if (Fortellis.treatment === "on") {
|
||||
wsssocket.emit("fortellis-selected-customer", { selectedCustomerId: generic, jobid });
|
||||
@@ -138,11 +165,15 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
};
|
||||
|
||||
const onCreateNew = () => {
|
||||
setOpen(false);
|
||||
if (dmsType === "rr") {
|
||||
// RR equivalent: signal create intent explicitly
|
||||
wsssocket.emit("rr-selected-customer", { bodyshopId, create: true, jobId: jobid });
|
||||
} else if (Fortellis.treatment === "on") {
|
||||
// RR: open inline creation modal (same as before)
|
||||
setOpen(true);
|
||||
setOpenCreate(true);
|
||||
return;
|
||||
}
|
||||
// Non-RR stays unchanged
|
||||
setOpen(false);
|
||||
if (Fortellis.treatment === "on") {
|
||||
wsssocket.emit("fortellis-selected-customer", { selectedCustomerId: null, jobid });
|
||||
} else {
|
||||
socket.emit(`${dmsType}-selected-customer`, null);
|
||||
@@ -150,12 +181,10 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
setSelectedCustomer(null);
|
||||
};
|
||||
|
||||
// ---------- Columns ----------
|
||||
|
||||
const fortellisColumns = [
|
||||
{
|
||||
title: t("jobs.fields.dms.id"),
|
||||
dataIndex: "customerId",
|
||||
key: "id"
|
||||
},
|
||||
{ title: t("jobs.fields.dms.id"), dataIndex: "customerId", key: "id" },
|
||||
{
|
||||
title: t("jobs.fields.dms.vinowner"),
|
||||
dataIndex: "vinOwner",
|
||||
@@ -187,11 +216,7 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
];
|
||||
|
||||
const cdkColumns = [
|
||||
{
|
||||
title: t("jobs.fields.dms.id"),
|
||||
dataIndex: ["id", "value"],
|
||||
key: "id"
|
||||
},
|
||||
{ title: t("jobs.fields.dms.id"), dataIndex: ["id", "value"], key: "id" },
|
||||
{
|
||||
title: t("jobs.fields.dms.vinowner"),
|
||||
dataIndex: "vinOwner",
|
||||
@@ -215,11 +240,7 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
];
|
||||
|
||||
const pbsColumns = [
|
||||
{
|
||||
title: t("jobs.fields.dms.id"),
|
||||
dataIndex: "ContactId",
|
||||
key: "ContactId"
|
||||
},
|
||||
{ title: t("jobs.fields.dms.id"), dataIndex: "ContactId", key: "ContactId" },
|
||||
{
|
||||
title: t("jobs.fields.dms.name1"),
|
||||
key: "name1",
|
||||
@@ -233,14 +254,10 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
}
|
||||
];
|
||||
|
||||
// RR is normalized to { custNo, name }
|
||||
const rrColumns = [
|
||||
{ title: t("jobs.fields.dms.id"), dataIndex: "custNo", key: "custNo" },
|
||||
{
|
||||
title: t("jobs.fields.dms.name1"),
|
||||
dataIndex: "name",
|
||||
key: "name",
|
||||
sorter: (a, b) => alphaSort(a?.name, b?.name)
|
||||
}
|
||||
{ title: t("jobs.fields.dms.name1"), dataIndex: "name", key: "name", sorter: (a, b) => alphaSort(a?.name, b?.name) }
|
||||
];
|
||||
|
||||
if (!open) return null;
|
||||
@@ -287,12 +304,14 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
: dmsType === "cdk"
|
||||
? record.id?.value || record.customerId
|
||||
: record.ContactId;
|
||||
setSelectedCustomer(key);
|
||||
setSelectedCustomer(key ? String(key) : null);
|
||||
},
|
||||
type: "radio",
|
||||
selectedRowKeys: [selectedCustomer]
|
||||
selectedRowKeys: selectedCustomer ? [selectedCustomer] : []
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* RR inline creation modal (unchanged) */}
|
||||
<Modal
|
||||
open={openCreate}
|
||||
title={t("jobs.actions.dms.createnewcustomer")}
|
||||
@@ -304,7 +323,6 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
form={createForm}
|
||||
layout="vertical"
|
||||
onFinish={(values) => {
|
||||
// Map a few sane defaults; BE tolerates partials
|
||||
const fields = {
|
||||
FirstName: values.FirstName,
|
||||
LastName: values.LastName,
|
||||
@@ -318,7 +336,7 @@ export function DmsCustomerSelector({ bodyshop, jobid }) {
|
||||
wsssocket.emit("rr-create-customer", { jobId: jobid, fields }, (ack) => {
|
||||
if (ack?.ok) {
|
||||
message.success(t("dms.messages.customerCreated"));
|
||||
setSelectedCustomer(ack.custNo);
|
||||
setSelectedCustomer(ack.custNo ? String(ack.custNo) : null);
|
||||
setOpenCreate(false);
|
||||
setOpen(false);
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DeleteFilled, DownOutlined } from "@ant-design/icons";
|
||||
import { DeleteFilled, DownOutlined, ReloadOutlined } from "@ant-design/icons";
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
@@ -28,13 +28,12 @@ import CurrencyInput from "../form-items-formatted/currency-form-item.component"
|
||||
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
|
||||
import { useSocket } from "../../contexts/SocketIO/useSocket";
|
||||
import { useSplitTreatments } from "@splitsoftware/splitio-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
const mapStateToProps = createStructuredSelector({
|
||||
bodyshop: selectBodyshop
|
||||
});
|
||||
const mapDispatchToProps = () => ({
|
||||
//setUserLanguage: language => dispatch(setUserLanguage(language))
|
||||
});
|
||||
const mapDispatchToProps = () => ({});
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(DmsPostForm);
|
||||
|
||||
export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
@@ -50,6 +49,52 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
const { t } = useTranslation();
|
||||
const { socket: wsssocket } = useSocket();
|
||||
|
||||
// Figure out DMS once and reuse
|
||||
const dms = useMemo(() => determineDmsType(bodyshop), [bodyshop]);
|
||||
|
||||
// RR advisors state
|
||||
const [advisors, setAdvisors] = useState([]);
|
||||
const [advLoading, setAdvLoading] = useState(false);
|
||||
|
||||
// Normalize advisor fields coming from various shapes
|
||||
const getAdvisorNumber = (a) => a?.advisorId;
|
||||
|
||||
const getAdvisorLabel = (a) => `${a?.firstName} ${a?.lastName}`?.trim();
|
||||
|
||||
const fetchRrAdvisors = () => {
|
||||
if (!wsssocket) return;
|
||||
setAdvLoading(true);
|
||||
|
||||
// Listen for the server's broadcast
|
||||
const onResult = (payload) => {
|
||||
try {
|
||||
const list = payload?.result ?? payload ?? [];
|
||||
setAdvisors(Array.isArray(list) ? list : []);
|
||||
} finally {
|
||||
setAdvLoading(false);
|
||||
wsssocket.off("rr-get-advisors:result", onResult);
|
||||
}
|
||||
};
|
||||
|
||||
wsssocket.once("rr-get-advisors:result", onResult);
|
||||
|
||||
// Emit with the correct event name + parse the ack shape
|
||||
wsssocket.emit("rr-get-advisors", { departmentType: "B" }, (ack) => {
|
||||
if (ack?.ok) {
|
||||
const list = ack.result ?? [];
|
||||
setAdvisors(Array.isArray(list) ? list : []);
|
||||
} else if (ack) {
|
||||
console.error("Something went wrong fetching DMS Advisors");
|
||||
}
|
||||
setAdvLoading(false);
|
||||
wsssocket.off("rr-get-advisors:result", onResult);
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (dms === "rr") fetchRrAdvisors();
|
||||
}, [dms, bodyshop?.id]);
|
||||
|
||||
const handlePayerSelect = (value, index) => {
|
||||
form.setFieldsValue({
|
||||
payers: form.getFieldValue("payers").map((payer, mapIndex) => {
|
||||
@@ -69,10 +114,9 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
};
|
||||
|
||||
const handleFinish = (values) => {
|
||||
const dms = determineDmsType(bodyshop);
|
||||
|
||||
// 1) RR takes precedence regardless of Fortellis split
|
||||
// 1) RR takes precedence regardless of Fortellis split
|
||||
if (dms === "rr") {
|
||||
// values will now include advisorNo from the RR dropdown
|
||||
wsssocket.emit("rr-export-job", {
|
||||
bodyshopId: bodyshop?.id || bodyshop?.bodyshopid || bodyshop?.uuid,
|
||||
jobId: job.id,
|
||||
@@ -81,7 +125,6 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
});
|
||||
} else {
|
||||
// 2) Fallback to existing behavior
|
||||
// TODO: Add this as a split instead.
|
||||
if (Fortellis.treatment === "on") {
|
||||
wsssocket.emit("fortellis-export-job", {
|
||||
jobid: job.id,
|
||||
@@ -91,6 +134,7 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// cdk/pbs/etc.
|
||||
socket.emit(`${dms}-export-job`, {
|
||||
jobid: job.id,
|
||||
txEnvelope: values
|
||||
@@ -98,7 +142,6 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Keep existing auto-scroll-to-logs behavior (fixing "curent" typo)
|
||||
if (logsRef?.current) {
|
||||
logsRef.current.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
@@ -130,70 +173,64 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
}}
|
||||
>
|
||||
<LayoutFormRow grow>
|
||||
<Form.Item
|
||||
name="journal"
|
||||
label={t("jobs.fields.dms.journal")}
|
||||
initialValue={bodyshop.cdk_configuration && bodyshop.cdk_configuration.default_journal}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
//message: t("general.validation.required"),
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="kmin"
|
||||
label={t("jobs.fields.kmin")}
|
||||
initialValue={job && job.kmin}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
//message: t("general.validation.required"),
|
||||
}
|
||||
]}
|
||||
>
|
||||
{dms !== "rr" && (
|
||||
<Form.Item
|
||||
name="journal"
|
||||
label={t("jobs.fields.dms.journal")}
|
||||
initialValue={bodyshop.cdk_configuration?.default_journal}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
{/* RR Advisor Number dropdown */}
|
||||
{dms === "rr" && (
|
||||
<Form.Item
|
||||
name="advisorNo"
|
||||
label={t("jobs.fields.dms.advisor")}
|
||||
rules={[{ required: true }]}
|
||||
style={{ minWidth: 260 }}
|
||||
>
|
||||
<Select
|
||||
loading={advLoading}
|
||||
placeholder={t("general.actions.select", "Select...")}
|
||||
popupMatchSelectWidth
|
||||
options={advisors
|
||||
.map((a) => {
|
||||
const value = getAdvisorNumber(a);
|
||||
if (value == null) return null;
|
||||
return { value: String(value), label: getAdvisorLabel(a) || String(value) };
|
||||
})
|
||||
.filter(Boolean)}
|
||||
notFoundContent={advLoading ? t("general.loading") : t("general.none")}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
<Form.Item name="kmin" label={t("jobs.fields.kmin")} initialValue={job?.kmin} rules={[{ required: true }]}>
|
||||
<InputNumber disabled />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="kmout"
|
||||
label={t("jobs.fields.kmout")}
|
||||
initialValue={job && job.kmout}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
//message: t("general.validation.required"),
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Form.Item name="kmout" label={t("jobs.fields.kmout")} initialValue={job?.kmout} rules={[{ required: true }]}>
|
||||
<InputNumber disabled />
|
||||
</Form.Item>
|
||||
|
||||
{dms === "rr" && (
|
||||
<Form.Item label=" " colon={false}>
|
||||
<Button onClick={fetchRrAdvisors} icon={<ReloadOutlined />} loading={advLoading}>
|
||||
{t("general.actions.refresh")}
|
||||
</Button>
|
||||
</Form.Item>
|
||||
)}
|
||||
</LayoutFormRow>
|
||||
|
||||
{bodyshop.cdk_dealerid && (
|
||||
<div>
|
||||
<LayoutFormRow style={{ justifyContent: "center" }} grow>
|
||||
<Form.Item
|
||||
name="dms_make"
|
||||
label={t("jobs.fields.dms.dms_make")}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Form.Item name="dms_make" label={t("jobs.fields.dms.dms_make")} rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="dms_model"
|
||||
label={t("jobs.fields.dms.dms_model")}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Form.Item name="dms_model" label={t("jobs.fields.dms.dms_model")} rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="inservicedate" label={t("jobs.fields.dms.inservicedate")}>
|
||||
@@ -212,15 +249,8 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
<Form.Item
|
||||
name="story"
|
||||
label={t("jobs.fields.dms.story")}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
|
||||
<Form.Item name="story" label={t("jobs.fields.dms.story")} rules={[{ required: true }]}>
|
||||
<Input.TextArea maxLength={240} />
|
||||
</Form.Item>
|
||||
|
||||
@@ -239,64 +269,53 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
value={Dinero(job.job_totals.totals.net_repairs).toFormat()}
|
||||
/>
|
||||
</Space>
|
||||
|
||||
<Form.List name={["payers"]}>
|
||||
{(fields, { add, remove }) => {
|
||||
return (
|
||||
<div>
|
||||
{fields.map((field, index) => (
|
||||
<Form.Item key={field.key}>
|
||||
<Space wrap>
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.name")}
|
||||
key={`${index}name`}
|
||||
name={[field.name, "name"]}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Select style={{ minWidth: "15rem" }} onSelect={(value) => handlePayerSelect(value, index)}>
|
||||
{bodyshop.cdk_configuration?.payers &&
|
||||
bodyshop.cdk_configuration.payers.map((payer) => (
|
||||
<Select.Option key={payer.name}>{payer.name}</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
{(fields, { add, remove }) => (
|
||||
<div>
|
||||
{fields.map((field, index) => (
|
||||
<Form.Item key={field.key}>
|
||||
<Space wrap>
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.name")}
|
||||
key={`${index}name`}
|
||||
name={[field.name, "name"]}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Select style={{ minWidth: "15rem" }} onSelect={(value) => handlePayerSelect(value, index)}>
|
||||
{bodyshop.cdk_configuration?.payers &&
|
||||
bodyshop.cdk_configuration.payers.map((payer) => (
|
||||
<Select.Option key={payer.name}>{payer.name}</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.dms_acctnumber")}
|
||||
key={`${index}dms_acctnumber`}
|
||||
name={[field.name, "dms_acctnumber"]}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Input disabled />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.dms_acctnumber")}
|
||||
key={`${index}dms_acctnumber`}
|
||||
name={[field.name, "dms_acctnumber"]}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input disabled />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.amount")}
|
||||
key={`${index}amount`}
|
||||
name={[field.name, "amount"]}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<CurrencyInput min={0} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label={t("jobs.fields.dms.payer.amount")}
|
||||
key={`${index}amount`}
|
||||
name={[field.name, "amount"]}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<CurrencyInput min={0} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={
|
||||
<div>
|
||||
{t("jobs.fields.dms.payer.controlnumber")}{" "}
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: bodyshop.cdk_configuration.controllist?.map((key, idx) => ({
|
||||
<Form.Item
|
||||
label={
|
||||
<div>
|
||||
{t("jobs.fields.dms.payer.controlnumber")}{" "}
|
||||
<Dropdown
|
||||
menu={{
|
||||
items:
|
||||
bodyshop.cdk_configuration.controllist?.map((key, idx) => ({
|
||||
key: idx,
|
||||
label: key.name,
|
||||
onClick: () => {
|
||||
@@ -310,93 +329,95 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
})
|
||||
});
|
||||
}
|
||||
}))
|
||||
}}
|
||||
>
|
||||
<a href=" #" onClick={(e) => e.preventDefault()}>
|
||||
<DownOutlined />
|
||||
</a>
|
||||
</Dropdown>
|
||||
</div>
|
||||
})) ?? []
|
||||
}}
|
||||
>
|
||||
<a href=" #" onClick={(e) => e.preventDefault()}>
|
||||
<DownOutlined />
|
||||
</a>
|
||||
</Dropdown>
|
||||
</div>
|
||||
}
|
||||
key={`${index}controlnumber`}
|
||||
name={[field.name, "controlnumber"]}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item shouldUpdate>
|
||||
{() => {
|
||||
const payers = form.getFieldValue("payers");
|
||||
const row = payers?.[index];
|
||||
const cdkPayer =
|
||||
bodyshop.cdk_configuration.payers &&
|
||||
bodyshop.cdk_configuration.payers.find((i) => i && row && i.name === row.name);
|
||||
if (i18n.exists(`jobs.fields.${cdkPayer?.control_type}`))
|
||||
return <div>{cdkPayer && t(`jobs.fields.${cdkPayer?.control_type}`)}</div>;
|
||||
else if (i18n.exists(`jobs.fields.dms.control_type.${cdkPayer?.control_type}`)) {
|
||||
return <div>{cdkPayer && t(`jobs.fields.dms.control_type.${cdkPayer?.control_type}`)}</div>;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
key={`${index}controlnumber`}
|
||||
name={[field.name, "controlnumber"]}
|
||||
rules={[
|
||||
{
|
||||
required: true
|
||||
}
|
||||
]}
|
||||
>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
}}
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item shouldUpdate>
|
||||
{() => {
|
||||
const payers = form.getFieldValue("payers");
|
||||
|
||||
const row = payers?.[index];
|
||||
|
||||
const cdkPayer =
|
||||
bodyshop.cdk_configuration.payers &&
|
||||
bodyshop.cdk_configuration.payers.find((i) => i && row && i.name === row.name);
|
||||
if (i18n.exists(`jobs.fields.${cdkPayer?.control_type}`))
|
||||
return <div>{cdkPayer && t(`jobs.fields.${cdkPayer?.control_type}`)}</div>;
|
||||
else if (i18n.exists(`jobs.fields.dms.control_type.${cdkPayer?.control_type}`)) {
|
||||
return <div>{cdkPayer && t(`jobs.fields.dms.control_type.${cdkPayer?.control_type}`)}</div>;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}}
|
||||
</Form.Item>
|
||||
|
||||
<DeleteFilled
|
||||
onClick={() => {
|
||||
remove(field.name);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
))}
|
||||
<Form.Item>
|
||||
<Button
|
||||
disabled={!(fields.length < 3)}
|
||||
onClick={() => {
|
||||
if (fields.length < 3) add();
|
||||
}}
|
||||
style={{ width: "100%" }}
|
||||
>
|
||||
{t("jobs.actions.dms.addpayer")}
|
||||
</Button>
|
||||
<DeleteFilled onClick={() => remove(field.name)} />
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
))}
|
||||
<Form.Item>
|
||||
<Button
|
||||
disabled={!(fields.length < 3)}
|
||||
onClick={() => {
|
||||
if (fields.length < 3) add();
|
||||
}}
|
||||
style={{ width: "100%" }}
|
||||
>
|
||||
{t("jobs.actions.dms.addpayer")}
|
||||
</Button>
|
||||
</Form.Item>
|
||||
</div>
|
||||
)}
|
||||
</Form.List>
|
||||
|
||||
<Form.Item shouldUpdate>
|
||||
{() => {
|
||||
//Perform Calculation to determine discrepancy.
|
||||
// 1) Sum allocated payers
|
||||
let totalAllocated = Dinero();
|
||||
|
||||
const payers = form.getFieldValue("payers");
|
||||
payers?.forEach((payer) => {
|
||||
const payers = form.getFieldValue("payers") || [];
|
||||
payers.forEach((payer) => {
|
||||
totalAllocated = totalAllocated.add(Dinero({ amount: Math.round((payer?.amount || 0) * 100) }));
|
||||
});
|
||||
|
||||
// 2) Subtotal from socket.allocationsSummary (existing behavior)
|
||||
const totals =
|
||||
socket.allocationsSummary &&
|
||||
socket.allocationsSummary.reduce(
|
||||
(acc, val) => {
|
||||
return {
|
||||
totalSale: acc.totalSale.add(Dinero(val.sale)),
|
||||
totalCost: acc.totalCost.add(Dinero(val.cost))
|
||||
};
|
||||
},
|
||||
{
|
||||
totalSale: Dinero(),
|
||||
totalCost: Dinero()
|
||||
}
|
||||
(acc, val) => ({
|
||||
totalSale: acc.totalSale.add(Dinero(val.sale)),
|
||||
totalCost: acc.totalCost.add(Dinero(val.cost))
|
||||
}),
|
||||
{ totalSale: Dinero(), totalCost: Dinero() }
|
||||
);
|
||||
|
||||
const discrep = totals ? totals.totalSale.subtract(totalAllocated) : Dinero();
|
||||
|
||||
// 3) New: validation gates
|
||||
const advisorOk = dms !== "rr" || !!form.getFieldValue("advisorNo");
|
||||
|
||||
// Require at least one complete payer row
|
||||
const payersOk =
|
||||
payers.length > 0 &&
|
||||
payers.every((p) => p?.name && p.dms_acctnumber && (p.amount ?? "") !== "" && p.controlnumber);
|
||||
|
||||
// 4) Disable rules:
|
||||
// - For non-RR: keep the original discrepancy rule (must have summary and zero discrepancy)
|
||||
// - For RR: ignore discrepancy rule, but require advisor + payer rows
|
||||
const nonRrDiscrepancyGate = dms !== "rr" && (socket.allocationsSummary ? discrep.getAmount() !== 0 : true);
|
||||
|
||||
const disablePost = !advisorOk || !payersOk || nonRrDiscrepancyGate;
|
||||
|
||||
return (
|
||||
<Space size="large" wrap align="center">
|
||||
<Statistic
|
||||
@@ -408,12 +429,10 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
<Typography.Title>=</Typography.Title>
|
||||
<Statistic
|
||||
title={t("jobs.labels.dms.notallocated")}
|
||||
valueStyle={{
|
||||
color: discrep.getAmount() === 0 ? "green" : "red"
|
||||
}}
|
||||
valueStyle={{ color: discrep.getAmount() === 0 ? "green" : "red" }}
|
||||
value={discrep.toFormat()}
|
||||
/>
|
||||
<Button disabled={!socket.allocationsSummary || discrep.getAmount() !== 0} htmlType="submit">
|
||||
<Button disabled={disablePost} htmlType="submit">
|
||||
{t("jobs.actions.dms.post")}
|
||||
</Button>
|
||||
</Space>
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// server/rr/rr-customers.js
|
||||
// Minimal RR customer create helper (maps dmsRecKey -> custNo for callers)
|
||||
|
||||
const { RRClient } = require("./lib/index.cjs");
|
||||
const { getRRConfigFromBodyshop } = require("./rr-config");
|
||||
const RRLogger = require("./rr-logger");
|
||||
@@ -35,7 +32,7 @@ function buildClientAndOpts(bodyshop) {
|
||||
|
||||
// minimal field extraction
|
||||
function digitsOnly(s) {
|
||||
return String(s || "").replace(/[^\d]/g, "");
|
||||
return String(s || "").replace(/\D/g, "");
|
||||
}
|
||||
|
||||
function buildCustomerPayloadFromJob(job, overrides = {}) {
|
||||
@@ -94,15 +91,7 @@ async function createRRCustomer({ bodyshop, job, overrides = {}, socket }) {
|
||||
const trx = res?.statusBlocks?.transaction;
|
||||
|
||||
// Primary: map dmsRecKey -> custNo
|
||||
let custNo =
|
||||
data?.dmsRecKey ??
|
||||
// legacy fallbacks (if shapes ever change)
|
||||
data?.custNo ??
|
||||
data?.CustNo ??
|
||||
data?.customerNo ??
|
||||
data?.CustomerNo ??
|
||||
data?.customer?.custNo ??
|
||||
data?.Customer?.CustNo;
|
||||
let custNo = data?.dmsRecKey;
|
||||
|
||||
if (!custNo) {
|
||||
log("error", "RR insertCustomer returned no dmsRecKey/custNo", {
|
||||
|
||||
@@ -1,28 +1,76 @@
|
||||
// server/rr/rr-job-export.js
|
||||
const { buildRRRepairOrderPayload } = require("./rr-job-helpers");
|
||||
const { buildClientAndOpts } = require("./rr-lookup");
|
||||
const { ensureRRServiceVehicle } = require("./rr-service-vehicles");
|
||||
const RRLogger = require("./rr-logger");
|
||||
|
||||
/**
|
||||
* Orchestrate an RR export (assumes custNo already resolved):
|
||||
* - Ensure service vehicle (create flows)
|
||||
* - Create or update the Repair Order
|
||||
*/
|
||||
async function exportJobToRR(args) {
|
||||
const { bodyshop, job, selectedCustomer, advisorNo, existing } = args;
|
||||
const { bodyshop, job, advisorNo, selectedCustomer, existing, socket } = args || {};
|
||||
const log = RRLogger(socket, { ns: "rr-export" });
|
||||
|
||||
// Build client + opts (opts carries routing)
|
||||
const { client, opts } = buildClientAndOpts(bodyshop);
|
||||
|
||||
const payload = buildRRRepairOrderPayload({ job, selectedCustomer, advisorNo });
|
||||
|
||||
let rrRes;
|
||||
if (existing?.dmsRepairOrderId) {
|
||||
rrRes = await client.updateRepairOrder({ ...payload, dmsRepairOrderId: existing.dmsRepairOrderId }, opts);
|
||||
} else {
|
||||
rrRes = await client.createRepairOrder(payload, opts);
|
||||
if (!bodyshop) throw new Error("exportJobToRR: bodyshop is required");
|
||||
if (!job) throw new Error("exportJobToRR: job is required");
|
||||
if (advisorNo == null || String(advisorNo).trim() === "") {
|
||||
throw new Error("exportJobToRR: advisorNo is required for RR");
|
||||
}
|
||||
|
||||
// Now strictly require custNo here
|
||||
const custNo =
|
||||
(selectedCustomer && (selectedCustomer.custNo || selectedCustomer.CustNo || selectedCustomer.customerNo)) ||
|
||||
(typeof selectedCustomer === "string" || typeof selectedCustomer === "number" ? String(selectedCustomer) : null);
|
||||
if (!custNo) throw new Error("exportJobToRR: selectedCustomer.custNo is required");
|
||||
|
||||
const { client, opts } = buildClientAndOpts(bodyshop);
|
||||
const finalOpts = {
|
||||
...opts,
|
||||
envelope: {
|
||||
...(opts?.envelope || {}),
|
||||
sender: {
|
||||
...(opts?.envelope?.sender || {}),
|
||||
task: "BSMRO",
|
||||
referenceId: existing?.dmsRepairOrderId ? "Update" : "Insert"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure service vehicle for create flows (best-effort)
|
||||
let svId = null;
|
||||
if (!existing?.dmsRepairOrderId) {
|
||||
try {
|
||||
const svRes = await ensureRRServiceVehicle({ bodyshop, custNo, job, overrides: {}, socket });
|
||||
svId = svRes?.svId || null;
|
||||
log("info", "RR service vehicle ensured", { created: svRes?.created, svId });
|
||||
} catch (e) {
|
||||
log("warn", "RR ensure service vehicle failed; continuing", { error: e?.message });
|
||||
}
|
||||
}
|
||||
|
||||
const payload = buildRRRepairOrderPayload({
|
||||
job,
|
||||
selectedCustomer: { custNo },
|
||||
advisorNo
|
||||
});
|
||||
|
||||
const rrRes = existing?.dmsRepairOrderId
|
||||
? await client.updateRepairOrder({ ...payload, dmsRepairOrderId: existing.dmsRepairOrderId }, finalOpts)
|
||||
: await client.createRepairOrder(payload, finalOpts);
|
||||
|
||||
const data = rrRes?.data || null;
|
||||
const roStatus = data?.roStatus || null;
|
||||
return {
|
||||
success: rrRes?.success === true,
|
||||
data: rrRes?.data || null,
|
||||
roStatus: rrRes?.data?.roStatus || null,
|
||||
success: rrRes?.success === true || roStatus?.status === "Success",
|
||||
data,
|
||||
roStatus,
|
||||
statusBlocks: rrRes?.statusBlocks || [],
|
||||
xml: rrRes?.xml,
|
||||
parsed: rrRes?.parsed
|
||||
parsed: rrRes?.parsed,
|
||||
custNo,
|
||||
svId
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -56,21 +56,49 @@ async function QueryJobData(ctx = {}, jobId) {
|
||||
* Build minimal RR RO payload (keys match your RR client’s expectations).
|
||||
* Uses fields that exist in your schema (v_vin, ro_number, owner fields, etc).
|
||||
*/
|
||||
/**
|
||||
* Build minimal RR RO payload (keys match RR client expectations).
|
||||
* - Requires advisorNo (maps to advNo)
|
||||
* - Uses custNo (normalized) and a cleaned VIN (17 chars, A–Z/0–9)
|
||||
*/
|
||||
function buildRRRepairOrderPayload({ job, selectedCustomer, advisorNo }) {
|
||||
const custNo =
|
||||
(selectedCustomer && (selectedCustomer.custNo || selectedCustomer.customerNo)) ||
|
||||
// Resolve custNo from object or primitive
|
||||
const custNoRaw =
|
||||
(selectedCustomer &&
|
||||
(selectedCustomer.custNo ||
|
||||
selectedCustomer.customerNo || // legacy alias, normalized below
|
||||
selectedCustomer.CustNo)) ||
|
||||
(typeof selectedCustomer === "string" || typeof selectedCustomer === "number" ? String(selectedCustomer) : null);
|
||||
|
||||
const custNo = custNoRaw ? String(custNoRaw).trim() : null;
|
||||
if (!custNo) throw new Error("No RR customer selected (custNo missing)");
|
||||
|
||||
const vin = safeVin(job);
|
||||
// For RR create flows, VIN is typically required; leave null allowed if you gate earlier in your flow.
|
||||
// Advisor is required for RR
|
||||
const advNo = advisorNo != null && String(advisorNo).trim() !== "" ? String(advisorNo).trim() : null;
|
||||
if (!advNo) throw new Error("advisorNo is required for RR export");
|
||||
|
||||
// Clean/normalize VIN if present
|
||||
const vinRaw = job?.v_vin || job?.vehicle?.vin || job?.vin;
|
||||
const vin =
|
||||
typeof vinRaw === "string"
|
||||
? vinRaw
|
||||
.replace(/[^A-Za-z0-9]/g, "")
|
||||
.toUpperCase()
|
||||
.slice(0, 17) || undefined
|
||||
: undefined;
|
||||
|
||||
// Pick a stable external RO number
|
||||
const ro =
|
||||
job?.ro_number != null ? job.ro_number : job?.job_number != null ? job.job_number : job?.id != null ? job.id : null;
|
||||
|
||||
if (ro == null) throw new Error("Missing repair order identifier (ro_number/job_number/id).");
|
||||
|
||||
return {
|
||||
repairOrderNumber: String(job?.ro_number || job?.job_number || job?.id),
|
||||
repairOrderNumber: String(ro),
|
||||
deptType: "B",
|
||||
vin: vin || undefined,
|
||||
custNo,
|
||||
advNo: advisorNo || undefined
|
||||
vin, // undefined if absent/empty after cleaning
|
||||
custNo: String(custNo),
|
||||
advNo // mapped from advisorNo
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
// server/rr/rr-logger.js
|
||||
// Robust socket + server logger for RR flows (no more [object Object] in UI)
|
||||
|
||||
"use strict";
|
||||
|
||||
const util = require("util");
|
||||
const appLogger = require("../utils/logger");
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// server/rr/rr-lookup.js
|
||||
// Reynolds & Reynolds lookup helpers that adapt our bodyshop record to the RR client
|
||||
|
||||
const { RRClient } = require("./lib/index.cjs");
|
||||
const { getRRConfigFromBodyshop } = require("./rr-config");
|
||||
|
||||
|
||||
82
server/rr/rr-service-vehicles.js
Normal file
82
server/rr/rr-service-vehicles.js
Normal file
@@ -0,0 +1,82 @@
|
||||
// server/rr/rr-service-vehicles.js
|
||||
const { RRClient } = require("./lib/index.cjs");
|
||||
const { getRRConfigFromBodyshop } = require("./rr-config");
|
||||
const RRLogger = require("./rr-logger");
|
||||
|
||||
function buildClientAndOpts(bodyshop) {
|
||||
const cfg = getRRConfigFromBodyshop(bodyshop);
|
||||
const client = new RRClient({
|
||||
baseUrl: cfg.baseUrl,
|
||||
username: cfg.username,
|
||||
password: cfg.password,
|
||||
timeoutMs: cfg.timeoutMs,
|
||||
retries: cfg.retries
|
||||
});
|
||||
const opts = {
|
||||
routing: cfg.routing,
|
||||
envelope: {
|
||||
sender: {
|
||||
component: "Rome",
|
||||
task: "SV", // Service Vehicle op code; adjust if your lib expects another
|
||||
referenceId: "Insert",
|
||||
creator: "RCI",
|
||||
senderName: "RCI"
|
||||
}
|
||||
}
|
||||
};
|
||||
return { client, opts };
|
||||
}
|
||||
|
||||
function buildServiceVehiclePayload({ job, custNo, overrides = {} }) {
|
||||
return {
|
||||
custNo: String(custNo), // tie SV to customer
|
||||
vin: overrides.vin ?? job?.v_vin,
|
||||
year: overrides.year ?? job?.v_model_yr,
|
||||
make: overrides.make ?? job?.dms_make ?? job?.v_make,
|
||||
model: overrides.model ?? job?.dms_model ?? job?.v_model,
|
||||
licensePlate: overrides.plate ?? job?.plate_no
|
||||
// add other safe keys your RR client supports (color, mileage, etc.)
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureRRServiceVehicle({ bodyshop, custNo, job, overrides = {}, socket }) {
|
||||
const log = RRLogger(socket, { ns: "rr" });
|
||||
const { client, opts } = buildClientAndOpts(bodyshop);
|
||||
|
||||
// Optional: first try a combined query by VIN to detect existing SV
|
||||
try {
|
||||
const queryRes = await client.combinedSearch(
|
||||
{ vin: job?.v_vin, maxRecs: 1 },
|
||||
{
|
||||
...opts,
|
||||
envelope: {
|
||||
...opts.envelope,
|
||||
sender: { ...opts.envelope.sender, task: "CVC", referenceId: "Query" }
|
||||
}
|
||||
}
|
||||
);
|
||||
const hasVehicle = Array.isArray(queryRes?.vehicles)
|
||||
? queryRes.vehicles.length > 0
|
||||
: Array.isArray(queryRes) && queryRes.length > 0;
|
||||
if (hasVehicle) {
|
||||
return { created: false, raw: queryRes };
|
||||
}
|
||||
} catch (e) {
|
||||
// non-fatal, continue to insert
|
||||
log("warn", "RR combined search failed before SV insert; proceeding to insert", { err: e?.message });
|
||||
}
|
||||
|
||||
const payload = buildServiceVehiclePayload({ job, custNo, overrides });
|
||||
const res = await client.insertServiceVehicle(payload, opts);
|
||||
const data = res?.data ?? res;
|
||||
|
||||
// Normalize a simple id for later (RR often returns DMSRecKey on insert)
|
||||
const svId = data?.svId ?? data?.serviceVehicleId ?? data?.dmsRecKey ?? data?.DMSRecKey;
|
||||
|
||||
if (!svId) {
|
||||
log("error", "RR insert service vehicle returned no id", { data });
|
||||
}
|
||||
return { created: true, svId, raw: data };
|
||||
}
|
||||
|
||||
module.exports = { ensureRRServiceVehicle };
|
||||
@@ -1,5 +1,3 @@
|
||||
// server/rr/rr-register-socket-events.js
|
||||
|
||||
const RRLogger = require("../rr/rr-logger");
|
||||
const { rrCombinedSearch, rrGetAdvisors, rrGetParts } = require("../rr/rr-lookup");
|
||||
const { QueryJobData } = require("../rr/rr-job-helpers");
|
||||
@@ -7,6 +5,7 @@ const { exportJobToRR } = require("../rr/rr-job-export");
|
||||
const CdkCalculateAllocations = require("../cdk/cdk-calculate-allocations").default;
|
||||
const { createRRCustomer } = require("../rr/rr-customers");
|
||||
|
||||
const { buildClientAndOpts } = require("../rr/rr-lookup");
|
||||
const { GraphQLClient } = require("graphql-request");
|
||||
const queries = require("../graphql-client/queries");
|
||||
|
||||
@@ -232,8 +231,9 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
}
|
||||
});
|
||||
|
||||
// Export flow
|
||||
socket.on("rr-export-job", async (payload = {}) => {
|
||||
const log = RRLogger(socket, { ns: "rr" });
|
||||
|
||||
try {
|
||||
// -------- 1) Resolve job --------
|
||||
let job = payload.job || payload.txEnvelope?.job;
|
||||
@@ -246,44 +246,36 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
|
||||
// -------- 2) Resolve bodyshop (+ full row via GraphQL) --------
|
||||
let bodyshopId = payload.bodyshopId || payload.bodyshopid || payload.bodyshopUUID || job?.bodyshop?.id;
|
||||
|
||||
if (!bodyshopId) {
|
||||
const sess = await getSessionOrSocket(redisHelpers, socket);
|
||||
bodyshopId = sess.bodyshopId;
|
||||
}
|
||||
if (!bodyshopId) throw new Error("RR export: bodyshopId required");
|
||||
|
||||
// Authoritative bodyshop row for RR routing (env fallback handled downstream)
|
||||
let bodyshop =
|
||||
const bodyshop =
|
||||
job?.bodyshop && (job.bodyshop.rr_dealerid || job.bodyshop.rr_configuration)
|
||||
? job.bodyshop
|
||||
: await getBodyshopForSocket({ bodyshopId, socket });
|
||||
|
||||
// Optional FE routing override (kept minimal/safe)
|
||||
const feRouting = payload.rrRouting;
|
||||
if (feRouting) {
|
||||
const cfg = bodyshop.rr_configuration || {};
|
||||
bodyshop = {
|
||||
...bodyshop,
|
||||
rr_dealerid: feRouting.dealerNumber ?? bodyshop.rr_dealerid,
|
||||
rr_configuration: {
|
||||
...cfg,
|
||||
storeNumber: feRouting.storeNumber ?? cfg.storeNumber,
|
||||
branchNumber: feRouting.areaNumber ?? cfg.branchNumber,
|
||||
areaNumber: feRouting.areaNumber ?? cfg.areaNumber
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// -------- 3) Resolve selected customer (payload → tx) --------
|
||||
// -------- 3) Resolve advisor number from the posting form --------
|
||||
const tx = (await redisHelpers.getSessionTransactionData(socket.id)) || {};
|
||||
const advisorNo = payload.advisorNo || payload.advNo || payload.txEnvelope?.advisorNo || tx.rrAdvisorNo || null;
|
||||
|
||||
if (!advisorNo || String(advisorNo).trim() === "") {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId, error: "Advisor is required (advisorNo)." });
|
||||
return;
|
||||
}
|
||||
// Persist for subsequent steps if useful
|
||||
await redisHelpers.setSessionTransactionData(socket.id, { ...tx, rrAdvisorNo: String(advisorNo) });
|
||||
|
||||
// -------- 4) Resolve selected customer (payload → tx) --------
|
||||
let selectedCustomer = null;
|
||||
|
||||
// from payload
|
||||
if (payload.selectedCustomer) {
|
||||
if (typeof payload.selectedCustomer === "object" && payload.selectedCustomer.custNo) {
|
||||
selectedCustomer = { custNo: String(payload.selectedCustomer.custNo) };
|
||||
} else if (typeof payload.selectedCustomer === "string") {
|
||||
} else if (typeof payload.selectedCustomer === "string" || typeof payload.selectedCustomer === "number") {
|
||||
selectedCustomer = { custNo: String(payload.selectedCustomer) };
|
||||
}
|
||||
}
|
||||
@@ -297,9 +289,11 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Flags
|
||||
const forceCreate = payload.forceCreate === true || tx.rrCreateCustomer === true;
|
||||
const autoCreateOnNoMatch = payload.autoCreateOnNoMatch !== false; // default TRUE
|
||||
|
||||
// -------- 4) If no selection & not "forceCreate", try auto-search then ask UI to pick --------
|
||||
// -------- 5) If no selection & not "forceCreate", try auto-search first --------
|
||||
if (!selectedCustomer && !forceCreate) {
|
||||
const customerQuery = makeCustomerSearchPayloadFromJob(job);
|
||||
const vehicleQuery = makeVehicleSearchPayloadFromJob(job);
|
||||
@@ -320,7 +314,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
});
|
||||
log("info", "rr-export-job:auto-selected-customer", { jobId, custNo: selectedCustomer.custNo });
|
||||
} else if (candidates.length > 1) {
|
||||
// emit picker data and stop; UI will call rr-selected-customer next
|
||||
// multiple matches → ask UI to pick and STOP here
|
||||
const table = candidates.map((c) => ({
|
||||
CustomerId: c.custNo,
|
||||
customerId: c.custNo,
|
||||
@@ -328,28 +322,57 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
}));
|
||||
socket.emit("rr-select-customer", table);
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: customer selection required", ts: Date.now() });
|
||||
return; // wait for user selection
|
||||
return;
|
||||
} else {
|
||||
// 0 matches → auto-create by default
|
||||
if (autoCreateOnNoMatch) {
|
||||
const { createRRCustomer } = require("../rr/rr-customers");
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
const custNo = created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey;
|
||||
if (!custNo) throw new Error("RR create customer returned no custNo");
|
||||
selectedCustomer = { custNo: String(custNo) };
|
||||
await redisHelpers.setSessionTransactionData(socket.id, {
|
||||
...tx,
|
||||
rrSelectedCustomer: selectedCustomer.custNo,
|
||||
rrCreateCustomer: false
|
||||
});
|
||||
log("info", "rr-export-job:auto-created-customer", { jobId, custNo: selectedCustomer.custNo });
|
||||
} else {
|
||||
await redisHelpers.setSessionTransactionData(socket.id, { ...tx, rrCreateCustomer: true });
|
||||
socket.emit("rr-customer-create-required");
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: create customer required", ts: Date.now() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// no usable query → fall back to create or UI prompt
|
||||
if (autoCreateOnNoMatch) {
|
||||
const { createRRCustomer } = require("../rr/rr-customers");
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
const custNo = created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey;
|
||||
if (!custNo) throw new Error("RR create customer returned no custNo");
|
||||
selectedCustomer = { custNo: String(custNo) };
|
||||
await redisHelpers.setSessionTransactionData(socket.id, {
|
||||
...tx,
|
||||
rrSelectedCustomer: selectedCustomer.custNo,
|
||||
rrCreateCustomer: false
|
||||
});
|
||||
log("info", "rr-export-job:auto-created-customer(no-query)", { jobId, custNo: selectedCustomer.custNo });
|
||||
} else {
|
||||
await redisHelpers.setSessionTransactionData(socket.id, { ...tx, rrCreateCustomer: true });
|
||||
socket.emit("rr-customer-create-required");
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: create customer required", ts: Date.now() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// no query or no matches → ask UI to create
|
||||
if (!selectedCustomer) {
|
||||
await redisHelpers.setSessionTransactionData(socket.id, { ...tx, rrCreateCustomer: true });
|
||||
socket.emit("rr-customer-create-required");
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: create customer required", ts: Date.now() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// -------- 5) If still not selected & creation is allowed, create now --------
|
||||
if (!selectedCustomer && forceCreate) {
|
||||
// -------- 6) If still not selected & creation is allowed, create now --------
|
||||
if (!selectedCustomer && (forceCreate || autoCreateOnNoMatch)) {
|
||||
const { createRRCustomer } = require("../rr/rr-customers");
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
// fallback when API returns only DMSRecKey
|
||||
const custNo = created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey;
|
||||
|
||||
if (!custNo) throw new Error("RR create customer returned no custNo");
|
||||
|
||||
selectedCustomer = { custNo: String(custNo) };
|
||||
await redisHelpers.setSessionTransactionData(socket.id, {
|
||||
...tx,
|
||||
@@ -361,18 +384,14 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
|
||||
if (!selectedCustomer?.custNo) throw new Error("RR export: selected customer missing custNo");
|
||||
|
||||
// -------- 6) Perform export --------
|
||||
const advisorNo = payload.advisorNo || payload.advNo || tx.rrAdvisorNo;
|
||||
const options = payload.options || payload.txEnvelope?.options || {};
|
||||
|
||||
// -------- 7) Perform export (ensure SV + create/update RO) --------
|
||||
const result = await exportJobToRR({
|
||||
bodyshop,
|
||||
job,
|
||||
selectedCustomer,
|
||||
advisorNo,
|
||||
existing: payload.existing,
|
||||
logger: log,
|
||||
...options
|
||||
socket
|
||||
});
|
||||
|
||||
if (result?.success) {
|
||||
@@ -393,7 +412,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
try {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId, error: error.message });
|
||||
} catch {
|
||||
//
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user