Files
Online-Topup-V1/application/tests/cash-in-posting.integration.test.js
T
2026-11-24 12:48:27 +07:00

147 lines
6.6 KiB
JavaScript

const { createServer } = require('node:http');
const { once } = require('node:events');
const express = require('express');
const request = require('supertest');
const migration = require('../../infrastructure/database/migrations/20261124000200_create_cash_in_sap_posting');
jest.mock('../../infrastructure/database/knex', () => require('knex')({
client: 'pg',
connection: process.env.TOPUP_TEST_CASH_IN_DB_URL,
pool: { min: 0, max: 1, acquireTimeoutMillis: 2000 },
}));
const connection = process.env.TOPUP_TEST_CASH_IN_DB_URL;
const integration = connection ? describe : describe.skip;
const soapResponse = `<Envelope><Body><ZFMCMS_FI_001.Response>
<E_DOCUMENTYEAR>2026</E_DOCUMENTYEAR><E_DOCUMENTNUMBER>100007</E_DOCUMENTNUMBER>
<C_T_RETURN><item><TYPE>S</TYPE><MESSAGE_1>OK</MESSAGE_1></item></C_T_RETURN>
</ZFMCMS_FI_001.Response></Body></Envelope>`;
integration('cash-in SAP posting with PostgreSQL and a local HTTP stand-in', () => {
let db;
let postCashIn;
let sap;
let app;
let answer;
const requests = [];
beforeAll(async () => {
const url = new URL(connection);
if (url.hostname !== '127.0.0.1' || url.pathname !== '/topup_cashin_test') {
throw new Error('Cash-in tests require a disposable localhost topup_cashin_test database');
}
db = require('../../infrastructure/database/knex');
postCashIn = require('../modules/cashin/cash-in-posting.service');
app = express();
app.use(express.json());
app.use('/api', require('../routes/cahsin.routes'));
await db.raw(`
CREATE SCHEMA payment;
CREATE SCHEMA trx;
CREATE TABLE payment.t_d_cash_in (
i_cash_in serial PRIMARY KEY, c_cash_in_no text UNIQUE, c_return_sap text, c_return_year_sap text
);
CREATE TABLE payment.t_d_cash_in_detail (i_cash_in integer, c_reservation_no text);
CREATE TABLE trx.t_d_reservation_balance (c_reservation_no text, c_return_cash_in_sap text, c_cash_in_no text);
CREATE TABLE public.posting_et (
doc_header_text text, ba text, doc_date date, posting_date date, fiscal_year text,
doc_type text, reference text, no_dok text, tcode text, amount integer,
debit_kredit text, customer text, account text, text text,
pos_status integer, status0 text, no_doksap text, status1 text
);
CREATE TABLE public.t_m_global_parameter_sap (c_status text, c_code text, c_value text);
`);
await migration.up(db);
sap = createServer((req, res) => {
requests.push(req.headers.authorization);
req.resume();
answer(res);
}).listen(0, '127.0.0.1');
await once(sap, 'listening');
await db('t_m_global_parameter_sap').insert([
{ c_code: 'SAP_FI_URL_FOR_FB70', c_value: `http://127.0.0.1:${sap.address().port}` },
{ c_code: 'SAP_AUTH_USERNAME', c_value: 'fixture' },
{ c_code: 'SAP_AUTH_PASSWORD', c_value: 'secret' },
].map((row) => ({ ...row, c_status: 'A' })));
});
afterAll(async () => {
if (sap) {
const closed = once(sap, 'close');
sap.close();
sap.closeAllConnections();
await closed;
}
await db?.destroy();
});
async function enqueue(code) {
const [cash] = await db('payment.t_d_cash_in').insert({ c_cash_in_no: code }).returning('i_cash_in');
await db('payment.t_d_cash_in_detail').insert({ i_cash_in: cash.i_cash_in, c_reservation_no: code });
await db('trx.t_d_reservation_balance').insert({ c_reservation_no: code });
const item = { no_dok: code, reference: code, tcode: 'FB70', pos_status: 4, amount: 100 };
await db('posting_et').insert([
{ ...item, debit_kredit: 'S', customer: '123' },
{ ...item, debit_kredit: 'H', account: '456' },
]);
}
test('releases the only DB connection during SAP and prevents a duplicate post', async () => {
await enqueue('CASH-SUCCESS');
const call = once(sap, 'request', { signal: AbortSignal.timeout(3000) });
let sapReply;
answer = (res) => { sapReply = res; };
const before = requests.length;
const first = request(app).post('/api/online/cash-in/posting').send({}).then((response) => response);
try {
await call;
expect(db.client.pool.numUsed()).toBe(0);
expect(await postCashIn('concurrent fixture')).toEqual([]);
expect(requests.slice(before)).toEqual([`Basic ${Buffer.from('fixture:secret').toString('base64')}`]);
} finally {
sapReply?.end(soapResponse);
expect((await first).body).toMatchObject({ code: '200', data: [{ no_dok: 'CASH-SUCCESS' }] });
}
expect(await db('payment.t_d_cash_in').where('c_cash_in_no', 'CASH-SUCCESS').first())
.toMatchObject({ c_return_sap: '100007', c_return_year_sap: '2026' });
expect(await db('trx.t_d_reservation_balance').where('c_reservation_no', 'CASH-SUCCESS').first())
.toMatchObject({ c_return_cash_in_sap: '100007' });
expect(await db('posting_et').where('no_dok', 'CASH-SUCCESS').pluck('pos_status')).toEqual([0, 0]);
});
test('holds a document for reconciliation when SAP returns an uncertain result', async () => {
await enqueue('CASH-UNKNOWN');
answer = (res) => { res.writeHead(500).end('uncertain'); };
const before = requests.length;
await postCashIn('fixture');
expect(await postCashIn('retry fixture')).toEqual([]);
expect(requests.length - before).toBe(1);
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-UNKNOWN').first())
.toMatchObject({ state: 'unknown', outcome: 'SAP_HTTP_ERROR' });
expect(await db('posting_et').where('no_dok', 'CASH-UNKNOWN').pluck('pos_status')).toEqual([4, 4]);
});
test('retries local finalization without another SAP request', async () => {
await enqueue('CASH-RECOVER');
await db.raw(`
ALTER TABLE public.posting_et ADD CONSTRAINT reject_fixture_finalize
CHECK (no_dok <> 'CASH-RECOVER' OR pos_status = 4)
`);
answer = (res) => res.end(soapResponse);
const before = requests.length;
try {
await expect(postCashIn('fixture')).rejects.toMatchObject({ code: '23514' });
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-RECOVER').first())
.toMatchObject({ state: 'accepted', document_no: '100007' });
expect(await db('payment.t_d_cash_in').where('c_cash_in_no', 'CASH-RECOVER').first())
.toMatchObject({ c_return_sap: null });
} finally {
await db.raw('ALTER TABLE public.posting_et DROP CONSTRAINT reject_fixture_finalize');
}
expect(await postCashIn('recovery fixture')).toEqual([]);
expect(requests.length - before).toBe(1);
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-RECOVER').first())
.toMatchObject({ state: 'completed' });
});
});