Files
SLACK_COORD_RELATORIO/logic/message.test.js
T
GustavoandClaude Sonnet 5 abc690ddb7 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>
2026-08-24 20:50:54 -03:00

64 lines
3.0 KiB
JavaScript

const { test } = require('node:test');
const assert = require('node:assert/strict');
const { buildTopMessage, buildCoordinationDigest, shortActionLabel, tituloCurto } = require('./message');
function selectedItem(overrides) {
return Object.assign({
ticket: {
id: 38611, titulo: 'Colocar etiqueta sala 03', tecnico_atribuido: 'Sem tecnico atribuido',
sem_tecnico: true, sla_vencido: false, dias_sem_interacao: 2, link_glpi: 'https://glpi/x?id=38611',
},
aiClassification: { classification: 'UNASSIGNED_ACTIONABLE', next_action: 'Atribuir e executar', is_fallback: false },
}, overrides);
}
test('mensagem final contem cabecalho, id, link e acao curta', () => {
const msg = buildTopMessage([selectedItem({})], '24/08', {});
assert.ok(msg.includes('#38611'));
assert.ok(msg.includes('https://glpi/x?id=38611'));
assert.ok(msg.includes('→'));
assert.ok(msg.includes('24/08'));
});
test('mensagem NAO contem score, confianca ou justificativa longa', () => {
const msg = buildTopMessage([selectedItem({})], '24/08', {});
assert.ok(!/confian(c|ç)a/i.test(msg));
assert.ok(!/score/i.test(msg));
});
test('linha de acao e curta (limite de tamanho)', () => {
const label = shortActionLabel({ classification: 'ACTIONABLE_NOW', next_action: 'x'.repeat(100), is_fallback: false });
assert.ok(label.length <= 40);
});
test('tituloCurto limita a 60 caracteres', () => {
const curto = tituloCurto('a'.repeat(100));
assert.ok(curto.length <= 60);
});
test('digest de coordenacao vazio retorna null (nao manda lista igual todo dia)', () => {
assert.equal(buildCoordinationDigest([], '24/08'), null);
});
test('mensagem nao tem linhas em branco duplicadas entre cabecalho e blocos', () => {
const msg = buildTopMessage([selectedItem({}), selectedItem({ ticket: { ...selectedItem({}).ticket, id: 38612 } })], '24/08', {});
assert.ok(!msg.includes('\n\n\n'), 'nao deveria haver 3+ quebras de linha seguidas');
});
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');
});