diff --git a/.71c131f2ce727b13210eef32232709400762e5fb-audit.json b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json index 08cdfc0..3d1c05a 100644 --- a/.71c131f2ce727b13210eef32232709400762e5fb-audit.json +++ b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json @@ -6,14 +6,9 @@ "auditLog": ".71c131f2ce727b13210eef32232709400762e5fb-audit.json", "files": [ { - "date": 1658895025434, - "name": "2022-07-27-onlinetopup.log", - "hash": "c42156dc1828aef26c15634e6e7b298696e24e0371d265e7db472a09f3b1da4a" - }, - { - "date": 1658975109023, - "name": "2022-07-28-onlinetopup.log", - "hash": "ff688ec2f8aeee014653b80877911239635fa446dae3cf382bd2a343fcace076" + "date": 1660880099380, + "name": "2022-08-19-onlinetopup.log", + "hash": "7bb01da8b3e9f89f45c3d0c9cd81b9af84a5f147df18c3a6f123eb377e62c230" } ], "hashType": "sha256" diff --git a/application/modules/invoice/invoice.controller.js b/application/modules/invoiceonline/invoice.controller.js similarity index 100% rename from application/modules/invoice/invoice.controller.js rename to application/modules/invoiceonline/invoice.controller.js diff --git a/application/modules/invoice/invoice.model.js b/application/modules/invoiceonline/invoice.model.js similarity index 100% rename from application/modules/invoice/invoice.model.js rename to application/modules/invoiceonline/invoice.model.js diff --git a/application/modules/invoicesemionline/invoice.controller.js b/application/modules/invoicesemionline/invoice.controller.js new file mode 100644 index 0000000..7b81c84 --- /dev/null +++ b/application/modules/invoicesemionline/invoice.controller.js @@ -0,0 +1,313 @@ +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 knex = require("../../../infrastructure/database/knex"); + +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(), + body('repost').notEmpty().withMessage('repost is required!').isBoolean().withMessage('repost must boolean!').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 apiGenerateInvoice = 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(req.body.trx_date).format("YYYY-MM-DD") + + let invoice = await _generateInvoice(invoiceDate, uniqueCode, req.body.repost) + + result = { + code: "200", + message: "Succes posting", + data: invoice + }; + + 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: {}, + }); + } + +}; + +// RETRY POSTING INVOICE +const apiPostingInvoice = 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`) + + const invoice = await _postingInvoice(uniqueCode) + + result = { + code: "200", + message: "Succes", + data: invoice, + } + + 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: {}, + }); + } +} + +const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { + + let invoice = [] + + 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 (const key in invoice) { + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(invoice)}`) + + let history = await model.writePaynentHistory(invoice[key], trx) + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify(history)}`) + + 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)}`) + } + + + }) + + if(invoice.length > 0){ + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`); + + 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' + + for (const key in invoice) { + + 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.debug(`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`); + + const response = await helper.postingSAP(url, xmlRequest) + + winston.logger.debug(`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${invoice[key].c_invoice_no} to SAP : ${JSON.stringify(response)}`); + + // new transaction + await knex.transaction(async trx => { + + const resSAP = helper.getXMLData(response) + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); + // UPDATE CMS + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`) + + const cms = await model.setReturnSAP(invoice[key], resSAP, trx) + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`) + + }) + } + } + + return invoice + +} + +const _postingInvoice = async (uniqueCode) => { + let postingEt = [] + await knex.transaction(async trx => { + + 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)}`) + // }) + } + + }) + + return postingEt + +} + +module.exports = { + validate, + apiPostingInvoice, + apiGenerateInvoice, + _postingInvoice, + _generateInvoice +}; \ No newline at end of file diff --git a/application/modules/invoicesemionline/invoice.model.js b/application/modules/invoicesemionline/invoice.model.js new file mode 100644 index 0000000..9169bd5 --- /dev/null +++ b/application/modules/invoicesemionline/invoice.model.js @@ -0,0 +1,156 @@ + +// GET PARTNER, MERCHANT, TERMINAL FROM TID +const generateInvoice = async (invoiceDate, repost, trx) => { + + let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)) + + return result; + +} + +const insertPostingEt = async (invoice, trx) => { + console.log("invoice : ", invoice) + let type = ['S', 'H'] + let et = [] + let posting_et = [] + type.forEach((item, index) => { + let data = { + file_name: invoice.file_name, + tcode: invoice.tcode, + reversal: invoice.reversal, + doc_type: invoice.doc_type, + fiscal_year: invoice.fisc_year, + posting_date: invoice.posting_date, + doc_date: invoice.doc_date, + no_dok: invoice.c_invoice_no, + reference: invoice.c_invoice_no, + amount: invoice.amount, + ba: invoice.ba, + indeks: (index+1), + totalidx: type.length, + doc_header_text: `POSTING INVOICE CMS ${invoice.c_invoice_no}`, + pos_status : 3 + } + + if(item == 'H'){ + data = {...data, ...{ + text: `KREDIT INVOICE CMS ${invoice.doc_header_text}`, + debit_kredit: item, + account: invoice.c_account_topup, + customer: null + }} + }else{ + data = {...data, ...{ + text: `DEBIT INVOICE CMS ${invoice.doc_header_text}`, + debit_kredit: item, + account: null, + customer: invoice.c_account_code_topup + }} + } + + et.push(data) + + }); + + posting_et = await trx('public.posting_et').insert(et, ['indeks', 'customer', 'account', 'ba', 'fiscal_year', 'amount', 'no_dok', 'text', 'debit_kredit']) + + return posting_et[0] + +} + +const getPostingEt = async(trx) => { + + const result = await trx('public.posting_et').select([ + 'doc_header_text', + 'ba', + 'doc_date', + 'posting_date', + 'fiscal_year', + trx.raw(`TO_CHAR(doc_date::DATE, 'MM') 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") + .whereIn('status0', ["3"]) + + .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 = {} + let t_load_balance = {} + + if(resSAP.type == 'S'){ + // update invoice + t_invoice = await trx('payment.t_d_invoice').update({ + c_return_sap: resSAP.data.E_DOCUMENTNUMBER + }, ['c_invoice_no','c_return_sap']) + .where({ + c_invoice_no: invoice.c_invoice_no + }); + + // update load balance + t_load_balance = await trx('trx.t_d_load_balance').update({ + c_return_sap: resSAP.data.E_DOCUMENTNUMBER + }, ['c_load_balance_no', 'c_return_sap']) + .whereRaw(`c_load_balance_no IN (SELECT c_load_balance_no FROM payment.t_d_payment_request_topup_online WHERE c_payment = '${invoice.c_invoice_no}')`) + + } + + // update posting et + const posting_et = await trx('public.posting_et').update({ + pos_status : resSAP.type == 'S' ? 0 : 3, + status0 : resSAP.type, + no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null, + status1 : resSAP.message ? resSAP.message : null + }, ['file_name','status0']).where({ + reference: invoice.c_invoice_no + }) + + return { + invoice : t_invoice, + load_balance : t_load_balance, + posting_et : posting_et + } + +} + +const writePaynentHistory = async (data, trx) => { + console.log(data) + const result = await trx('log.t_log_invoice').insert({ + i_log_name : 102, + d_log : trx.raw('NOW()'), + c_invoice_no : data.c_invoice_no, + c_partner_name : data.c_partner_name, + j_new_data : JSON.stringify(data), + d_payment_date: trx.raw('NOW()'), + c_note : 'SUCCESSFULLY', + c_status : 'S', + d_created : trx.raw('NOW()'), + m_amount : data.amount, + m_mdr_amount : 0, + m_mdr_net : data.amount + + }, ['i_log_name', 'c_note']) + + return result + +} + +module.exports = { + generateInvoice, + insertPostingEt, + setReturnSAP, + getPostingEt, + writePaynentHistory +}; \ No newline at end of file diff --git a/application/routes/invoice.routes.js b/application/routes/invoiceonline.routes.js similarity index 56% rename from application/routes/invoice.routes.js rename to application/routes/invoiceonline.routes.js index 8bff4d7..fd571b8 100644 --- a/application/routes/invoice.routes.js +++ b/application/routes/invoiceonline.routes.js @@ -1,19 +1,19 @@ const express = require("express"); const router = express.Router(); // const auth = require("../middlewares/jwt.middleware"); -const controller = require("../modules/invoice/invoice.controller"); +const controller = require("../modules/invoiceonline/invoice.controller"); router.post( - "/generate-invoice", - // auth.authenticateToken, + "/onlone/generate-invoice", + auth.authenticateToken, controller.validate("generateInvoice"), controller.apiGenerateInvoice ); router.get( - "/posting-invoice", - // controller.validate("postingInvoice"), - // auth.authenticateToken, + "/onlone/posting-invoice", + controller.validate("postingInvoice"), + auth.authenticateToken, controller.apiPostingInvoice ); diff --git a/index.js b/index.js index 4ac2dd0..9e54e0c 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,7 @@ const loadBalanceRoute = require("./application/routes/loadbalance.routes"); const hsmRoute = require("./application/routes/hsm.routes"); const historyRoute = require("./application/routes/history.routes"); const paymentReconRoute = require("./application/routes/paymentrecon.routes"); -const invoiceRoute = require("./application/routes/invoice.routes"); +const invoiceonlineRoute = require("./application/routes/invoiceonline.routes"); const cron = require('node-cron'); const moment = require('moment') require("dotenv").config(); @@ -49,7 +49,7 @@ app.use("/api/", hsmRoute); app.use("/api/", loadBalanceRoute); app.use("/api/", paymentReconRoute); app.use("/api/", reservationRoute); -app.use("/api/", invoiceRoute); +app.use("/api/", invoiceonlineRoute); // set port, listen for requests const PORT = process.env.PORT || 8000; @@ -60,14 +60,14 @@ app.listen(PORT, () => { // winston.logger.info(`Response : ${response()}`); // SCHEDULER FOR GENERATE INVOICE -const {_generateInvoice, _postingInvoice } = require("./application/modules/invoice/invoice.controller"); +const {_generateInvoice, _postingInvoice } = require("./application/modules/invoiceonline/invoice.controller"); cron.schedule('*/1 * * * *', async () => { try { let ivoiceDate = moment().add(1, 'days').format("YYYY-MM-DD"); let uniqueCode = helper.getUniqueCode() - winston.logger.info(`STARTING SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} `); + winston.logger.info(`START-SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} `); const generate = await _generateInvoice(ivoiceDate, uniqueCode, false) - winston.logger.info(`END SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} : ${JSON.stringify(generate)}`); + winston.logger.info(`END-SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} : ${JSON.stringify(generate)}`); } catch (error) { // create log winston.logger.error( @@ -79,9 +79,9 @@ cron.schedule('*/1 * * * *', async () => { cron.schedule('*/2 * * * *', async () => { try { let uniqueCode = helper.getUniqueCode() - winston.logger.info(`STARTING SCHEDULER-FB70 POSTING INVOICE`); + winston.logger.info(`START-SCHEDULER-FB70 POSTING INVOICE`); const posting = await _postingInvoice(uniqueCode) - winston.logger.info(`END SCHEDULER-FB70 POSTING INVOICE : ${JSON.stringify(posting)}`); + winston.logger.info(`END-SCHEDULER-FB70 POSTING INVOICE : ${JSON.stringify(posting)}`); } catch (error) { // create log winston.logger.error(