mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:56:27 +00:00
454 lines
14 KiB
JavaScript
454 lines
14 KiB
JavaScript
const CryptoJS = require('crypto-js');
|
|
const { randomUUID } = require('crypto');
|
|
const knex = require('../../infrastructure/database/knex');
|
|
|
|
// 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;
|
|
}
|
|
};
|
|
|
|
// CREATE HMAC
|
|
const createHMAC = async (payload) => {
|
|
let hash = await CryptoJS.HmacSHA256(
|
|
payload,
|
|
process.env.SECRET_KEY
|
|
).toString();
|
|
return hash;
|
|
};
|
|
|
|
// RANDOM UNIQUE CODE
|
|
function getUniqueCode() {
|
|
let maxDate = Date.now();
|
|
let timestamp = Math.floor(Math.random() * maxDate).toString();
|
|
return timestamp;
|
|
}
|
|
|
|
function getRandomArbitrary(min, max) {
|
|
return Math.floor(Math.random() * (max - min) + min) + 1;
|
|
}
|
|
|
|
function randomNumberInt() {
|
|
let 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 += `<item>
|
|
<!--Optional:-->
|
|
<ITEMNO_ACC>${String(index + 1).padStart(
|
|
10,
|
|
'0'
|
|
)}</ITEMNO_ACC>
|
|
<!--Optional:-->
|
|
<CUSTOMER>${item.c_account_code_topup
|
|
? item.c_account_code_topup
|
|
: ''
|
|
}</CUSTOMER>
|
|
<!--Optional:-->
|
|
<GL_ACCOUNT>${item.c_account_topup ? item.c_account_topup : ''
|
|
}</GL_ACCOUNT>
|
|
<!--Optional:-->
|
|
<BUS_AREA>${item.ba ? item.ba : ''}</BUS_AREA>
|
|
<!--Optional:-->
|
|
<AMT_DOCCUR>${item.amount ? item.amount : ''
|
|
}</AMT_DOCCUR>
|
|
<!--Optional:-->
|
|
<BLINE_DATE>${item.posting_date ? item.posting_date : ''
|
|
}</BLINE_DATE>
|
|
<!--Optional:-->
|
|
<COSTCENTER></COSTCENTER>
|
|
<!--Optional:-->
|
|
<PROFITCENTER></PROFITCENTER>
|
|
<!--Optional:-->
|
|
<ALLOC_NMBR>${item.c_invoice_no ? item.c_invoice_no : ''
|
|
}</ALLOC_NMBR>
|
|
<!--Optional:-->
|
|
<ITEM_TEXT>${item.item_text ? item.item_text : ''
|
|
}</ITEM_TEXT>
|
|
<!--Optional:-->
|
|
<DE_CRE_IND>${item.de_cre}</DE_CRE_IND>
|
|
</item>`;
|
|
});
|
|
|
|
xmlRequest = `<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'
|
|
xmlns:urn='urn:sap-com:document:sap:rfc:functions'>
|
|
<SOAP:Body>
|
|
<!--Optional-->
|
|
<urn:${urn}>
|
|
<!--You may enter the following 7 items in any order-->
|
|
<!--Optional:-->
|
|
<I_SIMULATE></I_SIMULATE>
|
|
<I_S_HEADER>
|
|
<!--Optional:-->
|
|
<HEADER_TXT>${headers.doc_header_text}</HEADER_TXT>
|
|
<!--Optional:-->
|
|
<COMP_CODE>${headers.ba}</COMP_CODE>
|
|
<!--Optional:-->
|
|
<DOC_DATE>${headers.doc_date}</DOC_DATE>
|
|
<!--Optional:-->
|
|
<PSTNG_DATE>${headers.posting_date}</PSTNG_DATE>
|
|
<!--Optional:-->
|
|
<FISC_YEAR>${headers.fisc_year}</FISC_YEAR>
|
|
<!--Optional:-->
|
|
<FIS_PERIOD>${headers.fisc_period}</FIS_PERIOD>
|
|
<!--Optional:-->
|
|
<!--default-->
|
|
<DOC_TYPE>${headers.doc_type}</DOC_TYPE>
|
|
<!--Optional:-->
|
|
<REF_DOC_NO>${headers.c_invoice_no}</REF_DOC_NO>
|
|
<!--Optional:-->
|
|
<CURRENCY>IDR</CURRENCY>
|
|
</I_S_HEADER>
|
|
<I_T_ITEM>
|
|
<!--Zero or more repetitions:-->
|
|
${xmlItem}
|
|
</I_T_ITEM>
|
|
<!--Optional:-->
|
|
<C_T_RETURN>
|
|
<!--Zero or more repetitions:-->
|
|
<item>
|
|
<!--Optional:-->
|
|
<TYPE></TYPE>
|
|
<!--Optional:-->
|
|
<DOC_NUMBER></DOC_NUMBER>
|
|
<!--Optional:-->
|
|
<MESSAGE_1></MESSAGE_1>
|
|
<!--Optional:-->
|
|
<MESSAGE_2></MESSAGE_2>
|
|
<!--Optional:-->
|
|
<MESSAGE_3></MESSAGE_3>
|
|
<!--Optional:-->
|
|
<MESSAGE_4></MESSAGE_4>
|
|
<!--Optional:-->
|
|
<MESSAGE_5></MESSAGE_5>
|
|
<!--Optional:-->
|
|
<MESSAGE_6></MESSAGE_6>
|
|
<!--Optional:-->
|
|
<MESSAGE_7></MESSAGE_7>
|
|
<!--Optional:-->
|
|
<MESSAGE_8></MESSAGE_8>
|
|
<!--Optional:-->
|
|
<MESSAGE_9></MESSAGE_9>
|
|
<!--Optional:-->
|
|
<MESSAGE_10></MESSAGE_10>
|
|
</item>
|
|
</C_T_RETURN>
|
|
</urn:${urn}>
|
|
</SOAP:Body>
|
|
</SOAP:Envelope>`;
|
|
break;
|
|
default:
|
|
console.log('Sorry, we are out of ' + urn + '.');
|
|
}
|
|
|
|
return xmlRequest;
|
|
}
|
|
|
|
// POSTING SAP
|
|
async function postingSAP(url, body, credential) {
|
|
try {
|
|
let axios = require('axios');
|
|
|
|
let config = {
|
|
headers: {
|
|
'Content-Type': 'text/xml',
|
|
responseType: 'text',
|
|
},
|
|
auth: {
|
|
username: credential.username,
|
|
password: credential.password,
|
|
},
|
|
};
|
|
|
|
let 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) {
|
|
let xml2js = require('xml2js');
|
|
// console.log(xmlString)
|
|
let resSAP = {
|
|
type: '',
|
|
message: '',
|
|
data: {
|
|
E_DOCUMENTYEAR: '',
|
|
E_DOCUMENTNUMBER: '',
|
|
// ITEM: [],
|
|
},
|
|
};
|
|
|
|
if (response.status == 200) {
|
|
let 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'];
|
|
|
|
let 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;
|
|
}
|
|
|
|
async function startScheduler(schedulerCode) {
|
|
return await knex.transaction(async (trx) => {
|
|
|
|
const job = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.where('c_scheduler_code', schedulerCode)
|
|
.where('c_status', 'idle')
|
|
.whereRaw(`
|
|
d_run_datetime BETWEEN NOW() - INTERVAL '3 minutes'
|
|
AND NOW() + INTERVAL '1 minute'
|
|
`)
|
|
.orderBy('d_run_datetime', 'desc')
|
|
.forUpdate()
|
|
.first();
|
|
|
|
let result;
|
|
|
|
if (!job) {
|
|
const master = await knex('log.t_monitoring_master_scheduler_name as mn')
|
|
.join('log.t_monitoring_master_scheduler_time as mt', 'mn.i_scheduler_name', 'mt.i_scheduler_name')
|
|
.transacting(trx)
|
|
.select(
|
|
'mn.i_scheduler_name',
|
|
'mn.c_scheduler_name',
|
|
'mn.c_scheduler_code',
|
|
'mn.c_category',
|
|
'mt.i_scheduler_time'
|
|
)
|
|
.where('mn.c_scheduler_code', schedulerCode)
|
|
.first();
|
|
|
|
if (!master) {
|
|
throw new Error('Master scheduler not found');
|
|
}
|
|
|
|
const token = randomUUID();
|
|
|
|
const inserted = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.insert({
|
|
i_scheduler_name: master.i_scheduler_name,
|
|
i_scheduler_time: master.i_scheduler_time,
|
|
c_scheduler_name: master.c_scheduler_name,
|
|
d_run_datetime: knex.fn.now(),
|
|
c_status: 'processing',
|
|
d_started_at: knex.fn.now(),
|
|
c_execution_token: token,
|
|
c_category: master.c_category,
|
|
c_type: 'AUTO',
|
|
d_created: knex.fn.now(),
|
|
i_create: 0,
|
|
c_create_username: 'system',
|
|
c_create_fullname: 'system',
|
|
c_scheduler_code: master.c_scheduler_code
|
|
})
|
|
.returning('*');
|
|
|
|
result = inserted[0];
|
|
|
|
} else {
|
|
const token = randomUUID();
|
|
|
|
const updated = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.where('i_scheduler_history', job.i_scheduler_history)
|
|
.update({
|
|
c_status: 'processing',
|
|
d_started_at: knex.fn.now(),
|
|
c_execution_token: token
|
|
})
|
|
.returning('*');
|
|
|
|
result = updated[0];
|
|
}
|
|
|
|
return result;
|
|
});
|
|
}
|
|
|
|
async function finishScheduler(token = null, schedulerCode = null) {
|
|
return await knex.transaction(async (trx) => {
|
|
|
|
let result = null;
|
|
|
|
if (token) {
|
|
const updated = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.where('c_execution_token', token)
|
|
.where('c_status', 'processing')
|
|
.update({
|
|
c_status: 'finished',
|
|
d_finished_at: knex.fn.now()
|
|
})
|
|
.returning('*');
|
|
|
|
if (updated.length > 0) {
|
|
result = updated[0];
|
|
}
|
|
}
|
|
|
|
if (!result && schedulerCode) {
|
|
|
|
const job = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.where('c_scheduler_code', schedulerCode)
|
|
.where('c_status', 'processing')
|
|
.whereNotNull('d_started_at')
|
|
.whereRaw(`d_started_at >= NOW() - INTERVAL '5 minutes'`)
|
|
.orderBy('d_started_at', 'desc')
|
|
.forUpdate()
|
|
.first();
|
|
|
|
if (job) {
|
|
const updated = await knex('log.t_monitoring_scheduler_history')
|
|
.transacting(trx)
|
|
.where('i_scheduler_history', job.i_scheduler_history)
|
|
.update({
|
|
c_status: 'finished',
|
|
d_finished_at: knex.fn.now()
|
|
})
|
|
.returning('*');
|
|
|
|
result = updated[0];
|
|
}
|
|
}
|
|
|
|
return result;
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
encryptText,
|
|
decryptText,
|
|
createHMAC,
|
|
getUniqueCode,
|
|
randomNumberInt,
|
|
generateXMLRequest,
|
|
postingSAP,
|
|
getXMLData,
|
|
startScheduler,
|
|
finishScheduler,
|
|
};
|