buy.js 2.27 KB
const MODULE_NAME = 'ACTIONS.BUY';

const logger = require('tektrans-logger');
const axios = require('axios').default;

const config = require('../config');
const configData = require('../config/data');

const buyToSDS = require('./buy-to-sds');

const client = axios.create({
    baseURL: config.core.url,
    timeout: config.core.request_timeout_ms,
    headers: {
        'x-access-token': config.core.access_token,
    },
});

/**
 * Buy a product from supplier sds
 *
 * @param {string} xid
 * @param {object} transaction
 *
 */
module.exports = async (xid, transaction) => {
    try {
        logger.verbose(`${MODULE_NAME} 4B139379: Buy product to sds`, {
            xid,
            transaction,
        });
        const iConfig = await configData.all();

        let productName = transaction.product_name;
        if (
            iConfig.products[transaction.product_name]
            && iConfig.products[transaction.product_name].remote
        ) {
            productName = iConfig.products[transaction.product_name].remote;
        }

        const productNames = productName.trim().split(/\s*,\s*/);
        // eslint-disable-next-line prefer-destructuring
        let quantity = transaction.quantity;

        if (productNames.length >= 2) {
            [productName, quantity] = productNames;
        }

        // const callbackUrl = `${iConfig.url}:${iConfig.port}/apikey/${iConfig.apikey}/updates`;
        const result = await buyToSDS(
            xid,
            `${transaction.request_id}-${transaction.id}`,
            transaction.destination,
            productName,
            quantity,
        );
        logger.verbose(`${MODULE_NAME} 5BDFAF41: result from sds`, {
            xid,
            trxId: transaction.id,
            result,
        });
        let rc = '40';
        if (result.code === '200') {
            rc = '68';
        }
        const params = {
            id: transaction.id,
            rc,
            amount: result.amount || null,
            message: result.text || '',
            sn: result.sn || null,
        };

        await client.post('/transactions/gateway-update', params);
    } catch (e) {
        logger.warn(`${MODULE_NAME} E9887C98: Exception`, {
            xid,
            message: e.message,
            code: e.code,
        });
    }
};