232 lines
6.4 KiB
JavaScript
232 lines
6.4 KiB
JavaScript
const { buildClientAndOpts, rrCombinedSearch } = require("./rr-lookup");
|
|
const CreateRRLogEvent = require("./rr-logger-event");
|
|
|
|
/**
|
|
* Pick and normalize VIN from inputs
|
|
* @param vin
|
|
* @param job
|
|
* @returns {string}
|
|
*/
|
|
const pickVin = ({ vin, job }) => {
|
|
const v = vin || job?.v_vin || job?.vehicle?.vin || job?.vin || job?.vehicleVin || null;
|
|
|
|
if (!v) return "";
|
|
return String(v)
|
|
.replace(/[^A-Za-z0-9]/g, "")
|
|
.toUpperCase()
|
|
.slice(0, 17);
|
|
};
|
|
|
|
/**
|
|
* Pick and normalize customer number from inputs
|
|
* @param selectedCustomerNo
|
|
* @param custNo
|
|
* @param customerNo
|
|
* @returns {string|string}
|
|
*/
|
|
const pickCustNo = ({ selectedCustomerNo, custNo, customerNo }) => {
|
|
const c = selectedCustomerNo ?? custNo ?? customerNo ?? null;
|
|
return c != null ? String(c).trim() : "";
|
|
};
|
|
|
|
/**
|
|
* Extract owner customer numbers from combined search results
|
|
* @param res
|
|
* @param wantedVin
|
|
* @returns {Set<any>}
|
|
*/
|
|
const ownersFromCombined = (res, wantedVin) => {
|
|
const blocks = Array.isArray(res?.data) ? res.data : [];
|
|
const owners = new Set();
|
|
for (const blk of blocks) {
|
|
const serv = Array.isArray(blk?.ServVehicle) ? blk.ServVehicle : [];
|
|
for (const sv of serv) {
|
|
const v = sv?.Vehicle || {};
|
|
const vin = (v?.Vin || v?.VIN || v?.vin || "").toString().toUpperCase();
|
|
const cust = sv?.VehicleServInfo?.CustomerNo;
|
|
if (vin && cust && (!wantedVin || vin === wantedVin)) {
|
|
owners.add(String(cust));
|
|
}
|
|
}
|
|
}
|
|
return owners;
|
|
};
|
|
|
|
/**
|
|
* Determine if error indicates "already exists"
|
|
* @param e
|
|
* @returns {boolean}
|
|
*/
|
|
const isAlreadyExistsError = (e) => {
|
|
if (!e) return false;
|
|
if (e.code === 300) return true;
|
|
const msg = (e.message || "").toUpperCase();
|
|
return msg.includes("ALREADY EXISTS") || msg.includes("VEHICLE ALREADY EXISTS");
|
|
};
|
|
|
|
/**
|
|
* Ensure/create a Service Vehicle in RR for the given VIN + customer.
|
|
* Args may contain:
|
|
* - client, routing (prebuilt) OR bodyshop (we'll build a client)
|
|
* - vin OR job (we'll derive vin from job)
|
|
* - selectedCustomerNo / custNo / customerNo
|
|
* - license (optional)
|
|
* - socket (for logging)
|
|
*
|
|
* Returns: { created:boolean, exists:boolean, vin, customerNo, svId?, status? }
|
|
*/
|
|
const ensureRRServiceVehicle = async (args = {}) => {
|
|
const {
|
|
client: inClient,
|
|
routing: inRouting,
|
|
bodyshop,
|
|
job,
|
|
vin,
|
|
selectedCustomerNo,
|
|
custNo,
|
|
customerNo,
|
|
license,
|
|
socket
|
|
} = args;
|
|
|
|
// Build/derive essentials
|
|
let client = inClient;
|
|
let routing = inRouting;
|
|
|
|
if (!client || !routing) {
|
|
if (!bodyshop) {
|
|
throw new Error("ensureRRServiceVehicle: either (client & routing) or bodyshop is required");
|
|
}
|
|
const built = buildClientAndOpts(bodyshop);
|
|
client = built.client;
|
|
routing = built.opts?.routing;
|
|
}
|
|
|
|
const vinStr = pickVin({ vin, job });
|
|
const custNoStr = pickCustNo({ selectedCustomerNo, custNo, customerNo });
|
|
|
|
if (!vinStr) throw new Error("ensureRRServiceVehicle: vin required");
|
|
if (!custNoStr) throw new Error("ensureRRServiceVehicle: customerNo required");
|
|
|
|
// --- Preflight: does VIN already exist (and under whom)? ---
|
|
try {
|
|
let owners = new Set();
|
|
if (bodyshop) {
|
|
const combinedSearchResponse = await rrCombinedSearch(bodyshop, { kind: "vin", vin: vinStr, maxResults: 50 });
|
|
|
|
CreateRRLogEvent(socket, "silly", "{SV} Preflight combined search by VIN: raw response", {
|
|
response: combinedSearchResponse
|
|
});
|
|
|
|
owners = ownersFromCombined(combinedSearchResponse, vinStr);
|
|
}
|
|
// Short-circuit: VIN exists anywhere -> don't try to insert
|
|
if (owners.size > 0) {
|
|
const ownedBySame = owners.has(custNoStr);
|
|
|
|
CreateRRLogEvent(socket, ownedBySame ? "info" : "warn", "{SV} VIN already present in RR; skipping insert", {
|
|
vin: vinStr,
|
|
selectedCustomerNo: custNoStr,
|
|
owners: Array.from(owners)
|
|
});
|
|
|
|
return {
|
|
created: false,
|
|
exists: true,
|
|
vin: vinStr,
|
|
customerNo: custNoStr,
|
|
ownedBySame
|
|
};
|
|
}
|
|
} catch (e) {
|
|
// Preflight shouldn't be fatal; log and continue to insert (idempotency will still be handled)
|
|
CreateRRLogEvent(socket, "WARN", "{SV} VIN preflight lookup failed; continuing to insert", {
|
|
vin: vinStr,
|
|
error: e?.message
|
|
});
|
|
}
|
|
|
|
// --- Attempt insert (idempotent) ---
|
|
// IMPORTANT: The current RR lib build validates `vehicleServInfo.customerNo`.
|
|
// To be future-proof, we also include top-level `customerNo`.
|
|
const insertPayload = {
|
|
vin: vinStr,
|
|
customerNo: custNoStr, // fallback form (some builds accept this)
|
|
vehicleServInfo: { customerNo: custNoStr }, // primary form expected by the lib
|
|
vehicleDetail: license ? { licNo: String(license).trim() } : undefined
|
|
};
|
|
|
|
const insertOpts = {
|
|
routing,
|
|
envelope: {
|
|
sender: {
|
|
component: "Rome",
|
|
task: "SV",
|
|
referenceId: "Insert",
|
|
creator: "RCI",
|
|
senderName: "RCI"
|
|
}
|
|
}
|
|
};
|
|
|
|
CreateRRLogEvent(socket, "info", "{SV} Inserting service vehicle", {
|
|
vin: vinStr,
|
|
selectedCustomerNo: custNoStr,
|
|
payloadShape: Object.keys(insertPayload).filter((k) => insertPayload[k] != null)
|
|
});
|
|
|
|
try {
|
|
const res = await client.insertServiceVehicle(insertPayload, insertOpts);
|
|
|
|
CreateRRLogEvent(socket, "silly", "{SV} insertServiceVehicle: raw response", { res });
|
|
|
|
const data = res?.data ?? {};
|
|
const svId = data?.dmsRecKey || data?.svId || undefined;
|
|
|
|
CreateRRLogEvent(socket, "info", "{SV} insertServiceVehicle: success", {
|
|
vin: vinStr,
|
|
customerNo: custNoStr,
|
|
svId
|
|
});
|
|
|
|
return {
|
|
created: true,
|
|
exists: false,
|
|
vin: vinStr,
|
|
customerNo: custNoStr,
|
|
svId,
|
|
status: res?.statusBlocks?.transaction
|
|
};
|
|
} catch (e) {
|
|
if (isAlreadyExistsError(e)) {
|
|
// Treat as idempotent success
|
|
CreateRRLogEvent(socket, "warn", "{SV} insertServiceVehicle: already exists; treating as success", {
|
|
vin: vinStr,
|
|
customerNo: custNoStr,
|
|
code: e?.code,
|
|
status: e?.meta?.status || e?.status
|
|
});
|
|
|
|
return {
|
|
created: false,
|
|
exists: true,
|
|
vin: vinStr,
|
|
customerNo: custNoStr,
|
|
status: e?.meta?.status || e?.status
|
|
};
|
|
}
|
|
|
|
CreateRRLogEvent(socket, "error", "{SV} insertServiceVehicle: failure", {
|
|
message: e?.message,
|
|
code: e?.code,
|
|
status: e?.meta?.status || e?.status
|
|
});
|
|
|
|
throw e;
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
ensureRRServiceVehicle
|
|
};
|