feature/IO-3357-Reynolds-and-Reynolds-DMS-API-Integration - Checkpoint
This commit is contained in:
@@ -119,7 +119,7 @@ export function DmsPostForm({ bodyshop, socket, job, logsRef }) {
|
||||
if (dms === "rr") {
|
||||
// values will now include advisorNo from the RR dropdown
|
||||
wsssocket.emit("rr-export-job", {
|
||||
bodyshopId: bodyshop?.id || bodyshop?.bodyshopid || bodyshop?.uuid,
|
||||
bodyshopId: bodyshop?.id,
|
||||
jobId: job.id,
|
||||
job,
|
||||
txEnvelope: values
|
||||
|
||||
@@ -713,7 +713,7 @@ export const GET_JOB_BY_PK = gql`
|
||||
v_model_yr
|
||||
v_model_desc
|
||||
v_vin
|
||||
notes(where:{pinned: {_eq: true}}, order_by: {updated_at: desc}) {
|
||||
notes(where: { pinned: { _eq: true } }, order_by: { updated_at: desc }) {
|
||||
created_at
|
||||
created_by
|
||||
critical
|
||||
@@ -999,7 +999,6 @@ export const QUERY_JOB_CARD_DETAILS = gql`
|
||||
key
|
||||
type
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -2171,6 +2170,8 @@ export const QUERY_JOB_EXPORT_DMS = gql`
|
||||
ownr_fn
|
||||
ownr_ln
|
||||
ownr_co_nm
|
||||
ownr_ph1
|
||||
ownr_ph2
|
||||
ins_co_nm
|
||||
kmin
|
||||
kmout
|
||||
@@ -2179,6 +2180,10 @@ export const QUERY_JOB_EXPORT_DMS = gql`
|
||||
v_model_desc
|
||||
area_of_damage
|
||||
date_exported
|
||||
v_vin
|
||||
plate_no
|
||||
plate_st
|
||||
ownr_co_nm
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -2413,7 +2418,7 @@ export const QUERY_PARTS_QUEUE_CARD_DETAILS = gql`
|
||||
start
|
||||
status
|
||||
}
|
||||
notes(where:{pinned: {_eq: true}}, order_by: {updated_at: desc}) {
|
||||
notes(where: { pinned: { _eq: true } }, order_by: { updated_at: desc }) {
|
||||
created_at
|
||||
created_by
|
||||
critical
|
||||
|
||||
@@ -297,10 +297,12 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, selectedCustome
|
||||
await QueryDmsErrWip({ socket, redisHelpers, JobData });
|
||||
|
||||
const DmsError = await QueryDmsErrWip({ socket, redisHelpers, JobData });
|
||||
// //Delete the transaction
|
||||
|
||||
//Delete the transaction
|
||||
CreateFortellisLogEvent(socket, "DEBUG", `{{ 6.2 } Deleting Transaction ID ${socket.DMSTransHeader.transID}`);
|
||||
|
||||
const DmsBatchTxnDelete = await DeleteDmsWip({ socket, redisHelpers, JobData });
|
||||
// Delete DMS Wip
|
||||
await DeleteDmsWip({ socket, redisHelpers, JobData });
|
||||
|
||||
DmsError.errMsg
|
||||
.split("|")
|
||||
@@ -318,8 +320,12 @@ async function FortellisSelectedCustomer({ socket, redisHelpers, selectedCustome
|
||||
"ERROR",
|
||||
`DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}`
|
||||
);
|
||||
await InsertFailedExportLog({ socket, JobData, error: `DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}` });
|
||||
|
||||
await InsertFailedExportLog({
|
||||
socket,
|
||||
JobData,
|
||||
error: `DMS Batch Return code was not successful: ${DMSBatchTxn.rtnCode} - ${DMSBatchTxn.sendline}`
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// CdkBase.createLogEvent(socket, "ERROR", `Error encountered in CdkSelectedCustomer.${ error } `);
|
||||
@@ -1018,13 +1024,12 @@ async function InsertDmsStartWip({ socket, redisHelpers, JobData }) {
|
||||
// "rtnCode": "",
|
||||
// "sendline": "",
|
||||
// "groupName": "",
|
||||
"srcCo": JobData.bodyshop.cdk_configuration.srcco,
|
||||
"srcJrnl": txEnvelope.journal,
|
||||
"transID": "",
|
||||
"userID": "csr" || JobData.bodyshop.cdk_configuration.cashierid,
|
||||
"userName": "BSMS"
|
||||
},
|
||||
|
||||
srcCo: JobData.bodyshop.cdk_configuration.srcco,
|
||||
srcJrnl: txEnvelope.journal,
|
||||
transID: "",
|
||||
userID: "csr" || JobData.bodyshop.cdk_configuration.cashierid,
|
||||
userName: "BSMS"
|
||||
}
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -1238,8 +1243,7 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) {
|
||||
socket,
|
||||
jobid: JobData.id,
|
||||
requestPathParams: DMSTransHeader.transID,
|
||||
body: {
|
||||
}
|
||||
body: {}
|
||||
});
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -1252,11 +1256,13 @@ async function QueryDmsErrWip({ socket, redisHelpers, JobData }) {
|
||||
}
|
||||
|
||||
async function DeleteDmsWip({ socket, redisHelpers, JobData }) {
|
||||
|
||||
let DMSTransHeader;
|
||||
try {
|
||||
DMSTransHeader = await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(JobData.id), FortellisCacheEnums.DMSTransHeader);
|
||||
|
||||
DMSTransHeader = await redisHelpers.getSessionTransactionData(
|
||||
socket.id,
|
||||
getTransactionType(JobData.id),
|
||||
FortellisCacheEnums.DMSTransHeader
|
||||
);
|
||||
|
||||
const result = await MakeFortellisCall({
|
||||
...FortellisActions.PostBatchWip,
|
||||
@@ -1265,8 +1271,8 @@ async function DeleteDmsWip({ socket, redisHelpers, JobData }) {
|
||||
socket,
|
||||
jobid: JobData.id,
|
||||
body: {
|
||||
"opCode": "D",
|
||||
"transID": DMSTransHeader.transID
|
||||
opCode: "D",
|
||||
transID: DMSTransHeader.transID
|
||||
}
|
||||
});
|
||||
return result;
|
||||
|
||||
File diff suppressed because one or more lines are too long
1
server/rr/lib/index.mjs
Normal file
1
server/rr/lib/index.mjs
Normal file
File diff suppressed because one or more lines are too long
3
server/rr/lib/types.cjs
Normal file
3
server/rr/lib/types.cjs
Normal file
@@ -0,0 +1,3 @@
|
||||
'use strict';
|
||||
// CJS access point for JSDoc typedefs
|
||||
module.exports = require('./types.js');
|
||||
43
server/rr/rr-logger-event.js
Normal file
43
server/rr/rr-logger-event.js
Normal file
@@ -0,0 +1,43 @@
|
||||
// File: server/rr/rr-logger-event.js
|
||||
// Fortellis-style log helper for RR flows.
|
||||
// Usage: CreateRRLogEvent(socket, "DEBUG"|"INFO"|"WARN"|"ERROR", message, details?)
|
||||
|
||||
const RRLogger = require("../rr/rr-logger");
|
||||
|
||||
// Normalize level to upper + provide console + socket event with coherent payload
|
||||
function CreateRRLogEvent(socket, level = "DEBUG", message = "", details = {}) {
|
||||
const lvl = String(level || "DEBUG").toUpperCase();
|
||||
const ts = Date.now();
|
||||
|
||||
// Console (uses existing RRLogger, which also emits "RR:LOG" to sockets for live tail)
|
||||
try {
|
||||
const log = RRLogger(socket);
|
||||
const fn = lvl === "ERROR" ? "error" : lvl === "WARN" ? "warn" : lvl === "INFO" ? "info" : "debug";
|
||||
log(fn, message, { ts, ...safeJson(details) });
|
||||
} catch {
|
||||
/* ignore console/log failures */
|
||||
}
|
||||
|
||||
// Structured RR event for FE debug panel (parity with Fortellis' CreateFortellisLogEvent)
|
||||
try {
|
||||
socket?.emit?.("rr-log-event", {
|
||||
level: lvl,
|
||||
message,
|
||||
ts,
|
||||
...safeJson(details)
|
||||
});
|
||||
} catch {
|
||||
/* ignore socket emit failures */
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort ensure details are JSON-safe (avoid circular / BigInt)
|
||||
function safeJson(obj) {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(obj ?? {}));
|
||||
} catch {
|
||||
return { _unsafe: true };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CreateRRLogEvent;
|
||||
@@ -1,66 +1,56 @@
|
||||
const util = require("util");
|
||||
const appLogger = require("../utils/logger");
|
||||
// File: server/rr/rr-logger.js
|
||||
// Console logger for RR flows with safe JSON. No socket emission by default.
|
||||
|
||||
function RRLogger(socket, baseCtx = {}) {
|
||||
const levels = new Set(["error", "warn", "info", "http", "verbose", "debug", "silly"]);
|
||||
const baseLogger = require("../utils/logger");
|
||||
|
||||
const safeString = (v) => {
|
||||
if (v instanceof Error) return v.message;
|
||||
if (typeof v === "string") return v;
|
||||
function RRLogger(_socket, defaults = {}) {
|
||||
function safeSerialize(value) {
|
||||
try {
|
||||
return JSON.stringify(v);
|
||||
} catch {
|
||||
return util.inspect(v, { depth: 2, maxArrayLength: 50 });
|
||||
}
|
||||
};
|
||||
|
||||
return function log(levelOrMsg, msgOrCtx, ctx) {
|
||||
let level = "info";
|
||||
let message = undefined;
|
||||
let meta = {};
|
||||
|
||||
if (typeof levelOrMsg === "string" && levels.has(levelOrMsg)) {
|
||||
level = levelOrMsg;
|
||||
message = msgOrCtx;
|
||||
meta = ctx || {};
|
||||
} else {
|
||||
message = levelOrMsg;
|
||||
meta = msgOrCtx || {};
|
||||
}
|
||||
|
||||
// Prepare console line + metadata
|
||||
const emitError = message instanceof Error;
|
||||
if (emitError) {
|
||||
meta.err = {
|
||||
name: message.name,
|
||||
message: message.message,
|
||||
stack: message.stack
|
||||
};
|
||||
message = message.message;
|
||||
if (level === "info") level = "error";
|
||||
}
|
||||
|
||||
const messageString = safeString(message);
|
||||
const line = `[RR] ${new Date().toISOString()} [${String(level).toUpperCase()}] ${messageString}`;
|
||||
const loggerFn = appLogger?.logger?.[level] || appLogger?.logger?.info || ((...args) => console.log(...args));
|
||||
|
||||
loggerFn(line, { ...baseCtx, ...meta });
|
||||
|
||||
// Always emit a STRING for `message` to sockets to avoid React crashes
|
||||
// If the original message was an object, include it in `details`
|
||||
const details = message && typeof message !== "string" && !emitError ? message : undefined;
|
||||
|
||||
try {
|
||||
socket?.emit?.("rr-log-event", {
|
||||
level,
|
||||
message: messageString, // <-- normalized string for UI
|
||||
ctx: { ...baseCtx, ...meta },
|
||||
...(details ? { details } : {}),
|
||||
ts: Date.now()
|
||||
const seen = new WeakSet();
|
||||
return JSON.stringify(value, (key, val) => {
|
||||
if (typeof val === "bigint") return val.toString();
|
||||
if (val instanceof Error) return { name: val.name, message: val.message, stack: val.stack };
|
||||
if (typeof val === "function") return undefined;
|
||||
if (typeof val === "object" && val !== null) {
|
||||
if (seen.has(val)) return "[Circular]";
|
||||
seen.add(val);
|
||||
if (val instanceof Date) return val.toISOString();
|
||||
if (val instanceof Map) return Object.fromEntries(val);
|
||||
if (val instanceof Set) return Array.from(val);
|
||||
if (typeof Buffer !== "undefined" && Buffer.isBuffer?.(val)) return `<Buffer len=${val.length}>`;
|
||||
}
|
||||
return val;
|
||||
});
|
||||
} catch {
|
||||
/* ignore socket emission errors */
|
||||
try {
|
||||
return String(value);
|
||||
} catch {
|
||||
return "[Unserializable]";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return function log(level = "info", message = "", ctx = {}) {
|
||||
const lvl = String(level || "info").toLowerCase();
|
||||
const iso = new Date().toISOString();
|
||||
|
||||
const msgStr = typeof message === "string" ? message : safeSerialize(message);
|
||||
const mergedCtx = ctx && typeof ctx === "object" ? { ...defaults, ...ctx } : { ...defaults };
|
||||
|
||||
const ctxStr = Object.keys(mergedCtx || {}).length ? ` ${safeSerialize(mergedCtx)}` : "";
|
||||
const line = `[RR] ${iso} [${lvl.toUpperCase()}] ${msgStr}${ctxStr}`;
|
||||
|
||||
const logger = baseLogger?.logger || baseLogger || console;
|
||||
const fn = (logger[lvl] || logger.log || logger.info || console[lvl] || console.log).bind(logger);
|
||||
|
||||
try {
|
||||
fn(line);
|
||||
} catch {
|
||||
try {
|
||||
console.log(line);
|
||||
} catch {}
|
||||
}
|
||||
// INTENTIONALLY no socket emit here to avoid FE duplicates.
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -41,76 +41,90 @@ function buildClientAndOpts(bodyshop) {
|
||||
*/
|
||||
function toCombinedSearchPayload(args = {}) {
|
||||
const q = { ...args };
|
||||
let kind = (q.kind || "").toString().trim().toLowerCase();
|
||||
|
||||
// Decide kind if not provided
|
||||
let kind = (q.kind || "").toString().trim();
|
||||
if (!kind) {
|
||||
if (q.phone) kind = "phone";
|
||||
else if (q.license) kind = "license";
|
||||
else if (q.vin) kind = "vin";
|
||||
else if (q.nameRecId || q.custId) kind = "namerecid";
|
||||
else if (q.name && (q.name.fname || q.name.lname || q.name.mname || q.name.name)) kind = "name";
|
||||
else if (q.stkNo || q.stock) kind = "stkno";
|
||||
else if (q.nameRecId || q.custId) kind = "nameRecId";
|
||||
else if (typeof q.name === "string" || (q.name && (q.name.fname || q.name.lname || q.name.mname || q.name.name))) {
|
||||
kind = "name";
|
||||
} else if (q.stkNo || q.stock) kind = "stkNo";
|
||||
}
|
||||
|
||||
// Map loose aliases into the RR builder’s expected fields
|
||||
const payload = { maxResults: q.maxResults || q.maxRecs || 50, kind };
|
||||
const payload = {
|
||||
maxResults: q.maxResults || q.maxRecs || 50,
|
||||
kind
|
||||
};
|
||||
|
||||
switch (kind) {
|
||||
switch ((kind || "").toLowerCase()) {
|
||||
case "phone":
|
||||
payload.kind = "phone";
|
||||
payload.phone = q.phone;
|
||||
payload.phone = String(q.phone ?? "").trim();
|
||||
break;
|
||||
|
||||
case "license":
|
||||
payload.kind = "license";
|
||||
payload.license = q.license;
|
||||
payload.license = String(q.license ?? "").trim();
|
||||
break;
|
||||
|
||||
case "vin":
|
||||
payload.kind = "vin";
|
||||
payload.vin = q.vin;
|
||||
payload.vin = String(q.vin ?? "").trim();
|
||||
break;
|
||||
case "namerecid":
|
||||
payload.kind = "nameRecId";
|
||||
payload.nameRecId = q.nameRecId || q.custId;
|
||||
payload.nameRecId = String(q.nameRecId ?? q.custId ?? "").trim();
|
||||
break;
|
||||
|
||||
case "stkno":
|
||||
case "stkNo":
|
||||
payload.kind = "stkNo";
|
||||
payload.stkNo = String(q.stkNo ?? q.stock ?? "").trim();
|
||||
break;
|
||||
case "name": {
|
||||
payload.kind = "name";
|
||||
const name = q.name;
|
||||
if (name.name) {
|
||||
payload.name = { name: name.name }; // For LName
|
||||
} else if (name.fname && name.lname) {
|
||||
payload.name = {
|
||||
fname: name.fname,
|
||||
lname: name.lname,
|
||||
...(name.mname ? { mname: name.mname } : {})
|
||||
}; // For FullName
|
||||
} else if (name.lname) {
|
||||
payload.name = { name: name.lname }; // Fallback to LName if only lname
|
||||
} else {
|
||||
// Invalid; but to handle gracefully, perhaps throw or skip
|
||||
const n = q.name;
|
||||
// STRING => last-name-only intent
|
||||
if (typeof n === "string") {
|
||||
const last = n.trim();
|
||||
if (last) payload.name = { name: last }; // <LName Name="..."/>
|
||||
break;
|
||||
}
|
||||
// OBJECT => always treat as FullName (even if only one of the parts is present)
|
||||
const fname = n?.fname && String(n.fname).trim();
|
||||
const lname = n?.lname && String(n.lname).trim();
|
||||
const mname = n?.mname && String(n.mname).trim();
|
||||
const lastOnly = n?.name && String(n.name).trim();
|
||||
|
||||
if (fname || lname || mname) {
|
||||
const full = {};
|
||||
if (fname) full.fname = fname;
|
||||
if (mname) full.mname = mname;
|
||||
if (lname) full.lname = lname;
|
||||
payload.name = full; // will render <FullName .../>
|
||||
} else if (lastOnly) {
|
||||
payload.name = { name: lastOnly }; // explicit last-only
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "stkno":
|
||||
payload.kind = "stkNo";
|
||||
payload.stkNo = q.stkNo || q.stock;
|
||||
break;
|
||||
|
||||
default:
|
||||
// Let the RR builder throw the canonical “Unsupported CombinedSearch kind”
|
||||
payload.kind = q.kind; // may be undefined; RR lib will validate
|
||||
payload.kind = kind;
|
||||
}
|
||||
|
||||
// Add compatible secondary fields for combinations
|
||||
if (q.vin && kind !== "vin") payload.vin = q.vin;
|
||||
if (q.phone && kind !== "phone") payload.phone = q.phone;
|
||||
if (q.license && kind !== "license") payload.license = q.license;
|
||||
|
||||
// Optional vehicle narrowing; the RR builder defaults to ANY/ANY/ANY if omitted
|
||||
if (q.make || q.model || q.year) {
|
||||
payload.make = q.make || "ANY";
|
||||
payload.model = q.model || "ANY";
|
||||
payload.year = q.year || "ANY";
|
||||
}
|
||||
|
||||
if (q.vin && payload.kind !== "vin") payload.vin = String(q.vin).trim();
|
||||
if (q.phone && payload.kind !== "phone") payload.phone = String(q.phone).trim();
|
||||
if (q.license && payload.kind !== "license") payload.license = String(q.license).trim();
|
||||
|
||||
return payload;
|
||||
}
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// File: server/rr/rr-register-socket-events.js
|
||||
// PATCH: add helper + modify rr-export-job customer preselect logic
|
||||
// RR events aligned to Fortellis flow with Fortellis-style logging via CreateRRLogEvent
|
||||
|
||||
const RRLogger = require("../rr/rr-logger");
|
||||
const CreateRRLogEvent = require("../rr/rr-logger-event");
|
||||
const { rrCombinedSearch, rrGetAdvisors, rrGetParts } = require("../rr/rr-lookup");
|
||||
const { QueryJobData } = require("../rr/rr-job-helpers");
|
||||
const { exportJobToRR } = require("../rr/rr-job-export");
|
||||
@@ -11,8 +11,8 @@ const { createRRCustomer } = require("../rr/rr-customers");
|
||||
const { GraphQLClient } = require("graphql-request");
|
||||
const queries = require("../graphql-client/queries");
|
||||
|
||||
// Use the same namespacing/TTL approach as Fortellis
|
||||
const { getTransactionType, defaultFortellisTTL } = require("../fortellis/fortellis-helpers");
|
||||
const getTransactionType = (jobid) => `rr:${jobid}`;
|
||||
const defaultRRTTL = 60 * 60;
|
||||
|
||||
// ---------------- cache keys (RR) ----------------
|
||||
const RRCacheEnums = {
|
||||
@@ -20,12 +20,10 @@ const RRCacheEnums = {
|
||||
JobData: "RR.JobData",
|
||||
SelectedCustomer: "RR.SelectedCustomer",
|
||||
AdvisorNo: "RR.AdvisorNo",
|
||||
// Vehicle keys reserved for future multi-vehicle UX parity
|
||||
VINCandidates: "RR.VINCandidates",
|
||||
SelectedVin: "RR.SelectedVin",
|
||||
ExportResult: "RR.ExportResult"
|
||||
};
|
||||
const defaultRRTTL = defaultFortellisTTL || 60 * 60; // fallback 1h
|
||||
|
||||
// ---------------- utils ----------------
|
||||
function resolveJobId(explicit, payload, job) {
|
||||
@@ -34,31 +32,40 @@ function resolveJobId(explicit, payload, job) {
|
||||
const digitsOnly = (s) => String(s || "").replace(/\D/g, "");
|
||||
|
||||
const makeVehicleSearchPayloadFromJob = (job) => {
|
||||
const vin = job?.v_vin || job?.vehicle?.vin || job?.vehicle_vin || job?.vin;
|
||||
if (vin) return { kind: "vin", vin: String(vin).trim() };
|
||||
const plate = job?.plate_no || job?.vehicle?.plate || job?.vehicle_plate || job?.plate;
|
||||
if (plate) return { kind: "license", license: String(plate).trim() };
|
||||
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?.customer?.mobile || job?.customer?.home_phone || job?.customer?.phone;
|
||||
const d = digitsOnly(phone);
|
||||
if (d.length >= 7) return { kind: "phone", phone: d };
|
||||
if (d.length >= 7) return { kind: "phone", phone: d, maxResults: 50 };
|
||||
|
||||
const lastName = job?.ownr_ln || job?.customer?.last_name || job?.customer?.lastName;
|
||||
const company = job?.ownr_co_nm || job?.customer?.company_name || job?.customer?.companyName;
|
||||
const lnOrCompany = lastName || company;
|
||||
if (lnOrCompany) return { kind: "name", name: { name: String(lnOrCompany).trim() } };
|
||||
const firstName = job?.ownr_fn;
|
||||
const lastName = job?.ownr_ln;
|
||||
const company = job?.ownr_co_nm;
|
||||
|
||||
const vin = job?.v_vin || job?.vehicle?.vin || job?.vehicle_vin || job?.vin;
|
||||
if (vin) return { kind: "vin", vin: String(vin).trim() };
|
||||
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 || job?.vehicle?.vin || job?.vin;
|
||||
if (vin) return { kind: "vin", vin: String(vin).trim(), maxResults: 50 };
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Normalize to the RR table shape expected by FE (custNo + name)
|
||||
const normalizeCustomerCandidates = (res) => {
|
||||
// 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) {
|
||||
@@ -68,12 +75,16 @@ const normalizeCustomerCandidates = (res) => {
|
||||
const nci = blk?.NameContactId;
|
||||
const ind = nci?.NameId?.IndName;
|
||||
const bus = nci?.NameId?.BusName;
|
||||
const personal = [ind?.FName, ind?.LName].filter(Boolean).join(" ").trim();
|
||||
const company = bus?.CompanyName;
|
||||
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}` });
|
||||
out.push({
|
||||
custNo: String(custNo),
|
||||
name: name || `Customer ${custNo}`,
|
||||
...(markVinOwner ? { vinOwner: true } : {})
|
||||
});
|
||||
}
|
||||
}
|
||||
const seen = new Set();
|
||||
@@ -90,7 +101,7 @@ async function getSessionOrSocket(redisHelpers, socket) {
|
||||
try {
|
||||
sess = await redisHelpers.getSessionData(socket.id);
|
||||
} catch {
|
||||
/* ignore */
|
||||
//
|
||||
}
|
||||
const bodyshopId = sess?.bodyshopId ?? socket.bodyshopId;
|
||||
const email = sess?.email ?? socket.user?.email;
|
||||
@@ -101,14 +112,11 @@ async function getSessionOrSocket(redisHelpers, socket) {
|
||||
async function getBodyshopForSocket({ bodyshopId, socket }) {
|
||||
const endpoint = process.env.GRAPHQL_ENDPOINT;
|
||||
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 bodyshop = res?.bodyshops_by_pk;
|
||||
if (!bodyshop) throw new Error(`Bodyshop not found: ${bodyshopId}`);
|
||||
return bodyshop;
|
||||
@@ -117,6 +125,7 @@ async function getBodyshopForSocket({ bodyshopId, socket }) {
|
||||
function readAdvisorNo(payload, cached) {
|
||||
const v =
|
||||
(payload?.txEnvelope?.advisorNo != null && String(payload.txEnvelope.advisorNo)) ||
|
||||
(payload?.txEnvelope?.advNo != null && String(payload.txEnvelope.advNo)) ||
|
||||
(payload?.advisorNo != null && String(payload.advisorNo)) ||
|
||||
(payload?.advNo != null && String(payload.advNo)) ||
|
||||
(cached != null && String(cached)) ||
|
||||
@@ -124,264 +133,212 @@ function readAdvisorNo(payload, cached) {
|
||||
return v && v.trim() !== "" ? v : null;
|
||||
}
|
||||
|
||||
// ---------------- register handlers ----------------
|
||||
function registerRREvents({ socket, redisHelpers }) {
|
||||
const log = RRLogger(socket);
|
||||
// VIN + Name merge; keep vinOwner flag if any source came from VIN
|
||||
async function rrMultiCustomerSearch(bodyshop, job, socket) {
|
||||
const queries = [];
|
||||
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 });
|
||||
|
||||
// --- NEW helper: run name + vin searches and merge ---
|
||||
async function rrMultiCustomerSearch(bodyshop, job) {
|
||||
const queries = [];
|
||||
if (!queries.length) return [];
|
||||
|
||||
// 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
|
||||
});
|
||||
const all = [];
|
||||
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);
|
||||
} catch (e) {
|
||||
CreateRRLogEvent(socket, "WARN", "Multi-search subquery failed", { kind: q.kind, error: e.message });
|
||||
}
|
||||
|
||||
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) ---------
|
||||
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());
|
||||
}
|
||||
|
||||
// ---------------- register handlers ----------------
|
||||
function registerRREvents({ socket, redisHelpers }) {
|
||||
// ---------- Lookup passthrough ----------
|
||||
socket.on("rr-lookup-combined", async ({ jobid, params } = {}, cb) => {
|
||||
try {
|
||||
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);
|
||||
|
||||
const rid = resolveJobId(jobid, { jobid }, null);
|
||||
cb?.({ jobid: rid, data: normalized });
|
||||
|
||||
// FE expects { custNo, name }
|
||||
socket.emit("rr-select-customer", normalized);
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-lookup-combined: emitted rr-select-customer", { count: normalized.length });
|
||||
} catch (e) {
|
||||
log("error", `RR combined lookup error: ${e.message}`, { jobid });
|
||||
CreateRRLogEvent(socket, "ERROR", "RR combined lookup error", { error: e.message, jobid });
|
||||
cb?.({ jobid, error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Advisors ---------
|
||||
// ---------- Advisors ----------
|
||||
socket.on("rr-get-advisors", async (args = {}, ack) => {
|
||||
try {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-get-advisors: begin", { args });
|
||||
const res = await rrGetAdvisors(bodyshop, args);
|
||||
ack?.({ ok: true, result: res });
|
||||
socket.emit("rr-get-advisors:result", res);
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-get-advisors: success", {
|
||||
count: Array.isArray(res) ? res.length : undefined
|
||||
});
|
||||
} catch (err) {
|
||||
log("error", err?.message || "get advisors failed", { err });
|
||||
CreateRRLogEvent(socket, "ERROR", "rr-get-advisors: failed", { error: err?.message });
|
||||
ack?.({ ok: false, error: err?.message || "get advisors failed" });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Parts ---------
|
||||
// ---------- Parts ----------
|
||||
socket.on("rr-get-parts", async (args = {}, ack) => {
|
||||
try {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-get-parts: begin", { args });
|
||||
const res = await rrGetParts(bodyshop, args);
|
||||
ack?.({ ok: true, result: res });
|
||||
socket.emit("rr-get-parts:result", res);
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-get-parts: success", {
|
||||
count: Array.isArray(res) ? res.length : undefined
|
||||
});
|
||||
} catch (err) {
|
||||
log("error", err?.message || "get parts failed", { err });
|
||||
CreateRRLogEvent(socket, "ERROR", "rr-get-parts: failed", { error: err?.message });
|
||||
ack?.({ ok: false, error: err?.message || "get parts failed" });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Persist customer selection / create-intent (table-first UX) ---------
|
||||
socket.on("rr-selected-customer", async ({ jobId, custNo, create } = {}, ack) => {
|
||||
const ns = getTransactionType(jobId || "unknown");
|
||||
// ================= Fortellis-style two-step export =================
|
||||
// 1) Stage export -> search -> emit rr-select-customer
|
||||
socket.on("rr-export-job", async ({ jobid, jobId, txEnvelope } = {}) => {
|
||||
const rid = resolveJobId(jobid || jobId, { jobId, jobid }, null);
|
||||
try {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
if (!jobId) throw new Error("jobId required");
|
||||
if (!rid) throw new Error("RR export: jobid required");
|
||||
CreateRRLogEvent(socket, "DEBUG", `{1} Received RR export request`, { jobid: rid });
|
||||
|
||||
// If caller passed a selection, just persist it.
|
||||
if (custNo && create !== true) {
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
getTransactionType(rid),
|
||||
RRCacheEnums.txEnvelope,
|
||||
txEnvelope || {},
|
||||
defaultRRTTL
|
||||
);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{1.1} Cached txEnvelope`, { hasTxEnvelope: !!txEnvelope });
|
||||
|
||||
const job = await QueryJobData({ redisHelpers }, rid);
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
getTransactionType(rid),
|
||||
RRCacheEnums.JobData,
|
||||
job,
|
||||
defaultRRTTL
|
||||
);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{1.2} Cached JobData`, { vin: job?.v_vin, ro: job?.ro_number });
|
||||
|
||||
const adv = readAdvisorNo(
|
||||
{ txEnvelope },
|
||||
await redisHelpers.getSessionTransactionData(socket.id, getTransactionType(rid), RRCacheEnums.AdvisorNo)
|
||||
);
|
||||
if (adv) {
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
String(custNo),
|
||||
getTransactionType(rid),
|
||||
RRCacheEnums.AdvisorNo,
|
||||
String(adv),
|
||||
defaultRRTTL
|
||||
);
|
||||
log("info", "rr-selected-customer", { jobId, custNo: String(custNo) });
|
||||
return ack?.({ ok: true });
|
||||
CreateRRLogEvent(socket, "DEBUG", `{1.3} Cached advisorNo`, { advisorNo: String(adv) });
|
||||
}
|
||||
|
||||
// No custNo (or create: true) => create immediately from JobData (Fortellis parity)
|
||||
const job = await QueryJobData({ redisHelpers }, jobId);
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
const newCustNo = String(
|
||||
created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey || ""
|
||||
);
|
||||
if (!newCustNo) throw new Error("RR create customer returned no custNo");
|
||||
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);
|
||||
|
||||
socket.emit("rr-select-customer", candidates);
|
||||
CreateRRLogEvent(socket, "DEBUG", `{2.1} Emitted rr-select-customer`, {
|
||||
count: candidates.length,
|
||||
anyVinOwner: candidates.some((c) => c.vinOwner)
|
||||
});
|
||||
} catch (error) {
|
||||
CreateRRLogEvent(socket, "ERROR", `Error during RR export (prepare)`, {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
jobid: rid
|
||||
});
|
||||
try {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId: rid, error: error.message });
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2) Selection (or create) -> export
|
||||
socket.on("rr-selected-customer", async ({ jobid, jobId, selectedCustomerId, custNo, create } = {}, ack) => {
|
||||
const rid = resolveJobId(jobid || jobId, { jobid, jobId }, null);
|
||||
try {
|
||||
if (!rid) throw new Error("jobid required");
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3} rr-selected-customer`, {
|
||||
jobid: rid,
|
||||
custNo,
|
||||
selectedCustomerId,
|
||||
create: !!create
|
||||
});
|
||||
|
||||
const ns = getTransactionType(rid);
|
||||
let selectedCustNo =
|
||||
(custNo && String(custNo)) ||
|
||||
(selectedCustomerId && String(selectedCustomerId)) ||
|
||||
(await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.SelectedCustomer));
|
||||
|
||||
const job = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.JobData);
|
||||
const txEnvelope = (await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.txEnvelope)) || {};
|
||||
if (!job) throw new Error("Staged JobData not found (run rr-export-job first).");
|
||||
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
|
||||
if (create === true || !selectedCustNo) {
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3.1} Creating RR customer`);
|
||||
const created = await createRRCustomer({ bodyshop, job, socket });
|
||||
selectedCustNo = String(
|
||||
created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey || ""
|
||||
);
|
||||
if (!selectedCustNo) throw new Error("RR create customer returned no custNo");
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3.2} Created customer`, { custNo: selectedCustNo });
|
||||
}
|
||||
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
newCustNo,
|
||||
String(selectedCustNo),
|
||||
defaultRRTTL
|
||||
);
|
||||
|
||||
log("info", "rr-create-customer:success", { jobId, custNo: newCustNo });
|
||||
return ack?.({ ok: true, custNo: newCustNo });
|
||||
} catch (err) {
|
||||
log("error", err?.message || "select/create customer failed", { err, jobId });
|
||||
return ack?.({ ok: false, error: err?.message || "select/create customer failed" });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Optional explicit create-customer (form) ---------
|
||||
socket.on("rr-create-customer", async ({ jobId, fields } = {}, ack) => {
|
||||
const ns = getTransactionType(jobId || "unknown");
|
||||
try {
|
||||
const { bodyshopId } = await getSessionOrSocket(redisHelpers, socket);
|
||||
const bodyshop = await getBodyshopForSocket({ bodyshopId, socket });
|
||||
|
||||
if (!jobId) throw new Error("jobId required");
|
||||
const job = await QueryJobData({ redisHelpers }, jobId);
|
||||
|
||||
const created = await createRRCustomer({ bodyshop, job, overrides: fields || {}, socket });
|
||||
const custNo = String(created?.custNo || created?.customerNo || created?.CustomerNo || created?.dmsRecKey || "");
|
||||
if (!custNo) throw new Error("RR create customer returned no custNo");
|
||||
|
||||
await redisHelpers.setSessionTransactionData(socket.id, ns, RRCacheEnums.SelectedCustomer, custNo, defaultRRTTL);
|
||||
await redisHelpers.setSessionTransactionData(socket.id, ns, "RR.CreateCustomerIntent", false, defaultRRTTL);
|
||||
|
||||
log("info", "rr-create-customer:success", { jobId, custNo });
|
||||
socket.emit("rr-customer-created", { custNo });
|
||||
ack?.({ ok: true, custNo });
|
||||
} catch (err) {
|
||||
log("error", err?.message || "create customer failed", { err, jobId });
|
||||
ack?.({ ok: false, error: err?.message || "create customer failed" });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Vehicle selection hooks (reserved for future parity) ---------
|
||||
socket.on("rr-selected-vehicle", async ({ jobId, vin } = {}, ack) => {
|
||||
const ns = getTransactionType(jobId || "unknown");
|
||||
try {
|
||||
await getSessionOrSocket(redisHelpers, socket);
|
||||
if (!vin) throw new Error("vin required");
|
||||
await redisHelpers.setSessionTransactionData(socket.id, ns, RRCacheEnums.SelectedVin, String(vin), defaultRRTTL);
|
||||
log("info", "rr-selected-vehicle", { jobId, vin: String(vin) });
|
||||
ack?.({ ok: true });
|
||||
} catch (err) {
|
||||
log("error", err?.message || "select vehicle failed", { err, jobId });
|
||||
ack?.({ ok: false, error: err?.message || "select vehicle failed" });
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("rr-create-vehicle", async ({ jobId, vehicle } = {}, ack) => {
|
||||
const ns = getTransactionType(jobId || "unknown");
|
||||
try {
|
||||
await getSessionOrSocket(redisHelpers, socket);
|
||||
if (!vehicle?.vin) throw new Error("vehicle.vin required");
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedVin,
|
||||
String(vehicle.vin),
|
||||
defaultRRTTL
|
||||
);
|
||||
log("info", "rr-create-vehicle", { jobId, vin: String(vehicle.vin) });
|
||||
ack?.({ ok: true });
|
||||
} catch (err) {
|
||||
log("error", err?.message || "create vehicle failed", { err, jobId });
|
||||
ack?.({ ok: false, error: err?.message || "create vehicle failed" });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Main export (Fortellis-style staging) ---------
|
||||
socket.on("rr-export-job", async (payload = {}) => {
|
||||
const _log = RRLogger(socket, { ns: "rr" });
|
||||
try {
|
||||
// (existing preamble unchanged)
|
||||
let job = payload.job || payload.txEnvelope?.job;
|
||||
const jobId = payload.jobId || payload.jobid || payload.txEnvelope?.jobId || job?.id;
|
||||
if (!job) {
|
||||
if (!jobId) throw new Error("RR export: job or jobId required");
|
||||
job = await QueryJobData({ redisHelpers }, jobId);
|
||||
}
|
||||
const ns = getTransactionType(job.id);
|
||||
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.txEnvelope,
|
||||
payload.txEnvelope || {},
|
||||
defaultRRTTL
|
||||
);
|
||||
await redisHelpers.setSessionTransactionData(socket.id, ns, RRCacheEnums.JobData, job, defaultRRTTL);
|
||||
|
||||
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");
|
||||
|
||||
const bodyshop =
|
||||
job?.bodyshop && (job.bodyshop.rr_dealerid || job.bodyshop.rr_configuration)
|
||||
? job.bodyshop
|
||||
: await getBodyshopForSocket({ bodyshopId, socket });
|
||||
CreateRRLogEvent(socket, "DEBUG", `{3.3} Cached selected customer`, { custNo: String(selectedCustNo) });
|
||||
|
||||
const cachedAdvisor = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.AdvisorNo);
|
||||
const advisorNo = readAdvisorNo(payload, cachedAdvisor);
|
||||
const advisorNo = readAdvisorNo({ txEnvelope }, cachedAdvisor);
|
||||
if (!advisorNo) {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId, error: "Advisor is required (advisorNo)." });
|
||||
return;
|
||||
CreateRRLogEvent(socket, "ERROR", `Advisor is required (advisorNo)`);
|
||||
socket.emit("export-failed", { vendor: "rr", jobId: rid, error: "Advisor is required (advisorNo)." });
|
||||
return ack?.({ ok: false, error: "Advisor is required (advisorNo)." });
|
||||
}
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
@@ -391,141 +348,29 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
defaultRRTTL
|
||||
);
|
||||
|
||||
let selectedCust = null;
|
||||
if (payload.selectedCustomer) {
|
||||
if (typeof payload.selectedCustomer === "object" && payload.selectedCustomer.custNo) {
|
||||
selectedCust = { custNo: String(payload.selectedCustomer.custNo) };
|
||||
} else if (typeof payload.selectedCustomer === "string" || typeof payload.selectedCustomer === "number") {
|
||||
selectedCust = { custNo: String(payload.selectedCustomer) };
|
||||
}
|
||||
if (selectedCust?.custNo) {
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
socket.id,
|
||||
ns,
|
||||
RRCacheEnums.SelectedCustomer,
|
||||
selectedCust.custNo,
|
||||
defaultRRTTL
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!selectedCust) {
|
||||
const cached = await redisHelpers.getSessionTransactionData(socket.id, ns, RRCacheEnums.SelectedCustomer);
|
||||
if (cached) selectedCust = { custNo: String(cached) };
|
||||
}
|
||||
|
||||
const forceCreate = payload.forceCreate === true;
|
||||
const autoCreateOnNoMatch = payload.autoCreateOnNoMatch !== false;
|
||||
|
||||
// --- MODIFIED: multi-search (name + vin) when beginning selection ---
|
||||
if (!selectedCust && !forceCreate) {
|
||||
const mergedCandidates = await rrMultiCustomerSearch(bodyshop, job);
|
||||
|
||||
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 (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;
|
||||
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(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()
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedCust?.custNo) throw new Error("RR export: selected customer missing custNo");
|
||||
|
||||
// (rest of existing export logic unchanged)
|
||||
CreateRRLogEvent(socket, "DEBUG", `{4} Performing RR export`);
|
||||
const result = await exportJobToRR({
|
||||
bodyshop,
|
||||
job,
|
||||
selectedCustomer: selectedCust,
|
||||
selectedCustomer: { custNo: String(selectedCustNo) },
|
||||
advisorNo: String(advisorNo),
|
||||
existing: payload.existing,
|
||||
existing: txEnvelope?.existing,
|
||||
socket
|
||||
});
|
||||
|
||||
if (result?.success) {
|
||||
socket.emit("export-success", { vendor: "rr", jobId, roStatus: result.roStatus });
|
||||
CreateRRLogEvent(socket, "DEBUG", `{5} Export success`, { roStatus: result.roStatus });
|
||||
socket.emit("export-success", { vendor: "rr", jobId: rid, roStatus: result.roStatus });
|
||||
ack?.({ ok: true, result });
|
||||
} else {
|
||||
CreateRRLogEvent(socket, "ERROR", `Export failed`, { roStatus: result?.roStatus, error: result?.error });
|
||||
socket.emit("export-failed", {
|
||||
vendor: "rr",
|
||||
jobId,
|
||||
jobId: rid,
|
||||
roStatus: result?.roStatus,
|
||||
error: result?.error || "RR export failed"
|
||||
});
|
||||
ack?.({ ok: false, error: result?.error || "RR export failed", result });
|
||||
}
|
||||
|
||||
await redisHelpers.setSessionTransactionData(
|
||||
@@ -535,24 +380,32 @@ function registerRREvents({ socket, redisHelpers }) {
|
||||
result || {},
|
||||
defaultRRTTL
|
||||
);
|
||||
socket.emit("rr-export-job:result", { jobId, bodyshopId, result });
|
||||
socket.emit("rr-export-job:result", { jobId: rid, bodyshopId, result });
|
||||
} catch (error) {
|
||||
const jobId = payload.jobId || payload.jobid || payload.txEnvelope?.jobId || payload?.job?.id;
|
||||
_log("error", `Error during RR export: ${error.message}`, { jobId, stack: error.stack });
|
||||
CreateRRLogEvent(socket, "ERROR", `Error during RR export (selected-customer)`, {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
jobid: rid
|
||||
});
|
||||
try {
|
||||
socket.emit("export-failed", { vendor: "rr", jobId, error: error.message });
|
||||
} catch {}
|
||||
socket.emit("export-failed", { vendor: "rr", jobId: rid, error: error.message });
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
ack?.({ ok: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// --------- Allocations (reuse CDK calculator) ---------
|
||||
// ---------- Allocations (parity) ----------
|
||||
socket.on("rr-calculate-allocations", async (jobid, cb) => {
|
||||
try {
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-calculate-allocations: begin", { jobid });
|
||||
const allocations = await CdkCalculateAllocations(socket, jobid);
|
||||
cb?.(allocations);
|
||||
socket.emit("rr-calculate-allocations:result", allocations);
|
||||
CreateRRLogEvent(socket, "DEBUG", "rr-calculate-allocations: success", { items: allocations?.length });
|
||||
} catch (e) {
|
||||
log("error", `RR allocations error: ${e.message}`, { jobid });
|
||||
CreateRRLogEvent(socket, "ERROR", "rr-calculate-allocations: failed", { error: e.message, jobid });
|
||||
cb?.({ ok: false, error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user