feature/IO-3357-Reynolds-and-Reynolds-DMS-API-Integration - Checkpoint
This commit is contained in:
@@ -7,94 +7,36 @@ const { QueryJobData } = require("../rr/rr-job-helpers");
|
||||
const { exportJobToRR } = require("../rr/rr-job-export");
|
||||
const CdkCalculateAllocations = require("../cdk/cdk-calculate-allocations").default;
|
||||
const { createRRCustomer } = require("../rr/rr-customers");
|
||||
const { ensureRRServiceVehicle } = require("../rr/rr-service-vehicles");
|
||||
const {
|
||||
makeVehicleSearchPayloadFromJob,
|
||||
ownersFromVinBlocks,
|
||||
readAdvisorNo,
|
||||
getTransactionType,
|
||||
normalizeCustomerCandidates,
|
||||
defaultRRTTL,
|
||||
RRCacheEnums
|
||||
} = require("../rr/rr-utils");
|
||||
|
||||
const { GraphQLClient } = require("graphql-request");
|
||||
const queries = require("../graphql-client/queries");
|
||||
|
||||
const getTransactionType = (jobid) => `rr:${jobid}`;
|
||||
const defaultRRTTL = 60 * 60;
|
||||
|
||||
// ---------------- cache keys (RR) ----------------
|
||||
const RRCacheEnums = {
|
||||
txEnvelope: "RR.txEnvelope",
|
||||
JobData: "RR.JobData",
|
||||
SelectedCustomer: "RR.SelectedCustomer",
|
||||
AdvisorNo: "RR.AdvisorNo",
|
||||
VINCandidates: "RR.VINCandidates",
|
||||
SelectedVin: "RR.SelectedVin",
|
||||
ExportResult: "RR.ExportResult"
|
||||
};
|
||||
|
||||
// ---------------- utils ----------------
|
||||
function resolveJobId(explicit, payload, job) {
|
||||
return explicit || payload?.jobId || payload?.jobid || job?.id || job?.jobId || job?.jobid || null;
|
||||
}
|
||||
const digitsOnly = (s) => String(s || "").replace(/\D/g, "");
|
||||
|
||||
const makeVehicleSearchPayloadFromJob = (job) => {
|
||||
const vin = job?.v_vin;
|
||||
if (vin) return { kind: "vin", vin: String(vin).trim(), maxResults: 50 };
|
||||
const plate = job?.plate_no;
|
||||
if (plate) return { kind: "license", license: String(plate).trim(), maxResults: 50 };
|
||||
return null;
|
||||
};
|
||||
|
||||
const makeCustomerSearchPayloadFromJob = (job) => {
|
||||
const phone = job?.ownr_ph1 || job?.ownr_ph2;
|
||||
const d = digitsOnly(phone);
|
||||
if (d.length >= 7) return { kind: "phone", phone: d, maxResults: 50 };
|
||||
|
||||
const firstName = job?.ownr_fn;
|
||||
const lastName = job?.ownr_ln;
|
||||
const company = job?.ownr_co_nm;
|
||||
|
||||
if (firstName || lastName) {
|
||||
const nameObj = {};
|
||||
if (firstName) nameObj.fname = String(firstName).trim();
|
||||
if (lastName) nameObj.lname = String(lastName).trim();
|
||||
return { kind: "name", name: nameObj, maxResults: 50 };
|
||||
}
|
||||
if (company) {
|
||||
return { kind: "name", name: { name: String(company).trim() }, maxResults: 50 };
|
||||
}
|
||||
|
||||
const vin = job?.v_vin;
|
||||
if (vin) return { kind: "vin", vin: String(vin).trim(), maxResults: 50 };
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Normalize candidates FE expects: { custNo, name } and flag vinOwner when sourced via VIN
|
||||
const normalizeCustomerCandidates = (res, { markVinOwner = false } = {}) => {
|
||||
const blocks = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
|
||||
const out = [];
|
||||
for (const blk of blocks) {
|
||||
const serv = Array.isArray(blk?.ServVehicle) ? blk.ServVehicle : [];
|
||||
const custNos = serv.map((sv) => sv?.VehicleServInfo?.CustomerNo).filter(Boolean);
|
||||
|
||||
const nci = blk?.NameContactId;
|
||||
const ind = nci?.NameId?.IndName;
|
||||
const bus = nci?.NameId?.BusName;
|
||||
const personal = [ind?.FirstName || ind?.FName, ind?.LastName || ind?.LName].filter(Boolean).join(" ").trim();
|
||||
const company = bus?.CompanyName || bus?.BName;
|
||||
const name = (personal || company || "").trim();
|
||||
|
||||
for (const custNo of custNos) {
|
||||
out.push({
|
||||
custNo: String(custNo),
|
||||
name: name || `Customer ${custNo}`,
|
||||
...(markVinOwner ? { vinOwner: true } : {})
|
||||
});
|
||||
}
|
||||
}
|
||||
const seen = new Set();
|
||||
return out.filter((c) => {
|
||||
const key = String(c.custNo || "").trim();
|
||||
if (!key || seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
function sortVehicleOwnerFirst(list) {
|
||||
return list
|
||||
.map((v, i) => ({ v, i }))
|
||||
.sort((a, b) => {
|
||||
const ao = a.v?.isVehicleOwner ? 1 : 0;
|
||||
const bo = b.v?.isVehicleOwner ? 1 : 0;
|
||||
if (ao !== bo) return bo - ao;
|
||||
return a.i - b.i;
|
||||
})
|
||||
.map(({ v }) => v);
|
||||
}
|
||||
|
||||
async function getSessionOrSocket(redisHelpers, socket) {
|
||||
let sess = null;
|
||||
@@ -114,54 +56,77 @@ async function getBodyshopForSocket({ bodyshopId, socket }) {
|
||||
if (!endpoint) throw new Error("GRAPHQL_ENDPOINT not configured");
|
||||
const token = (socket?.data && socket.data.authToken) || (socket?.handshake?.auth && socket.handshake.auth.token);
|
||||
const client = new GraphQLClient(endpoint, {});
|
||||
const res = await client
|
||||
.setHeaders({ Authorization: `Bearer ${token}` })
|
||||
.request(queries.GET_BODYSHOP_BY_ID, { id: bodyshopId });
|
||||
const res = await client.setHeaders({ Authorization: `Bearer ${token}` }).request(queries.GET_BODYSHOP_BY_ID, {
|
||||
id: bodyshopId
|
||||
});
|
||||
const bodyshop = res?.bodyshops_by_pk;
|
||||
if (!bodyshop) throw new Error(`Bodyshop not found: ${bodyshopId}`);
|
||||
return bodyshop;
|
||||
}
|
||||
|
||||
function readAdvisorNo(payload, cached) {
|
||||
const v =
|
||||
(payload?.txEnvelope?.advisorNo != null && String(payload.txEnvelope.advisorNo)) ||
|
||||
(payload?.advisorNo != null && String(payload.advisorNo)) ||
|
||||
(cached != null && String(cached)) ||
|
||||
null;
|
||||
return v && v.trim() !== "" ? v : null;
|
||||
}
|
||||
|
||||
// VIN + Name merge; keep vinOwner flag if any source came from VIN
|
||||
async function rrMultiCustomerSearch(bodyshop, job, socket) {
|
||||
/**
|
||||
* VIN + Full Name merge (export flow):
|
||||
* - Name query from job first/last or company
|
||||
* - VIN query from job VIN
|
||||
* - Cache VIN raw blocks (res.data) under RRCacheEnums.VINCandidates
|
||||
* - Mark isVehicleOwner only if candidate.custNo is in the VIN owners set (exact match)
|
||||
*/
|
||||
async function rrMultiCustomerSearch({ bodyshop, job, socket, redisHelpers }) {
|
||||
const queries = [];
|
||||
|
||||
// 1) Full Name (preferred)
|
||||
const firstName = job?.ownr_fn && String(job.ownr_fn).trim();
|
||||
const lastName = job?.ownr_ln && String(job.ownr_ln).trim();
|
||||
const company = job?.ownr_co_nm && String(job.ownr_co_nm).trim();
|
||||
|
||||
if (firstName || lastName) {
|
||||
queries.push({
|
||||
q: { kind: "name", name: { fname: firstName || undefined, lname: lastName || undefined }, maxResults: 50 },
|
||||
fromVin: false
|
||||
});
|
||||
} else if (company) {
|
||||
queries.push({ q: { kind: "name", name: { name: company }, maxResults: 50 }, fromVin: false });
|
||||
}
|
||||
|
||||
// 2) VIN (owner association)
|
||||
const vehQ = makeVehicleSearchPayloadFromJob(job);
|
||||
if (vehQ) queries.push({ q: vehQ, fromVin: vehQ.kind === "vin" });
|
||||
const custQ = makeCustomerSearchPayloadFromJob(job);
|
||||
if (custQ) queries.push({ q: custQ, fromVin: false });
|
||||
if (vehQ && vehQ.kind === "vin") queries.push({ q: vehQ, fromVin: true });
|
||||
|
||||
if (!queries.length) return [];
|
||||
|
||||
const all = [];
|
||||
let ownersSet = null;
|
||||
const merged = [];
|
||||
|
||||
for (const { q, fromVin } of queries) {
|
||||
try {
|
||||
CreateRRLogEvent(socket, "DEBUG", `{RR-SEARCH} Executing ${q.kind} query`, { q });
|
||||
const res = await rrCombinedSearch(bodyshop, q);
|
||||
const norm = normalizeCustomerCandidates(res, { markVinOwner: !!fromVin });
|
||||
all.push(...norm);
|
||||
|
||||
// If VIN query, compute ownersSet & cache raw blocks
|
||||
if (fromVin) {
|
||||
const blocks = Array.isArray(res?.data) ? res.data : [];
|
||||
ownersSet = ownersFromVinBlocks(blocks, job?.v_vin);
|
||||
try {
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
getTransactionType(job.id),
|
||||
RRCacheEnums.VINCandidates,
|
||||
blocks,
|
||||
defaultRRTTL
|
||||
);
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
const norm = normalizeCustomerCandidates(res, { ownersSet });
|
||||
merged.push(...norm);
|
||||
} catch (e) {
|
||||
CreateRRLogEvent(socket, "WARN", "Multi-search subquery failed", { kind: q.kind, error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
const byCust = new Map();
|
||||
for (const c of all) {
|
||||
const key = c?.custNo && String(c.custNo).trim();
|
||||
if (!key) continue;
|
||||
const prev = byCust.get(key);
|
||||
if (!prev) byCust.set(key, c);
|
||||
else if (c.vinOwner && !prev.vinOwner) byCust.set(key, { ...prev, vinOwner: true });
|
||||
}
|
||||
return Array.from(byCust.values());
|
||||
return sortVehicleOwnerFirst(merged);
|
||||
}
|
||||
|
||||
// ---------------- register handlers ----------------
|
||||
@@ -172,12 +137,23 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-lookup-combined: begin", { jobid, params });
|
||||
|
||||
const res = await rrCombinedSearch(bodyshop, params || {});
|
||||
const normalized = normalizeCustomerCandidates(res);
|
||||
let ownersSet = null;
|
||||
|
||||
if ((params?.kind || "").toLowerCase() === "vin") {
|
||||
const blocks = Array.isArray(res?.data) ? res.data : [];
|
||||
ownersSet = ownersFromVinBlocks(blocks); // no job VIN filter in ad-hoc lookup
|
||||
}
|
||||
|
||||
const normalized = sortVehicleOwnerFirst(normalizeCustomerCandidates(res, { ownersSet }));
|
||||
const rid = resolveJobId(jobid, { jobid }, null);
|
||||
|
||||
cb?.({ jobid: rid, data: normalized });
|
||||
socket.emit("rr-select-customer", normalized);
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-lookup-combined: emitted rr-select-customer", { count: normalized.length });
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-lookup-combined: emitted rr-select-customer", {
|
||||
count: normalized.length
|
||||
});
|
||||
} catch (e) {
|
||||
CreateRRLogEvent(socket, "ERROR", "RR combined lookup error", { error: e.message, jobid });
|
||||
cb?.({ jobid, error: e.message });
|
||||
@@ -221,7 +197,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
});
|
||||
|
||||
// ================= Fortellis-style two-step export =================
|
||||
// 1) Stage export -> search -> emit rr-select-customer
|
||||
// 1) Stage export -> search (Full Name + VIN) -> emit rr-select-customer
|
||||
socket.on("rr-export-job", async ({ jobid, jobId, txEnvelope } = {}) => {
|
||||
const rid = resolveJobId(jobid || jobId, { jobId, jobid }, null);
|
||||
try {
|
||||
@@ -265,13 +241,13 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
|
||||
CreateRRLogEvent(socket, "DEBUG", `{2} Running multi-search (VIN + Name)`);
|
||||
const candidates = await rrMultiCustomerSearch(bodyshop, job, socket);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{2} Running multi-search (Full Name + VIN)`);
|
||||
const candidates = await rrMultiCustomerSearch({ bodyshop, job, socket, redisHelpers });
|
||||
|
||||
socket.emit("rr-select-customer", candidates);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{2.1} Emitted rr-select-customer`, {
|
||||
count: candidates.length,
|
||||
anyVinOwner: candidates.some((c) => c.vinOwner)
|
||||
anyOwner: candidates.some((c) => c.isVehicleOwner)
|
||||
});
|
||||
} catch (error) {
|
||||
CreateRRLogEvent(socket, "ERROR", `Error during RR export (prepare)`, {
|
||||
@@ -287,7 +263,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
}
|
||||
});
|
||||
|
||||
// 2) Selection (or create) -> export
|
||||
// 2) Selection (or create) -> ensure vehicle -> export
|
||||
socket.on("rr-selected-customer", async ({ jobid, jobId, selectedCustomerId, custNo, create } = {}, ack) => {
|
||||
const rid = resolveJobId(jobid || jobId, { jobid, jobId }, null);
|
||||
try {
|
||||
@@ -329,6 +305,16 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3.3} Cached selected customer`, { custNo: String(selectedCustNo) });
|
||||
|
||||
// Ensure service vehicle exists and is owned by selected customer (uses cached VIN blocks when present)
|
||||
const ensureVeh = await ensureRRServiceVehicle({
|
||||
bodyshop,
|
||||
custNo: String(selectedCustNo),
|
||||
job,
|
||||
socket,
|
||||
redisHelpers
|
||||
});
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3.4} ensureRRServiceVehicle`, ensureVeh);
|
||||
|
||||
const cachedAdvisor = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.AdvisorNo);
|
||||
const advisorNo = readAdvisorNo({ txEnvelope }, cachedAdvisor);
|
||||
if (!advisorNo) {
|
||||
|
||||
Reference in New Issue
Block a user