This commit is contained in:
2026-03-17 17:58:40 -03:00
parent b8a84962ce
commit e8445fcf2f
18 changed files with 6689 additions and 2010 deletions
@@ -26,13 +26,41 @@ $(document).ready(function () {
$('#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();
});
if ($("#formMode").val() == "VIEW") {
showAndBlock(["all"]);
$("#btnConsultarChaveNfe").prop("disabled", true).hide();
} else {
//show the right fields
var activity = $("#activity").val();
var requestDate = getCurrentDate();
if (String(activity) !== "6") {
$("#btnConsultarChaveNfe").prop("disabled", true).hide();
}
$(".activity").hide();
$(".activity-" + activity).show();
@@ -51,10 +79,14 @@ $(document).ready(function () {
updt_line();
} else if (activity == 6) {
showAndBlock([0, 4]);
$("#userValidacaoCompras").val($("#currentUserName").val());
$("#dataValidacaoCompras").val(
requestDate[0] + " - " + requestDate[1]
);
if ($("#usuarioEmissorNfe").val() == "") {
$("#usuarioEmissorNfe").val($("#currentUserName").val());
}
if ($("#dataEmissaoNfe").val() == "") {
$("#dataEmissaoNfe").val(
requestDate[0] + " - " + requestDate[1]
);
}
if ($("#justificativaDecisaoGestor").val() == "") {
$(".justificativa-activity-4").hide();
@@ -66,6 +98,9 @@ $(document).ready(function () {
$("#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() == "") {
@@ -81,7 +116,21 @@ $(document).ready(function () {
$("#dataRealizacaoCompras").val(
requestDate[0] + " - " + requestDate[1]
);
showAndBlock([0, 4, 6, 57]);
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();
@@ -111,9 +160,11 @@ $(document).ready(function () {
$("input[name=validacaoItens]").on("change", function () {
$(".justificativaDecisaoItens").hide();
var validacaoItensSelecionada = $("input[name=validacaoItens]:checked").val();
if (
$("input[name=validacaoItens]:checked").val() == "incorreto" ||
$("input[name=validacaoItens]:checked").val() == "naoEntregue"
validacaoItensSelecionada == "divergencia" ||
validacaoItensSelecionada == "incorreto" ||
validacaoItensSelecionada == "naoEntregue"
) {
$(".justificativaDecisaoItens").show();
}
@@ -146,6 +197,7 @@ $(document).ready(function () {
invisibleBtnUpload("fdAnexo_Coleta");
invisibleBtnUpload("fdAnexo_Entrega");
invisibleBtnUpload("fdAnexo_recebimento");
processarConferenciaNfe();
// gerarTabelaCotacaoIndica("tabelaCotacaoIndica", "tabelaItens");
@@ -238,6 +290,589 @@ function getCurrentDate() {
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_ID = "Motoristas";
var motoristasEntregaCache = null;
var motoristasEntregaLoading = false;
function loadMotoristasEntregaSelect(forceReload) {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
if (!forceReload && motoristasEntregaCache && motoristasEntregaCache.length) {
renderMotoristasEntregaOptions(motoristasEntregaCache);
return;
}
if (motoristasEntregaLoading) return;
motoristasEntregaLoading = true;
var requestPayload = {
name: "ds_motoristas_grupo",
fields: null,
constraints: [{
_field: "GROUP_ID",
_initialValue: MOTORISTAS_GROUP_ID,
_finalValue: MOTORISTAS_GROUP_ID,
_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) || []);
motoristasEntregaCache = normalizeMotoristasEntregaRows(values);
renderMotoristasEntregaOptions(motoristasEntregaCache);
}).fail(function (xhr) {
console.error("Falha ao carregar motoristas do dataset:", xhr);
motoristasEntregaCache = [];
renderMotoristasEntregaOptions([]);
}).always(function () {
motoristasEntregaLoading = 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) {
var select = $("#motoristaEntregaSelecionado");
if (!select.length) return;
var selectedValue = String($("#motoristaEntregaLogin").val() || select.val() || "").trim();
select.empty();
select.append($("<option></option>").val("").text("Selecione o motorista"));
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 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 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='4'>Sem conferencia.</td></tr>";
} else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowClass = row.status === "OK" ? "" : " class='danger'";
html += "<tr" + rowClass + ">" +
"<td>" + escapeHtml(row.key) + "</td>" +
"<td>" + formatConferenciaNumero(row.requestedQty) + "</td>" +
"<td>" + formatConferenciaNumero(row.nfeQty) + "</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 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) {
@@ -288,16 +923,71 @@ var beforeSendValidate = function (numState, nextState) {
} else if (numState == 4) {
//
} 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) {
throw "Existem " + qtdDivergencias + " divergencia(s) entre itens solicitados e itens da NFe.";
}
} else if (numState == 31) {
if ($("#motoristaColetaNome").val() == "") {
throw "'Motorista responsável pela coleta' é obrigatório.";
}
if ($("#dataColeta").val() == "") {
throw "'Data da coleta' é obrigatória.";
}
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.";
}
} else if (numState == 18) {
if (
$("input[name='validacaoItens']:checked").val() == "" ||
$("input[name='validacaoItens']:checked").val() == undefined
) {
throw "'Consegue resolver?' é obrigatório.";
var validacaoItens = $("input[name='validacaoItens']:checked").val();
if (validacaoItens == "" || validacaoItens == undefined) {
throw "'Validação do recebimento' é obrigatória.";
} else if (
$("input[name='validacaoItens']:checked").val() == "naoEntregue" ||
$("input[name='validacaoItens']:checked").val() == "incorreto"
validacaoItens == "divergencia" ||
validacaoItens == "naoEntregue" ||
validacaoItens == "incorreto"
) {
if ($("#justificativaDecisaoItens").val() == "") {
$("#justificativaDecisaoItens")
@@ -358,24 +1048,38 @@ function setSelectedZoomItem(selectedItem) {
// }
if (name_item == "centroCusto") {
$("#gestorNome").val(selectedItem["gestorCentroCusto"]);
$("#gestorEmail").val(selectedItem["emailGestor"]);
$("#gestor_cc").val(selectedItem["idGestor"]);
$("#gestorNome").val(selectedItem["RESPONSAVEL_LOJA"] || "");
$("#gestorEmail").val(selectedItem["emailGestor"] || "");
$("#gestor_cc").val(selectedItem["COLLEAGUE_ID"] || "");
}
if (name_item == "estabelecimento") {
$("#gestorNomeE").val(selectedItem["gestorCentroCusto"]);
$("#gestorEmailE").val(selectedItem["emailGestor"]);
$("#gestor_cce").val(selectedItem["idGestor"]);
$("#gestorNomeE").val(selectedItem["RESPONSAVEL_LOJA"] || "");
$("#gestorEmailE").val(selectedItem["emailGestor"] || "");
$("#gestor_cce").val(selectedItem["COLLEAGUE_ID"] || "");
}
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"] || "";
$("#codigoItem" + "___" + indice).val(itemDescricao);
$("#codigoProdutoItem" + "___" + indice).val(itemCode);
$("#productIdItem" + "___" + indice).val(itemProductId);
processarConferenciaNfe();
}
}
@@ -396,17 +1100,32 @@ function removedZoomItem(removedItem) {
$("#gestorNome").val("");
$("#gestorEmail").val("");
$("#gestor_cc").val("");
} else if (name_item == "estabelecimento") {
$("#gestorNomeE").val("");
$("#gestorEmailE").val("");
$("#gestor_cce").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("");
$("#quantidadeItem___" + linha[1]).val("");
processarConferenciaNfe();
}
}
if (name_item == "descricao") {
$("#codigoItem" + "___" + indice).val("");
$("#codigoProdutoItem" + "___" + indice).val("");
$("#productIdItem" + "___" + indice).val("");
processarConferenciaNfe();
}
}
@@ -425,6 +1144,7 @@ function updt_line() {
function remove_row(element) {
fnWdkRemoveChild(element);
updt_line();
processarConferenciaNfe();
}
@@ -767,26 +1487,40 @@ function btnState(idInput, acao, btn){
*/
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(getFormMode() == "VIEW"){
if(mode == "VIEW"){
btnUpFile.remove();
if(inputFile.val() != ""){
btnViewerFile.prop("disabled", false);
btnViewerFile.show()
btnDownloadFile.prop("disabled", false);
btnDownloadFile.show()
}
}
if(getFormMode() == "MOD" && inputFile.val() != ""){
btnUpFile.remove();
// btnState(inputFile[0].id, "delete", "viewer")
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){
@@ -795,7 +1529,35 @@ function displayBtnFiles(){
}
}
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
@@ -804,7 +1566,11 @@ function displayBtnFiles(){
*/
function invisibleBtnUpload(inputFile){
try{
if(getFormMode() == "MOD" || getFormMode() == "VIEW"){
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();
@@ -925,3 +1691,4 @@ window.parent.$("#ecm-navigation-inputFile-clone").on('change', function () {
carregarItensDoExcel("excelUpload");
}
});