Sindbad~EG File Manager

Current Path : /home/infinitibizsol/.trash/controllers/
Upload File :
Current File : /home/infinitibizsol/.trash/controllers/auctionLaneController.js

const db = require("../models");
const { col, Op, sequelize } = require("sequelize");
const CircularJSON = require("circular-json");
const flatted = require("flatted");

const getAuctionsAndLanesByAuctioneerId = async (req, res) => {
  try {
    const { auctioneer_id } = req.body;
    let result = await db.tblAuctionLane.findAll({
      attributes: ["name", "lane_id"], // Select the columns you want to retrieve
      include: [
        {
          model: db.tblAuction,
          attributes: ["name"],
          raw: true,
        },
      ],
      where: {
        auctioneer_id: auctioneer_id,
      },
    });

    const transformedData = result.map((item) => ({
      lane_id: item.lane_id,
      name: item.name,
      auction_name: item.tblAuction.name,
    }));

    const data = transformedData.reduce(
      (acc, { lane_id, name, auction_name }) => {
        const auctionEntry = acc.find(
          (entry) => entry.auction_name === auction_name
        );

        if (auctionEntry) {
          auctionEntry.lane_names.push({ lane_id, name });
        } else {
          acc.push({ auction_name, lane_names: [{ lane_id, name }] });
        }

        return acc;
      },
      []
    );

    return res.json({ status: 200, data: data });
  } catch (error) {
    return res.json(error.message);
  }
};

/* const getAuctionsByAuctioneerId = async (req, res) => {
  try {
    const { auctioneer_id, user_id, week_id } = req.body;

    const result = await db.tblAuctionLane.findAll({
      attributes: [],
      include: [
        {
          model: db.tblAuction,
          as: "auction_details",
          attributes: ["auction_id", "name"],
          nest: true, // Add this line
          raw: true,
        },
        {
          model: db.tblVehicleRun,
          as: "lane_details",
          raw: true,
          include: [
            {
              model: db.tblAuctionLane,
              as: "lane_details",
              // attributes: ["auction_id", "name"],
              nest: true, // Add this line
              raw: true,
            },
            {
              model: db.tblVehicle,
              attributes: [
                "vehicle_id",
                "year",
                "make",
                "model",
                "trim",
                "mileage",
                "imageUrl",
              ],
              raw: true,
              include: [
                {
                  model: db.tblOpportunity,
                  attributes: [],
                  where: {
                    user_id: user_id,
                    week_id: week_id,
                  },
                },
              ],
              where: {
                user_id: user_id,
              },
            },
          ],
        },
      ],
    });

    // return res.json(result);
    const firstOutput = result.map((entry) => ({
      auction_name: entry.auction_details.name,
      auction_id: entry.auction_details.auction_id,
      lane_details: entry.lane_details,
      lane_numbers: entry.lane_details.lane_details,
    }));

    const secondOutput = firstOutput.reduce((acc, entry) => {
      const existingEntry = acc.find((e) => e.auction_id === entry.auction_id);

      if (!existingEntry) {
        acc.push({
          auction_name: entry.auction_name,
          auction_id: entry.auction_id,
          lane_details: entry.lane_details,
        });
      } else {
        existingEntry.lane_details.push(...entry.lane_details);
      }

      return acc;
    }, []);
    // return res.json(secondOutput);
    const thirdOutput = secondOutput.map(
      ({ auction_name, auction_id, lane_details }) => {
        const vehiclesList = lane_details.map((vehicleRun) => {
          const vehicleRunDetails = vehicleRun.get({ plain: true });
          const vehicleInfo = vehicleRun.tblVehicle.get({ plain: true });
          const laneDetails = vehicleRun.lane_details.get({ plain: true });

          return {
            vehicle_run_id: vehicleRunDetails.vehicle_run_id,
            vehicle_id: vehicleRunDetails.vehicle_id,
            year: vehicleInfo.year,
            make: vehicleInfo.make,
            model: vehicleInfo.model,
            trim: vehicleInfo.trim,
            mileage: vehicleInfo.mileage,
            imageUrl: vehicleInfo.imageUrl,
            condition_light: vehicleRunDetails.condition_light,
            announcements: vehicleRunDetails.announcements,
            reserve: vehicleRunDetails.reserve,
            sale_price: vehicleRunDetails.sale_price,
            auction_fee: vehicleRunDetails.auction_fee,
            net_profit: vehicleRunDetails.net_profit,
            sale_status: vehicleRunDetails.sale_status,
            run_no: vehicleRunDetails.run_no,
            lane_id: vehicleRunDetails.lane_id,
            lane_name: laneDetails.name,
          };
        });

        return {
          auction_name,
          auction_id,
          units: vehiclesList.length,
          vehicles_list: vehiclesList,
        };
      }
    );

    const responseData = {
      data: thirdOutput,
    };

    return res.json(responseData);
  } catch (error) {
    return res.json(error.message);
  }
}; */

function transformFormat(originalData) {
  const transformedData = { data: [] };

  originalData.forEach((opportunity) => {
    const auctionData = {
      auction_name:
        opportunity.tblVehicles.length > 0 &&
        opportunity.tblVehicles[0][0].lane_details
          ? opportunity.tblVehicles[0][0].lane_details.auction_details.name
          : null,
      auction_id:
        opportunity.tblVehicles.length > 0 &&
        opportunity.tblVehicles[0][0].lane_details
          ? opportunity.tblVehicles[0][0].lane_details.auction_details
              .auction_id
          : null,
      units: opportunity.tblVehicles.length,
      vehicles_list: [],
    };

    opportunity.tblVehicles.forEach((vehicleArray) => {
      vehicleArray.forEach((vehicle) => {
        const vehicleData = {
          vehicle_run_id:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].vehicle_run_id
              : null,
          vehicle_id: vehicle.vehicle_id,
          year: vehicle.year,
          make: vehicle.make,
          model: vehicle.model,
          trim: vehicle.trim,
          mileage: vehicle.mileage,
          imageUrl: vehicle.imageUrl,
          condition_light:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].condition_light
              : null,
          announcements:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].announcements
              : null,
          reserve:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].reserve
              : null,
          sale_price:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].sale_price
              : null,
          auction_fee:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].auction_fee
              : null,
          net_profit:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].net_profit
              : null,
          sale_status:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].sale_status
              : null,
          run_no:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].run_no
              : null,
          lane_id:
            vehicle.tblVehicleRuns.length > 0
              ? vehicle.tblVehicleRuns[0].lane_id
              : null,
          lane_name:
            vehicle.tblVehicleRuns.length > 0 &&
            vehicle.tblVehicleRuns[0].lane_details
              ? vehicle.tblVehicleRuns[0].lane_details.name
              : null,
        };

        auctionData.vehicles_list.push(vehicleData);
      });
    });

    transformedData.data.push(auctionData);
  });

  return transformedData;
}

/* const getAuctionsByAuctioneerId = async (req, res) => {
  try {
    const { user_id, week_id } = req.body;

    let result = await db.tblOpportunity.findAll({
      attributes: ["opportunity_id", "week_id", "user_id", "auctioneer_id"],
      include: [
        {
          model: db.tblVehicle,
          attributes: [
            "vehicle_id",
            "year",
            "make",
            "model",
            "trim",
            "mileage",
            "imageUrl",
          ],
          include: [
            {
              model: db.tblVehicleRun,
              raw: true,
              include: [
                {
                  model: db.tblAuctionLane,
                  as: "lane_details",
                  nest: true,
                  raw: true,
                  include: [
                    {
                      model: db.tblAuction,
                      as: "auction_details",
                      attributes: ["auction_id", "name"],
                      nest: true,
                      raw: true,
                    },
                  ],
                },
              ],
            },
          ],
          where: {
            user_id: user_id,
          },
        },
      ],
      where: {
        user_id: user_id,
        week_id: week_id,
      },
    });

    return res.json({ data: result });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
}; */

/* const getAuctionsByAuctioneerId = async (req, res) => {
  try {
    const { user_id, week_id } = req.body;

    let result = await db.tblOpportunity.findAll({
      attributes: [],
      where: {
        user_id: user_id,
        week_id: week_id,
      },
      include: [
        {
          model: db.tblAuctioneer,
          attributes: ["auctioneer_id", "first_name"],
          raw: true,
          include: [
            {
              model: db.tblAuctionLane,
              attributes: ["lane_id"],
              raw: true,
              include: [
                {
                  model: db.tblAuction,
                  attributes: ["auction_id", "name"],
                  raw: true,
                },
                {
                  model: db.tblVehicleRun,
                  attributes: ["vehicle_id", "condition_light", "sale_status"],
                  raw: true,
                },
              ],
            },
          ],
        },
      ],
    });
    // return res.json({ data: result });
    const uniqueAuctions = new Set();
    const formattedResult = result.reduce((result, item) => {
      item.tblAuctioneer.tblAuctionLanes.forEach((lane) => {
        const auctionName = lane.tblAuction.name;
        const auctionId = lane.tblAuction.auction_id;
        // const units = lane.tblVehicleRuns.length;
        if (!uniqueAuctions.has(auctionName)) {
          uniqueAuctions.add(auctionName);
          result.push({
            lane_id: lane.lane_id,
            auction_id: auctionId,
            auction_name: auctionName,
            // units: units || 0,
          });
        }
      });
      return result;
    }, []);

    let auctionData = await db.tblAuctionLane.findAll({
      attributes: [
        "lane_id",
        [
          db.sequelize.fn(
            "COALESCE",
            db.sequelize.fn(
              "COUNT",
              db.sequelize.literal("tblVehicleRuns.lane_id")
            ),
            0
          ),
          "units",
        ],
      ],
      include: [
        {
          model: db.tblAuction,
          attributes: ["auction_id", "name"],
          where: {
            auction_id: 1,
          },
        },
        {
          model: db.tblVehicleRun,
          attributes: ["vehicle_run_id", "vehicle_id", "lane_id"],
          required: false,
        },
      ],
      group: [
        "tblAuctionLane.lane_id",
        "tblAuction.auction_id",
        "tblVehicleRuns.vehicle_run_id",
      ],
    });

    // auctionData = auctionData.map((item, index) => {
    //   return {
    //     // auction_id: item.auction_id,
    //     lane_id: item.tblAuctionLanes.map((item1) => item1.lane_id),
    //   };
    // });

    return res.json({ status: 200, message: "Success", data: formattedResult });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};
 */

const getAuctionsByAuctioneerId = async (req, res) => {
  try {
    const { user_id, week_id } = req.body;

    let result = await db.tblOpportunity.findAll({
      attributes: [],
      where: {
        user_id: user_id,
        week_id: week_id,
      },
      include: [
        {
          model: db.tblAuctioneer,
          attributes: ["auctioneer_id", "first_name", "auctioneer_id"],
          raw: true,
          include: [
            {
              model: db.tblAuctionLane,
              attributes: ["lane_id"],
              raw: true,
              include: [
                {
                  model: db.tblAuction,
                  attributes: ["auction_id", "name"],
                  raw: true,
                },
                {
                  model: db.tblVehicleRun,
                  attributes: ["vehicle_id", "condition_light", "sale_status"],
                  raw: true,
                },
              ],
            },
          ],
        },
      ],
    });

    const formattedResult = [];
    // return res.json({ data: result });
    for (const item of result) {
      for (const lane of item.tblAuctioneer.tblAuctionLanes) {
        const auctionName = lane.tblAuction.name;
        const auctionId = lane.tblAuction.auction_id;

        // Calculate the length of tblVehicleRuns for each lane_id

        const units = await db.tblVehicleRun.count({
          where: {
            lane_id: lane.lane_id,
          },
        });

        formattedResult.push({
          lane_id: lane.lane_id,
          auctioneer_id: item.tblAuctioneer.auctioneer_id,
          auction_id: auctionId,
          auction_name: auctionName,
          units: units,
        });
      }
    }

    // Create a Map to store aggregated units for each auction_id or auction_name
    const aggregatedDataMap = new Map();

    formattedResult.forEach((entry) => {
      const key = entry.auction_id + entry.auction_name;

      if (aggregatedDataMap.has(key)) {
        // If the key exists, add the units to the existing value
        aggregatedDataMap.set(key, {
          ...entry,
          units: aggregatedDataMap.get(key).units + entry.units,
        });
      } else {
        // If the key does not exist, add a new entry to the Map
        aggregatedDataMap.set(key, { ...entry });
      }
    });

    // Convert the Map values to an array to match the original format
    const resultData = Array.from(aggregatedDataMap.values());

    return res.json({ status: 200, message: "Success", data: resultData });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

module.exports = {
  getAuctionsAndLanesByAuctioneerId,
  getAuctionsByAuctioneerId,
};

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists