const { once } = require('node:events'); const { createServer } = require('node:http'); const db = require('../../infrastructure/database/knex'); const helper = require('../helpers/helper'); const model = require('../modules/invoiceonline/invoice.model'); const { generateInvoice, retryInvoices } = require('../modules/invoiceonline/invoice-posting.service'); jest.mock('../../infrastructure/database/knex', () => ({ transaction: jest.fn() })); jest.mock('../helpers/helper', () => ({ generateXMLRequest: jest.fn(), postingSAP: jest.fn(), getXMLData: jest.fn(), })); jest.mock('../helpers/winston.logger', () => ({ logger: { warn: jest.fn() } })); jest.mock('../modules/invoiceonline/invoice.model'); const invoiceNo = 'INV-TEST-1'; const generated = { c_invoice_no: invoiceNo, c_account_code_topup: 'DEBIT', c_account_topup: 'CREDIT', }; const queued = { reference: invoiceNo, customer: 'DEBIT', account: 'CREDIT' }; beforeEach(() => { jest.resetAllMocks(); helper.generateXMLRequest.mockReturnValue(''); model.getSapSettings.mockResolvedValue({ url: 'http://sap.test', username: 'fixture', password: 'fixture' }); model.getPostingEt.mockResolvedValue([queued]); model.getAcceptedSapPostings.mockResolvedValue([]); model.getInvoice.mockResolvedValue(generated); }); test('generation commits its queue before SAP and finalizes after a confirmed document', async () => { const trx = {}; let committed = false; db.transaction.mockImplementation(async (callback) => { const result = await callback(trx); committed = true; return result; }); model.generateInvoice.mockResolvedValue([generated]); model.claimSapPosting.mockResolvedValue(true); model.finishSapPosting.mockResolvedValue(generated); helper.postingSAP.mockImplementation(() => { expect(committed).toBe(true); return { status: 200 }; }); helper.getXMLData.mockReturnValue({ type: 'S', data: { E_DOCUMENTNUMBER: '0000123456' } }); await expect(generateInvoice('2026-11-23', 'run', false)).resolves.toEqual([generated]); expect(model.insertPostingEt).toHaveBeenCalledWith(generated, trx); expect(model.claimSapPosting).toHaveBeenCalledWith(db, invoiceNo, true); expect(helper.postingSAP).toHaveBeenCalledWith( 'http://sap.test', '', { username: 'fixture', password: 'fixture' }, { timeoutMs: 15000, maxRedirects: 0 } ); expect(model.recordSapOutcome).toHaveBeenCalledWith(db, invoiceNo, '0000123456', 'SAP_CONFIRMED'); expect(model.finishSapPosting).toHaveBeenCalledWith(db, invoiceNo); }); test.each([ [{ status: 500, errorCode: 'ERR_CANCELED' }, 'SAP_TIMEOUT'], [{ status: 502 }, 'SAP_HTTP_ERROR'], [{ status: 200 }, 'SAP_INVALID_RESPONSE'], ])('one claim stops concurrent and later retries after an ambiguous result', async (response, outcome) => { let claimed = false; model.claimSapPosting.mockImplementation(async () => { if (claimed) return false; claimed = true; return true; }); helper.postingSAP.mockResolvedValue(response); helper.getXMLData.mockImplementation(() => { throw new Error('invalid XML'); }); await Promise.all([retryInvoices('first'), retryInvoices('concurrent')]); await retryInvoices('later'); expect(helper.postingSAP).toHaveBeenCalledTimes(1); expect(model.recordSapOutcome).toHaveBeenCalledWith(db, invoiceNo, null, outcome); expect(model.releaseUnsentPosting).not.toHaveBeenCalled(); }); test('a connection refusal makes the invoice eligible for another attempt', async () => { model.claimSapPosting.mockResolvedValue(true); helper.postingSAP.mockResolvedValue({ status: 500, errorCode: 'ECONNREFUSED' }); await retryInvoices('run'); expect(model.releaseUnsentPosting).toHaveBeenCalledWith(db, invoiceNo); expect(model.recordSapOutcome).not.toHaveBeenCalled(); }); test('retries a previously accepted invoice locally after finalization fails', async () => { model.getAcceptedSapPostings.mockResolvedValue([invoiceNo]); model.getPostingEt.mockResolvedValue([]); model.finishSapPosting.mockRejectedValueOnce(new Error('database unavailable')).mockResolvedValue(generated); await expect(retryInvoices('first')).rejects.toThrow('database unavailable'); await expect(retryInvoices('second')).resolves.toEqual([generated]); expect(helper.postingSAP).not.toHaveBeenCalled(); }); test('real SAP HTTP client aborts a request whose response never finishes', async () => { const { postingSAP } = jest.requireActual('../helpers/helper'); const server = createServer((req) => req.resume()); const listening = once(server, 'listening'); server.listen(0, '127.0.0.1'); await listening; const incoming = once(server, 'request', { signal: AbortSignal.timeout(3000) }); try { const response = postingSAP( `http://127.0.0.1:${server.address().port}/sap`, '', { username: 'fixture', password: 'fixture' }, { timeoutMs: 250, maxRedirects: 0 } ); await incoming; expect((await response).errorCode).toMatch(/ERR_CANCELED|ECONNABORTED/); } finally { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); } });