Update invoice

This commit is contained in:
Nuranggi Hermawan
2022-07-18 20:55:34 +07:00
parent c37767be04
commit fd227c2dc3
5 changed files with 241 additions and 60 deletions
+1 -1
View File
@@ -189,7 +189,7 @@ async function postingSAP(url, body){
*/
return {
status : 500,
message: "SAP : no response",
message: "can't connect to sap network".toUpperCase(),
data : []
}
} else {
+176 -26
View File
@@ -1,8 +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 moment = require("moment");
const xml2js = require('xml2js');
const knex = require("../../../infrastructure/database/knex");
moment.locale("id");
@@ -10,19 +10,57 @@ moment.locale("id");
var result = {};
var uniqueCode;
// VALIDATION
const validate = (method) => {
switch (method) {
case "generateInvoice":
return [
body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(),
];
case "postingInvoice":
return [
body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(),
];
default:
break;
}
};
// POSTING INVOICE
const postingInvoice = async () => {
const generateInvoice = async (req, res) => {
try {
// generate unique code
uniqueCode = helper.getUniqueCode();
// return uniqueCode
// log info
winston.logger.info(
`${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}`
);
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: "400",
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
// time
let invoiceDate = moment('2020-01-25').format("YYYY-MM-DD")
let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD")
let invoice = []
let xmlRequest = ''
await knex.transaction(async trx => {
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
@@ -43,7 +81,7 @@ const postingInvoice = async () => {
}
// })
})
if(invoice.length > 0){
@@ -64,7 +102,7 @@ const postingInvoice = async () => {
c_invoice_no : invoice[key].c_invoice_no ? invoice[key].c_invoice_no : ""
}
let xmlItem = ['S', 'H'].map((item, index) => {
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 : "",
@@ -86,7 +124,7 @@ const postingInvoice = async () => {
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 => {
await knex.transaction(async trx => {
const resSAP = helper.getXMLData(response)
@@ -98,12 +136,12 @@ const postingInvoice = async () => {
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`)
// })
})
}
}
})
// })
result = {
code: "200",
@@ -111,28 +149,140 @@ const postingInvoice = async () => {
data: invoice,
};
return JSON.stringify(result)
return res.status(200).json(result);
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
result = {
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
}
return JSON.stringify(result)
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
});
}
};
// RETRY POSTING INVOICE
const postingInvoice = async (req, res) => {
try {
// generate unique code
uniqueCode = helper.getUniqueCode()
// log info
winston.logger.info(
`${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}`
);
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: "400",
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
// return uniqueCode
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`)
await knex.transaction(async trx => {
const postingEt = await model.getPostingEt(trx)
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(postingEt)}`)
for (const item of postingEt) {
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}`);
const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'
const response = await helper.postingSAP(url, xmlRequest)
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${item.reference} to SAP : ${JSON.stringify(response)}`);
// new transaction
// await knex.transaction(async trx => {
const resSAP = helper.getXMLData(response)
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
// UPDATE CMS
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`)
const cms = await model.setReturnSAP({c_invoice_no : item.reference}, resSAP, trx)
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`)
// })
}
result = {
code: "200",
message: "Succes posting",
data: postingEt,
}
return res.status(200).json(result);
})
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
});
}
}
module.exports = {
validate,
postingInvoice,
generateInvoice
};
+35 -22
View File
@@ -1,3 +1,4 @@
// GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, trx) => {
@@ -33,14 +34,14 @@ const insertPostingEt = async (invoice, trx) => {
if(item == 'H'){
data = {...data, ...{
text: `DEBIT INVOICE CMS ${invoice.doc_header_text}`,
text: `KREDIT INVOICE CMS ${invoice.doc_header_text}`,
debit_kredit: item,
account: invoice.c_account_topup,
customer: null
}}
}else{
data = {...data, ...{
text: `KREDIT INVOICE CMS ${invoice.doc_header_text}`,
text: `DEBIT INVOICE CMS ${invoice.doc_header_text}`,
debit_kredit: item,
account: null,
customer: invoice.c_account_code_topup
@@ -57,24 +58,35 @@ const insertPostingEt = async (invoice, trx) => {
}
// const getPostingEt = async(invoiceDate, trx) => {
// const result = await trx('public.posting_et').select([
// trx.raw(`LPAD(indeks::text, 10, '0') `),
// 'file_name',
// 't_code',
// 'doc_type',
// 'posting_date',
// 'doc_date',
// 'debit_kredit',
// 'account',
// 'amount',
// 'ba',
// 'customer',
// 'fiscal_year',
// 'text',
// 'doc_header_text'
// ])
// }
const getPostingEt = async(trx) => {
const result = await trx('public.posting_et').select([
'doc_header_text',
'ba',
'doc_date',
'posting_date',
'fiscal_year',
trx.raw(`'01' AS fis_period`),
'doc_type',
'reference',
'tcode',
'amount',
trx.raw(`'IDR' AS currency`),
trx.raw(`(SELECT customer FROM public.posting_et where no_dok = no_dok and debit_kredit = 'S') as customer `),
trx.raw(`(SELECT account FROM public.posting_et where no_dok = no_dok and debit_kredit = 'H') as account `),
trx.raw(`(SELECT text FROM public.posting_et where no_dok = no_dok and debit_kredit = 'S') as text1`),
trx.raw(`(SELECT text FROM public.posting_et where no_dok = no_dok and debit_kredit = 'H') as text2`)
])
.where('tcode', '=', "FB70")
.where('status0', '!=', "S")
.orWhere({
'status0' : null,
})
.groupBy(['doc_header_text', 'ba', 'doc_header_text', 'tcode', 'ba', 'amount', 'posting_date', 'doc_date', 'doc_type', 'fiscal_year', 'reference'])
return result
}
const setReturnSAP = async (invoice, resSAP, trx) => {
let t_invoice = {}
@@ -104,7 +116,7 @@ const setReturnSAP = async (invoice, resSAP, trx) => {
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
status1 : resSAP.message ? resSAP.message : null
}, ['file_name','status0']).where({
file_name: invoice.c_invoice_no
reference: invoice.c_invoice_no
})
return {
@@ -118,5 +130,6 @@ const setReturnSAP = async (invoice, resSAP, trx) => {
module.exports = {
generateInvoice,
insertPostingEt,
setReturnSAP
setReturnSAP,
getPostingEt
};
+9 -1
View File
@@ -1,10 +1,18 @@
const express = require("express");
const router = express.Router();
const auth = require("../middlewares/jwt.middleware");
// const auth = require("../middlewares/jwt.middleware");
const controller = require("../modules/invoice/invoice.controller");
router.post(
"/generate-invoice",
// auth.authenticateToken,
controller.validate("generateInvoice"),
controller.generateInvoice
);
router.get(
"/posting-invoice",
// controller.validate("postingInvoice"),
// auth.authenticateToken,
controller.postingInvoice
);
+20 -10
View File
@@ -58,19 +58,29 @@ app.listen(PORT, () => {
// winston.logger.info(`Response : ${response()}`);
// SCHEDULER FOR POSTING INVOICE
const invoiceSch = require("./application/modules/invoice/invoice.controller");
cron.schedule('*/10 * * * * *', async () => { // Every minute offset 30 seconds
// // console.log()
try {
winston.logger.info(`[${moment().format('YYYY-MM-DD hh:mm:ss')}] : `, await invoiceSch.postingInvoice());
} catch (error) {
winston.logger.info(`[${moment().format('YYYY-MM-DD hh:mm:ss')}] : `, error.message);
}
// const invoiceControler = require("./application/modules/invoice/invoice.controller");
// cron.schedule('*/10 * * * * *', async () => { // Every minute offset 30 seconds
// try {
// console.log("first")
// let as = await invoiceControler.generateInvoice()
// console.log(as)
// } catch (error) {
// winston.logger.info(`[${moment().format('YYYY-MM-DD hh:mm:ss')}] : err`, error);
// }
});
// });
// const soap = `<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'><SOAP:Header/><SOAP:Body><ns0:ZFMCMS_FI_001.Response xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><E_DOCUMENTNUMBER/><E_DOCUMENTYEAR>0000</E_DOCUMENTYEAR><C_T_RETURN><item><TYPE>E</TYPE><DOC_NUMBER>$</DOC_NUMBER><MESSAGE_1>Error in document: BKPFF $ KAQCLNT100</MESSAGE_1><MESSAGE_2/><MESSAGE_3/><MESSAGE_4/><MESSAGE_5/><MESSAGE_6/><MESSAGE_7/><MESSAGE_8/><MESSAGE_9/><MESSAGE_10/></item><item><TYPE>E</TYPE><DOC_NUMBER>$</DOC_NUMBER><MESSAGE_1>Period 01 is not allowed</MESSAGE_1><MESSAGE_2/><MESSAGE_3/><MESSAGE_4/><MESSAGE_5/><MESSAGE_6/><MESSAGE_7/><MESSAGE_8/><MESSAGE_9/><MESSAGE_10/></item><item><TYPE>E</TYPE><DOC_NUMBER>$</DOC_NUMBER><MESSAGE_1>Period 01 is not valid</MESSAGE_1><MESSAGE_2/><MESSAGE_3/><MESSAGE_4/><MESSAGE_5/><MESSAGE_6/><MESSAGE_7/><MESSAGE_8/><MESSAGE_9/><MESSAGE_10/></item></C_T_RETURN></ns0:ZFMCMS_FI_001.Response></SOAP:Body></SOAP:Envelope>`
// `
// let resSAP = helper.getXMLData({status: 200}, soap)
// winston.logger.info(`SCHEDULER-FB70 RESPONSE posting to SAP ${JSON.stringify(resSAP)}`);
// winston.logger.info(`SCHEDULER-FB70 RESPONSE posting to SAP ${JSON.stringify(resSAP)}`);
// const invoiceSch = require("./application/modules/invoice/invoice.model");
// const postingEt = async () => {
// // const rs = await invoiceSch.getPostingEt()
// const rs = await invoiceControler.postingInvoice()
// console.log("Posting ET : ", rs)
// }
// postingEt()