64 lines
1.9 KiB
JavaScript
64 lines
1.9 KiB
JavaScript
/**
|
|
* Loads per-bodyshop RR routing from Hasura.
|
|
* Expected table fields (adapt if your schema differs):
|
|
* - bodyshops.id = $bodyshopId
|
|
* - bodyshops.rr_dealerid (string)
|
|
* - bodyshops.rr_configuration JSON { storeNumber?, branchNumber? }
|
|
*
|
|
* Requires env:
|
|
* HASURA_GRAPHQL_ENDPOINT, HASURA_ADMIN_SECRET
|
|
*/
|
|
const { GraphQLClient, gql } = require("graphql-request");
|
|
|
|
const HASURA_URL = process.env.HASURA_GRAPHQL_ENDPOINT || process.env.HASURA_URL;
|
|
const HASURA_SECRET = process.env.HASURA_ADMIN_SECRET || process.env.HASURA_GRAPHQL_ADMIN_SECRET;
|
|
|
|
if (!HASURA_URL || !HASURA_SECRET) {
|
|
// Warn loudly at startup; you can hard fail if you prefer
|
|
console.warn("[RR] HASURA env not set (HASURA_GRAPHQL_ENDPOINT / HASURA_ADMIN_SECRET).");
|
|
}
|
|
|
|
const client = HASURA_URL
|
|
? new GraphQLClient(HASURA_URL, {
|
|
headers: { "x-hasura-admin-secret": HASURA_SECRET }
|
|
})
|
|
: null;
|
|
|
|
const Q_BODYSHOP_RR = gql`
|
|
query RR_Config($id: uuid!) {
|
|
bodyshops_by_pk(id: $id) {
|
|
id
|
|
rr_dealerid
|
|
rr_configuration
|
|
}
|
|
}
|
|
`;
|
|
|
|
/**
|
|
* @param {string} bodyshopId
|
|
* @returns {Promise<{dealerNumber:string, storeNumber?:string, areaNumber?:string}>}
|
|
*/
|
|
async function getRRConfigForBodyshop(bodyshopId) {
|
|
if (!client) throw new Error("Hasura client not configured.");
|
|
|
|
const data = await client.request(Q_BODYSHOP_RR, { id: bodyshopId });
|
|
const row = data?.bodyshops_by_pk;
|
|
if (!row) throw new Error(`Bodyshop not found: ${bodyshopId}`);
|
|
|
|
const dealerNumber = row.rr_dealerid;
|
|
|
|
const cfg = row.rr_configuration || {};
|
|
|
|
if (!dealerNumber) {
|
|
throw new Error(`RR not configured for bodyshop ${bodyshopId} (missing rr_dealerid).`);
|
|
}
|
|
|
|
// The RR client expects "areaNumber" (Rome "branch")
|
|
const storeNumber = cfg.storeNumber || cfg.store_no || cfg.store || null;
|
|
const areaNumber = cfg.branchNumber || cfg.branch_no || cfg.branch || null;
|
|
|
|
return { dealerNumber, storeNumber, areaNumber };
|
|
}
|
|
|
|
module.exports = { getRRConfigForBodyshop };
|