const CryptoJS = require("crypto-js");
// ENCRYPT TEXT
const encryptText = (text) => {
try {
return CryptoJS.AES.encrypt(text, process.env.SECRET_KEY).toString();
} catch (error) {
return error.message;
}
};
// DECRYPT TEXT
const decryptText = (cipherText) => {
try {
return CryptoJS.AES.decrypt(cipherText, process.env.SECRET_KEY).toString(
CryptoJS.enc.Utf8
);
} catch (error) {
return error.message;
}
};
// RANDOM UNIQUE CODE
function getUniqueCode() {
const maxDate = Date.now();
const timestamp = Math.floor(Math.random() * maxDate).toString();
return timestamp;
}
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min) + 1;
}
function randomNumberInt() {
const result = [];
while (result.length !== 3) {
let random = getRandomArbitrary(0, 9);
if (!result.includes(random)) result.push(random);
// To check if the first no is not zero
if (result.length === 1 && random === 0) result.pop();
}
return parseInt( result.join("") );
}
// GENERATE XML REQUEST
function generateXMLRequest(urn, headers, items) {
let xmlRequest = ''
switch (urn.toUpperCase()) {
case 'ZFMCMS_FI_001':
let xmlItem = ''
items.map((item, index) => {
xmlItem += `-
${String(index+1).padStart(10, '0')}
${item.c_account_code_topup ? item.c_account_code_topup : ""}
${item.c_account_topup ? item.c_account_topup : ""}
${item.ba ? item.ba : ""}
${item.amount ? item.amount : ""}
${item.posting_date ? item.posting_date : ""}
${item.c_invoice_no ? item.c_invoice_no : ""}
${item.item_text ? item.item_text : ""}
${item.de_cre}
`
})
xmlRequest = `
${headers.doc_header_text}
${headers.ba}
${headers.doc_date}
${headers.posting_date}
${headers.fisc_year}
${headers.fisc_period}
${headers.doc_type}
${headers.c_invoice_no}
IDR
${xmlItem}
-
`
break;
default:
console.log('Sorry, we are out of ' + urn + '.');
}
return xmlRequest
}
// POSTING SAP
async function postingSAP(url, body, credential){
try {
const axios = require("axios");
const config = {
headers : {
'Content-Type': 'text/xml',
'responseType': 'text',
},
auth: {
username: credential.username,
password: credential.password
}
}
const resp = await axios.post(url, body, config)
return {
status : resp.status,
message: "Success",
data : resp.data
}
} catch (error) {
// Error 😨
if (error.response) {
/*
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
return {
status : error.response.status,
message: error.message,
data : []
}
} else if (error.request) {
/*
* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js
*/
return {
status : 500,
message: "can't connect to sap network".toUpperCase(),
data : []
}
} else {
// Something happened in setting up the request and triggered an Error
return {
status : 500,
message: error.message,
data : []
}
}
}
}
// GET SOAP RESPONSE DATA
function getXMLData(response) {
const xml2js = require('xml2js');
// console.log(xmlString)
let resSAP = {
type: '',
message : '',
data : {
E_DOCUMENTYEAR: '',
E_DOCUMENTNUMBER: '',
// ITEM: [],
}
}
if(response.status == 200){
const options = {
explicitArray: false,
tagNameProcessors: [xml2js.processors.stripPrefix]
}
xml2js.parseString(response.data, options, (err, result) => {
if (err) throw err
let soapBody = result.Envelope.Body;
if (soapBody.$) delete soapBody.$
resSAP.data.E_DOCUMENTYEAR = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] : "0000"
resSAP.data.E_DOCUMENTNUMBER = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] : ""
if(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']){
if (!Array.isArray(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'])) {
// resSAP.data.ITEM.push(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'])
resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['TYPE']
resSAP.message = "[SAP] " + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['MESSAGE_1']
} else {
// resSAP.data.ITEM = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']
resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE']
const indexMessage = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1
let message = "[SAP] "+ soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][indexMessage]['MESSAGE_1']
resSAP.message = message
}
}
});
}else {
resSAP.type = 'E'
resSAP.message = response.message ? response.message : "aa"
}
return resSAP
}
module.exports = {
encryptText,
decryptText,
getUniqueCode,
randomNumberInt,
generateXMLRequest,
postingSAP,
getXMLData
};