router_function_getAnalyticMessage.js

const konfig = require('../../config.js');
const axios = require('axios');
const moment = require('moment');
const { KeiLog } = require('../../lib/Logger');
// Assuming you have the exchange rate
const exchangeRate = 1; // Replace this with the actual exchange rate value
/**
 * Module for retrieving message analytics data from the Facebook Graph API.
 *@module message_analytic
 * @param {object} app - The Express application object.
 */

module.exports = async function (app) {
  app.get('/message_analytic', async (req, res) => {
    const startDate = req.query.start || '2023-05-01';
    const endDate = req.query.end || '2023-05-10';

    // Convert human-readable dates to epoch timestamps
    const startEpoch = new Date(startDate).getTime() / 1000;
    const endEpoch = new Date(endDate).getTime() / 1000;
    try {
      const result = await axios.get(
        // Replace this URL with the updated API endpoint
        `https://graph.facebook.com/v16.0/${konfig.waba_id}?fields=analytics.start(${startEpoch}).end(${endEpoch}).granularity(HALF_HOUR).phone_numbers(%5B6282120764986%5D).metric_types(%5B"COST"%2C"DELIVERED"%2C"RECEIVED"%2C"SENT"%5D).product_types(%5B0%2C2%5D).message_media_types(%5B"AUDIO_VIDEO"%2C"DOCUMENT"%2C"IMAGE"%2C"LIST"%2C"LOCATION"%2C"OTHER"%2C"TEXT"%5D).interaction_types(%5B"BUTTONS"%2C"NO_BUTTONS"%5D).country_codes(%5B%5D)&locale=en_GB&method=get&pretty=0&suppress_http_code=1&xref=f2347389484222`,
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + konfig.token,
          },
        }
      );

      const response = result.data;

      // Initialize counts
      let messageSentCount = 0;
      let messageDeliveredCount = 0;
      let messageFailedCount = 0;
      
      // Iterate through data points
      response.analytics.data_points.forEach((dataPoint) => {
        messageSentCount += dataPoint.sent;
        messageDeliveredCount += dataPoint.delivered;
      
        // Update failed count only if sent and delivered are not equal
        if (dataPoint.sent !== dataPoint.delivered) {
          messageFailedCount += Math.abs(dataPoint.sent - dataPoint.delivered);
        }
      
        // Convert start and end timestamps to human-readable dates
        dataPoint.start = moment.unix(dataPoint.start).format('YYYY-MM-DD HH:mm:ss');
        dataPoint.end = moment.unix(dataPoint.end).format('YYYY-MM-DD HH:mm:ss');
      });

      // Calculate failed messages
      messageFailedCount = Math.max(messageSentCount - messageDeliveredCount, 0);

      // Return counts and updated data points in the response
      res.json({
        messageSentCount,
        messageDeliveredCount,
        messageFailedCount,
        dataPoints: response.analytics.data_points,
      });
    } catch (error) {
      res.send(error);
    }
  });
};