164 lines
5.9 KiB
JavaScript
164 lines
5.9 KiB
JavaScript
function carregarItensDoExcel(fileInputId) {
|
|
const fileInput = document.getElementById(fileInputId);
|
|
const file = fileInput ? fileInput.files[0] : null;
|
|
if (!file) {
|
|
FLUIGC.toast({ title: 'Erro', message: 'Nenhum arquivo selecionado.', type: 'danger' });
|
|
return;
|
|
}
|
|
if (typeof XLSX === "undefined") {
|
|
FLUIGC.toast({ title: 'Erro', message: 'Biblioteca XLSX nao carregada.', type: 'danger' });
|
|
return;
|
|
}
|
|
|
|
showExcelLoading();
|
|
|
|
const reader = new FileReader();
|
|
reader.onload = function (e) {
|
|
// Permite o navegador renderizar o overlay antes de processar.
|
|
setTimeout(function () {
|
|
try {
|
|
const data = new Uint8Array(e.target.result);
|
|
const workbook = XLSX.read(data, { type: 'array' });
|
|
const sheetName = workbook.SheetNames[0];
|
|
const sheet = workbook.Sheets[sheetName];
|
|
const linhas = XLSX.utils.sheet_to_json(sheet, { defval: "" });
|
|
|
|
// Limpa a tabela (sem usar form)
|
|
const indices = $("input[id^='codigoItem___']").map(function () {
|
|
return $(this).attr("id").split("___")[1];
|
|
}).get();
|
|
$.each(indices, function (_, idx) {
|
|
fnWdkRemoveChild(idx);
|
|
});
|
|
|
|
const linhasValidas = [];
|
|
$.each(linhas, function (_, item) {
|
|
const codigo = getCellByAliases(item, ["codigoItem", "codigo", "codItem", "sku", "code", "item"]);
|
|
const quantidade = getCellByAliases(item, ["quantidadeItem", "quantidade", "qtd", "qtde"]);
|
|
const descricao = getCellByAliases(item, ["descricao", "description", "desc"]);
|
|
|
|
if (!codigo || !quantidade) {
|
|
return;
|
|
}
|
|
|
|
linhasValidas.push({
|
|
codigo: String(codigo).trim(),
|
|
quantidade: String(quantidade).trim(),
|
|
descricao: String(descricao || "").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) {
|
|
const idx = wdkAddChild('tabelaItens');
|
|
const 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);
|
|
|
|
var descricaoFinal = item.descricao || buscarDescricaoProduto(item.codigo);
|
|
if (descricaoFinal) {
|
|
$(`#codigoItem___${idx}`).val(descricaoFinal);
|
|
}
|
|
});
|
|
|
|
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 buscarDescricaoProduto(codigo) {
|
|
try {
|
|
if (typeof DatasetFactory === "undefined" || typeof ConstraintType === "undefined") {
|
|
return "";
|
|
}
|
|
|
|
var codigoTxt = String(codigo || "").trim();
|
|
if (!codigoTxt) return "";
|
|
|
|
var cCodigo = DatasetFactory.createConstraint("Code", codigoTxt, codigoTxt, ConstraintType.MUST);
|
|
var ds = DatasetFactory.getDataset("ds_rgb_products", null, [cCodigo], null);
|
|
if (!ds || !ds.values || !ds.values.length) {
|
|
return "";
|
|
}
|
|
|
|
for (var i = 0; i < ds.values.length; i++) {
|
|
var row = ds.values[i] || {};
|
|
if (String(row.Code || "").trim() === codigoTxt) {
|
|
return String(row.descricao || row.Description || "").trim();
|
|
}
|
|
}
|
|
|
|
var first = ds.values[0] || {};
|
|
return String(first.descricao || first.Description || "").trim();
|
|
} catch (e) {
|
|
console.error("Erro ao buscar descricao por codigo:", e);
|
|
return "";
|
|
}
|
|
}
|
|
|
|
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";
|
|
}
|
|
}
|