2026-03-27 08:13:35 -03:00

1983 lines
70 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

$(document).ready(function () {
// Quando clicar em "Adicionar arquivo"
$('#btnAdicionarExcel').on('click', function () {
$('#excelUpload').click(); // aciona o input escondido
});
// Quando um arquivo for selecionado
$('#excelUpload').on('change', function () {
const file = this.files[0];
if (file) {
$('#nomeArquivoExcel').text('Arquivo selecionado: ' + file.name);
$('#btnAdicionarExcel').hide();
$('#btnRemoverExcel').show();
carregarItensDoExcel('excelUpload'); // chama sua função
}
});
// Quando clicar em "Remover arquivo"
$('#btnRemoverExcel').on('click', function () {
$('#excelUpload').val('');
$('#nomeArquivoExcel').text('Nenhum arquivo selecionado');
$('#btnAdicionarExcel').show();
$('#btnRemoverExcel').hide();
});
$('#chaveNfe').on('input', function () {
var key = normalizeNfeKey($(this).val());
$(this).val(key);
clearNfeConsultaFields();
setNfeFeedback("", "hidden");
});
$('#btnConsultarChaveNfe').on('click', function () {
consultarChaveNfe();
});
$(document).on("change", "input[name='tipoMotoristaEntrega']", function () {
applyMotoristaEntregaMode($(this).val(), false);
});
$(document).on("change", "#motoristaEntregaSelecionado", function () {
applySelectedMotoristaEntregaOption();
});
$(document).on("input", "input[name^='quantidadeItem___']", function () {
processarConferenciaNfe();
});
var activity = String($("#activity").val() || "");
applyTransferStatus(activity);
if ($("#formMode").val() == "VIEW") {
showAndBlock(["all"]);
$("#btnConsultarChaveNfe").prop("disabled", true).hide();
updateConferenciaNfeVisibility(activity);
} else {
//show the right fields
var requestDate = getCurrentDate();
if (String(activity) !== "6") {
$("#btnConsultarChaveNfe").prop("disabled", true).hide();
}
$(".activity").hide();
$(".activity-" + activity).show();
if (activity == 0 || activity == 1) {
//primeira atividade
//$("#dataAbertura").val(requestDate[0] + " - " + requestDate[1]);
$("#dataAbertura").val(requestDate[0]);
// add_new_row("tabelaItens");
} else if (activity == 4) {
showAndBlock([0]);
$("#userValidacaoGestor").val($("#currentUserName").val());
$("#dataValidacaoGestor").val(
requestDate[0] + " - " + requestDate[1]
);
updt_line();
} else if (activity == 6) {
showAndBlock([0, 4]);
if ($("#usuarioEmissorNfe").val() == "") {
$("#usuarioEmissorNfe").val($("#currentUserName").val());
}
if ($("#dataEmissaoNfe").val() == "") {
$("#dataEmissaoNfe").val(
requestDate[0] + " - " + requestDate[1]
);
}
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
}
updt_line();
} else if (activity == 57) {
$("#userCotacaoGestor").val($("#currentUserName").val());
$("#dataAprovCompras").val(
requestDate[0] + " - " + requestDate[1]
);
$("#blocoTipoMotoristaEntrega, #blocoOutroMotoristaEntrega").hide();
$("input[name='tipoMotoristaEntrega']").prop("disabled", true);
$("#motoristaEntregaSelecionado").prop("disabled", true);
showAndBlock([0, 4, 6]);
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
}
if ($("#justificativaDecisaoCompras").val() == "") {
$(".justificativa-activity-6").hide();
}
updt_line();
} else if (activity == 31) {
$("#userRealizacaoCompras").val($("#currentUserName").val());
$("#dataRealizacaoCompras").val(
requestDate[0] + " - " + requestDate[1]
);
if ($("#motoristaColetaNome").val() == "") {
$("#motoristaColetaNome").val($("#currentUserName").val());
}
if ($("#motoristaColetaLogin").val() == "") {
$("#motoristaColetaLogin").val($("#currentUserId").val());
}
if ($("#dataColeta").val() == "") {
$("#dataColeta").val(requestDate[0] + " " + requestDate[1]);
}
initMotoristaEntregaEscolha();
$("#blocoTipoMotoristaEntrega").show();
$("input[name='tipoMotoristaEntrega']").prop("disabled", false);
$("#motoristaEntregaSelecionado").prop("disabled", false);
// Mantem apenas etapas anteriores bloqueadas; card de coleta e entrega estao separados.
showAndBlock([0, 4, 6]);
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
}
if ($("#justificativaDecisaoCompras").val() == "") {
$(".justificativa-activity-6").hide();
}
updt_line();
} else if (activity == 18) {
var campoJustificativaProblema = $("#justificativaValidaProblema");
if (campoJustificativaProblema.length && campoJustificativaProblema.val() != "") {
showAndBlock([0, 4, 6, 24, 31, 57]);
} else {
showAndBlock([0, 4, 6, 31, 57]);
}
$("#userValidacaoItens").val($("#currentUserName").val());
$("#dataValidacaoItens").val(requestDate[0] + " - " + requestDate[1]);
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
}
if ($("#justificativaDecisaoCompras").val() == "") {
$(".justificativa-activity-6").hide();
}
if ($("#consideracoesCompras").val() == "") {
$(".justificativa-activity-31").hide();
}
$("input[name=validacaoItens]").on("change", function () {
$(".justificativaDecisaoItens").hide();
var validacaoItensSelecionada = $("input[name=validacaoItens]:checked").val();
if (
validacaoItensSelecionada == "divergencia" ||
validacaoItensSelecionada == "incorreto" ||
validacaoItensSelecionada == "naoEntregue"
) {
$(".justificativaDecisaoItens").show();
}
});
$("input[name=validacaoItens]").trigger("change");
updt_line();
} else if (activity == 24) {
showAndBlock([0, 4, 6, 31, 18]);
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
}
if ($("#justificativaDecisaoCompras").val() == "") {
$(".justificativa-activity-6").hide();
}
if ($("#consideracoesCompras").val() == "") {
$(".justificativa-activity-31").hide();
}
updt_line();
}
updateConferenciaNfeVisibility(activity);
}
formatarMoedasTabela("preco___");
//formatarMoedasTabela("precoIndica___");
formatarMoedasTabela("ValorTotal");
displayBtnFiles();
invisibleBtnUpload("fnAnexo_Nfe");
invisibleBtnUpload("fdAnexo_Coleta");
invisibleBtnUpload("fdAnexo_Entrega");
invisibleBtnUpload("fdAnexo_recebimento");
initAttachmentPlugins();
processarConferenciaNfe();
// gerarTabelaCotacaoIndica("tabelaCotacaoIndica", "tabelaItens");
});
function applyTransferStatus(activity) {
var current = String(activity || "");
var pills = $("#transferStatus .status-pill");
if (!pills.length) return;
pills.removeClass("is-active is-done");
var activeOrder = -1;
pills.each(function () {
var pill = $(this);
var activities = String(pill.attr("data-activities") || "").split(",");
for (var i = 0; i < activities.length; i++) {
if ($.trim(activities[i]) === current) {
pill.addClass("is-active");
var order = parseInt(pill.attr("data-order"), 10);
if (!isNaN(order)) {
activeOrder = order;
}
break;
}
}
});
if (activeOrder < 0) return;
pills.each(function () {
var pill = $(this);
var order = parseInt(pill.attr("data-order"), 10);
if (!isNaN(order) && order < activeOrder) {
pill.addClass("is-done");
}
});
}
function resolveFormModeFallback() {
var mode = ($("#formMode").val() || "").toUpperCase();
if (mode) return mode;
try {
if (window.parent && window.parent.WCMAPI && typeof window.parent.WCMAPI.getFormMode === "function") {
return String(window.parent.WCMAPI.getFormMode() || "").toUpperCase();
}
} catch (e) {}
return "ADD";
}
if (typeof window.getFormMode !== "function") {
window.getFormMode = resolveFormModeFallback;
}
function formatarMoedasTabela(ids) {
$(document).on('input', `[id^="${ids}"]`, function() {
let valor = $(this).val();
// Remove tudo que não for número
valor = valor.replace(/\D/g, '');
// Converte para número decimal
let numero = parseFloat(valor) / 100;
// Formata para Real Brasileiro
if (!isNaN(numero)) {
valor = numero.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
// Atualiza o campo com a formatação correta
$(this).val(valor);
    });
}
//show the activity and then block the fields
function showAndBlock(activity) {
for (var i = 0, l = activity.length; i < l; i++) {
$(".activity-" + activity[i]).show();
$(".hideButton").hide();
$(".activity-" + activity[i] + " :input").each(function () {
$(this).attr("readonly", "readonly");
$(this)
.css("background-color", "#eee")
.children("option:not(:selected)")
.prop("disabled", true);
$(this).on("mousedown", function (e) {
this.blur();
window.focus();
});
if ($(this).is(":checkbox")) {
$(this).attr("disabled", true);
} else if ($(this).is(":radio")) {
$(this).on("click", function () {
return false;
});
}
});
}
}
function getCurrentDate() {
var newDate = new Date();
var h = newDate.getHours();
if (h < 10) {
h = "0" + h;
}
var m = newDate.getMinutes();
if (m < 10) {
m = "0" + m;
}
var hour = h + ":" + m; // + ":" + s;
var day = newDate.getDate();
if (day < 10) {
day = "0" + day;
}
var month = newDate.getMonth() + 1;
if (month < 10) {
month = "0" + month;
}
newDate = day + "/" + month + "/" + newDate.getFullYear();
var currentDate = [newDate, hour];
return currentDate;
}
function initMotoristaEntregaEscolha() {
var escolha = String($("input[name='tipoMotoristaEntrega']:checked").val() || "");
if (!escolha) {
var coletaLogin = String($("#motoristaColetaLogin").val() || "").trim();
var entregaLogin = String($("#motoristaEntregaLogin").val() || "").trim();
if (entregaLogin && coletaLogin && entregaLogin !== coletaLogin) {
escolha = "outro";
} else {
escolha = $("#motoristaColetaNome").val() ? "mesmo" : "outro";
}
$("input[name='tipoMotoristaEntrega'][value='" + escolha + "']").prop("checked", true);
}
applyMotoristaEntregaMode(escolha, true);
}
function applyMotoristaEntregaMode(mode, keepValues) {
var escolha = String(mode || "");
var blocoOutro = $("#blocoOutroMotoristaEntrega");
if (!blocoOutro.length) return;
if (escolha === "outro") {
blocoOutro.show();
loadMotoristasEntregaSelect(false);
if (!keepValues) {
$("#motoristaEntregaNome").val("");
$("#motoristaEntregaLogin").val("");
clearZoomField("motoristaEntregaSelecionado");
} else {
syncMotoristaEntregaSelectFromHidden();
}
return;
}
blocoOutro.hide();
if (escolha === "mesmo") {
var coletaNome = String($("#motoristaColetaNome").val() || "").trim();
var coletaLogin = String($("#motoristaColetaLogin").val() || "").trim();
if (coletaNome) $("#motoristaEntregaNome").val(coletaNome);
if (coletaLogin) $("#motoristaEntregaLogin").val(coletaLogin);
}
}
function clearZoomField(fieldId) {
try {
if (window[fieldId] && typeof window[fieldId].clear === "function") {
window[fieldId].clear();
}
} catch (e) {}
try {
if (window[fieldId] && typeof window[fieldId].setValue === "function") {
window[fieldId].setValue("");
}
} catch (e2) {}
$("#" + fieldId).val("");
}
var MOTORISTAS_GROUP_DEFAULT_ID = "Motoristas";
var MOTORISTAS_GROUP_BY_UF = {
AL: "motoristaAL",
BA: "motoristaBA",
SE: "motoristaSE"
};
var motoristasEntregaCacheByGroup = {};
var motoristasEntregaLoadingByGroup = {};
var motoristaEntregaGroupAtual = "";
function normalizeUfCode(value) {
return String(value || "").toUpperCase().replace(/[^A-Z]/g, "").substring(0, 2);
}
function resolveMotoristasGroupIdByUf(uf) {
var ufCode = normalizeUfCode(uf);
if (!ufCode) {
return MOTORISTAS_GROUP_DEFAULT_ID;
}
if (MOTORISTAS_GROUP_BY_UF[ufCode]) {
return String(MOTORISTAS_GROUP_BY_UF[ufCode] || "").trim() || MOTORISTAS_GROUP_DEFAULT_ID;
}
// Convencao para facilitar novos estados sem precisar alterar o JS.
return "motorista" + ufCode;
}
function getMotoristasEntregaQueryContext() {
var uf = normalizeUfCode($("#ufDestino").val());
var groupId = resolveMotoristasGroupIdByUf(uf);
return {
uf: uf,
groupId: groupId,
cacheKey: groupId
};
}
function loadMotoristasEntregaSelect(forceReload) {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
var context = getMotoristasEntregaQueryContext();
var cacheKey = context.cacheKey;
motoristaEntregaGroupAtual = context.groupId;
if (!forceReload && Object.prototype.hasOwnProperty.call(motoristasEntregaCacheByGroup, cacheKey)) {
renderMotoristasEntregaOptions(motoristasEntregaCacheByGroup[cacheKey], context);
return;
}
if (motoristasEntregaLoadingByGroup[cacheKey]) return;
motoristasEntregaLoadingByGroup[cacheKey] = true;
select.prop("disabled", true);
var requestPayload = {
name: "ds_motoristas_grupo",
fields: null,
constraints: [{
_field: "GROUP_ID",
_initialValue: context.groupId,
_finalValue: context.groupId,
_type: 1
}],
order: null
};
$.ajax({
type: "POST",
url: "/api/public/ecm/dataset/datasets/",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(requestPayload)
}).done(function (response) {
var values = ((((response || {}).content || {}).values) || []);
var rows = normalizeMotoristasEntregaRows(values);
motoristasEntregaCacheByGroup[cacheKey] = rows;
if (motoristaEntregaGroupAtual === context.groupId) {
renderMotoristasEntregaOptions(rows, context);
}
}).fail(function (xhr) {
console.error("Falha ao carregar motoristas do dataset (" + context.groupId + "):", xhr);
motoristasEntregaCacheByGroup[cacheKey] = [];
if (motoristaEntregaGroupAtual === context.groupId) {
renderMotoristasEntregaOptions([], context);
}
}).always(function () {
motoristasEntregaLoadingByGroup[cacheKey] = false;
if (motoristaEntregaGroupAtual === context.groupId) {
select.prop("disabled", false);
}
});
}
function normalizeMotoristasEntregaRows(values) {
var out = [];
var map = {};
for (var i = 0; i < values.length; i++) {
var row = values[i] || {};
var colleagueId = String(row.COLLEAGUE_ID || row.colleagueId || row.colleagueid || "").trim();
if (!colleagueId) continue;
if (map[colleagueId]) continue;
map[colleagueId] = true;
out.push({
COLLEAGUE_ID: colleagueId,
NOME: String(row.NOME || row.colleagueName || row.nome || "").trim(),
LOGIN: String(row.LOGIN || row.login || "").trim(),
EMAIL: String(row.EMAIL || row.mail || row.email || "").trim()
});
}
out.sort(function (a, b) {
var aNome = (a.NOME || a.LOGIN || a.COLLEAGUE_ID).toLowerCase();
var bNome = (b.NOME || b.LOGIN || b.COLLEAGUE_ID).toLowerCase();
return aNome < bNome ? -1 : (aNome > bNome ? 1 : 0);
});
return out;
}
function renderMotoristasEntregaOptions(rows, context) {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
var selectedValue = String($("#motoristaEntregaLogin").val() || select.val() || "").trim();
var placeholder = "Selecione o motorista";
if (context && context.uf) {
placeholder = "Selecione o motorista da UF " + context.uf;
}
if ((rows || []).length === 0 && context && context.uf) {
placeholder = "Sem motoristas cadastrados para UF " + context.uf;
}
select.empty();
select.append($("<option></option>").val("").text(placeholder));
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var nome = String(row.NOME || row.LOGIN || row.COLLEAGUE_ID);
var label = row.LOGIN ? (nome + " (" + row.LOGIN + ")") : nome;
var option = $("<option></option>")
.val(row.COLLEAGUE_ID)
.text(label)
.attr("data-nome", nome)
.attr("data-login", String(row.LOGIN || ""));
select.append(option);
}
if (selectedValue) {
select.val(selectedValue);
}
if (!select.val()) {
// Limpa selecao visual quando o valor salvo nao existe mais no dataset.
select.val("");
}
applySelectedMotoristaEntregaOption();
}
function refreshMotoristasEntregaByUf(forceReload) {
var escolha = String($("input[name='tipoMotoristaEntrega']:checked").val() || "");
if (escolha !== "outro") return;
loadMotoristasEntregaSelect(forceReload === true);
}
function syncMotoristaEntregaSelectFromHidden() {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
var storedId = String($("#motoristaEntregaLogin").val() || "").trim();
if (!storedId) {
select.val("");
return;
}
select.val(storedId);
if (select.val()) {
applySelectedMotoristaEntregaOption();
}
}
function applySelectedMotoristaEntregaOption() {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
var selectedId = String(select.val() || "").trim();
if (!selectedId) {
if (String($("input[name='tipoMotoristaEntrega']:checked").val() || "") === "outro") {
$("#motoristaEntregaNome").val("");
$("#motoristaEntregaLogin").val("");
}
return;
}
var option = select.find("option:selected");
var nome = String(option.attr("data-nome") || option.text() || "").trim();
$("#motoristaEntregaLogin").val(selectedId);
$("#motoristaEntregaNome").val(nome);
$("#tipoMotoristaEntregaOutro").prop("checked", true);
}
function updateConferenciaNfeVisibility(activity) {
var activityValue = String(activity || $("#activity").val() || "");
var exibirConferencia = (activityValue === "6" || activityValue === "18");
$("#blocoConferenciaNfe").toggle(exibirConferencia);
// Na emissao (6), mostra apenas a tabela de conferencia.
// Os campos de validacao de recebimento ficam apenas na atividade 18.
var showOnlyConferencia = (activityValue === "6");
$("input[name='validacaoItens']").closest(".row").toggle(!showOnlyConferencia);
$("#fdAnexo_recebimento").closest(".row").toggle(!showOnlyConferencia);
$(".justificativaDecisaoItens").toggle(!showOnlyConferencia);
}
var ATTACHMENT_PLUGIN_CONFIG = {
fnAnexo_Nfe: {
filename: "Nota Fiscal",
accept: ".pdf,.xml,image/*"
},
fdAnexo_Coleta: {
filename: "Comprovante de Coleta",
accept: ".pdf,image/*"
},
fdAnexo_Entrega: {
filename: "Comprovante de Entrega",
accept: ".pdf,image/*"
},
fdAnexo_recebimento: {
filename: "Comprovante de Recebimento",
accept: ".pdf,image/*"
}
};
function initAttachmentPlugins() {
var mode = getFormMode();
var allowedInputs = getAllowedAttachmentInputs();
var hasPlugin = typeof $.fn.fluigFormAttachment === "function";
if (!hasPlugin) {
console.warn("fluigFormAttachment.js nao carregado; campos de anexo sem botoes de upload.");
return;
}
Object.keys(ATTACHMENT_PLUGIN_CONFIG).forEach(function (inputId) {
var cfg = ATTACHMENT_PLUGIN_CONFIG[inputId];
var input = $("#" + inputId);
if (!input.length) return;
var dynamicFilename = resolveAttachmentFilename(inputId, cfg.filename);
var canUploadHere = (mode !== "VIEW" && allowedInputs.indexOf(inputId) >= 0);
try {
if (!input.data("fluigFormAttachment")) {
input.fluigFormAttachment({
filename: dynamicFilename,
accept: cfg.accept,
showActionButton: canUploadHere
});
} else {
input.fluigFormAttachment("filename", dynamicFilename);
}
if (canUploadHere) {
input.fluigFormAttachment("showActionButton");
} else {
input.fluigFormAttachment("hideActionButton");
}
} catch (e) {
console.error("Falha ao inicializar anexo '" + inputId + "':", e);
}
});
}
function resolveAttachmentFilename(inputId, fallback) {
if (inputId !== "fnAnexo_Nfe") return fallback;
var solicitacao = String($("#WKNumProces").val() || "").trim();
if (!solicitacao) return "Nota Fiscal";
return "Nota Fiscal - " + solicitacao;
}
function normalizeNfeKey(value) {
return String(value == null ? "" : value).replace(/\D/g, "").substring(0, 44);
}
function clearNfeConsultaFields() {
$("#numeroNfeConsulta").val("");
$("#serieNfeConsulta").val("");
$("#dataEmissaoApiNfe").val("");
$("#situacaoNfeConsulta").val("");
$("#fornecedorNfeConsulta").val("");
$("#valorNfeConsulta").val("");
$("#dataEntradaNfeConsulta").val("");
$("#itensNfeConsulta").val("");
$("#operacaoNfeConsulta").val("");
$("#lojaNfeConsulta").val("");
$("#invoiceIdNfeConsulta").val("");
$("#storeIdNfeConsulta").val("");
$("#itensNfeJson").val("[]");
$("#qtdDivergenciasNfe").val("0");
renderTabelaConferencia([], 0, 0, "Consulte a chave da NFe para gerar o confronto dos itens.", "info");
}
function setNfeFeedback(message, type) {
var feedback = $("#consultaNfeFeedback");
if (!feedback.length) {
return;
}
feedback.removeClass("alert-success alert-danger alert-info alert-warning");
if (!message || type === "hidden") {
feedback.hide().text("");
return;
}
if (type === "success") {
feedback.addClass("alert-success");
} else if (type === "warning") {
feedback.addClass("alert-warning");
} else if (type === "info") {
feedback.addClass("alert-info");
} else {
feedback.addClass("alert-danger");
}
feedback.text(message).show();
}
function formatNfeCurrency(value) {
var textValue = String(value == null ? "" : value).trim();
if (textValue === "") {
return "";
}
var numberValue = parseFloat(textValue.replace(",", "."));
if (isNaN(numberValue)) {
return textValue;
}
try {
return numberValue.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
} catch (e) {
return textValue;
}
}
function fillNfeConsultaFields(row) {
var emissionDate = String(row.emissionDate || "");
$("#numeroNfeConsulta").val(String(row.invoiceNumber || ""));
$("#serieNfeConsulta").val(String(row.serie || ""));
$("#dataEmissaoApiNfe").val(emissionDate);
$("#situacaoNfeConsulta").val(String(row.situation || ""));
$("#fornecedorNfeConsulta").val(String(row.supplierName || ""));
$("#valorNfeConsulta").val(formatNfeCurrency(row.documentValue));
$("#dataEntradaNfeConsulta").val(String(row.updatedAt || ""));
$("#itensNfeConsulta").val(String(row.itemCount || ""));
$("#operacaoNfeConsulta").val(String(row.fiscalOperationDescription || ""));
$("#lojaNfeConsulta").val(String(row.storeId || ""));
$("#invoiceIdNfeConsulta").val(String(row.invoiceId || ""));
$("#storeIdNfeConsulta").val(String(row.storeId || ""));
$("#itensNfeJson").val(String(row.itensJson || "[]"));
if (emissionDate) {
$("#dataEmissaoNfe").val(emissionDate);
}
processarConferenciaNfe();
}
function processarConferenciaNfe() {
var nfeItems = parseItensNfeJson();
if (nfeItems.length === 0) {
$("#qtdDivergenciasNfe").val("0");
renderTabelaConferencia([], 0, 0, "Consulte a chave da NFe para gerar o confronto dos itens.", "info");
return;
}
var solicitacaoMap = buildSolicitacaoMap();
var nfeMap = buildNfeMap(nfeItems);
var allKeys = mergeKeys(solicitacaoMap, nfeMap);
var rows = [];
var divergencias = 0;
for (var i = 0; i < allKeys.length; i++) {
var key = allKeys[i];
var req = solicitacaoMap[key] || { qty: 0, label: key };
var nfe = nfeMap[key] || { qty: 0, label: key };
var status = "OK";
if (req.qty === 0 && nfe.qty > 0) {
status = "Somente NFe";
} else if (nfe.qty === 0 && req.qty > 0) {
status = "Somente solicitacao";
} else if (Math.abs(req.qty - nfe.qty) > 0.00001) {
status = "Quantidade divergente";
}
if (status !== "OK") {
divergencias++;
}
rows.push({
key: req.label || nfe.label || key,
requestedQty: req.qty,
nfeQty: nfe.qty,
status: status
});
}
$("#qtdDivergenciasNfe").val(String(divergencias));
var resumo = "Conferencia finalizada: " + rows.length + " item(ns), " + divergencias + " divergencia(s).";
var resumoType = divergencias > 0 ? "warning" : "success";
renderTabelaConferencia(rows, rows.length, divergencias, resumo, resumoType);
}
function parseItensNfeJson() {
var raw = String($("#itensNfeJson").val() || "[]");
try {
var parsed = JSON.parse(raw);
return parsed instanceof Array ? parsed : [];
} catch (e) {
return [];
}
}
function buildSolicitacaoMap() {
var out = {};
$("input[name^='quantidadeItem___']").each(function () {
var name = $(this).attr("name") || "";
var indice = name.split("___")[1];
if (!indice) return;
var qty = toFloatSafe($(this).val());
if (qty <= 0) return;
var productId = String($("#productIdItem___" + indice).val() || "").trim();
var code = resolveSolicitacaoItemCode(indice, $(this));
var descricao = String($("#codigoItem___" + indice).val() || "").trim();
var key = resolveConferenciaKey(productId, code, "ROW:" + indice);
var label = productId ? ("PID " + productId) : (code || descricao || ("Linha " + indice));
if (!out[key]) {
out[key] = { qty: 0, label: label };
}
out[key].qty += qty;
});
return out;
}
function resolveSolicitacaoItemCode(indice, qtyInput) {
var code = String($("#codigoProdutoItem___" + indice).val() || "").trim();
if (code) return normalizeCodigoComparacao(code);
code = String($("#descricao___" + indice).val() || "").trim();
if (code) return normalizeCodigoComparacao(code);
var row = qtyInput && qtyInput.length ? qtyInput.closest("tr") : $();
if (row.length) {
var byName = findFirstFilledValue(row.find("input[name='descricao___" + indice + "']"));
if (byName) return normalizeCodigoComparacao(byName);
var anyDescricao = findFirstFilledValue(row.find("input[name^='descricao']"));
if (anyDescricao) return normalizeCodigoComparacao(anyDescricao);
var byIdLike = findFirstFilledValue(row.find("input[id*='descricao']"));
if (byIdLike) return normalizeCodigoComparacao(byIdLike);
var codigoCellInputs = row.find("td").eq(1).find("input,select,textarea");
var fromCodigoCell = findFirstFilledValue(codigoCellInputs);
if (fromCodigoCell) return normalizeCodigoComparacao(fromCodigoCell);
// Em modo bloqueado/view, o Zoom pode renderizar apenas texto em span/div.
var codigoCell = row.find("td").eq(1);
var zoomRendered = findFirstFilledText(codigoCell.find(
".select2-selection__rendered, .select2-chosen, .zoom-value, .zoom-span, span, div"
));
if (zoomRendered) return normalizeCodigoComparacao(zoomRendered);
// Fallback final: texto bruto da célula.
var rawCellText = String(codigoCell.text() || "").trim();
if (rawCellText) return normalizeCodigoComparacao(rawCellText);
}
return "";
}
function findFirstFilledValue(elements) {
if (!elements || !elements.length) return "";
for (var i = 0; i < elements.length; i++) {
var $el = $(elements[i]);
var val = String($el.val() || "").trim();
if (!val) {
val = String($el.attr("value") || "").trim();
}
if (!val) {
val = String($el.attr("data-value") || "").trim();
}
if (val) return val;
}
return "";
}
function findFirstFilledText(elements) {
if (!elements || !elements.length) return "";
for (var i = 0; i < elements.length; i++) {
var txt = String($(elements[i]).text() || "").trim();
if (txt) return txt;
}
return "";
}
function normalizeCodigoComparacao(value) {
var raw = String(value || "").trim();
if (!raw) return "";
// Zoom pode trazer "75655 - DESCRICAO"; para conferencia usamos o primeiro token.
var firstToken = raw.split(" - ")[0].split(" | ")[0].trim();
return firstToken || raw;
}
function buildNfeMap(items) {
var out = {};
for (var i = 0; i < items.length; i++) {
var item = items[i] || {};
var qty = toFloatSafe(item.quantity);
if (qty <= 0) continue;
var productId = String(item.productId || "").trim();
var code = String(item.code || "").trim();
var key = resolveConferenciaKey(productId, code, "NFE:" + i);
var label = productId ? ("PID " + productId) : (code || ("Item NFe " + (i + 1)));
if (!out[key]) {
out[key] = { qty: 0, label: label };
}
out[key].qty += qty;
}
return out;
}
function resolveConferenciaKey(productId, code, fallback) {
var pid = String(productId || "").trim();
if (pid) {
return "ITEM:" + pid;
}
var cod = String(code || "").trim();
if (cod) {
return "ITEM:" + cod;
}
return String(fallback || "");
}
function mergeKeys(a, b) {
var obj = {};
for (var ka in a) obj[ka] = true;
for (var kb in b) obj[kb] = true;
return Object.keys(obj);
}
function renderTabelaConferencia(rows, totalItens, divergencias, mensagem, tipo) {
var tbody = $("#tabelaConferenciaNfeBody");
var resumo = $("#resumoConferenciaNfe");
if (!tbody.length || !resumo.length) return;
var html = "";
if (!rows || rows.length === 0) {
html = "<tr><td colspan='5'>Sem conferencia.</td></tr>";
} else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowClass = row.status === "OK" ? "" : " class='danger'";
var itemSolicitado = row.key;
var qtdSolicitada = formatConferenciaNumero(row.requestedQty);
var itemNfe = row.key;
var qtdNfe = formatConferenciaNumero(row.nfeQty);
if (row.status === "Somente solicitacao") {
itemNfe = "-";
qtdNfe = "0";
} else if (row.status === "Somente NFe") {
itemSolicitado = "-";
qtdSolicitada = "0";
}
html += "<tr" + rowClass + ">" +
"<td>" + escapeHtml(itemSolicitado) + "</td>" +
"<td>" + escapeHtml(qtdSolicitada) + "</td>" +
"<td>" + escapeHtml(itemNfe) + "</td>" +
"<td>" + escapeHtml(qtdNfe) + "</td>" +
"<td>" + escapeHtml(row.status) + "</td>" +
"</tr>";
}
}
tbody.html(html);
var typeClass = "alert-info";
if (tipo === "success") typeClass = "alert-success";
if (tipo === "warning") typeClass = "alert-warning";
if (tipo === "danger" || tipo === "error") typeClass = "alert-danger";
resumo.removeClass("alert-info alert-success alert-warning alert-danger");
resumo.addClass(typeClass);
resumo.text(mensagem || ("Conferencia: " + totalItens + " item(ns), " + divergencias + " divergencia(s)."));
}
function montarResumoDivergenciasConferencia(limit) {
var max = parseInt(limit, 10);
if (isNaN(max) || max <= 0) max = 5;
var linhas = [];
$("#tabelaConferenciaNfeBody tr.danger").each(function () {
var cols = $(this).find("td");
if (!cols || cols.length < 5) return;
var itemSolicitado = String($(cols[0]).text() || "").trim();
var qtdSolicitada = String($(cols[1]).text() || "").trim();
var itemNfe = String($(cols[2]).text() || "").trim();
var qtdNfe = String($(cols[3]).text() || "").trim();
linhas.push("Item solicitado: " + itemSolicitado + " / Quantidade: " + qtdSolicitada + " | Item emitido na nota: " + itemNfe + " / Quantidade: " + qtdNfe);
});
if (!linhas.length) return "";
if (linhas.length > max) {
var restantes = linhas.length - max;
return linhas.slice(0, max).join("; ") + "; ... +" + restantes + " item(ns)";
}
return linhas.join("; ");
}
function listarProdutosDivergentes(limit) {
var max = parseInt(limit, 10);
if (isNaN(max) || max <= 0) max = 10;
var items = [];
var seen = {};
$("#tabelaConferenciaNfeBody tr.danger").each(function () {
var cols = $(this).find("td");
if (!cols || cols.length < 5) return;
var itemSolicitado = String($(cols[0]).text() || "").trim();
var itemNfe = String($(cols[2]).text() || "").trim();
if (itemSolicitado && itemSolicitado !== "-" && !seen[itemSolicitado]) {
seen[itemSolicitado] = true;
items.push(itemSolicitado);
}
if (itemNfe && itemNfe !== "-" && !seen[itemNfe]) {
seen[itemNfe] = true;
items.push(itemNfe);
}
});
if (!items.length) return "";
if (items.length > max) {
return items.slice(0, max).join(", ") + " ... +" + (items.length - max);
}
return items.join(", ");
}
function toFloatSafe(value) {
var text = String(value == null ? "" : value).replace(",", ".").trim();
var n = parseFloat(text);
return isNaN(n) ? 0 : n;
}
function formatConferenciaNumero(value) {
var n = toFloatSafe(value);
return String(n).indexOf(".") >= 0 ? n.toFixed(2) : String(n);
}
function escapeHtml(value) {
return String(value == null ? "" : value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function consultarChaveNfe() {
var key = normalizeNfeKey($("#chaveNfe").val());
$("#chaveNfe").val(key);
clearNfeConsultaFields();
if (key.length !== 44) {
setNfeFeedback("Informe uma chave com 44 digitos para consultar.", "warning");
return;
}
setNfeFeedback("Consultando chave da NFe...", "info");
try {
var constraint = DatasetFactory.createConstraint("key", key, key, ConstraintType.MUST);
var dataset = DatasetFactory.getDataset("ds_fiscal_invoice_by_keys", null, [constraint], null);
if (!dataset || !dataset.values || dataset.values.length === 0) {
setNfeFeedback("Nao foi possivel consultar a NFe no momento.", "error");
return;
}
var row = dataset.values[0] || {};
var success = String(row.success || "").toLowerCase() === "true";
if (!success) {
setNfeFeedback(String(row.message || "NFe nao encontrada para a chave informada."), "error");
return;
}
fillNfeConsultaFields(row);
if ($("#invoiceIdNfeConsulta").val() === "") {
setNfeFeedback("A consulta retornou sem identificador tecnico da NFe.", "error");
return;
}
setNfeFeedback("NFe localizada e vinculada a solicitacao.", "success");
} catch (e) {
setNfeFeedback("Erro ao consultar chave da NFe: " + e, "error");
}
}
var beforeSendValidate = function (numState, nextState) {
$(".errorValidate").removeClass("errorValidate");
if (numState == 0 || numState == 1) {
if ($("#estabelecimento ").val() == "") {
$("#estabelecimento ").parent("div").addClass("errorValidate");
throw "'Estabelecimento/filial ' é obrigatório.";
} else if ($("#enderecoSolicitante").val() == "") {
$("#enderecoSolicitante").parent("div").addClass("errorValidate");
throw "'Endereço do solicitante' é obrigatório.";
} else if ($("#complemento").val() == "") {
$("#complemento").parent("div").addClass("errorValidate");
throw "'Complemento' é obrigatório.";
} else if ($("#justificativa").val() == "") {
$("#justificativa").parent("div").addClass("errorValidate");
throw "'Qual o motivo da transferência?' é obrigatório.";
} else {
$("input[id^='quantidadeItem___']").each(function (index, value) {
var linha = $(value).attr("name").split("___")[1];
if (
$("#descricao___" + linha).val() == "" &&
$("#quantidadeItem___" + linha).val() == ""
) {
remove_row(value);
}
});
$("input[id^='quantidadeItem___']").each(function (index, value) {
var linha = $(value).attr("name").split("___")[1];
if ($("#descricao___" + linha).val() == "") {
$("#descricao___" + linha)
.parent("div")
.addClass("errorValidate");
throw "Selecione o item " + (index + 1) + ".";
} else if ($("#quantidadeItem___" + linha).val() == "") {
$("#quantidadeItem___" + linha)
.parent("div")
.addClass("errorValidate");
throw "Preencha a quantidade do item " + (index + 1) + ".";
}
});
if ($("input[name^='quantidadeItem___']").length == 0) {
throw "Ao menos um item é necessário para iniciar a solicitação.";
}
}
} else if (numState == 4) {
if (String(nextState) == "39") {
if ($("#justificativaDecisaoGestor").val() == "") {
$("#justificativaDecisaoGestor").parent("div").addClass("errorValidate");
throw "'Justificativa da decisão' é obrigatória para reprovar.";
}
}
} else if (numState == 6) {
var chaveNfe = normalizeNfeKey($("#chaveNfe").val());
$("#chaveNfe").val(chaveNfe);
if (chaveNfe == "") {
$("#chaveNfe").parent("div").addClass("errorValidate");
throw "'Chave de acesso da NFe' e obrigatoria.";
}
if (chaveNfe.length !== 44) {
$("#chaveNfe").parent("div").addClass("errorValidate");
throw "'Chave de acesso da NFe' deve conter 44 digitos.";
}
if ($("#invoiceIdNfeConsulta").val() == "") {
$("#chaveNfe").parent("div").addClass("errorValidate");
throw "Consulte a chave da NFe antes de enviar a etapa.";
}
var qtdDivergencias = parseInt($("#qtdDivergenciasNfe").val() || "0", 10);
if (!isNaN(qtdDivergencias) && qtdDivergencias > 0) {
var produtos = listarProdutosDivergentes(10);
var msg = "A nota tem produtos divergentes da solicitacao.";
if (produtos) {
msg += " Produtos: " + produtos + ".";
}
throw msg;
}
} else if (numState == 31) {
if ($("#motoristaColetaNome").val() == "") {
throw "'Motorista responsável pela coleta' é obrigatório.";
}
if ($("#dataColeta").val() == "") {
throw "'Data da coleta' é obrigatória.";
}
if ($("#fdAnexo_Coleta").val() == "") {
throw "'Anexo da Coleta' é obrigatório.";
}
if (invalidFile("fdAnexo_Coleta")) {
throw "O arquivo informado em 'Anexo da Coleta' não foi encontrado na aba de anexos.";
}
var tipoMotoristaEntrega31 = $("input[name='tipoMotoristaEntrega']:checked").val();
if (!tipoMotoristaEntrega31) {
throw "Informe quem vai fazer a entrega (mesmo motorista da coleta ou outro).";
}
if (tipoMotoristaEntrega31 === "mesmo") {
if ($("#motoristaColetaLogin").val() == "") {
throw "Nao foi encontrado login do motorista da coleta para enviar a etapa de entrega.";
}
$("#motoristaEntregaNome").val($("#motoristaColetaNome").val());
$("#motoristaEntregaLogin").val($("#motoristaColetaLogin").val());
} else if ($("#motoristaEntregaLogin").val() == "") {
throw "Selecione o outro motorista responsavel pela entrega.";
}
} else if (numState == 57) {
if ($("#motoristaEntregaLogin").val() == "") {
throw "Motorista da entrega nao definido. Configure na etapa de coleta.";
}
if ($("#motoristaEntregaNome").val() == "") {
throw "'Motorista responsável pela entrega' é obrigatório.";
}
if ($("#dataEntrega").val() == "") {
var entregaNow = getCurrentDate();
$("#dataEntrega").val(entregaNow[0] + " " + entregaNow[1]);
}
if ($("#dataEntrega").val() == "") {
throw "'Data da entrega' é obrigatória.";
}
if (String($("#nomerecebedor").val() || "").trim() == "") {
throw "'Nome de quem recebeu a mercadoria' é obrigatório.";
}
} else if (numState == 18) {
var validacaoItens = $("input[name='validacaoItens']:checked").val();
if (validacaoItens == "" || validacaoItens == undefined) {
throw "'Validação do recebimento' é obrigatória.";
} else if (
validacaoItens == "divergencia" ||
validacaoItens == "naoEntregue" ||
validacaoItens == "incorreto"
) {
if ($("#justificativaDecisaoItens").val() == "") {
$("#justificativaDecisaoItens")
.parent("div")
.addClass("errorValidate");
throw "'Justificativa' é obrigatório.";
}
}
} else if (numState == 24) {
$('#justificativaValidaProblema').parent().removeClass('has-error errorValidate');
if ($('#justificativaValidaProblema').val() == "") {
$('#justificativaValidaProblema').parent().addClass('has-error errorValidate');
throw "Preencha os campos obrigatórios."
}
}
};
function setSelectedZoomItem(selectedItem) {
var name_item = selectedItem.inputId;
var ehItem = name_item.indexOf("___") >= 0;
var indice = "";
if (ehItem){
var valores = name_item.split("___");
name_item = valores[0];
indice = valores[1];
}
// var dtsCentroCusto = DatasetFactory.getDataset(
// "ds_LojasTransf",
// null,
// null,
// null
// ).values;
// var nomeGestorComercial = dtsCentroCusto[0].gestorCentroCusto;
// var emailGestorComercial = dtsCentroCusto[0].emailGestor;
// var idGestorComercial = dtsCentroCusto[0].idGestor;
// var nomeGestorOperacoes = dtsCentroCusto[2].gestorCentroCusto;
// var emailGestorOperacoes = dtsCentroCusto[2].emailGestor;
// var idGestorOperacoes = dtsCentroCusto[2].idGestor;
// if (name_item == "estabelecimento") {
// let estabelecimento = selectedItem["estabelecimento"];
// if (estabelecimento.includes("ESCRITÓRIO")) {
// } else if (estabelecimento.includes("CD")) {
// window["centroCusto"].setValue("Operações");
// $("#gestorNome").val(nomeGestorOperacoes);
// $("#gestorEmail").val(emailGestorOperacoes);
// $("#gestor_cc").val(idGestorOperacoes);
// } else {
// window["centroCusto"].setValue("Comercial");
// $("#gestorNome").val(nomeGestorComercial);
// $("#gestorEmail").val(emailGestorComercial);
// $("#gestor_cc").val(idGestorComercial);
// }
// }
if (name_item == "centroCusto") {
$("#gestorNome").val(selectedItem["RESPONSAVEL_LOJA"] || "");
$("#gestorEmail").val(selectedItem["emailGestor"] || "");
$("#gestor_cc").val(selectedItem["COLLEAGUE_ID"] || "");
$("#ufDestino").val(selectedItem["UF"] || "");
refreshMotoristasEntregaByUf(true);
}
if (name_item == "estabelecimento") {
$("#gestorNomeE").val(selectedItem["RESPONSAVEL_LOJA"] || "");
$("#gestorEmailE").val(selectedItem["emailGestor"] || "");
$("#gestor_cce").val(selectedItem["COLLEAGUE_ID"] || "");
$("#ufOrigem").val(selectedItem["UF"] || "");
}
if (name_item == "userSolicitante") {
$("#emailSolicitante").val(selectedItem.mail);
}
if (name_item == "motoristaEntregaSelecionado") {
var motoristaNome = selectedItem["NOME"] || selectedItem["colleagueName"] || selectedItem["LOGIN"] || selectedItem["login"] || "";
var motoristaColleagueId = selectedItem["COLLEAGUE_ID"] || selectedItem["colleaguePK.colleagueId"] || "";
$("#motoristaEntregaNome").val(String(motoristaNome || ""));
$("#motoristaEntregaLogin").val(String(motoristaColleagueId || ""));
$("#tipoMotoristaEntregaOutro").prop("checked", true);
applyMotoristaEntregaMode("outro", true);
}
if (name_item == "descricao") {
var itemDescricao = selectedItem["descricao"] || selectedItem["Description"] || "";
var itemCode = selectedItem["Code"] || selectedItem["sku"] || "";
var itemProductId = selectedItem["id"] || selectedItem["productId"] || "";
var itemCategoria = selectedItem["categoria"] || selectedItem["strategicDescription"] || "";
$("#codigoItem" + "___" + indice).val(itemDescricao);
$("#codigoProdutoItem" + "___" + indice).val(itemCode);
$("#productIdItem" + "___" + indice).val(itemProductId);
$("#categoriaItem" + "___" + indice).val(itemCategoria);
processarConferenciaNfe();
}
}
function removedZoomItem(removedItem) {
var name_item = removedItem.inputId;
var ehItem = name_item.indexOf("___") >= 0;
var indice = "";
if (ehItem){
var valores = name_item.split("___");
name_item = valores[0];
indice = valores[1];
}
if (name_item == "userSolicitante") {
$("#emailSolicitante").val("");
} else if (name_item == "centroCusto") {
$("#gestorNome").val("");
$("#gestorEmail").val("");
$("#gestor_cc").val("");
$("#ufDestino").val("");
refreshMotoristasEntregaByUf(true);
} else if (name_item == "estabelecimento") {
$("#gestorNomeE").val("");
$("#gestorEmailE").val("");
$("#gestor_cce").val("");
$("#ufOrigem").val("");
} else if (name_item == "motoristaEntregaSelecionado") {
if ($("input[name='tipoMotoristaEntrega']:checked").val() === "outro") {
$("#motoristaEntregaNome").val("");
$("#motoristaEntregaLogin").val("");
}
} else if (~name_item.indexOf("___")) {
var linha = name_item.split("___");
if (linha[0] == "descricao") {
$("#codigoItem___" + linha[1]).val("");
$("#codigoProdutoItem___" + linha[1]).val("");
$("#productIdItem___" + linha[1]).val("");
$("#categoriaItem___" + linha[1]).val("");
$("#quantidadeItem___" + linha[1]).val("");
processarConferenciaNfe();
}
}
if (name_item == "descricao") {
$("#codigoItem" + "___" + indice).val("");
$("#codigoProdutoItem" + "___" + indice).val("");
$("#productIdItem" + "___" + indice).val("");
$("#categoriaItem" + "___" + indice).val("");
processarConferenciaNfe();
}
}
function add_new_row(table) {
var row = wdkAddChild(table);
updt_line();
}
function updt_line() {
$(".tabela_itens_id").each(function (index, item) {
if (index == 0) return;
$(item)[0].innerHTML = index;
});
}
function remove_row(element) {
fnWdkRemoveChild(element);
updt_line();
processarConferenciaNfe();
}
// Andrey, nao esqueca de ver isso
// function removedZoomItem(removedItem) {
// // if (removedItem.inputId === "estabelecimento") {
// // document.getElementById("setor-container").style.display = "none"; // Oculta ao remover
// window["centroCusto"].setValue("")[0]
// // }
// }
$(document).ready(function() {
// $('#gerarTabela').click(function() {
// var numCotacoes = $('#numCotacoes').val();
// var tbody = $("#tabelaCotacao tbody");
// tbody.empty(); // Limpa a tabela antes de gerar novas linhas
// // Supondo que você já tenha uma tabela de origem com os produtos
// $('table.table[tablename="tabelaItens"] tbody tr:visible').each(function(index, element) {
// var nomeItem = $(element).find('input[name^="nomeItem"]').val();
// var quantidadeItem = $(element).find('input[name^="quantidadeItem"]').val();
// for (var i = 0; i < numCotacoes; i++) {
// var row = `<tr>
// <td>${index + 1}.${i + 1}</td>
// <td>${nomeItem}</td>
// <td>${quantidadeItem}</td>
// <td><input type="text" class="form-control" name="fornecedor_${index}_${i}" /></td>
// <td><input type="number" class="form-control" name="preco_${index}_${i}" /></td>
// <td><input type="date" class="form-control" name="dataEntrega_${index}_${i}" /></td>
// <td><input type="email" class="form-control" name="email_${index}_${i}" /></td>
// </tr>`;
// tbody.append(row);
// }
// });
// });
$('#gerarTabela').click(function() {
});
});
/**
* Toda a lógica para o correto funcionamento desse componente foi feito em cima das classes abaixo:
* .componentAnexo, .descAnexo, .inputAnexo, .btnUpFile, .btnViewerFile, .btnDownloadFile e o atributo data-acao
* Sem elas o código não irá funcionar, então se por acaso você quiser alterar os nomes dessas classes
* lembre-se de alterar nas funções desse arquivo e também no css
*/
/**
* Direciona para cada função correspondente ao valor que esta no atributo data-acao do botão
* @param {object} event Parâmetro obrigatório, o própio elemento que sofreu o evento click
* @return {void}
* @author Sérgio Machado
*/
function anexo(event){
console.log("event")
console.log(event)
try{
const acao = event.currentTarget.getAttribute("data-acao");
const inputFile = $(event.currentTarget).parent().parent().find(".inputAnexo")[0]
const fileDescription = $(event.currentTarget).parent().parent().find(".descAnexo").val()
if(acao == "upload"){
uploadFile(fileDescription, inputFile.id)
}
if(acao == "viewer"){
viewerFile(fileDescription)
}
if(acao == "download"){
downloadFile(fileDescription, inputFile.id)
}
if(acao == "delete"){
removeFileConfirm(fileDescription, inputFile.id)
}
}catch(e){
console.error("Houve um erro inesperado na função anexo")
console.error(e)
}
}
/**
* Envia arquivos para a aba Anexos do Fluig
* Função adaptada por Sérgio Machado
* @param {String} fileDescription Parâmetro obrigatório, Descrição do arquivo que ficará na aba anexos do Fluig
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @return {void}
*/
function uploadFile(fileDescription, idInput) {
try{
var tabAttachments = parent.document.getElementById("tab-attachments");
if (tabAttachments) {
//Verifica se o navegador é o Ie9 para realizar o devido tratamento
if (parent.WCMAPI.isIe9()) {
$(".ecm-navigation-silverlight", parent.document).show("fade").css("top", 0);
$("#ecm-navigation-silverlight", parent.document).attr({
"data-on-camera": "true", "data-file-name-camera": fileDescription, "data-inputNameFile": idInput
});
$(parent.document).on("keyup", this.actionKeyup)
} else {
var element = parent.document.getElementById("ecm-navigation-inputFile-clone");
if (element && document.createEvent) {
element.setAttribute("data-on-camera", "true");
if (fileDescription && idInput) {
element.setAttribute("data-file-name-camera", fileDescription)
element.setAttribute("data-inputNameFile", idInput)
}
//Realiza o click no botão "Carregar arquivos" que tem na aba de anexos
element.click();
}
}
}
}catch(e){
console.error("Houve um erro inesperado na função uploadFile")
console.error(e)
}
}
/**
* Função executada após a escolha do arquivo a ser enviado para o Fluig.
* Verifica se o anexo já existe, seta o valor do arquivo fisico no campo e altera o estado dos botões
* @return {void}
*/
$(function(){
try{
window.parent.$("#ecm-navigation-inputFile-clone").on('change', function(e) {
const inputNameFile = this.getAttribute("data-inputNameFile");
const fileDescription = this.getAttribute("data-file-name-camera");
const filePhisical = this.files[0].name;
if(fileDescription && fileDescription){
/**
* O trecho de código abaixo percorre os anexos do Fluig e caso já exista um anexo com a mesma descrição, ele será removido.
* Em seguida limpa o campo onde é armazenado o nome fisico do arquivo
*/
$.each(parent.ECM.attachmentTable.getData(), function(i, attachment) {
var descricao = attachment.description;
if (fileDescription == descricao) {
parent.WKFViewAttachment.removeAttach([i]);
setFilePhisicalName(inputNameFile, "");
}
});
setFilePhisicalName(inputNameFile, filePhisical)
if(getFormMode() == "ADD"){
btnState(inputNameFile, 'delete', 'download');
}
if(getFormMode() == "MOD"){
btnState(inputNameFile, 'delete', 'viewer');
}
if(getFormMode() == "VIEW"){
btnState(inputNameFile, 'download', 'viewer');
}
}
});
}catch(e){
console.error("Houve um erro inesperado ao selecionar o arquivo")
console.error(e)
}
});
/**
* Visualizar arquivos que esta na aba Anexos do Fluig
* @param {String} fileDescription Parâmetro obrigatório, Descrição do anexo
* @return {void}
*/
function viewerFile(fileDescription) {
try{
if(hasFileFluig(fileDescription)){
const anexos = parent.ECM.attachmentTable.getData();
for(let i = 0; i < anexos.length; i++){
var descricao = anexos[i].description;
if (fileDescription == descricao) {
parent.WKFViewAttachment.openAttachmentView('adm', anexos[i].documentId);
return
}
}
}else{
FLUIGC.toast({
title: "Atenção",
message: "Anexo não encontrado",
type: "warning"
});
}
}catch(e){
console.error("Houve um erro inesperado na função viewerFile")
console.error(e)
}
}
/**
* Realiza o download do arquivo que esta na aba Anexos do Fluig
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @param {String} fileDescription Parâmetro obrigatório, Descrição do arquivo que esta na aba anexos do Fluig
* @return {void}
*/
function downloadFile(fileDescription, idInput) {
try{
const filename = getFormMode() == "VIEW" ? $(`#${idInput}`).text() : $(`#${idInput}`).val()
FLUIGC.message.confirm({
message: `Deseja baixar o anexo <b>${filename}</b>?`,
title: 'Confirmação',
labelYes: 'Sim, quero baixar',
labelNo: 'Não, quero cancelar',
}, function(result) {
if (result) {
$.each(parent.ECM.attachmentTable.getData(), function(i, attachment) {
var descricao = attachment.description;
if (fileDescription == descricao) {
parent.WKFViewAttachment.downloadAttach([i]);
}
});
}
});
}catch(e){
console.error("Houve um erro inesperado na função downloadFile")
console.error(e)
}
}
/**
* Confirmação para Remove arquivo que esta na aba Anexos do Fluig
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @param {String} fileDescription Parâmetro obrigatório, Descrição do arquivo que esta na aba anexos do Fluig
* @return {void}
* @author Sérgio Machado
*/
function removeFileConfirm(fileDescription, idInput) {
try{
const filename = $(`#${idInput}`).val()
FLUIGC.message.confirm({
message: `Deseja remover o anexo <b>${filename}</b>?`,
title: 'Confirmação',
labelYes: 'Sim, quero remover',
labelNo: 'Não, quero cancelar',
}, function(result) {
if (result) {
removeFile(fileDescription)
setFilePhisicalName(idInput, "")
btnState(idInput, "upload", "download")
}
});
}catch(e){
console.error("Houve um erro inesperado na função removeFileConfirm")
console.error(e)
}
}
/**
* Remove arquivo que esta na aba Anexos do Fluig
* @param {String} fileDescription Parâmetro obrigatório, Descrição do arquivo que esta na aba anexos do Fluig
* @return {void}
* @author Sérgio Machado
*/
function removeFile(fileDescription) {
try{
$.each(parent.ECM.attachmentTable.getData(), function(i, attachment) {
if (attachment.description == fileDescription) {
parent.WKFViewAttachment.removeAttach([i]);
}
});
}catch(e){
console.error("Houve um erro inesperado na função removeFile")
console.error(e)
}
}
/**
* Seta o nome do arquivo fisico no campo e realiza tratativa caso o campo esteja bloqueado pelo enableFields
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @param {String} filePhisical Parâmetro obrigatório, nome do arquivo fisico
* @return {void}
* @author Sérgio Machado
*/
function setFilePhisicalName(idInput, filePhisical){
try{
if(idInput.indexOf("_") == 0){
$("#" + idInput.substring(1)).val(filePhisical);
}
$("#" + idInput).val(filePhisical);
}catch(e){
console.error("Houve um erro inesperado na função setFilePhisicalName")
console.error(e)
}
}
/**
* Altera o estado e visibilidade dos botões de anexos
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @param {String} acao Parâmetro obrigatório, ação para ser executada no momento do click, se é delete ou upload
* @param {String} btn Parâmetro obrigatório, botão secundário que deve sofrer ação de ficar visível ou não. Botão de Download ou Viewer
* @return {void}
* @author Sérgio Machado
*/
function btnState(idInput, acao, btn){
try{
let btnUpFile = $(`#${idInput}`).parent().parent().find(".btnUpFile");
let btnDownloadFile = $(`#${idInput}`).parent().parent().find(".btnDownloadFile");
let btnViewerFile = $(`#${idInput}`).parent().parent().find(".btnViewerFile");
if(acao == "delete"){
btnUpFile.removeClass("btn-success").addClass("btn-danger");
btnUpFile.attr({'data-acao': acao, 'title': 'Excluir'});
btnUpFile.find("i").removeClass("fluigicon-file-upload").addClass("fluigicon-trash");
if(btn == "download"){
btnDownloadFile.prop("disabled", false);
btnDownloadFile.show()
}
if(btn == "viewer"){
btnViewerFile.prop("disabled", false);
btnViewerFile.show()
}
}
if(acao == "upload"){
btnUpFile.removeClass("btn-danger").addClass("btn-success");
btnUpFile.attr({'data-acao': acao, 'title': 'Selecionar'});
btnUpFile.find("i").removeClass("fluigicon-trash").addClass("fluigicon-file-upload");
btnDownloadFile.prop("disabled", true);
btnDownloadFile.hide()
btnViewerFile.prop("disabled", true);
btnViewerFile.hide()
}
}catch(e){
console.error("Houve um erro inesperado na função btnState")
console.error(e)
}
}
/**
* Faz tratativa nos botões do anexos percorrente cada class .componentAnexo
* Em modo de visualização o botão de upload é removido, e caso tenha anexo, habilita o botão de visualização do anexo
* Se em modo de edição e conter anexo o botão de upload é alterado para o botão de deletar anexos e habilita o botão de visualização
* @return {void}
* @author Sérgio Machado
*/
function displayBtnFiles(){
try{
var mode = getFormMode();
var allowedInputs = getAllowedAttachmentInputs();
$('.componentAnexo').each(function(i, element) {
let inputFile = $(element).find(".inputAnexo")
let inputId = inputFile.attr("id") || "";
let normalizedInputId = inputId.indexOf("_") === 0 ? inputId.substring(1) : inputId;
let btnUpFile = $(element).find(".btnUpFile");
let btnViewerFile = $(element).find(".btnViewerFile");
let btnDownloadFile = $(element).find(".btnDownloadFile");
let canUploadHere = allowedInputs.indexOf(normalizedInputId) >= 0;
if(mode == "VIEW"){
btnUpFile.remove();
if(inputFile.val() != ""){
btnViewerFile.prop("disabled", false);
btnViewerFile.show()
btnDownloadFile.prop("disabled", false);
btnDownloadFile.show()
}
}
if(mode == "MOD"){
if(inputFile.val() != ""){
if(canUploadHere){
btnState(inputId, "delete", "viewer");
} else {
btnUpFile.remove();
btnViewerFile.prop("disabled", false);
btnViewerFile.show()
btnDownloadFile.prop("disabled", false);
btnDownloadFile.show()
}
} else if(!canUploadHere){
btnUpFile.remove();
}
}
});
}catch(e){
console.error("Houve um erro inesperado na função displayBtnFiles")
console.error(e)
}
}
function getAllowedAttachmentInputs() {
var mode = getFormMode();
var activity = String($("#activity").val() || "");
if (mode === "VIEW") {
return [];
}
if (mode !== "MOD" && mode !== "ADD") {
return [];
}
if (activity === "6") {
return ["fnAnexo_Nfe"];
}
if (activity === "31") {
return ["fdAnexo_Coleta"];
}
if (activity === "57") {
return ["fdAnexo_Entrega"];
}
if (activity === "18") {
return ["fdAnexo_recebimento"];
}
return [];
}
/**
* Remove o botão de upload/delete
* @param {String} inputFile Parâmetro obrigatório, Id do campo
* @return {void}
* @author Sérgio Machado
*/
function invisibleBtnUpload(inputFile){
try{
var mode = getFormMode();
var allowedInputs = getAllowedAttachmentInputs();
var canUploadHere = allowedInputs.indexOf(inputFile) >= 0;
if(mode == "VIEW" || ((mode == "MOD" || mode == "ADD") && !canUploadHere)){
if($(`#_${inputFile}`).length){
let btnUpFile = $(`#_${inputFile}`).parent().parent().find(".btnUpFile");
btnUpFile.remove();
} else{
let btnUpFile = $(`#${inputFile}`).parent().parent().find(".btnUpFile");
btnUpFile.remove();
}
}
if($(`#_${inputFile}`).length){
if($(`#_${inputFile}`).val() == ""){
$(`#_${inputFile}`).attr({placeholder:"Nenhum anexo selecionado"});
}
} else{
if($(`#${inputFile}`).val() == ""){
$(`#${inputFile}`).attr({placeholder:"Nenhum anexo selecionado"});
}
}
}catch(e){
console.error("Houve um erro inesperado na função invisibleBtnUpload")
console.error(e)
}
}
/**
* Verifica se os campos do anexo de uma tabela pai e filho esta preenchido,
* caso esteja, ele verifica se o anexo esta presente na aba de anexos do Fluig
* @param {String} tablename Parâmetro obrigatório, tablename da tabela pai e filho.
* @param {String} idInput Parâmetro obrigatório, Id do campo de anexo que deseja verificar
* @return {String} - Retorna string de erros caso apresente erros
* @author Sérgio Machado
*/
function invalidFilesTable(tablename, idInput){
try {
let errors = "";
const countRows = $(`[tablename='${tablename}']`).find('tbody tr').not(':first');
for(let i = 0; i < countRows.length; i++){
let indice = getIndice(countRows.eq(i).find("input")[0].id);
let inputNameFile = $(`#_${idInput}___${indice}`).length ? $(`#_${idInput}___${indice}`) : $(`#${idInput}___${indice}`)
let fileDescription = inputNameFile.parent().find(".descAnexo").val()
if(inputNameFile.val() && !hasFileFluig(fileDescription)){
errors += `<li style='margin-bottom: 5px;'>O anexo <b>${inputNameFile.val()}</b> da linha <b>${i+1}</b> não foi encontrado</li>`
}
}
return errors
} catch (e) {
console.error('Houve um erro inesperado na função invalidFileTable')
console.error(e)
}
}
/**
* Verifica se o campo do anexo esta preenchido, caso esteja, ele verifica se o anexo esta válido
* @param {String} idInput Parâmetro obrigatório, Id do campo em que o nome do arquivo fisico é gravado
* @return {Boolean}
* @author Sérgio Machado
*/
function invalidFile(idInput){
try {
const inputNameFile = String($(`#${idInput}`).val() || "").trim();
if(inputNameFile){
let fileDescription = "";
if($(`#_${idInput}`).length){
fileDescription = String($(`#_${idInput}`).parent().find(".descAnexo").val() || "").trim();
} else{
fileDescription = String($(`#${idInput}`).parent().find(".descAnexo").val() || "").trim();
}
if (!fileDescription) {
fileDescription = inputNameFile;
}
return !hasFileFluig(fileDescription)
}else{
return false
}
} catch (e) {
console.error('Houve um erro inesperado na função invalidFile')
console.error(e)
}
}
/**
* Verifica se o anexo existe na aba de anexos do Fluig
* @param {String} fileDescription Parâmetro obrigatório, Descrição do arquivo
* @return {Boolean} - Retorna verdadeiro caso o arquivo exista
* @author Sérgio Machado
*/
function hasFileFluig(fileDescription){
try {
var target = String(fileDescription || "").trim();
if (!target) return false;
const anexos = parent.ECM.attachmentTable.getData();
for(let i = 0; i < anexos.length; i++){
var descricao = String(anexos[i].description || "").trim();
if (target == descricao || descricao.indexOf(target + " - ") === 0) {
return true
}
}
return false
} catch (e) {
console.error('Houve um erro inesperado na função hasFileFluig')
console.error(e)
}
}
//Quando o Fluig finalizar o upload e o anexo for escolhido
window.parent.$("#ecm-navigation-inputFile-clone").on('change', function () {
const fileDescription = this.getAttribute("data-file-name-camera");
const file = this.files[0];
if (fileDescription === "Planilha de Itens Excel") {
// Copia o arquivo para o input técnico
const dt = new DataTransfer();
dt.items.add(file);
document.getElementById("excelUpload").files = dt.files;
// Atualiza nome mostrado
$("#nomeArquivoExcel").text("Arquivo selecionado: " + file.name);
// Agora sim o arquivo está dentro do input e pode ser lido
carregarItensDoExcel("excelUpload");
}
});