/
home
/
infinitibizsol
/
.trash
/
controllers.2
/
File Upload :
llllll
Current File: /home/infinitibizsol/.trash/controllers.2/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; // const test = await db.tblVehicleRunFee.findAll(); // return res.json(test); // Validate lane_id if present 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); } // 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 }, }); 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||null, }; }); 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 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, }); if (results.length === 0) { return res.json({ status: 200, message: "Success", net_proceed: 0, total_profit: 0, unit_sold: 0, }); } const transformedData = results.reduce((result, vehicle) => { const existingUser = result.find( (user) => user.user_id === vehicle.user_id ); if (existingUser) { // If user exists, update totals existingUser.total_profit += vehicle.tblVehicleRuns.reduce( (sum, run) => sum + run.sale_price, 0 ); existingUser.net_profit += vehicle.tblVehicleRuns.reduce( (sum, run) => sum + run.net_profit, 0 ); existingUser.sold_units += vehicle.tblVehicleRuns.length; } else { // If user doesn't exist, add a new user entry const newUser = { user_id: vehicle.user_id, total_profit: vehicle.tblVehicleRuns.reduce( (sum, run) => sum + run.sale_price, 0 ), net_profit: vehicle.tblVehicleRuns.reduce( (sum, run) => sum + run.net_profit, 0 ), sold_units: vehicle.tblVehicleRuns.length, }; result.push(newUser); } return result; }, []); return res.json({ status: 200, message: "Success", net_proceed: transformedData[0]?.net_profit || 0, total_profit: transformedData[0]?.total_profit || 0, unit_sold: transformedData[0]?.sold_units || 0, }); } catch (error) { return res.status(500).json({ status: 500, 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,getVehicleFees, totalSaleAndNetProceed,getSingleVehicle };
Copyright ©2k19 -
Hexid
|
Tex7ure