Your IP : 216.73.216.220


Current Path : /home/deltalab/PMS/partner-manager-backend/services/
Upload File :
Current File : //home/deltalab/PMS/partner-manager-backend/services/amqp.js

/* eslint-disable max-len */
/* eslint-disable no-await-in-loop */

require('dotenv').config();
const amqp = require('amqplib/callback_api');
const oms = require('./oms');
const utility = require('./utility');

const { AMQP_HOST } = process.env;
const { AMQP_QUEUE } = process.env;
const { AMQP_DELAY } = process.env;

function rabbitMQ() {
  amqp.connect(AMQP_HOST, (error0, connection) => {
    if (error0) {
      throw error0;
    }
    connection.createChannel((error1, channel) => {
      if (error1) {
        throw error1;
      }

      const ch = channel;

      // consume one message at a time
      ch.prefetch(1);

      ch.assertExchange('order_error_exchange', 'fanout', { durable: false });
      ch.assertExchange('order_intermediate_exchange', 'fanout', { durable: false });
      ch.assertExchange('order_final_delayed_exchange', 'fanout', { durable: false });

      // setup intermediate queue which will never be listened.
      // all messages are TTLed so when they are 'dead', they come to another exchange
      const ecommerceQueue = AMQP_QUEUE;
      ch.assertQueue(ecommerceQueue, {
        deadLetterExchange: 'order_final_delayed_exchange',
        messageTtl: parseInt(AMQP_DELAY, 10), // Time To Live (TLL) in temporary queue
      }, (err, q) => {
        ch.bindQueue(q.queue, 'order_intermediate_exchange', '');
      });

      const queueError = 'PMS.queueError';
      ch.assertQueue(queueError, {}, (err, q) => {
        ch.bindQueue(q.queue, 'order_error_exchange', '');
      });

      ch.assertQueue('PMS.queueOrder', {
        deadLetterExchange: 'order_error_exchange',
      }, (err, q) => {
        ch.bindQueue(q.queue, 'order_final_delayed_exchange', '');
        console.log(`[AMQP] Waiting for messages in queue '${q.queue}'`);

        ch.consume(q.queue, async (msg) => {
          console.log('[AMQP] Received %s', msg.content.toString());
          const message = JSON.parse(msg.content.toString());
          const data = JSON.parse(message.message);

          if (data.action === utility.ACTION_MASSIVE_EMAIL) {
            if (data.activity && !data.activity[utility.ACTIVITY_SELLER_EMAIL]) {
              throw new Error('The MASSIVE_EMAIL action does not have an activity');
            }
            console.log('SEND MAIL TO ALL SELLERS');
            const success = await oms.sendRecapEmail(data.orderList.split(utility.ORDER_LIST_SEPARATOR), data.indaco.instance_id, data.order.store.storeview_code);
            if (success) {
              console.log('[AMQP] Seller email Checked and acked');
              // send acknowledgment and remove message from the queue
              channel.ack(msg);
              console.log('[AMQP] Seller email success');
            } else {
              channel.nack(msg, false, false);
              console.log(`[AMQP] Error sending email for orders ${data.orderList}`);
            }
            return;
          }

          const omsorders = await oms.fetchOrderRest(data.order.increment_id, data.indaco.instance_id, data.order.store.storeview_code)
            .catch((error) => {
              // send message to error queue
              channel.nack(msg, false, false);
              throw Error(error);
            });
          for (let i = 0; i < omsorders.length; i++) {
            // checking a single order
            console.log('[AMQP] Checking order');
            await oms.checkOrder(omsorders[i], data.indaco.instance_id, data.order.store.storeview_code, data.action, data.activity)
              .then((check) => {
                if (check.success) {
                  console.log('[AMQP] Checked and acked');
                  // send acknowledgment and remove message from the queue
                  channel.ack(msg);
                  console.log(`[AMQP] Order ${check.order.name} check success`);
                }
              })
              .catch((error) => {
                // send message to error queue
                channel.nack(msg, false, false);
                console.log(`[AMQP] Error checking order ${omsorders[i].name}: ${error}`);
              });
          }
        }, {
          // manual acknowledgment mode
          noAck: false,
        });
      });
    });
  });
}

module.exports = {
  rabbitMQ,
};