sales.js 1.6 KB
"use strict";

var json2csv = require('json2csv');

var config;
var db;

function init(options) {
    config = options.config;
    db = options.db;
}

function _getLastHoursSalesPerChipInfo(hour, cb) {
    let dbConnection = db.connection();
    if (!dbConnection) {
        cb("db is not connected");
        return;
    }

    let query = "select CHIP_INFO, COUNT(1) as TRX, sum(PRICE) as AMOUNT, to_char(max(TIME_START), 'YYYY-MM-DD HH24:mm:ss') as LAST_TS from T_TRANS where TIME_START >= sysdate - :hour / 24 and CHIP_INFO is not null and (TRANS_STAT = '200' or TRANS_STAT = '1200') group by CHIP_INFO order by CHIP_INFO asc";
    dbConnection.execute(query, [hour], function(err, res) {
        if (err) {
            cb(err, null);
            return;
        }

        let retval = db.createResultObject(res);

        if (retval && retval.length > 0) {
            cb(null, retval);
        }
        else {
            cb(null, null);
        }
    });
}

function getLastHoursSalesPerChipInfo(req, res, next) {
    let hour = req.params.hour;
    if (!hour) {
        hour = 1;
    }

    _getLastHoursSalesPerChipInfo(hour, function(err, result) {
        if (err) {
            res.send(err.message);
            return;
        }

        if (req.params.outputFormat == 'csv') {
            let fields = ['CHIP_INFO', 'TRX', 'AMOUNT', 'LAST_TS']
            let csv = json2csv({data: result, fields: fields});

            res.type('text');
            res.send(csv);

        } else {
            res.send(result);
        }
    });
}

exports.init = init;
exports.getLastHoursSalesPerChipInfo = getLastHoursSalesPerChipInfo;