mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-06 23:16:28 +00:00
Prevent duplicate SAP invoice posting and shorten transactions
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user