72 lines
1.7 KiB
JavaScript
72 lines
1.7 KiB
JavaScript
/**
|
|
* Copyright (c) 2026 Niolla
|
|
* All rights reserved.
|
|
*
|
|
* This source code is proprietary and confidential.
|
|
* Unauthorized copying, modification, distribution, or use
|
|
* of this file, via any medium, is strictly prohibited.
|
|
*/
|
|
|
|
// app/utils/validation/validateSupplier.util.js
|
|
|
|
|
|
const db = require("../../models");
|
|
const Supplier = db.Vendor;
|
|
|
|
const extractCellValue = (value) => {
|
|
if (value && typeof value === "object") {
|
|
return value.text || value.result || "";
|
|
}
|
|
return value?.toString().trim() || "";
|
|
};
|
|
|
|
const validateSupplierColumn = async (worksheet, columns) => {
|
|
const supplierIdCol =
|
|
columns.findIndex((col) => col.column_name === "supplier_id") + 1;
|
|
|
|
if (!supplierIdCol) return;
|
|
|
|
const supplierIds = new Set();
|
|
const errors = [];
|
|
|
|
// 🔹 Extract values (ONLY collect non-empty)
|
|
for (let i = 2; i <= worksheet.rowCount; i++) {
|
|
let value = extractCellValue(
|
|
worksheet.getRow(i).getCell(supplierIdCol).value
|
|
);
|
|
|
|
if (value) {
|
|
supplierIds.add(value);
|
|
}
|
|
}
|
|
|
|
if (supplierIds.size === 0) return [];
|
|
|
|
// 🔹 Batch DB validation
|
|
const suppliers = await Supplier.findAll({
|
|
where: {
|
|
vendor_id: [...supplierIds],
|
|
},
|
|
});
|
|
|
|
const validIds = new Set(suppliers.map((s) => s.vendor_id));
|
|
|
|
// 🔹 Validate ONLY non-empty values
|
|
for (let i = 2; i <= worksheet.rowCount; i++) {
|
|
let value = extractCellValue(
|
|
worksheet.getRow(i).getCell(supplierIdCol).value
|
|
);
|
|
|
|
if (value && !validIds.has(value)) {
|
|
errors.push({
|
|
row: i,
|
|
column: "supplier_id",
|
|
message: `Invalid supplier ID: ${value}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
return errors;
|
|
};
|
|
|
|
module.exports = { validateSupplierColumn }; |