feat(v2): real Slack send pipeline (guard, idempotency, success/failure registration)
Implements the actual send branch: Selecionar Top N -> Montar Mensagem ->
Guard de Envio -> Slack real -> registrar resultado (only after
confirmed success/failure) -- previously simulated/absent.
logic/slack.js (new): shouldSendByConfig (SEND_ENABLED gate, defaults
false), computeMessageHash (djb2Hash of the exact message text, reused
from logic/hash.js), alreadySentSuccessfully (idempotency check: only a
prior status='success' record for the same report_date+run_type+
message_hash blocks a resend -- a prior 'failed' record does not, so
retries after a real failure aren't stuck), evaluateSendGuard (single
auditable decision combining both), buildEnvioDigestRecord.
logic/slack.test.js: 13 tests covering all of the above, explicitly
labeled against the mission's required tests #13-#16.
New node drivers:
- guard-envio-slack.node.js: reads the digest + recent envio records
(fetched by report_date), computes the send decision.
- Slack node itself (n8n-nodes-base.slack, native, not a raw webhook):
reuses the real "Slack account" credential (slackApi) and
$vars.SLACK_CHANNEL_TECNICO channel variable already used by this
org's own "Notificacao de Erros Globais" workflow on the same n8n
instance -- V1's own Slack webhook URL was never actually deployed
(its Config value is literally "SEU/WEBHOOK/AQUI", same class of
placeholder as the old GLPI URL from the prior cycle), so this reuses
the one REAL, credentialed Slack mechanism that exists in this
environment rather than inventing a new destination. onError:
continueErrorOutput splits success/failure into two branches.
- registrar-envio-sucesso.node.js / registrar-envio-falha.node.js: build
the success/failure record; only the success path continues to the
existing per-ticket send-counter logic (rewired below).
- lancar-erro-envio.node.js: after the failure record is written,
explicitly throws so the n8n execution shows status=error (never
silently swallow a send failure).
- pular-envio.node.js: terminal no-op for the "should not send" branch
(SEND_ENABLED=false or already sent today), for observability only.
n8n/nodes/prepare-envio-record.node.js: rewired to read the Top10
selection by name ($('Code - Selecionar Top 10').all()) instead of
$input, since it now runs downstream of the Slack-success registration,
not directly off Selecionar Top10 -- registering per-ticket send counts
before Slack ever confirmed anything was the exact "don't register
before confirmation" bug the mission called out.
logic/message.test.js: added a full-Top10 message-length regression test
(mission requirement: message stays short, no leaked JSON/score/evidence).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
e0f4b9a5d0
commit
abc690ddb7
@@ -49,3 +49,15 @@ test('digest de coordenacao lista apenas os itens passados (novos/alterados)', (
|
||||
const digest = buildCoordinationDigest([{ ticket: { id: 37691 }, aiClassification: { reason: 'aguardando definicao' }, exclusionReason: 'needs_coordination' }], '24/08');
|
||||
assert.ok(digest.includes('#37691'));
|
||||
});
|
||||
|
||||
test('mensagem com 10 chamados continua curta (teste obrigatorio #19 -- nao vira relatorio longo)', () => {
|
||||
const dezItens = Array.from({ length: 10 }, (_, i) => selectedItem({
|
||||
ticket: { ...selectedItem({}).ticket, id: 38600 + i, titulo: `Titulo do chamado numero ${i} com texto razoavelmente longo` },
|
||||
}));
|
||||
const msg = buildTopMessage(dezItens, '25/08', {});
|
||||
// 10 blocos de ~4 linhas curtas cada + cabecalho: bem abaixo de um "relatorio". Limite
|
||||
// generoso o suficiente pra nao quebrar por titulos longos, mas que pegaria regressao real
|
||||
// (ex.: reason/evidence/JSON vazando pra mensagem).
|
||||
assert.ok(msg.length < 2000, `mensagem ficou com ${msg.length} caracteres, esperado < 2000`);
|
||||
assert.ok(!/"classification"|"evidence"|"confidence"/.test(msg), 'mensagem nao pode vazar campos internos/JSON');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
const { djb2Hash } = require('./hash');
|
||||
|
||||
// Hash estavel do texto exato que seria enviado -- usado como parte da chave de
|
||||
// idempotencia (junto com report_date/run_type). Duas mensagens com o mesmo conteudo no
|
||||
// mesmo dia nunca devem gerar dois envios reais.
|
||||
function computeMessageHash(text) {
|
||||
return djb2Hash(String(text || ''));
|
||||
}
|
||||
|
||||
// SEND_ENABLED e o unico gate de "isso pode realmente sair pro Slack" -- nunca depende de
|
||||
// editar codigo (missao "finalizacao para producao", secao 22).
|
||||
function shouldSendByConfig(config) {
|
||||
return Boolean(config && config.sendEnabled);
|
||||
}
|
||||
|
||||
// Idempotencia: so conta como "ja enviado" um registro com status 'success' para a MESMA
|
||||
// data + tipo de execucao + hash de mensagem. Um retry apos falha (status 'failed') nao
|
||||
// bloqueia um novo envio -- so um sucesso anterior bloqueia.
|
||||
function alreadySentSuccessfully(existingRecords, { reportDate, runType, messageHash }) {
|
||||
return (existingRecords || []).some((record) => (
|
||||
record
|
||||
&& record.status === 'success'
|
||||
&& record.report_date === reportDate
|
||||
&& record.run_type === runType
|
||||
&& record.message_hash === messageHash
|
||||
));
|
||||
}
|
||||
|
||||
// Decisao unica de "devo mandar pro Slack agora" -- centraliza os dois motivos possiveis de
|
||||
// NAO enviar (SEND_ENABLED=false, ou ja enviado com sucesso hoje) num so lugar auditavel.
|
||||
function evaluateSendGuard({ config, existingRecords, reportDate, runType, messageHash }) {
|
||||
if (!shouldSendByConfig(config)) {
|
||||
return { shouldSend: false, reason: 'send_disabled' };
|
||||
}
|
||||
if (alreadySentSuccessfully(existingRecords, { reportDate, runType, messageHash })) {
|
||||
return { shouldSend: false, reason: 'already_sent' };
|
||||
}
|
||||
return { shouldSend: true, reason: 'ok' };
|
||||
}
|
||||
|
||||
function buildEnvioDigestRecord({ reportDate, runType, messageHash, sentAt, status, errorDetail }) {
|
||||
return {
|
||||
report_date: reportDate,
|
||||
run_type: runType,
|
||||
message_hash: messageHash,
|
||||
sent_at: sentAt,
|
||||
status,
|
||||
error_detail: errorDetail || null,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeMessageHash,
|
||||
shouldSendByConfig,
|
||||
alreadySentSuccessfully,
|
||||
evaluateSendGuard,
|
||||
buildEnvioDigestRecord,
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
computeMessageHash, shouldSendByConfig, alreadySentSuccessfully, evaluateSendGuard, buildEnvioDigestRecord,
|
||||
} = require('./slack');
|
||||
|
||||
test('computeMessageHash e deterministico para o mesmo texto', () => {
|
||||
assert.equal(computeMessageHash('ola mundo'), computeMessageHash('ola mundo'));
|
||||
});
|
||||
|
||||
test('computeMessageHash muda quando o texto muda', () => {
|
||||
assert.notEqual(computeMessageHash('ola mundo'), computeMessageHash('ola mundo!'));
|
||||
});
|
||||
|
||||
test('SEND_ENABLED=false nunca deixa enviar -- missao secao 22/13', () => {
|
||||
assert.equal(shouldSendByConfig({ sendEnabled: false }), false);
|
||||
});
|
||||
|
||||
test('SEND_ENABLED=true libera o envio (sujeito ainda a idempotencia)', () => {
|
||||
assert.equal(shouldSendByConfig({ sendEnabled: true }), true);
|
||||
});
|
||||
|
||||
test('alreadySentSuccessfully detecta envio de sucesso identico (mesma data/tipo/hash)', () => {
|
||||
const existing = [{ report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'abc', status: 'success' }];
|
||||
assert.equal(alreadySentSuccessfully(existing, { reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' }), true);
|
||||
});
|
||||
|
||||
test('alreadySentSuccessfully ignora registros de falha -- retry apos erro nao fica bloqueado', () => {
|
||||
const existing = [{ report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'abc', status: 'failed' }];
|
||||
assert.equal(alreadySentSuccessfully(existing, { reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' }), false);
|
||||
});
|
||||
|
||||
test('alreadySentSuccessfully ignora envios de outro dia ou outro hash', () => {
|
||||
const existing = [{ report_date: '2026-08-24', run_type: 'scheduled', message_hash: 'abc', status: 'success' }];
|
||||
assert.equal(alreadySentSuccessfully(existing, { reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' }), false);
|
||||
const existing2 = [{ report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'xyz', status: 'success' }];
|
||||
assert.equal(alreadySentSuccessfully(existing2, { reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' }), false);
|
||||
});
|
||||
|
||||
test('evaluateSendGuard: Slack NAO envia com SEND_ENABLED=false -- teste obrigatorio #13', () => {
|
||||
const result = evaluateSendGuard({ config: { sendEnabled: false }, existingRecords: [], reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' });
|
||||
assert.equal(result.shouldSend, false);
|
||||
assert.equal(result.reason, 'send_disabled');
|
||||
});
|
||||
|
||||
test('evaluateSendGuard: Slack envia com SEND_ENABLED=true e nenhum envio anterior -- teste obrigatorio #14', () => {
|
||||
const result = evaluateSendGuard({ config: { sendEnabled: true }, existingRecords: [], reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' });
|
||||
assert.equal(result.shouldSend, true);
|
||||
assert.equal(result.reason, 'ok');
|
||||
});
|
||||
|
||||
test('evaluateSendGuard: envio duplicado e bloqueado -- teste obrigatorio #15', () => {
|
||||
const existing = [{ report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'abc', status: 'success' }];
|
||||
const result = evaluateSendGuard({ config: { sendEnabled: true }, existingRecords: existing, reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' });
|
||||
assert.equal(result.shouldSend, false);
|
||||
assert.equal(result.reason, 'already_sent');
|
||||
});
|
||||
|
||||
test('evaluateSendGuard: retry (mensagem diferente) apos falha anterior nao e bloqueado', () => {
|
||||
const existing = [{ report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'abc', status: 'failed' }];
|
||||
const result = evaluateSendGuard({ config: { sendEnabled: true }, existingRecords: existing, reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc' });
|
||||
assert.equal(result.shouldSend, true);
|
||||
});
|
||||
|
||||
test('buildEnvioDigestRecord monta o registro de sucesso corretamente', () => {
|
||||
const record = buildEnvioDigestRecord({ reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc', sentAt: 12345, status: 'success' });
|
||||
assert.deepEqual(record, {
|
||||
report_date: '2026-08-25', run_type: 'scheduled', message_hash: 'abc', sent_at: 12345, status: 'success', error_detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('buildEnvioDigestRecord monta o registro de falha com error_detail -- falha nunca registra sucesso (teste obrigatorio #16)', () => {
|
||||
const record = buildEnvioDigestRecord({
|
||||
reportDate: '2026-08-25', runType: 'scheduled', messageHash: 'abc', sentAt: 12345, status: 'failed', errorDetail: 'HTTP 500',
|
||||
});
|
||||
assert.equal(record.status, 'failed');
|
||||
assert.equal(record.error_detail, 'HTTP 500');
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
// @requires config.js hash.js slack.js
|
||||
// Roda depois de "Data Table - Buscar Envios Recentes" (fetch por report_date=hoje), que existe
|
||||
// so pra trazer os registros de envio ja existentes; os dados do digest sao lidos por nome
|
||||
// (mesmo padrao ja usado em Code - Comparar Legacy x V2).
|
||||
const digestData = $('Code - Montar Digest Coordenacao').first().json; // { mensagem, selected, excluded, dateStr, digest, changedBlocked }
|
||||
const config = digestData.selected.length ? digestData.selected[0].config : parseConfig($('Config - Coordenador GLPI v2').first().json);
|
||||
const existingRecords = $input.all().map((item) => item.json);
|
||||
|
||||
// $execution.mode: 'manual' quando disparado pelo Manual Trigger, senao ('trigger' no
|
||||
// Schedule Trigger) tratamos como execucao agendada. Nao inventa um mecanismo novo de deteccao.
|
||||
const runType = $execution.mode === 'manual' ? 'manual' : 'scheduled';
|
||||
const messageHash = computeMessageHash(digestData.mensagem);
|
||||
const guard = evaluateSendGuard({
|
||||
config, existingRecords, reportDate: digestData.dateStr, runType, messageHash,
|
||||
});
|
||||
|
||||
return [{
|
||||
json: {
|
||||
mensagem: digestData.mensagem,
|
||||
dateStr: digestData.dateStr,
|
||||
runType,
|
||||
messageHash,
|
||||
shouldSend: guard.shouldSend,
|
||||
reason: guard.reason,
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,10 @@
|
||||
// Roda depois de "Data Table - Registrar Envio Digest (Falha)" ja ter gravado o status=failed.
|
||||
// So agora propaga o erro de verdade, pra a execucao no n8n ficar visivelmente com status de
|
||||
// erro (missao "finalizacao para producao", secao 19: "Nao silenciar erro").
|
||||
const registro = $input.first().json;
|
||||
throw new Error(`Envio ao Slack falhou (report_date=${registro.report_date}, run_type=${registro.run_type}): ${registro.error_detail}`);
|
||||
// eslint-disable-next-line no-unreachable -- linha morta de proposito: o validador estatico do
|
||||
// n8n-mcp exige um "return" literal no texto do node (heuristica que nao reconhece um node cujo
|
||||
// unico proposito e lancar erro -- confirmado via validate_node, mesmo comportamento do falso
|
||||
// positivo do .join() ja documentado neste projeto). Nunca executa; o throw acima sempre sai primeiro.
|
||||
return [];
|
||||
@@ -1,6 +1,9 @@
|
||||
const ONE_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
return $input.all()
|
||||
// So roda depois de "Data Table - Registrar Envio Digest (Sucesso)" -- ou seja, so depois do
|
||||
// Slack confirmar sucesso de verdade (missao "finalizacao para producao", secao 19). Os dados
|
||||
// do Top10 sao lidos por nome (nao por $input, que aqui e o registro do envio, nao os tickets).
|
||||
return $('Code - Selecionar Top 10').all()
|
||||
.filter((item) => item.json._grupo === 'selected')
|
||||
.map((item) => {
|
||||
const data = item.json;
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Branch "nao deve enviar" do guard (SEND_ENABLED=false ou ja enviado com sucesso hoje).
|
||||
// Node terminal, so pra deixar visivel na execucao do n8n por que nao mandou nada -- sem
|
||||
// escrever em nenhuma Data Table (nao e uma falha, e uma decisao esperada).
|
||||
const data = $input.first().json;
|
||||
return [{ json: { skipped: true, reason: data.reason, dateStr: data.dateStr, runType: data.runType } }];
|
||||
@@ -0,0 +1,18 @@
|
||||
// @requires hash.js slack.js
|
||||
// So roda no output de erro do node "Slack - Enviar Mensagem" (onError: continueErrorOutput).
|
||||
// Registra status=failed com o erro real ANTES de propagar a falha (proximo node lanca o
|
||||
// erro de verdade, pra execucao ficar visivelmente vermelha no n8n -- nao silenciar).
|
||||
const guardData = $('Code - Guard de Envio Slack').first().json;
|
||||
const errorItem = $input.first().json || {};
|
||||
const errorMessage = String(errorItem.error || errorItem.message || 'Erro desconhecido ao enviar mensagem ao Slack').slice(0, 500);
|
||||
|
||||
const record = buildEnvioDigestRecord({
|
||||
reportDate: guardData.dateStr,
|
||||
runType: guardData.runType,
|
||||
messageHash: guardData.messageHash,
|
||||
sentAt: Date.now(),
|
||||
status: 'failed',
|
||||
errorDetail: errorMessage,
|
||||
});
|
||||
|
||||
return [{ json: record }];
|
||||
@@ -0,0 +1,14 @@
|
||||
// @requires hash.js slack.js
|
||||
// So roda no output de sucesso do node "Slack - Enviar Mensagem" (onError: continueErrorOutput).
|
||||
// Registrar sent_at/status so DEPOIS da confirmacao real do Slack -- nunca antes (missao
|
||||
// "finalizacao para producao", secao 19).
|
||||
const guardData = $('Code - Guard de Envio Slack').first().json;
|
||||
const record = buildEnvioDigestRecord({
|
||||
reportDate: guardData.dateStr,
|
||||
runType: guardData.runType,
|
||||
messageHash: guardData.messageHash,
|
||||
sentAt: Date.now(),
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
return [{ json: record }];
|
||||
Reference in New Issue
Block a user