reverse-report.js 2.41 KB
const fs = require('fs');
const http = require('http');
const url = require('url');

const stringify = require("json-stringify-pretty-compact");

const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');

const partner = require('../partner');
const irs = require('komodo-gw-irs-lib');

const localRc = fs.existsSync(__dirname + '/../../rc-local.json') ? require('../../rc-local.json') : null;
if (localRc) {
    logger.info('REVERSE-REPORT: Found rc-local.json', {
        useRcLocalOnReverseReport: config.partner.reverse_report_using_rc_local,
        localRc,
    });
}

function processPartnerReport(qs) {
    let rc = '68';
    
    if (config.partner.reverse_report_using_rc_local && localRc && qs.statuscode) {
        rc = localRc[qs.statuscode] || '40'; 
    } else if (qs.statuscode === '1') {
        rc = '00';
    } else if (qs.statuscode === '2') {
        rc = '40';
    }

    if (rc === '40') {
        rc = irs.getRcFromMessage(qs.msg) || '40';
    }

    let amount = null;
    if (rc === '00') {
        amount = Number(qs.hrg);
        if (!amount) {
            amount = irs.getPriceFromMessage(
                qs.msg, 
                config.partner.price_pattern || config.price_pattern
            ) || null;
        }
    }

    const balance = irs.getBalanceFromMessage(qs.msg, config.partner.balance_pattern) || null;
    if (balance) {
        logger.verbose('REVERSE-REPORT: Balance from supplier extracted', {
            trxId: qs.clientid,
            balance,
        })
    }

    partner.report({
        trx_id: qs.clientid,
        rc: rc,
        message: 'REVERSE-REPORT: ' + stringify(qs),
        raw: stringify(qs),
        sn: (qs.sn ? qs.sn : null) || irs.getSnFromMessage(qs.msg, config.partner.sn_pattern) || null,
        amount: amount,
        balance,
        misc: {}
    })
}

function create() {
    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        const qs = url.parse(req.url, true).query;
        res.end('OK');

        const remote_ip = req.connection ? req.connection.remoteAddress : null;
        logger.verbose('REVERSE-REPORT: got report from partner', {url: req.url, remote_ip: remote_ip, method: req.method});

        processPartnerReport(qs);
    }).listen(config.reverse_report_port);

    logger.info('REVERSE-REPORT: listen on port ' + config.reverse_report_port);
}

config.reverse_report_port && create();