Sindbad~EG File Manager

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

// const { Op } = require("sequelize");
const db = require("../models");
const { col, literal, fn, Op, transaction } = require("sequelize");

function calculateDateRange(timeRange) {
  const currentDate = new Date();

  switch (timeRange) {
    case "currentweek":
      const currentWeekStartDate = new Date(currentDate);
      currentWeekStartDate.setDate(
        currentDate.getDate() - currentDate.getDay()
      );
      currentWeekStartDate.setHours(0, 0, 0, 0);

      const currentWeekEndDate = new Date(currentDate);
      currentWeekEndDate.setDate(
        currentWeekEndDate.getDate() + (6 - currentWeekEndDate.getDay())
      );
      currentWeekEndDate.setHours(23, 59, 59, 999);

      return { startDate: currentWeekStartDate, endDate: currentWeekEndDate };

    case "lastweek":
      const lastWeekStartDate = new Date(currentDate);
      lastWeekStartDate.setDate(
        lastWeekStartDate.getDate() - lastWeekStartDate.getDay() - 7
      );
      lastWeekStartDate.setHours(0, 0, 0, 0);

      const lastWeekEndDate = new Date(currentDate);
      lastWeekEndDate.setDate(
        lastWeekEndDate.getDate() - lastWeekEndDate.getDay() - 1
      );
      lastWeekEndDate.setHours(23, 59, 59, 999);

      return { startDate: lastWeekStartDate, endDate: lastWeekEndDate };

    case "last4weeks":
      const last4WeeksStartDate = new Date(currentDate);
      last4WeeksStartDate.setDate(last4WeeksStartDate.getDate() - 28);
      last4WeeksStartDate.setHours(0, 0, 0, 0);

      const last4WeeksEndDate = new Date(currentDate);
      last4WeeksEndDate.setDate(last4WeeksEndDate.getDate());
      last4WeeksEndDate.setHours(23, 59, 59, 999);

      return { startDate: last4WeeksStartDate, endDate: last4WeeksEndDate };
    case "last12weeks":
      const last12WeeksStartDate = new Date(currentDate);
      last12WeeksStartDate.setDate(last12WeeksStartDate.getDate() - 84);
      last12WeeksStartDate.setHours(0, 0, 0, 0);

      const last12WeeksEndDate = new Date(currentDate);
      last12WeeksEndDate.setDate(last12WeeksEndDate.getDate());
      last12WeeksEndDate.setHours(23, 59, 59, 999);

      return { startDate: last12WeeksStartDate, endDate: last12WeeksEndDate };

    default:
      // Handle other cases or return an error
      return null;
  }
}

const updateVehicleStatus = async (req, res) => {
  try {
    const { fee_amount, auctioneer_fee_id, vehicle_id, ...data } = req.body;
    if (data.lane_id) {
      const lane = await db.tblAuctionLane.findByPk(data.lane_id);
      if (!lane) {
        return res.status(400).json({
          status: 400,
          message: `Invalid lane_id: ${data.lane_id}`,
        });
      }
    }

    // Update vehicle run or create if it does not exist
    const [vehicleRun, vehicleRunCreated] = await db.tblVehicleRun.findOrCreate(
      {
        where: { vehicle_id },
        defaults: data,
      }
    );
    const vehicle_run_id = await db.tblVehicleRun.findOne({
      attributes: ["vehicle_run_id"],
      where: { vehicle_id: vehicle_id },
    });
    // If vehicle run exists and there are changes, update it
    if (!vehicleRunCreated && Object.keys(data).length > 0) {
      await vehicleRun.update(data);
    }
    // return res.json({ data: vehicle_run_id });

    // Handle vehicle run fees
    if (vehicle_run_id.vehicle_run_id) {
      const feePromises = auctioneer_fee_id.map((item, index) =>
        db.tblVehicleRunFee
          .findOrCreate({
            where: {
              vehicle_run_id: vehicle_run_id.vehicle_run_id,
              auctioneer_fee_id: item,
            },
            defaults: {
              vehicle_run_id: vehicle_run_id.vehicle_run_id,
              auctioneer_fee_id: item,
              fee_amount: fee_amount[index],
            },
          })
          .then(([record, created]) => {
            // Only update if fee_amount is provided and record was not newly created
            return !created && fee_amount !== undefined
              ? record.update({ fee_amount: fee_amount[index] })
              : record;
          })
      );

      await Promise.all(feePromises);
    }

    // Respond with success status
    return res.json({
      status: 200,
      message: "Success",
    });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const getVehicleFees = async (req, res) => {
  try {
    const vehicle_id = req.params.id;
    const vehicle_run_id = await db.tblVehicleRun.findOne({
      where: { vehicle_id: vehicle_id },
    });
    if (!vehicle_run_id) {
      return res.status(400).json({
        status: 400,
        message: `Invalid vehicle_id: ${vehicle_id}`,
      });
    }
    let result = await db.tblVehicleRunFee.findAll({
      attributes: ["vehicle_run_fee_id", "auctioneer_fee_id", "fee_amount"],
      where: {
        vehicle_run_id: vehicle_run_id.vehicle_run_id,
      },
      include: [
        {
          model: db.tblAuctioneerFee,
          attributes: ["name", "default_amount"],
          raw: true,
        },
      ],
    });

    result = result.map((item) => {
      return {
        vehicle_run_fee_id: item.vehicle_run_fee_id,
        auctioneer_fee_id: item.auctioneer_fee_id,
        fee_amount: item.fee_amount || 300,
        name: item.tblAuctioneerFee.name,
      };
    });
    return res.json({ status: 200, message: "Success", data: result });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

//testingsale

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

    let timeRange;
    if (!req.body.timeRange) {
      timeRange = "currentweek";
    } else {
      timeRange = req.body.timeRange;
    }
    timeRange = timeRange.replace(/\s/g, "");
    timeRange = timeRange.toLowerCase();

    const weekRange = calculateDateRange(timeRange);
    const start_date = weekRange.startDate;
    const end_date = weekRange.endDate;
    let [result] = await db.sequelize.query(
      "CALL UserStats(:user_id,:start_date,:end_date)",
      {
        replacements: { user_id, start_date, end_date },
      }
    );
    if (!result) {
      return res.json({
        status: 200,
        message: "success",
        data: {
          sold_units: 0,
          total_sales: 0,
          net_proceeds: 0,
        },
      });
    }
    return res.json({
      status: 200,
      message: "success",
      data: result,
    });
    // const results = await db.tblVehicle.findAll({
    //   attributes: [
    //     "vehicle_id",
    //     "user_id",
    //     /* [
    //       db.sequelize.literal("SUM(`tblVehicleRuns`.`sale_price`)"),
    //       "total_sale",
    //     ],
    //     [
    //       db.sequelize.literal("SUM(`tblVehicleRuns`.`net_profit`)"),
    //       "total_net_profit",
    //     ], */
    //   ],
    //   include: [
    //     {
    //       model: db.tblVehicleRun,
    //       attributes: [
    //         "vehicle_run_id",
    //         "sale_price",
    //         "vehicle_total_fee",
    //         "net_proceed",
    //         "sale_status",
    //       ],
    //       raw: true,
    //       where: {
    //         sale_price: { [Op.ne]: null },
    //         createdAt: {
    //           [Op.between]: [weekRange.startDate, weekRange.endDate],
    //         },
    //       },
    //     },
    //   ],
    //   where: {
    //     user_id: user_id,
    //   },
    //   // order: [["createdAt", "ASC"]],
    // });
    // return res.json({
    //   status: 200,
    //   message: "success",
    //   net_proceed: 0,
    //   total_profit: 0,
    //   unit_sold: 0,
    // });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const getSingleVehicle = async (req, res) => {
  try {
    let vehicle_id = req.params.id;

    const results = await db.tblVehicle.findAll({
      attributes: [
        "vehicle_id",
        "vin",
        "trim",
        "year",
        "make",
        "model",
        "imageUrl",
      ],
      include: [
        {
          model: db.tblVehicleRun,
          attributes: [
            "vehicle_run_id",
            "condition_light",
            "announcements",
            "reserve",
            "sale_status",
            "sale_price",
            "run_no",
            "lane_id",
            "net_proceed",
            "vehicle_total_fee",
          ],
          include: [
            {
              model: db.tblAuctionLane,

              attributes: ["lane_id", "name"],
              include: [
                {
                  model: db.tblAuction,
                  required: true,
                  attributes: ["name"],
                },
              ],
            },
          ],
        },
      ],
      where: {
        vehicle_id: vehicle_id,
      },
    });

    // return res.json(results);
    const formattedData = results.map((item) => {
      const vehicle_run = item.tblVehicleRuns[0] || {};
      // If vehicle_run exists, use it to get auction_lane, otherwise set default values
      const auction_lane = vehicle_run.tblAuctionLane || {
        lane_id: null,
        name: null,
        tblAuction: {
          name: null,
        },
      };
      // Now access the auction from auction_lane
      const auction = auction_lane.tblAuction || { name: null };

      return {
        vehicle_id: item.vehicle_id,
        vin: item.vin.trim(),
        year: item.year,
        make: item.make.trim(),
        model: item.model.trim(),
        trim: item.trim.trim(),
        imageUrl: item.imageUrl,
        condition_light: vehicle_run.condition_light || 4,
        announcements: vehicle_run.announcements || null,
        reserve: vehicle_run.reserve || null,
        sale_status: vehicle_run.sale_status || false,
        sale_price: vehicle_run.sale_price || null,
        run_no: vehicle_run.run_no || null,
        net_proceed: vehicle_run.net_proceed || null,
        vehicle_total_fee: vehicle_run.vehicle_total_fee || null,
        lane_id: auction_lane.lane_id, // Removed the duplication by deleting one 'lane_id'
        lane_name: auction_lane.name,
        auction_name: auction.name,
      };
    });

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

module.exports = {
  updateVehicleStatus,
  totalSaleAndNetProceed,
  getVehicleFees,
  getSingleVehicle,
};

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