Sindbad~EG File Manager

Current Path : /home/infinitibizsol/autocrm.infinitibizsol.com/controllers/
Upload File :
Current File : /home/infinitibizsol/autocrm.infinitibizsol.com/controllers/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,rmvd_fees = [],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);
//     }

// const removedFeesResult = await db.tblVehicleRunFee.destroy({
//       where: {
//         auctioneer_fee_id: { [Op.in]: rmvd_fees },
//       },
//     });

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

const updateVehicleStatus = async (req, res) => {
  try {
    const { fee_amount, auctioneer_fee_id, vehicle_id, ...data } = req.body;
    const vehicleRun1 = await db.tblVehicleRun.findOne({
      where: { vehicle_id: vehicle_id },
      attributes: ["opportunity_id", "vehicle_run_id"],
      include: [
        {
          model: db.tblOpportunity,
          attributes: ["auctioneer_id", "user_id"],
        },
      ],
    });

    if (!vehicleRun1) {
      // Handle the case when the vehicle run is not found
      throw new BadRequestError("Vehicle run not found");
    }


    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 transaction = await db.sequelize.transaction(); // Start a new transaction

      try {
        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] },
                    { transaction }
                  )
                : record;
            })
        );

        const updatedRecords = await Promise.all(feePromises);
        const updatedRecordIds = updatedRecords.map(
          (record) => record.vehicle_run_fee_id
        );

        await db.tblVehicleRunFee.destroy({
          where: {
            vehicle_run_id: vehicle_run_id.vehicle_run_id,
            vehicle_run_fee_id: { [Op.notIn]: updatedRecordIds },
          },
          transaction,
        });

        // If everything went well, commit the transaction
        await transaction.commit();
      } catch (error) {
        await transaction.rollback();
        throw error;
      }
    }

    // Respond with success status
    return res.status(200).json({
      status: 200,
      message: "Success",
    });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      error: "Internal Server Error",
      message: 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,
    });
    
    
    
  } 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",
        "mileage",
        "color",
        "color_name",
        "imageUrl",
      ],
      include: [
        {
          model: db.tblVehicleRun,
          attributes: [
            "vehicle_run_id",
            "condition_light",
            "announcements",
            "reserve",
            "sale_status",
            "sale_price",
            "run_no",
            "lane_id",
            "net_proceeds",
            "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||null,
        mileage: item.mileage||null,
        color: item.color||null,
        color_name: item.color_name||null,
        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_proceeds: vehicle_run.net_proceeds || 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