From a37d59b8268d2c79a3be0bc5e5c980866841a796 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Nov 2025 16:24:06 +0530 Subject: [PATCH] HS code validation added --- app/controllers/establishment.controller.js | 57 ++++++++++++++------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/app/controllers/establishment.controller.js b/app/controllers/establishment.controller.js index 780cb3e..a82dd37 100644 --- a/app/controllers/establishment.controller.js +++ b/app/controllers/establishment.controller.js @@ -977,13 +977,28 @@ exports.establishmentBulkUpload = async (req, res) => { emirateMap[e.name.trim().toLowerCase()] = e.id; }); - const products = await Product.findAll({ attributes: ["id", "hs_code"] }); - const productMap = {}; - products.forEach(p => { - const normalized = p.hs_code.replace(/[^0-9]/g, "").replace(/^0+/, ""); - productMap[normalized] = p.id; - }); + function normalizeHS(val) { + if (!val) return ""; + return val + .toString() + .normalize("NFKD") + .replace(/[^\d]/g, "") + .trim(); + } + + const products = await Product.findAll({ attributes: ["id", "hs_code"] }); + + const productMap = {}; + + products.forEach(p => { + const cleaned = normalizeHS(p.hs_code); + + // Only store valid HS codes 1–10 digits + if (cleaned.length >= 1 && cleaned.length <= 10) { + productMap[cleaned] = p.id; + } + }); const existingEsts = await Establishment.findAll({ attributes: ["establishment_code", "factory_name", "establishment_contact_email"] }); @@ -1121,22 +1136,26 @@ exports.establishmentBulkUpload = async (req, res) => { // DB-level HS Code validation const invalid = []; - for (const raw of hsRaw) { - const cleaned = raw.replace(/\D/g, ""); // remove non-numeric fast + for (const raw of hsRaw) { + const cleaned = normalizeHS(raw); - // Check 10-digit requirement + DB existence - if (cleaned.length !== 10 || !productMap[cleaned]) { - invalid.push(raw); // always push RAW value + if (cleaned.length < 1 || cleaned.length > 10) { + invalid.push(raw); + continue; + } + + if (!productMap[cleaned]) { + invalid.push(raw); + } } - } - if (invalid.length > 0) { - errors.push({ - row: rowNum, - error: `HS Code not found in database: ${invalid.join(", ")}` - }); - continue; - } + if (invalid.length > 0) { + errors.push({ + row: rowNum, + error: `HS Code not found in database: ${invalid.join(", ")}` + }); + continue; + } prepared.push({ est,