feature/IO-3357-Reynolds-and-Reynolds-DMS-API-Integration - Checkpoint
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
// File: server/rr/rr-register-socket-events.js
|
||||
// PATCH: add helper + modify rr-export-job customer preselect logic
|
||||
|
||||
const RRLogger = require("../rr/rr-logger");
|
||||
const { rrCombinedSearch, rrGetAdvisors, rrGetParts } = require("../rr/rr-lookup");
|
||||
const { QueryJobData } = require("../rr/rr-job-helpers");
|
||||
@@ -125,6 +128,67 @@ function readAdvisorNo(payload, cached) {
|
||||
function registerRREvents({ socket, redisHelpers }) {
|
||||
const log = RRLogger(socket);
|
||||
|
||||
// --- NEW helper: run name + vin searches and merge ---
|
||||
async function rrMultiCustomerSearch(bodyshop, job) {
|
||||
const queries = [];
|
||||
|
||||
// Extract fields
|
||||
const fname = (job?.ownr_fn || job?.customer?.first_name || job?.customer?.firstName || "").trim();
|
||||
const lname = (job?.ownr_ln || job?.customer?.last_name || job?.customer?.lastName || "").trim();
|
||||
const vin = (job?.v_vin || job?.vehicle?.vin || job?.vin || "").trim();
|
||||
|
||||
// Build combined query if possible
|
||||
if (vin && (fname || lname)) {
|
||||
const nameObj = {};
|
||||
if (fname) nameObj.fname = fname;
|
||||
if (lname) nameObj.lname = lname;
|
||||
queries.push({
|
||||
kind: "name",
|
||||
name: nameObj,
|
||||
vin: vin,
|
||||
maxResults: 50
|
||||
});
|
||||
} else if (vin) {
|
||||
queries.push({ kind: "vin", vin: vin, maxResults: 50 });
|
||||
} else if (fname || lname) {
|
||||
// Standalone name: prefer FullName if both, else LName if only lname (though spec prefers combos)
|
||||
// Note: Standalone Last Name not in spec; use with caution or add MMY if available
|
||||
const nameObj = {};
|
||||
if (fname) nameObj.fname = fname;
|
||||
if (lname) nameObj.lname = lname;
|
||||
queries.push({
|
||||
kind: "name",
|
||||
name: nameObj,
|
||||
maxResults: 50
|
||||
});
|
||||
}
|
||||
|
||||
if (!queries.length) return [];
|
||||
|
||||
// Execute searches serially (could be Promise.all; keep serial for vendor rate safety)
|
||||
const all = [];
|
||||
for (const q of queries) {
|
||||
try {
|
||||
const res = await rrCombinedSearch(bodyshop, q);
|
||||
const norm = normalizeCustomerCandidates(res);
|
||||
all.push(...norm);
|
||||
} catch (e) {
|
||||
log("warn", "multi-search subquery failed", { kind: q.kind, error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
// De-dupe by custNo
|
||||
const seen = new Set();
|
||||
const merged = [];
|
||||
for (const c of all) {
|
||||
const k = c && c.custNo && String(c.custNo).trim();
|
||||
if (!k || seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
merged.push({ custNo: String(c.custNo), name: c.name });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// --------- Lookups (customer search → open table) ---------
|
||||
socket.on("rr-lookup-combined", async ({ jobid, params } = {}, cb) => {
|
||||
try {
|
||||
@@ -282,9 +346,8 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
// --------- Main export (Fortellis-style staging) ---------
|
||||
socket.on("rr-export-job", async (payload = {}) => {
|
||||
const _log = RRLogger(socket, { ns: "rr" });
|
||||
|
||||
try {
|
||||
// 1) Resolve job
|
||||
// (existing preamble unchanged)
|
||||
let job = payload.job || payload.txEnvelope?.job;
|
||||
const jobId = payload.jobId || payload.jobid || payload.txEnvelope?.jobId || job?.id;
|
||||
if (!job) {
|
||||
@@ -293,7 +356,6 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
}
|
||||
const ns = getTransactionType(job.id);
|
||||
|
||||
// Persist txEnvelope + job
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
@@ -303,7 +365,6 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
);
|
||||
await redisHelpers.setSessionTransactionData(socket.id, ns, RRCacheEnums.JobData, job, defaultRRTTL);
|
||||
|
||||
// 2) Resolve bodyshop
|
||||
let bodyshopId = payload.bodyshopId || payload.bodyshopid || payload.bodyshopUUID || job?.bodyshop?.id;
|
||||
if (!bodyshopId) {
|
||||
const sess = await getSessionOrSocket(redisHelpers, socket);
|
||||
@@ -316,7 +377,6 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
? job.bodyshop
|
||||
: await getBodyshopForSocket({ bodyshopId, socket });
|
||||
|
||||
// 3) Resolve advisor number (from form or cache)
|
||||
const cachedAdvisor = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.AdvisorNo);
|
||||
const advisorNo = readAdvisorNo(payload, cachedAdvisor);
|
||||
if (!advisorNo) {
|
||||
@@ -331,9 +391,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
defaultRRTTL
|
||||
);
|
||||
|
||||
// 4) Resolve selected customer (payload → cache)
|
||||
let selectedCust = null;
|
||||
|
||||
if (payload.selectedCustomer) {
|
||||
if (typeof payload.selectedCustomer === "object" && payload.selectedCustomer.custNo) {
|
||||
selectedCust = { custNo: String(payload.selectedCustomer.custNo) };
|
||||
@@ -350,47 +408,74 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedCust) {
|
||||
const cached = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.SelectedCustomer);
|
||||
if (cached) selectedCust = { custNo: String(cached) };
|
||||
}
|
||||
|
||||
// Flags
|
||||
const forceCreate = payload.forceCreate === true;
|
||||
const autoCreateOnNoMatch = payload.autoCreateOnNoMatch !== false; // default TRUE
|
||||
const autoCreateOnNoMatch = payload.autoCreateOnNoMatch !== false;
|
||||
|
||||
// 5) If no selection & not "forceCreate", try auto-search
|
||||
// --- MODIFIED: multi-search (name + vin) when beginning selection ---
|
||||
if (!selectedCust && !forceCreate) {
|
||||
const customerQuery = makeCustomerSearchPayloadFromJob(job);
|
||||
const vehicleQuery = makeVehicleSearchPayloadFromJob(job);
|
||||
const query = customerQuery || vehicleQuery;
|
||||
const mergedCandidates = await rrMultiCustomerSearch(bodyshop, job);
|
||||
|
||||
if (query) {
|
||||
_log("info", "rr-export-job:customer-preselect-search", { query, jobId });
|
||||
const searchRes = await rrCombinedSearch(bodyshop, query);
|
||||
const candidates = normalizeCustomerCandidates(searchRes);
|
||||
if (mergedCandidates.length === 1) {
|
||||
selectedCust = { custNo: String(mergedCandidates[0].custNo) };
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
_log("info", "rr-export-job:auto-selected-customer(multi)", { jobId, custNo: selectedCust.custNo });
|
||||
} else if (mergedCandidates.length > 1) {
|
||||
socket.emit("rr-select-customer", mergedCandidates);
|
||||
socket.emit("rr-log-event", {
|
||||
level: "info",
|
||||
message: "RR: customer selection required (multi-search)",
|
||||
ts: Date.now()
|
||||
});
|
||||
return; // wait for user selection
|
||||
} else {
|
||||
// Fallback to original single-query logic (phone etc.) only if no multi results
|
||||
// (retain legacy behavior)
|
||||
const fallbackQuery = makeCustomerSearchPayloadFromJob(job) || makeVehicleSearchPayloadFromJob(job) || null;
|
||||
|
||||
if (candidates.length === 1) {
|
||||
selectedCust = { custNo: String(candidates[0].custNo) };
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
_log("info", "rr-export-job:auto-selected-customer", { jobId, custNo: selectedCust.custNo });
|
||||
} else if (candidates.length > 1) {
|
||||
// multiple matches → table and stop
|
||||
socket.emit("rr-select-customer", candidates); // FE expects [{custNo,name}]
|
||||
socket.emit("rr-log-event", {
|
||||
level: "info",
|
||||
message: "RR: customer selection required",
|
||||
ts: Date.now()
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
if (fallbackQuery) {
|
||||
_log("info", "rr-export-job:fallback-single-query", { fallbackQuery, jobId });
|
||||
try {
|
||||
const searchRes = await rrCombinedSearch(bodyshop, fallbackQuery);
|
||||
const candidates = normalizeCustomerCandidates(searchRes);
|
||||
if (candidates.length === 1) {
|
||||
selectedCust = { custNo: String(candidates[0].custNo) };
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
_log("info", "rr-export-job:auto-selected-customer(fallback)", {
|
||||
jobId,
|
||||
custNo: selectedCust.custNo
|
||||
});
|
||||
} else if (candidates.length > 1) {
|
||||
socket.emit("rr-select-customer", candidates);
|
||||
socket.emit("rr-log-event", {
|
||||
level: "info",
|
||||
message: "RR: customer selection required",
|
||||
ts: Date.now()
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
_log("warn", "rr-export-job:fallback-query failed", { error: e.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedCust) {
|
||||
if (autoCreateOnNoMatch) {
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
const custNo = created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey;
|
||||
@@ -403,39 +488,26 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
_log("info", "rr-export-job:auto-created-customer", { jobId, custNo: selectedCust.custNo });
|
||||
_log("info", "rr-export-job:auto-created-customer(multi-zero)", {
|
||||
jobId,
|
||||
custNo: selectedCust.custNo
|
||||
});
|
||||
} else {
|
||||
socket.emit("rr-customer-create-required");
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: create customer required", ts: Date.now() });
|
||||
socket.emit("rr-log-event", {
|
||||
level: "info",
|
||||
message: "RR: create customer required",
|
||||
ts: Date.now()
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// no usable query → create or prompt
|
||||
if (autoCreateOnNoMatch) {
|
||||
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");
|
||||
selectedCust = { custNo: String(custNo) };
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
_log("info", "rr-export-job:auto-created-customer(no-query)", { jobId, custNo: selectedCust.custNo });
|
||||
} else {
|
||||
socket.emit("rr-customer-create-required");
|
||||
socket.emit("rr-log-event", { level: "info", message: "RR: create customer required", ts: Date.now() });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedCust?.custNo) throw new Error("RR export: selected customer missing custNo");
|
||||
|
||||
// 6) Perform export (ensure SV + create/update RO inside exportJobToRR)
|
||||
// (rest of existing export logic unchanged)
|
||||
const result = await exportJobToRR({
|
||||
bodyshop,
|
||||
job,
|
||||
@@ -469,9 +541,7 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
_log("error", `Error during RR export: ${error.message}`, { jobId, stack: error.stack });
|
||||
try {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId, error: error.message });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user