import { test, after } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'fs'; import path from 'path'; import express from 'express'; import { AddressInfo } from 'net'; import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, isTinyCall, silenceConsole } from './helpers'; setTestEnv({ N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' }); const runtimeDir = process.env.RUNTIME_DATA_DIR!; const { handleTinyStockUpdate } = require('../src/controllers/webhook.controller'); const webhookRoutes = require('../src/routes/webhook.route'); const calls = mockAxiosPost(async (url, data) => { if (!isTinyCall(url)) return { status: 200, data: {} }; return tinyOrder(new URLSearchParams(data.toString()).get('id')!); }); const capture = silenceConsole(); after(() => { capture.restore(); fs.rmSync(runtimeDir, { recursive: true, force: true }); }); const stockWebhook = (saldo: number) => ({ query: {}, body: { dados: { idProduto: '555', nome: 'Camiseta', saldo } } }) as any; test('stock memory and CSV are written to the persistent runtime directory', async () => { await handleTinyStockUpdate(stockWebhook(10), fakeRes()); await handleTinyStockUpdate(stockWebhook(25), fakeRes()); const memory = JSON.parse(fs.readFileSync(path.join(runtimeDir, 'stock_memory.json'), 'utf-8')); assert.equal(memory['555'].saldo, 25); assert.ok(fs.readFileSync(path.join(runtimeDir, 'stock_log.csv'), 'utf-8').includes('"555","Camiseta","10","25","15"')); const forwarded = calls.filter(c => c.url === 'http://n8n.test/stock').map(c => c.data.dados); assert.equal(forwarded[1].delta_estoque, 15); }); test('draining on shutdown waits for webhooks that were acked but still queued', async () => { const app = express(); app.use(express.json()); app.use('/api/webhooks', webhookRoutes.default); const server = app.listen(0); const { port } = server.address() as AddressInfo; try { const ids = [3001, 3002, 3003]; for (const id of ids) { const res = await fetch(`http://127.0.0.1:${port}/api/webhooks/tiny/order-status`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ dados: { id, codigoSituacao: 'pronto_envio', descricaoSituacao: 'Pronto para envio' } }) }); assert.equal(res.status, 200); } const forwardedBefore = calls.filter(c => c.url === 'http://n8n.test/status').length; assert.ok(forwardedBefore < ids.length, 'some orders are still queued when shutdown starts'); const remaining = await webhookRoutes.drainWebhookWork(10000); assert.equal(remaining, 0); assert.equal(calls.filter(c => c.url === 'http://n8n.test/status').length, ids.length); } finally { server.close(); } });