254 lines
8.6 KiB
JavaScript
254 lines
8.6 KiB
JavaScript
var xlsxLoader = {
|
|
loading: false,
|
|
callbacks: []
|
|
};
|
|
|
|
function carregarItensDoExcel(fileInputId) {
|
|
var fileInput = document.getElementById(fileInputId);
|
|
var file = fileInput ? fileInput.files[0] : null;
|
|
if (!file) {
|
|
FLUIGC.toast({ title: 'Erro', message: 'Nenhum arquivo selecionado.', type: 'danger' });
|
|
return;
|
|
}
|
|
|
|
showExcelLoading();
|
|
ensureXlsxLibrary(function (err) {
|
|
if (err) {
|
|
hideExcelLoading();
|
|
FLUIGC.toast({ title: 'Erro', message: 'Biblioteca XLSX indisponivel.', type: 'danger' });
|
|
console.error("Erro ao carregar XLSX:", err);
|
|
return;
|
|
}
|
|
|
|
processarArquivoExcel(file);
|
|
});
|
|
}
|
|
|
|
function ensureXlsxLibrary(callback) {
|
|
if (typeof XLSX !== "undefined") {
|
|
callback();
|
|
return;
|
|
}
|
|
|
|
xlsxLoader.callbacks.push(callback);
|
|
if (xlsxLoader.loading) {
|
|
return;
|
|
}
|
|
|
|
xlsxLoader.loading = true;
|
|
loadXlsxScript(0);
|
|
}
|
|
|
|
function loadXlsxScript(index) {
|
|
var urls = [
|
|
"/portal/resources/js/xlsx.full.min.js",
|
|
"https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"
|
|
];
|
|
|
|
if (index >= urls.length) {
|
|
flushXlsxCallbacks(new Error("Biblioteca XLSX nao encontrada."));
|
|
return;
|
|
}
|
|
|
|
$.getScript(urls[index])
|
|
.done(function () {
|
|
if (typeof XLSX === "undefined") {
|
|
loadXlsxScript(index + 1);
|
|
return;
|
|
}
|
|
flushXlsxCallbacks();
|
|
})
|
|
.fail(function () {
|
|
loadXlsxScript(index + 1);
|
|
});
|
|
}
|
|
|
|
function flushXlsxCallbacks(err) {
|
|
var callbacks = xlsxLoader.callbacks.splice(0, xlsxLoader.callbacks.length);
|
|
xlsxLoader.loading = false;
|
|
|
|
for (var i = 0; i < callbacks.length; i++) {
|
|
callbacks[i](err);
|
|
}
|
|
}
|
|
|
|
function processarArquivoExcel(file) {
|
|
var reader = new FileReader();
|
|
reader.onload = function (e) {
|
|
// Permite o navegador renderizar o overlay antes de processar.
|
|
setTimeout(function () {
|
|
try {
|
|
var data = new Uint8Array(e.target.result);
|
|
var workbook = XLSX.read(data, { type: 'array' });
|
|
var sheetName = workbook.SheetNames[0];
|
|
var sheet = workbook.Sheets[sheetName];
|
|
var linhas = XLSX.utils.sheet_to_json(sheet, { defval: "" });
|
|
|
|
// Limpa a tabela (sem usar form)
|
|
var indices = $("input[id^='codigoItem___']").map(function () {
|
|
return $(this).attr("id").split("___")[1];
|
|
}).get();
|
|
$.each(indices, function (_, idx) {
|
|
fnWdkRemoveChild(idx);
|
|
});
|
|
|
|
var linhasValidas = [];
|
|
$.each(linhas, function (_, item) {
|
|
var codigo = getCellByAliases(item, ["codigoItem", "codigo", "codItem", "sku", "code", "item"]);
|
|
var quantidade = getCellByAliases(item, ["quantidadeItem", "quantidade", "qtd", "qtde"]);
|
|
var descricao = getCellByAliases(item, ["descricao", "description", "desc"]);
|
|
var categoria = getCellByAliases(item, ["categoria", "category"]);
|
|
|
|
if (!codigo || !quantidade) {
|
|
return;
|
|
}
|
|
|
|
linhasValidas.push({
|
|
codigo: String(codigo).trim(),
|
|
quantidade: String(quantidade).trim(),
|
|
descricao: String(descricao || "").trim(),
|
|
categoria: String(categoria || "").trim()
|
|
});
|
|
});
|
|
|
|
if (!linhasValidas.length) {
|
|
FLUIGC.toast({
|
|
title: "Atencao",
|
|
message: "Nenhuma linha valida encontrada. Use colunas de codigo e quantidade.",
|
|
type: "warning"
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Adiciona os itens da planilha
|
|
$.each(linhasValidas, function (_, item) {
|
|
var idx = wdkAddChild('tabelaItens');
|
|
var zoomObj = window["descricao___" + idx];
|
|
if (zoomObj && typeof zoomObj.setValue === "function") {
|
|
zoomObj.setValue(item.codigo);
|
|
} else {
|
|
// Fallback visual caso o objeto zoom ainda nao esteja pronto no momento.
|
|
$("#descricao___" + idx).val(item.codigo);
|
|
}
|
|
|
|
$("#quantidadeItem___" + idx).val(item.quantidade);
|
|
$("#codigoProdutoItem___" + idx).val(item.codigo);
|
|
|
|
var produtoInfo = buscarProdutoPorCodigo(item.codigo);
|
|
if (produtoInfo.id) {
|
|
$("#productIdItem___" + idx).val(produtoInfo.id);
|
|
}
|
|
|
|
var descricaoFinal = item.descricao || produtoInfo.descricao;
|
|
if (descricaoFinal) {
|
|
$("#codigoItem___" + idx).val(descricaoFinal);
|
|
}
|
|
|
|
var categoriaFinal = item.categoria || produtoInfo.categoria;
|
|
if (categoriaFinal) {
|
|
$("#categoriaItem___" + idx).val(categoriaFinal);
|
|
}
|
|
});
|
|
|
|
if (typeof processarConferenciaNfe === "function") {
|
|
processarConferenciaNfe();
|
|
}
|
|
|
|
FLUIGC.toast({ title: 'Sucesso', message: linhasValidas.length + ' itens carregados com sucesso!', type: 'success' });
|
|
} catch (err) {
|
|
FLUIGC.toast({ title: 'Erro', message: 'Falha ao processar Excel: ' + err.message, type: 'danger' });
|
|
console.error("Erro em carregarItensDoExcel:", err);
|
|
} finally {
|
|
hideExcelLoading();
|
|
}
|
|
}, 30);
|
|
};
|
|
|
|
reader.onerror = function () {
|
|
FLUIGC.toast({ title: 'Erro', message: 'Nao foi possivel ler o arquivo Excel.', type: 'danger' });
|
|
hideExcelLoading();
|
|
};
|
|
|
|
reader.readAsArrayBuffer(file);
|
|
}
|
|
|
|
function getCellByAliases(row, aliases) {
|
|
if (!row) return "";
|
|
const keys = Object.keys(row);
|
|
for (let i = 0; i < aliases.length; i++) {
|
|
const alias = normalizeHeader(aliases[i]);
|
|
for (let k = 0; k < keys.length; k++) {
|
|
const originalKey = keys[k];
|
|
if (normalizeHeader(originalKey) === alias) {
|
|
return row[originalKey];
|
|
}
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function normalizeHeader(text) {
|
|
return String(text || "")
|
|
.normalize("NFD")
|
|
.replace(/[\u0300-\u036f]/g, "")
|
|
.replace(/\s+/g, "")
|
|
.replace(/[^a-zA-Z0-9]/g, "")
|
|
.toLowerCase();
|
|
}
|
|
|
|
function buscarProdutoPorCodigo(codigo) {
|
|
try {
|
|
if (typeof DatasetFactory === "undefined" || typeof ConstraintType === "undefined") {
|
|
return { descricao: "", id: "", categoria: "" };
|
|
}
|
|
|
|
var codigoTxt = String(codigo || "").trim();
|
|
if (!codigoTxt) return { descricao: "", id: "", categoria: "" };
|
|
|
|
var cCodigo = DatasetFactory.createConstraint("Code", codigoTxt, codigoTxt, ConstraintType.MUST);
|
|
var ds = DatasetFactory.getDataset("ds_rgb_products_v2", null, [cCodigo], null);
|
|
if (!ds || !ds.values || !ds.values.length) {
|
|
return { descricao: "", id: "", categoria: "" };
|
|
}
|
|
|
|
for (var i = 0; i < ds.values.length; i++) {
|
|
var row = ds.values[i] || {};
|
|
if (String(row.Code || "").trim() === codigoTxt) {
|
|
return {
|
|
descricao: String(row.descricao || row.Description || "").trim(),
|
|
id: String(row.id || "").trim(),
|
|
categoria: String(row.categoria || row.strategicDescription || "").trim()
|
|
};
|
|
}
|
|
}
|
|
|
|
var first = ds.values[0] || {};
|
|
return {
|
|
descricao: String(first.descricao || first.Description || "").trim(),
|
|
id: String(first.id || "").trim(),
|
|
categoria: String(first.categoria || first.strategicDescription || "").trim()
|
|
};
|
|
} catch (e) {
|
|
console.error("Erro ao buscar descricao por codigo:", e);
|
|
return { descricao: "", id: "", categoria: "" };
|
|
}
|
|
}
|
|
|
|
function buscarDescricaoProduto(codigo) {
|
|
return buscarProdutoPorCodigo(codigo).descricao;
|
|
}
|
|
|
|
function showExcelLoading() {
|
|
var overlay = document.getElementById("excelLoadingOverlay");
|
|
if (overlay) {
|
|
overlay.style.display = "flex";
|
|
}
|
|
}
|
|
|
|
function hideExcelLoading() {
|
|
var overlay = document.getElementById("excelLoadingOverlay");
|
|
if (overlay) {
|
|
overlay.style.display = "none";
|
|
}
|
|
}
|