priceplan.js 5.59 KB
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('komodo-sdk/logger');
const dbKomodo = require('../../db-komodo');

const DEBUG = process.env.NODE_ENV !== 'production';
// logger.info(`PRODUCTION MODE: ${!DEBUG}`);

const router = express.Router();
module.exports = router;

const cache = {};

function lookupCorrectPriceplan(storeId, originStoreId, recursiveLevel = 0) {
    return new Promise((resolve) => {
        if (DEBUG) {
            logger.verbose('PRICEPLAN.lookupCorrectPriceplan: Looking up', {
                storeId,
                originStoreId,
                recursiveLevel,
            });
        }

        if (cache[`STORE_ID_${storeId}`]) {
            logger.verbose('PRICPLAN.lookupCorrectPriceplan: Got from cache', {
                storeId,
                priceplan: cache[`STORE_ID_${storeId}`].priceplan,
            });
            resolve({
                priceplan: cache[`STORE_ID_${storeId}`].priceplan,
                recursiveLevel: null,
            });

            return;
        }

        const query = `
                -- KOMODO MIGRATION EVO - PRICEPLAN - pageShouldBe
                SELECT SQL_CACHE parent_id, priceplan_name
                FROM stores USE INDEX (PRIMARY)
                WHERE id = ?
                LIMIT 1
            `.trim();

        const values = [storeId];

        dbKomodo.query(query, values, async (err, result) => {
            if (err) {
                const fullQuery = await dbKomodo.format(query, values);
                logger.warn(`PRICEPLAN.lookupCorrectPriceplan: DB ERROR. ${err.toString()}`, {
                    storeId, originStoreId, recursiveLevel, fullQuery,
                });

                resolve({
                    priceplan: null,
                    recursiveLevel,
                });
                return;
            }

            const data = result && result[0];

            if (!data) {
                logger.warn('PRICEPLAN.lookupCorrectPriceplan: STORE not found', { storeId, originStoreId, recursiveLevel });
                resolve({
                    priceplan: null,
                    recursiveLevel,
                });
                return;
            }

            if (data.priceplan_name.toUpperCase() === 'MARKUP') {
                if (!data.parent_id) {
                    logger.warn('PRICEPLAN.lookupCorrectPriceplan: Suitable priceplan not found', {
                        storeId,
                        originStoreId,
                        recursiveLevel,
                    });

                    resolve({
                        priceplan: null,
                        recursiveLevel,
                    });
                    return;
                }

                if (DEBUG) {
                    logger.verbose('PRICEPLAN.lookupCorrectPriceplan: Priceplan is MARKUP, going to look up on parent', {
                        storeId,
                        originStoreId,
                        recursiveLevel,
                        parentId: data.parent_id,
                    });
                }
                const dataFromParent = await lookupCorrectPriceplan(
                    data.parent_id, originStoreId, recursiveLevel + 1,
                );

                resolve({
                    priceplan: dataFromParent.priceplan,
                    recursiveLevel: dataFromParent.recursiveLevel,
                });
                return;
            }

            cache[`STORE_ID_${storeId}`] = {
                priceplan: data.priceplan_name,
                recursiveLevel,
            };

            if (DEBUG) {
                logger.verbose('PRICEPLAN.lookupCorrectPriceplan: Got suitable result', {
                    storeId,
                    originStoreId,
                    priceplanName: data.priceplan_name,
                    recursiveLevel,
                });
            }

            resolve({
                priceplan: data.priceplan_name,
                recursiveLevel,
            });
        });
    });
}

async function pageShouldBe(req, res) {
    if (!req.body) req.body = {};

    const startTime = new Date();

    const storeId = req.body.store_id || req.query.store_id;
    if (!storeId) {
        res.json({
            error: true,
            error_message: 'Undefined parameter store_id',
        });
        return;
    }

    logger.verbose('PRICEPLAN.pageShouldBe: Got a request', {
        method: req.method,
        storeId,
    });

    const data = await lookupCorrectPriceplan(storeId, storeId, 0);

    const deltaTime = Number(new Date() - startTime);
    logger.info(`PRICEPLAN.pageShouldBe: Lookup finished ${deltaTime} ms`, {
        storeId,
        newPriceplan: data && data.priceplanName,
        dbPoolStatus: {
            // eslint-disable-next-line no-underscore-dangle,max-len
            all: (dbKomodo.pool && dbKomodo.pool._allConnections && dbKomodo.pool._allConnections.length) || 0,
            // eslint-disable-next-line no-underscore-dangle,max-len
            free: (dbKomodo.pool && dbKomodo.pool._freeConnections && dbKomodo.pool._freeConnections.length) || 0,
            // eslint-disable-next-line no-underscore-dangle,max-len
            queue: (dbKomodo.pool && dbKomodo.pool._connectionQueue && dbKomodo.pool._connectionQueue.length) || 0,
        },
    });

    res.json({
        error: false,
        error_message: null,
        store_id: storeId,
        recursive_level: (data && data.recursiveLevel) || null,
        priceplan_should_be: (data && data.priceplan) || null,
        raw: data,
    });
}

router.all('/should-be', bodyParser.urlencoded({ extended: false }), pageShouldBe);