Prevent duplicate SAP invoice posting and shorten transactions

This commit is contained in:
Mohamad Ihsan
2026-11-23 17:34:52 +07:00
parent 8d1f7a40e9
commit 5762f218fd
7 changed files with 442 additions and 533 deletions
+8 -2
View File
@@ -175,15 +175,18 @@ function generateXMLRequest(urn, headers, items) {
}
// POSTING SAP
async function postingSAP(url, body, credential) {
async function postingSAP(url, body, credential, { timeoutMs = 15000, maxRedirects } = {}) {
try {
let axios = require('axios');
let config = {
headers: {
'Content-Type': 'text/xml',
responseType: 'text',
},
responseType: 'text',
timeout: timeoutMs,
signal: AbortSignal.timeout(timeoutMs),
maxRedirects,
auth: {
username: credential.username,
password: credential.password,
@@ -207,6 +210,7 @@ async function postingSAP(url, body, credential) {
*/
return {
status: error.response.status,
errorCode: error.code,
message: error.message,
data: [],
};
@@ -218,6 +222,7 @@ async function postingSAP(url, body, credential) {
*/
return {
status: 500,
errorCode: error.code,
message: "can't connect to sap network".toUpperCase(),
data: [],
};
@@ -225,6 +230,7 @@ async function postingSAP(url, body, credential) {
// Something happened in setting up the request and triggered an Error
return {
status: 500,
errorCode: error.code,
message: error.message,
data: [],
};
@@ -0,0 +1,130 @@
const { setTimeout: delay } = require('node:timers/promises');
const helper = require('../../helpers/helper');
const { logger } = require('../../helpers/winston.logger');
const db = require('../../../infrastructure/database/knex');
const model = require('./invoice.model');
const preConnectErrors = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ERR_INVALID_URL']);
const sapTimeoutMs = 15000;
async function generateInvoice(invoiceDate, uniqueCode, repost) {
const invoices = await db.transaction(async (trx) => {
const generated = await model.generateInvoice(invoiceDate, repost, trx);
for (const invoice of generated) await model.insertPostingEt(invoice, trx);
return generated;
});
return postInvoices(invoices, uniqueCode, true);
}
async function retryInvoices(uniqueCode) {
const invoices = [];
for (const invoiceNo of await model.getAcceptedSapPostings(db)) {
const invoice = await model.finishSapPosting(db, invoiceNo);
if (invoice) invoices.push(invoice);
}
const queued = await model.getPostingEt(db);
return [...invoices, ...await postInvoices(queued, uniqueCode, false)];
}
async function postInvoices(items, uniqueCode, initialPosting) {
if (items.length === 0) return [];
const settings = await model.getSapSettings(db);
const invoices = [];
for (const [index, item] of items.entries()) {
const invoiceNo = initialPosting ? item.c_invoice_no : item.reference;
const spacingMs = index < items.length - 1 ? (initialPosting ? 1000 : 2000) : 0;
const invoice = await postInvoice(item, invoiceNo, settings, uniqueCode, initialPosting, spacingMs);
if (invoice) invoices.push(invoice);
}
return invoices;
}
async function postInvoice(item, invoiceNo, settings, uniqueCode, initialPosting, spacingMs) {
const { url, username, password } = settings;
const debitAccount = initialPosting ? item.c_account_code_topup : item.customer;
const creditAccount = initialPosting ? item.c_account_topup : item.account;
if (!invoiceNo || !url || !username || !password || !debitAccount || !creditAccount) {
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} SAP settings or accounts missing`);
return invoiceNo ? model.getInvoice(invoiceNo, db) : null;
}
const xml = generatePostingXml(item, invoiceNo, debitAccount, creditAccount, initialPosting);
if (!await model.claimSapPosting(db, invoiceNo, initialPosting)) {
return await model.finishSapPosting(db, invoiceNo) || (initialPosting ? model.getInvoice(invoiceNo, db) : null);
}
const invoice = await submitClaimedInvoice(
invoiceNo, uniqueCode, url, xml, { username, password }
);
if (spacingMs) await delay(spacingMs);
return invoice;
}
async function submitClaimedInvoice(invoiceNo, uniqueCode, url, xml, credentials) {
// Klaim sudah commit. Timeout atau kematian proses setelah pengiriman menahan retry.
const response = await helper.postingSAP(url, xml, credentials, {
timeoutMs: sapTimeoutMs,
maxRedirects: 0,
});
if (preConnectErrors.has(response.errorCode)) {
await model.releaseUnsentPosting(db, invoiceNo);
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} SAP connection not established`);
return model.getInvoice(invoiceNo, db);
}
const { documentNo, outcome } = readSapOutcome(response);
await model.recordSapOutcome(db, invoiceNo, documentNo, outcome);
if (documentNo) return model.finishSapPosting(db, invoiceNo);
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} requires SAP reconciliation (${outcome})`);
return model.getInvoice(invoiceNo, db);
}
function readSapOutcome(response) {
if (response.status !== 200) {
const timedOut = ['ERR_CANCELED', 'ECONNABORTED', 'ETIMEDOUT'].includes(response.errorCode);
return { documentNo: null, outcome: timedOut ? 'SAP_TIMEOUT' : 'SAP_HTTP_ERROR' };
}
try {
const result = helper.getXMLData(response);
const documentNo = result.data.E_DOCUMENTNUMBER;
if (result.type === 'S' && /^\d+$/.test(documentNo) && /[1-9]/.test(documentNo)) {
return { documentNo, outcome: 'SAP_CONFIRMED' };
}
} catch {
return { documentNo: null, outcome: 'SAP_INVALID_RESPONSE' };
}
return { documentNo: null, outcome: 'SAP_UNCONFIRMED' };
}
function generatePostingXml(item, invoiceNo, debitAccount, creditAccount, initialPosting) {
const header = {
doc_header_text: item.doc_header_text || '',
ba: item.ba || '',
doc_date: item.doc_date || '',
posting_date: item.posting_date || '',
fisc_year: (initialPosting ? item.fisc_year : item.fiscal_year) || '',
fisc_period: (initialPosting ? item.fisc_period : item.fis_period) || '',
doc_type: item.doc_type || '',
c_invoice_no: invoiceNo,
};
const lines = ['S', 'H'].map((side) => {
const debit = side === 'S';
const itemText = initialPosting
? `${debit ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${item.doc_header_text}`
: (debit ? item.text1 : item.text2);
return {
c_account_code_topup: debit ? debitAccount : '',
c_account_topup: debit ? '' : creditAccount,
ba: item.ba,
amount: item.amount,
posting_date: item.posting_date,
c_invoice_no: invoiceNo,
item_text: itemText,
de_cre: side,
};
});
return helper.generateXMLRequest('ZFMCMS_FI_001', header, lines);
}
module.exports = { generateInvoice, retryInvoices };
@@ -1,9 +1,8 @@
const { param, body, validationResult } = require('express-validator');
const helper = require('../../helpers/helper');
const winston = require('../../helpers/winston.logger');
const model = require('./invoice.model');
const { generateInvoice: _generateInvoice, retryInvoices: _postingInvoice } = require('./invoice-posting.service');
const moment = require('moment');
const knex = require('../../../infrastructure/database/knex');
moment.locale('id');
// VALIDATION
@@ -173,367 +172,6 @@ const apiPostingInvoice = async (req, res) => {
}
};
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
let invoice = [];
let collection = [];
await knex.transaction(async (trx) => {
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
);
invoice = await model.generateInvoice(invoiceDate, repost, trx);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify(
invoice
)}`
);
if (invoice.length > 0) {
for (let key in invoice) {
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(
invoice[key]
)}`
);
let postingEt = await model.insertPostingEt(invoice[key], trx);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(
postingEt
)}`
);
}
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
);
let credUsername = await model.getParameterSetting(
knex,
'SAP_AUTH_USERNAME'
);
let credPassword = await model.getParameterSetting(
knex,
'SAP_AUTH_PASSWORD'
);
let parameter = await model.getParameterSetting(
knex,
'SAP_FI_URL_FOR_FB70'
);
for (let key in invoice) {
let prepare = {
status: true,
cms: true,
message: 'Success',
};
if (!credUsername) {
prepare = {
status: false,
cms: false,
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME',
};
}
if (!credPassword) {
prepare = {
status: false,
cms: false,
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
};
}
if (!parameter) {
prepare = {
status: false,
cms: false,
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
};
}
let credential = {
username: credUsername.c_value,
password: credPassword.c_value,
};
if (
invoice[key].c_account_code_topup == null ||
invoice[key].c_account_topup == null
) {
prepare = {
status: false,
cms: false,
message:
'[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP',
};
}
if (
invoice[key].c_account_code_topup == '' ||
invoice[key].c_account_topup == ''
) {
prepare = {
status: false,
cms: false,
message:
'[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP',
};
}
let xmlHeader = {
doc_header_text: invoice[key].doc_header_text
? invoice[key].doc_header_text
: '',
ba: invoice[key].ba ? invoice[key].ba : '',
doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
posting_date: invoice[key].posting_date
? invoice[key].posting_date
: '',
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
c_invoice_no: invoice[key].c_invoice_no
? invoice[key].c_invoice_no
: '',
};
let xmlItem = ['S', 'H'].map((item) => {
return {
c_account_code_topup:
item == 'S' ? invoice[key].c_account_code_topup : '',
c_account_topup: item == 'H' ? invoice[key].c_account_topup : '',
ba: invoice[key].ba,
amount: invoice[key].amount,
posting_date: invoice[key].posting_date,
c_invoice_no: invoice[key].c_invoice_no,
item_text: `${item == 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${
invoice[key].doc_header_text
}`,
de_cre: item,
};
});
let xmlRequest = helper.generateXMLRequest(
'ZFMCMS_FI_001',
xmlHeader,
xmlItem
);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
);
let response = {};
if (prepare.status) {
response = await helper.postingSAP(
parameter.c_value,
xmlRequest,
credential
);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
invoice[key].c_invoice_no
} to SAP : ${JSON.stringify(response)}`
);
}
// new transaction
// await knex.transaction(async (trx) => {
let resSAP;
if (prepare.status) {
resSAP = helper.getXMLData(response);
} else {
resSAP = {
type: 'E',
message: prepare?.message || 'FAILED GET PARAMETER SETTING',
data: {},
};
}
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
resSAP
)}`
);
await wait(1000);
let cms = await model.setReturnSAP(
invoice[key],
resSAP,
trx,
true,
invoice[key].c_invoice_no
);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
);
collection.push(cms.invoice[0]);
// });
}
}
});
return collection;
};
const _postingInvoice = async (uniqueCode) => {
let postingEt = [];
let collection = [];
postingEt = await model.getPostingEt(knex);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(
postingEt
)}`
);
let credUsername = await model.getParameterSetting(knex, 'SAP_AUTH_USERNAME');
let credPassword = await model.getParameterSetting(knex, 'SAP_AUTH_PASSWORD');
let parameter = await model.getParameterSetting(knex, 'SAP_FI_URL_FOR_FB70');
let prepare = {
status: true,
message: 'Success',
};
if (!credUsername) {
prepare = {
status: false,
message: 'FAILED GET SETTING FOR SAP_AUTH_USERNAME',
};
}
if (!credPassword) {
prepare = {
status: false,
message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
};
}
if (!parameter) {
prepare = {
status: false,
message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
};
}
let credential = {
username: credUsername.c_value,
password: credPassword.c_value,
};
for (let item of postingEt) {
await knex.transaction(async (trx) => {
let response = {};
let resSAP = {};
if (prepare.status) {
let xmlHeader = {
doc_header_text: item.doc_header_text ? item.doc_header_text : '',
ba: item.ba ? item.ba : '',
doc_date: item.doc_date ? item.doc_date : '',
posting_date: item.posting_date ? item.posting_date : '',
fisc_year: item.fiscal_year ? item.fiscal_year : '',
fisc_period: item.fis_period ? item.fis_period : '',
doc_type: item.doc_type ? item.doc_type : '',
c_invoice_no: item.reference ? item.reference : '',
};
let xmlItem = ['S', 'H'].map((key) => {
return {
c_account_code_topup: key == 'S' ? item.customer : '',
c_account_topup: key == 'H' ? item.account : '',
ba: item.ba,
amount: item.amount,
posting_date: item.posting_date,
c_invoice_no: item.reference,
item_text: key == 'S' ? item.text1 : item.text2,
de_cre: key,
};
});
let xmlRequest = helper.generateXMLRequest(
'ZFMCMS_FI_001',
xmlHeader,
xmlItem
);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
);
response = await helper.postingSAP(
parameter.c_value,
xmlRequest,
credential
);
winston.logger.debug(
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
item.reference
} to SAP : ${JSON.stringify(response)}`
);
resSAP = helper.getXMLData(response);
} else {
resSAP = {
type: 'E',
message: prepare?.message || 'FAILED GET PARAMETER SETTING',
data: {},
};
}
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
// UPDATE CMS
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
resSAP
)}`
);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`
);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`
);
let invoice = await model.getInvoice(item.reference, trx);
await wait(1000);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`
);
let cms = await model.setReturnSAP(
invoice,
resSAP,
trx,
false,
item.reference
);
await wait(1000);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
);
collection.push(cms.invoice[0]);
});
}
return collection;
};
function wait(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
module.exports = {
validate,
apiPostingInvoice,
+113 -168
View File
@@ -1,15 +1,19 @@
const sapPostingTable = 'payment.t_invoice_sap_posting';
// GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.raw(`SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)
let result = await trx.raw(
'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)',
[invoiceDate, repost]
);
return result.rows || result;
}
const insertPostingEt = async (invoice, trx) => {
console.log("invoice : ", invoice)
let type = ['S', 'H']
let et = []
let posting_et = []
@@ -98,6 +102,11 @@ const getPostingEt = async (trx) => {
WHERE
pe.tcode = 'FB70'
AND pe.pos_status = '3'
AND NOT EXISTS (
SELECT 1
FROM payment.t_invoice_sap_posting sap
WHERE sap.invoice_no = pe.reference
)
-- Prefix search still index friendly
AND pe.doc_header_text LIKE 'INV%'
@@ -176,170 +185,102 @@ const getPostingEt = async (trx) => {
}
const setReturnSAP = async (invoice, resSAP, trx, posting = false, c_invoice_no) => {
let t_invoice = {}
let t_load_balance = {}
let posting_et = {}
const paymentRequestSql = `
SELECT c_load_balance_no
FROM payment.t_d_payment_request_topup_online
WHERE c_payment = ?
`;
async function claimSapPosting(db, invoiceNo, initialPosting) {
// Dokumen lama yang sudah tercatat di CMS juga tidak boleh dikirim ulang.
const invoice = await getInvoice(invoiceNo, db);
if (!invoice || invoice.c_return_sap) return false;
const postedEntry = await db('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 0 })
.first('no_dok');
if (postedEntry) return false;
if (resSAP.type == 'S') {
// update invoice
t_invoice = await trx.raw(
`
UPDATE payment.t_d_invoice
SET c_return_sap = ?
WHERE c_invoice_no = ?
RETURNING *
`,
[resSAP.data.E_DOCUMENTNUMBER, c_invoice_no]
);
const inserted = await db(sapPostingTable)
.insert({ invoice_no: invoiceNo, state: 'sending', initial_posting: initialPosting })
.onConflict('invoice_no').ignore()
.returning('invoice_no');
return inserted.length === 1;
}
// update load balance
t_load_balance = await trx.raw(
`
UPDATE trx.t_d_load_balance
SET c_return_sap = ?
WHERE c_load_balance_no IN (
${paymentRequestSql}
)
RETURNING c_load_balance_no, c_return_sap
`,
[resSAP.data.E_DOCUMENTNUMBER, c_invoice_no]
);
function releaseUnsentPosting(db, invoiceNo) {
return db(sapPostingTable).where({ invoice_no: invoiceNo, state: 'sending' }).del();
}
posting_et = await trx.raw(
`
UPDATE public.posting_et
SET pos_status = 0,
status0 = ?,
no_doksap = ?,
status1 = ?
WHERE no_dok = ?
RETURNING file_name, status0
`,
[
resSAP.type,
resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
resSAP.message ? resSAP.message : null,
c_invoice_no
]
);
function recordSapOutcome(db, invoiceNo, documentNo, outcome) {
return db.transaction(async (trx) => {
const [posting] = await trx(sapPostingTable)
.where({ invoice_no: invoiceNo, state: 'sending' })
.update({
state: documentNo ? 'accepted' : 'unknown',
document_no: documentNo,
outcome,
updated_at: trx.fn.now(),
})
.returning('initial_posting');
if (!posting || documentNo) return;
if (posting) {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESSFULLY", 102, trx)
} else {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
await trx('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
.update({ status0: 'E', status1: outcome });
const invoice = await getInvoice(invoiceNo, trx);
if (invoice) {
await writePaynentHistory(
invoice,
`SAP reconciliation required: ${outcome}`,
posting.initial_posting ? 102 : 118,
trx
);
}
});
}
} else {
function getAcceptedSapPostings(db) {
return db(sapPostingTable).where({ state: 'accepted' }).orderBy('invoice_no').pluck('invoice_no');
}
let text = resSAP.message;
let result = text.toUpperCase();
// Klaim finalisasi dan seluruh perubahan lokal di-commit bersama.
async function finishSapPosting(db, invoiceNo) {
return db.transaction(async (trx) => {
const [posting] = await trx(sapPostingTable)
.where({ invoice_no: invoiceNo, state: 'accepted' })
.update({ state: 'completed', updated_at: trx.fn.now() })
.returning(['document_no', 'initial_posting']);
if (!posting) return null;
if (result.includes("ALREADY")) {
let result = text.toUpperCase().split('-');
let doc_number = result[1].trim().split(" ")[0]
posting_et = await trx.raw(
`
UPDATE public.posting_et
SET pos_status = 0,
status0 = 'S',
no_doksap = ?,
status1 = ?
WHERE no_dok = ?
RETURNING file_name, status0
`,
[doc_number, resSAP.message ? resSAP.message : null, c_invoice_no]
);
// update invoice
t_invoice = await trx.raw(
`
UPDATE payment.t_d_invoice
SET c_return_sap = ?
WHERE c_invoice_no = ?
RETURNING *
`,
[doc_number, c_invoice_no]
);
// update load balance
t_load_balance = await trx.raw(
`
UPDATE trx.t_d_load_balance
SET c_return_sap = ?
WHERE c_load_balance_no IN (
${paymentRequestSql}
)
RETURNING c_load_balance_no, c_return_sap
`,
[doc_number, c_invoice_no]
);
if (posting) {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESSFULLY", 102, trx)
} else {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
}
} else {
// update posting et
posting_et = await trx.raw(
`
UPDATE public.posting_et
SET pos_status = ?,
status0 = ?,
no_doksap = ?,
status1 = ?
WHERE no_dok = ?
RETURNING file_name, status0
`,
[
resSAP.type == 'S' ? 0 : 3,
resSAP.type,
resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
resSAP.message ? resSAP.message : null,
c_invoice_no
]
);
// update invoice
t_invoice = await trx.raw(
`
SELECT *
FROM payment.t_d_invoice
WHERE c_invoice_no = ?
`,
[c_invoice_no]
);
if (posting) {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], `SUCCESS WITH SAP ERR: ${resSAP.message}`, 102, trx)
} else {
await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], `FAIL TO RETRY WITH SAP ERR: ${resSAP.message}`, 118, trx)
}
}
}
// update posting et
return {
invoice: t_invoice.rows || t_invoice,
load_balance: t_load_balance.rows || t_load_balance,
posting_et: posting_et.rows || posting_et
}
const { document_no: documentNo, initial_posting: initialPosting } = posting;
const [invoice] = await trx('payment.t_d_invoice')
.where('c_invoice_no', invoiceNo)
.where(function () {
this.whereNull('c_return_sap').orWhereIn('c_return_sap', ['', documentNo]);
})
.update({ c_return_sap: documentNo })
.returning('*');
if (!invoice) throw new Error('Invoice missing or already associated with a different SAP document');
const paymentRequests = trx('payment.t_d_payment_request_topup_online')
.where('c_payment', invoiceNo)
.select('c_load_balance_no');
await trx('trx.t_d_load_balance')
.whereIn('c_load_balance_no', paymentRequests)
.update({ c_return_sap: documentNo });
await trx('public.posting_et')
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
.update({
pos_status: 0,
status0: 'S',
no_doksap: documentNo,
status1: 'SAP document confirmed',
});
await writePaynentHistory(
invoice,
initialPosting ? 'SUCCESSFULLY' : 'SUCCESS TO RETRY SAP',
initialPosting ? 102 : 118,
trx
);
return invoice;
});
}
const writePaynentHistory = async (data, message, i_log_name, trx) => {
console.log(data)
const result = await trx('log.t_log_invoice').insert({
// i_log_name : 102,
i_log_name: i_log_name,
@@ -361,17 +302,17 @@ const writePaynentHistory = async (data, message, i_log_name, trx) => {
}
const getParameterSetting = async (trx, code) => {
const result = await trx('public.t_m_global_parameter_sap AS tmgps').select([
"c_value"
])
.where('c_code', '=', code)
.where('c_status', '=', "A")
.first()
return result
async function getSapSettings(db) {
const codes = {
SAP_FI_URL_FOR_FB70: 'url',
SAP_AUTH_USERNAME: 'username',
SAP_AUTH_PASSWORD: 'password',
};
const rows = await db('public.t_m_global_parameter_sap')
.where('c_status', 'A')
.whereIn('c_code', Object.keys(codes))
.select('c_code', 'c_value');
return Object.fromEntries(rows.map(({ c_code, c_value }) => [codes[c_code], c_value]));
}
const getInvoice = async (code, trx) => {
@@ -387,9 +328,13 @@ const getInvoice = async (code, trx) => {
module.exports = {
generateInvoice,
insertPostingEt,
setReturnSAP,
claimSapPosting,
releaseUnsentPosting,
recordSapOutcome,
getAcceptedSapPostings,
finishSapPosting,
getPostingEt,
writePaynentHistory,
getParameterSetting,
getSapSettings,
getInvoice
};
};
+122
View File
@@ -0,0 +1,122 @@
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('<fixture/>');
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', '<fixture/>', { 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`,
'<fixture/>',
{ 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));
}
});
+33
View File
@@ -0,0 +1,33 @@
# Posting invoice FB70
Jalankan migrasi Knex sebelum mengaktifkan kode posting invoice. Jeda scheduler
dan pemanggil endpoint posting selama peralihan, lalu tunggu proses versi lama
selesai. Migrasi menahan antrean FB70 online yang masih berstatus 3 dan belum
memiliki nomor dokumen CMS sebagai `unknown` dengan penanda `LEGACY_PENDING`.
Rekonsiliasi tiap referensi di SAP sebelum membuka retry untuk invoice tersebut.
Status lama bisa mencakup request yang sudah sampai ke SAP sebelum CMS menerima
balasannya.
Nomor invoice adalah kunci unik di `payment.t_invoice_sap_posting`. Klaim
`sending` di-commit sebelum HTTP dikirim. Timeout total HTTP adalah 15 detik.
Jeda antar posting dalam satu batch berjalan setelah transaksi lokal selesai.
Hasil yang belum bisa dipastikan disimpan sebagai `unknown`. Proses yang mati
di tengah pengiriman dapat meninggalkan `sending`. Kedua status memerlukan
rekonsiliasi dan umur klaim saja tidak cukup untuk mengizinkan retry.
Status `accepted` berarti nomor dokumen SAP sudah tersimpan. Jalur retry
menyelesaikan invoice, load balance, posting ET, dan riwayat dalam satu
transaksi lokal, lalu menyimpan status `completed`. Jika transaksi lokal gagal,
status tetap `accepted` sehingga proses berikutnya hanya mengulang finalisasi.
Jika SAP mengonfirmasi dokumen untuk referensi tersebut, operator yang berwenang
dapat mengisi `document_no` yang terverifikasi dan mengalihkan status dari
`unknown` atau `sending` ke `accepted`. Jika SAP mengonfirmasi bahwa tidak ada
posting dan tidak ada request yang masih berjalan, operator dapat melepas klaim
tersebut supaya invoice masuk antrean lagi. Catat bukti rekonsiliasi terlebih
dahulu. Aplikasi melepas klaim secara otomatis hanya untuk kegagalan yang
diketahui terjadi sebelum koneksi HTTP terbentuk.
Saat rollback aplikasi, pertahankan tabel klaim dan jeda posting versi lama
hingga status invoice yang belum selesai sudah direkonsiliasi. Versi lama
tidak membaca klaim tersebut.
@@ -0,0 +1,35 @@
exports.up = async (knex) => {
await knex.schema.withSchema('payment').createTable('t_invoice_sap_posting', (table) => {
table.text('invoice_no').primary();
table.text('state').notNullable();
table.boolean('initial_posting').notNullable();
table.text('document_no');
table.text('outcome');
table.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now());
table.check("state IN ('sending', 'unknown', 'accepted', 'completed')");
table.check("(state IN ('accepted', 'completed')) = (document_no IS NOT NULL)");
});
await knex.raw(`
CREATE INDEX idx_invoice_sap_posting_accepted
ON payment.t_invoice_sap_posting (invoice_no)
WHERE state = 'accepted'
`);
// Status antrean lama tidak membuktikan bahwa SAP belum menerima invoice.
await knex.raw(`
INSERT INTO payment.t_invoice_sap_posting (invoice_no, state, initial_posting, outcome)
SELECT DISTINCT pe.reference, 'unknown', false, 'LEGACY_PENDING'
FROM public.posting_et pe
JOIN payment.t_d_invoice invoice ON invoice.c_invoice_no = pe.reference
WHERE pe.tcode = 'FB70'
AND pe.pos_status = '3'
AND pe.doc_header_text LIKE 'INV%'
AND NULLIF(invoice.c_return_sap::text, '') IS NULL
`);
};
exports.down = async (knex) => {
const state = await knex('payment.t_invoice_sap_posting').select('invoice_no').first();
if (state) throw new Error('Cannot drop invoice SAP posting records while the ledger contains data');
await knex.schema.withSchema('payment').dropTable('t_invoice_sap_posting');
};