2026-03-01 17:27:48 -03:00

283 lines
12 KiB
JavaScript
Raw Permalink 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.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

function displayFields(form, customHTML) {
var activity = getValue('WKNumState');
var userId = getValue('WKUser');
form.setShowDisabledFields(true);
form.setHidePrintLink(true);
form.setValue("WKNumProces", getValue('WKNumProces'));
form.setValue("activity", activity);
form.setValue("formMode", form.getFormMode());
form.setValue("empresa", getValue("WKCompany"));
var c1 = DatasetFactory.createConstraint("colleagueId", userId, userId, ConstraintType.MUST);
var filter = new Array(c1);
var fields = new Array("colleagueName");
var retorno = DatasetFactory.getDataset("colleague", fields, filter, null);
//requester
if (activity == 0) {
form.setValue("usuario_abertura", retorno.getValue(0, "colleagueName"));
form.setValue("requesterMail", retorno.getValue(0, "mail"));
form.setValue("requesterId", userId);
} else {
form.setValue("currentUserName", retorno.getValue(0, "colleagueName"));
form.setValue("currentUsermail", retorno.getValue(0, "mail"));
form.setValue("currentUserId", userId);
}
// ✅ Quando for atividade de aprovação do gestor
if (activity == 121) {
var hoje = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());
form.setValue("user_validacao_gestor", retorno.getValue(0, "colleagueName"));
form.setValue("data_validacao_gestor", hoje);
}
if (activity == 133) {
var hoje = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());
form.setValue("gestor_validacao_aprova", retorno.getValue(0, "colleagueName"));
form.setValue("data_validacao_aprova_gestor", hoje);
}
if (activity == 137) {
var hoje = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());
form.setValue("user_validacao_aprova", retorno.getValue(0, "colleagueName"));
form.setValue("data_validacao_aprova", hoje);
}
if (activity == 147) {
var hoje = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());
form.setValue("gerf_validacao_aprova", retorno.getValue(0, "colleagueName"));
form.setValue("data_validacao_aprova_gerf", hoje);
}
if (activity == 18) {
var hoje = new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());
form.setValue("userValidacaoItens", retorno.getValue(0, "colleagueName"));
form.setValue("dataValidacaoItens", hoje);
}
// ✅ Injetar dados da SC do Protheus (se já tiverem sido preenchidos no servicetask)
var camposSC = [
"numeroSCProtheus",
"statusSCProtheus",
"solicitanteSCProtheus",
"emissaoSCProtheus",
"qtdItensSCProtheus",
"dataCadastroSCProtheus",
"horaCadastroSCProtheus"
];
camposSC.forEach(function(campo) {
var valor = form.getValue(campo);
if (valor) {
customHTML.append("<script>$('#" + campo + "_label').text('" + valor + "');</script>");
}
});
// cor no status
var status = form.getValue("statusSCProtheus");
if (status) {
var badgeClass = "badge bg-secondary";
if (status.toLowerCase().indexOf("sucesso") >= 0) badgeClass = "badge bg-success";
if (status.toLowerCase().indexOf("erro") >= 0) badgeClass = "badge bg-danger";
customHTML.append("<script>$('#statusSCProtheus_label').removeClass().addClass('" + badgeClass + "').text('" + status + "');</script>");
}
// Consultar informações adicionais da SC no Protheus
var numSC = form.getValue("numeroSCProtheus");
if (numSC) {
try {
var c1 = DatasetFactory.createConstraint("numeroSCProtheus", numSC, numSC, ConstraintType.MUST);
var ds = DatasetFactory.getDataset("ds_consultaSC", null, [c1], null);
if (ds && ds.rowsCount > 0) {
var status = ds.getValue(0, "STATUS") || "";
var cotacao = ds.getValue(0, "C1_COTACAO") || "";
var pedido = ds.getValue(0, "C1_PEDIDO") || "";
// grava nos hidden inputs
form.setValue("statusAtendimento", status);
form.setValue("cotacaoSCProtheus", cotacao);
form.setValue("pedidoSCProtheus", pedido);
// mostra nos cards (HTML)
customHTML.append("<script>$('#statusSC_label').text('" + status + "');</script>");
customHTML.append("<script>$('#cotacaoSC_label').text('" + cotacao + "');</script>");
customHTML.append("<script>$('#pedidoSC_label').text('" + pedido + "');</script>");
}
} catch (e) {
log.error("❌ Erro ao consultar dataset ds_consultaSC: " + e);
}
}
try {
var msgs = [];
var numeroSC = form.getValue("numeroSCProtheus");
var cotacaoSC = form.getValue("cotacaoSCProtheus");
var pedidoSC = form.getValue("pedidoSCProtheus");
if (numeroSC) msgs.push("📌 Gerou SC Protheus nº " + numeroSC);
if (cotacaoSC) msgs.push("📌 SC originou Cotação nº " + cotacaoSC);
if (pedidoSC) msgs.push("📌 Cotação finalizou → Pedido nº " + pedidoSC);
if (msgs.length === 0) {
msgs.push(" Nenhum dado de integração Protheus encontrado no formulário");
}
// Monta conteúdo HTML do histórico
var htmlHistorico = "<ul class='hist-list'>";
for (var i = 0; i < msgs.length; i++) {
htmlHistorico += "<li class='hist-item'>" + msgs[i] + "</li>";
}
htmlHistorico += "</ul>";
// Script para abrir modal ao clicar no botão
customHTML.append("<script>");
customHTML.append("$('#btnHistorico').off('click').on('click', function(){");
customHTML.append(" var myModal = FLUIGC.modal({");
customHTML.append(" title: 'Histórico do Processo',");
customHTML.append(" content: `" + htmlHistorico + "`,");
customHTML.append(" id: 'modalHistorico',");
customHTML.append(" size: 'large'");
customHTML.append(" });");
customHTML.append("});");
customHTML.append("</script>");
} catch (e) {
log.error("[displayFields] Erro ao montar histórico: " + e);
}
var numCot = form.getValue("cotacaoSCProtheus");
var numSC = form.getValue("numeroSCProtheus"); // pega a SC atual
function formatCurrency(v) {
if (!v || isNaN(v)) return "R$ 0,00";
var num = parseFloat(v).toFixed(2);
return "R$ " + num.replace(".", ",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
function formatDate(v) {
if (!v || v.length !== 8) return v || "";
var y = v.substring(0,4);
var m = v.substring(4,6);
var d = v.substring(6,8);
return d + "/" + m + "/" + y;
}
function formatPrazo(v) {
if (!v) return "";
return v + " dias úteis";
}
if (!numCot) {
customHTML.append("<script>");
customHTML.append("$('#cotacaoContainer').html('<p>⚠️ Cotação não informada no formulário.</p>');");
customHTML.append("</script>");
return;
}
var c = DatasetFactory.createConstraint("numCotacao", numCot, numCot, ConstraintType.MUST);
var ds = DatasetFactory.getDataset("dsComprasCotacao", null, [c], null);
var precoFormatado = formatCurrency(preco);
var totalFormatado = formatCurrency(total);
if (ds && ds.rowsCount > 0) {
for (var i = 0; i < ds.rowsCount; i++) {
var item = ds.getValue(i, "C8_ITEM");
var desc = ds.getValue(i, "B1_DESC");
var qtd = ds.getValue(i, "C8_QUANT");
var preco = ds.getValue(i, "C8_PRECO");
var total = ds.getValue(i, "C8_TOTAL");
// adiciona linha na tabela pai-filho
customHTML.append("<script>");
customHTML.append("var idx = wdkAddChild('tbCotacao');");
customHTML.append("$('#item___'+idx).val('" + item + "');");
customHTML.append("$('#produto___'+idx).val('" + desc + "');");
customHTML.append("$('#qtdc___'+idx).val('" + qtd + "');");
customHTML.append("$('#preco___' + idx).val('" + precoFormatado + "');");
customHTML.append("$('#total___' + idx).val('" + totalFormatado + "');");
customHTML.append("</script>");
}
} else {
customHTML.append("<script>$('#tbCotacao tbody').html('<tr><td colspan=6>⏳ Nenhum item encontrado.</td></tr>');</script>");
}
try {
var numPedido = form.getValue("pedidoSCProtheus"); // hidden no formulário
if (!numPedido) {
customHTML.append("<script>");
customHTML.append("$('#espelhoPedido').html('<span class=\"badge bg-warning\">⏳ O pedido ainda não foi criado</span>');");
customHTML.append("</script>");
return;
}
var c = DatasetFactory.createConstraint("numeroPed", numPedido, numPedido, ConstraintType.MUST);
var ds = DatasetFactory.getDataset("dsComprasGateway", null, [c], null);
if (!ds || ds.rowsCount === 0) {
customHTML.append("<script>");
customHTML.append("$('#espelhoPedido').html('<span class=\"badge bg-warning\">⏳ O pedido ainda não foi criado</span>');");
customHTML.append("</script>");
return;
}
var html = "";
for (var i = 0; i < ds.rowsCount; i++) {
var rowNum = ds.getValue(i, "C7_NUM");
var desc = ds.getValue(i, "B1_DESC");
var qtd = ds.getValue(i, "C7_QUANT");
var valor = ds.getValue(i, "C7_TOTAL");
var un = ds.getValue(i, "B1_UM");
var pr = ds.getValue(i, "C7_DATPRF");
html += "<div class='pedido-card'>"
+ " <div class='pedido-header'>Pedido nº " + (rowNum || "-") + "</div>"
+ " <div class='pedido-grid'>"
+ " <div class='pedido-box'><b>Descrição</b><br>" + (desc || "-") + "</div>"
+ " <div class='pedido-box'><b>Quantidade</b><br>" + parseInt(qtd || 0) + " " + (un || "") + "</div>"
+ " <div class='pedido-box'><b>Valor</b><br>" + formatCurrency(valor) + "</div>"
+ " <div class='pedido-box'><b>Data de Entrega</b><br>" + formatDate(pr) + "</div>"
+ " </div>"
+ "</div>";
}
customHTML.append("<script>");
customHTML.append("$('#espelhoPedido').html(" + JSON.stringify(html) + ");");
customHTML.append("</script>");
} catch (e) {
var msg = "❌ Erro displayFields Pedido: " + (e && e.message ? e.message : e);
log.error(msg);
customHTML.append("<script>");
customHTML.append("console.error(" + JSON.stringify(msg) + ");"); // aparece no console do navegador
customHTML.append("$('#espelhoPedido').html('<span class=\"badge bg-danger\">" + msg + "</span>');");
customHTML.append("</script>");
}
// Se estou na atividade do Gestor do CC (ex: 133)
if (activity == 133) {
// Copia a justificativa do solicitante para o campo de exibição
form.setValue("observacoesdosolicitante", form.getValue("observacoes"));
}
// Se estou na atividade do GERF (ex: 147)
if (activity == 147) {
form.setValue("justi_decisao__soli", form.getValue("observacoes")); // solicitante
form.setValue("justi_decisao_gc", form.getValue("justi_decisao_aprova_gestor")); // gestor
}
// Se estou na atividade do CEO (ex: 158)
if (activity == 158) {
form.setValue("justi_decisao_solic", form.getValue("observacoes")); // solicitante
form.setValue("justi_decisaogc", form.getValue("justi_decisao_aprova_gestor")); // gestor
form.setValue("justi_decisao_gerf", form.getValue("justi_decisao_aprova_gerente")); // gerente financeiro
}
}