/
home
/
infinitibizsol
/
.trash
/
controllers.1
/
File Upload :
llllll
Current File: /home/infinitibizsol/.trash/controllers.1/userController.js
const { Op, INTEGER, col } = require("sequelize"); const db = require("../models"); const bcrypt = require("bcrypt"); const updateUserProfile = async (req, res) => { let { user_id, ...data } = req.body; if (req.body.password) { const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(req.body.password, salt); data.password = hashedPassword; } // return res.json(data); try { let result = await db.tblUser.update(data, { where: { user_id: user_id, }, }); return res.json({ status: 200, message: "profile updated", }); } catch (error) { console.log(error.message); return res.json({ status: 500, message: `${error.message}` }); } }; const getUserProfile = async (req, res) => { const user_id = req.params.id; try { let [result] = await db.tblUser.findAll({ where: { user_id: user_id, }, }); if (!result) { return res.json({ status: 402, message: "No user Found" }); } return res.json({ status: 200, data: [ { user_id: result.user_id, first_name: result.first_name, last_name: result.last_name, email: result.email, contact: result.contact, address: result.address, business_address: result.business_address, business_name: result.business_name, username: result.username, }, ], }); } catch (error) { console.log(error.message); return res.json({ status: 500, message: `${error.message}` }); } }; const getAllCarsByAuctioneerId = async (req, res) => { try { const { opportunity_id, user_id, sortBy, orderDirection } = req.body; // Adjust the where clause based on sortBy if (sortBy == "sold_price") { sortBy = "vehicle_id"; /* whereClause.sold_price = { [Op.not]: null, }; */ } const result = await db.tblVehicle.findAll({ attributes: [ "vehicle_id", "year", "vin", "make", "model", "mileage", "color", "color_name", "imageUrl", ], include: [ { model: db.tblVehicleRun, attributes: [ "condition_light", "reserve", "announcements", "sale_price", "sale_status", "lane_id", "auction_fee", ], include: [ { model: db.tblAuctionLane, attributes: ["lane_id", "name"], // as: "lane_details", include: [ { model: db.tblAuction, attributes: ["name"], // as: "auction_details", }, ], }, ], }, ], where: { opportunity_id: opportunity_id, user_id: user_id, }, raw: true, // Get plain JSON objects directly order: [[sortBy || "vehicle_id", orderDirection || "ASC"]], }); // return res.json({ data: result }); const formattedResult = result.map((item) => { return { vehicle_id: item.vehicle_id, year: item.year, make: item.make, model: item.model, vin: item.vin, mileage: item.mileage, color: item.color, color_name: item.color_name, imageUrl: item.imageUrl, condition_light: item["tblVehicleRuns.condition_light"] || null, reserve: item["tblVehicleRuns.reserve"] || null, announcements: item["tblVehicleRuns.announcements"] || null, sale_price: item["tblVehicleRuns.sale_price"] || null, sale_status: item["tblVehicleRuns.sale_status"] || null, lane_id: item["tblVehicleRuns.tblAuctionLane.lane_id"] || null, auction_fee: item["tblVehicleRuns.auction_fee"] || null, lane_name: item["tblVehicleRuns.tblAuctionLane.name"] || null, auction_name: item["tblVehicleRuns.tblAuctionLane.tblAuction.name"] || null, }; }); return res.json({ data: formattedResult }); } catch (error) { return res.json(error.message); } }; const getAllCarsWithStatus = async (req, res) => { try { let { auctioneer_id, user_id, weekId, sortBy, orderDirection } = req.body; // let { sortBy, orderDirection } = req.body; // Define the base where clause let whereClause = { user_id: user_id, }; // Adjust the where clause based on sortBy if (sortBy == "sold_price") { sortBy = "vehicle_id"; /* whereClause.sold_price = { [Op.not]: null, }; */ } let resultTableCar = await db.tblVehicle.findAll({ where: whereClause, include: [ { model: db.tblVehicleRun, attributes: ["condition_light"], raw: true, }, ], order: [[sortBy || "vehicle_id", orderDirection || "ASC"]], }); let resultTableAdminUsers = await db.tblOpportunity.findAll({}); const adminIdsInUsers = new Set( resultTableAdminUsers.map((item) => item.opportunity_id) ); // Add a new "status" field to each vehicle object resultTableCar = resultTableCar.map((item) => item.get()); let data = await Promise.all( resultTableCar.map(async (vehicle, index) => { const tblVehicleRuns = vehicle.tblVehicleRuns || []; const condition_light = tblVehicleRuns.length > 0 ? tblVehicleRuns[0].condition_light : undefined; return { vehicle_id: vehicle.vehicle_id, vin: vehicle.vin, year: vehicle.year, make: vehicle.make, model: vehicle.model, trim: vehicle.trim, mileage: vehicle.mileage, color: vehicle.color, color_name: vehicle.color_name, details: vehicle.details, imageUrl: vehicle.imageUrl, opportunity_id: vehicle.opportunity_id, user_id: vehicle.user_id, createdAt: vehicle.createdAt, updatedAt: vehicle.updatedAt, condition_light: condition_light, status: adminIdsInUsers.has(vehicle.opportunity_id), weekId: await getWeekIds(vehicle.opportunity_id), auctioneer_name: await getAuctioneerName(vehicle.opportunity_id), selected_date: await getselectedDate(vehicle.opportunity_id), }; }) ); /* let data = await Promise.all( resultTableCar.map(async (vehicle, index) => ({ ...vehicle, status: adminIdsInUsers.has(vehicle.opportunity_id), weekId: await getWeekIds(vehicle.opportunity_id), auctioneer_name: await getAuctioneerName(vehicle.opportunity_id), selected_date: await getselectedDate(vehicle.opportunity_id), })) ); */ return res.json({ status: 200, data: data }); [ { vehicle_id: 1, vin: "DF54FG654C", year: 2024, make: "BMW", model: "Q-4", trim: "HDHDHYE", mileage: 8000, color: "fff44336", color_name: "Red", details: "SE.ONE OWNER CAR VERY CLEAN AND NICE INSIDE AND OUTSIDE.NO ACCIDENTS.", imageUrl: "preview.png", opportunity_id: 5, user_id: 1, createdAt: "2023-12-26T06:27:43.000Z", updatedAt: "2024-01-03T18:57:09.000Z", condition_light: 1, status: true, weekId: 50, auctioneer_name: "Steve", selected_date: "November 11-17", }, ]; } catch (error) { return res.json(error.message); } }; const getWeekIds = async (opportunity_id) => { try { const weekIds = await db.tblOpportunity.findAll({ attributes: ["week_id"], where: { opportunity_id: opportunity_id }, }); if (weekIds.length > 0) { return weekIds[0].week_id; } else { // Handle the case when no week_id is found for the given opportunity_id return null; // You can adjust this accordingly based on your requirements } } catch (error) { // Handle any errors that may occur during the database query console.error("Error fetching weekIds:", error.message); throw error; // You may want to handle this error in the calling function } }; const getAuctioneerName = async (opportunity_id) => { try { let weekIds = await db.tblOpportunity.findAll({ attributes: [], // Select the columns you want to retrieve include: [ { model: db.tblAuctioneer, attributes: ["first_name"], raw: true, }, ], where: { opportunity_id: opportunity_id, }, }); if (weekIds.length > 0) { // console.log(weekIds[0].dataValues.first_name); console.log(weekIds[0].dataValues.tblAuctioneer.dataValues.first_name); // console.log(weekIds[0].dataValues.tblAuctioneer.dataValues.last_name); return weekIds[0].dataValues.tblAuctioneer.dataValues.first_name; } else { // Handle the case when no week_id is found for the given opportunity_id return null; // You can adjust this accordingly based on your requirements } } catch (error) { // Handle any errors that may occur during the database query console.error("Error fetching weekIds:", error.message); throw error; // You may want to handle this error in the calling function } }; const getselectedDate = async (opportunity_id) => { try { const weekIds = await db.tblOpportunity.findAll({ attributes: ["date"], where: { opportunity_id: opportunity_id, }, }); if (weekIds.length > 0) { // Accessing the date property using dataValues console.log(weekIds[0].dataValues.date); // Returning the date property return weekIds[0].dataValues.date; } else { // Handle the case when no data is found for the given opportunity_id return null; // You can adjust this accordingly based on your requirements } } catch (error) { // Handle any errors that may occur during the database query console.error("Error fetching weekIds:", error.message); throw error; // You may want to handle this error in the calling function } }; /* const userAuctioneerListById = async (req, res) => { try { const { userId, weekId } = req.body; let result = await db.tblOpportunity.findAll({ attributes: ["opportunity_id"], // Select the columns you want to retrieve include: [ { model: db.tblAuctioneer, attributes: ["first_name", "last_name", "auctioneer_id"], // Select the columns you want to retrieve raw: true, }, { model: db.tblVehicle, attributes: [ "vehicle_id", "year", "make", "model", "mileage", "imageUrl", ], raw: true, include: [ { model: db.tblVehicleRun, attributes: [ "condition_light", "announcements", "reserve", "sale_price", "auction_fee", "sale_status", ], // Select the columns you want to retrieve raw: true, include: [ { model: db.tblAuctionLane, attributes: ["name", "lane_id"], // Select the columns you want to retrieve as: "lane_details", raw: true, include: [ { model: db.tblAuction, as: "auction_details", attributes: ["name"], raw: true, }, ], }, ], }, ], where: { user_id: userId, }, }, ], where: { user_id: userId, week_id: parseInt(weekId), }, }); const modifiedData = result.map((item, index) => ({ first_name: item.tblAuctioneer.first_name, auctioneer_id: item.tblAuctioneer.auctioneer_id, opportunity_id: item.opportunity_id, units: item.tblVehicles.length, vehicles_list: item.tblVehicles, })); // return res.json(modifiedData); const outputArray = modifiedData.map((auctioneer) => { return { first_name: auctioneer.first_name, auctioneer_id: auctioneer.auctioneer_id, opportunity_id: auctioneer.opportunity_id, units: auctioneer.units, vehicles_list: auctioneer.vehicles_list.map((vehicle) => { const tblVehicleRuns = vehicle.tblVehicleRuns[0] || {}; return { vehicle_id: vehicle.vehicle_id, vin: vehicle.vin, year: vehicle.year, make: vehicle.make, model: vehicle.model, trim: vehicle.trim, mileage: vehicle.mileage, color: vehicle.color, color_name: vehicle.color_name, details: vehicle.details, imageUrl: vehicle.imageUrl, opportunity_id: vehicle.opportunity_id, user_id: vehicle.user_id, createdAt: vehicle.createdAt, updatedAt: vehicle.updatedAt, condition_light: tblVehicleRuns.condition_light || null, announcements: tblVehicleRuns.announcements || null, reserve: tblVehicleRuns.reserve || null, sale_price: tblVehicleRuns.sale_price || null, auction_fee: tblVehicleRuns.auction_fee || null, sale_status: tblVehicleRuns.sale_status || null, lane_name: tblVehicleRuns.lane_details ? tblVehicleRuns.lane_details.name : null, lane_id: tblVehicleRuns.lane_details ? tblVehicleRuns.lane_details.lane_id : null, auction_name: tblVehicleRuns.lane_details ? tblVehicleRuns.lane_details.auction_details.name : null, }; }), }; }); return res.json({ status: 200, data: outputArray }); } catch (error) { return res.json(error.message); } }; */ //Optimized Code const userAuctioneerListById = async (req, res) => { try { const { userId, weekId } = req.body; const result = await db.tblOpportunity.findAll({ attributes: [ "opportunity_id", [ db.sequelize.fn( "COALESCE", db.sequelize.fn( "COUNT", db.sequelize.literal("tblVehicles.opportunity_id") ), 0 ), "units", ], ], include: [ { model: db.tblAuctioneer, attributes: ["first_name", "last_name", "auctioneer_id"], }, { model: db.tblVehicle, attributes: [], required: false, // Use LEFT JOIN to include opportunities without matching vehicles }, ], where: { user_id: userId, week_id: parseInt(weekId), }, group: ["tblOpportunity.opportunity_id", "tblAuctioneer.auctioneer_id"], }); // Format the result as needed const test = result.map((item) => { return { opportunity_id: item.dataValues.opportunity_id, units: parseInt(item.dataValues.units) || 0, // Use COALESCE to return 0 if units is falsy auctioneer_id: item.tblAuctioneer.auctioneer_id, first_name: item.tblAuctioneer.first_name, }; }); return res.json({ data: test }); } catch (error) { return res.json({ status: 500, message: error.message }); } }; const getAllAuctioneerList = async (req, res) => { try { const { weekId } = req.body; let resultTableAdmin = await db.tblAuctioneer.findAll(); let resultTableAdminUsers = await db.tblOpportunity.findAll({ where: { week_id: weekId, }, }); const adminIdsInUsers = new Set( resultTableAdminUsers.map((item) => item.auctioneer_id) ); resultTableAdmin = resultTableAdmin.map((item) => item.get()); const data = resultTableAdmin.map((item) => ({ ...item, status: adminIdsInUsers.has(item.auctioneer_id), // status: true, })); return res.json({ status: 200, data: data }); } catch (error) { return res.json(error.message); } }; const getAllSubscribedAuctioneerList = async (req, res) => { try { const { userId } = req.body; let resultTableAdmin = await db.tblAuctioneer.findAll(); let resultTableAdminUsers = await db.tblUserSubAuctioneer.findAll({ where: { user_id: userId, }, }); const adminIdsInUsers = new Set( resultTableAdminUsers.map((item) => item.auctioneer_id) ); resultTableAdmin = resultTableAdmin.map((item) => item.get()); const data = resultTableAdmin.map((item) => ({ ...item, status: adminIdsInUsers.has(item.auctioneer_id), // status: true, })); return res.json({ status: 200, data: data }); } catch (error) { return res.json(error.message); } }; const updateUserAuctioneerList = async (req, res) => { try { const { userId, auctioneer_ids, weekId, date } = req.body; let result; const promises = auctioneer_ids.map(async (item) => { try { result = await db.tblOpportunity.create({ user_id: userId, auctioneer_id: item, week_id: weekId, date: date, }); } catch (error) { console.error(error); return res .status(500) .json({ status: 500, message: "Internal Server Error" }); } }); await Promise.all(promises); return res.json({ status: 200, data: result }); } catch (error) { return res.json(error.message); } }; const deleteUserAuctioneer = async (req, res) => { try { console.log(req.body); const { auctioneer_ids, weekId, user_id } = req.body; let result; const promises = auctioneer_ids.map(async (item) => { const opportunitiesToDelete = await db.tblOpportunity.findAll({ attributes: ["opportunity_id"], // Select only the id column where: { [Op.and]: [ { auctioneer_id: item, }, { week_id: weekId, }, // If needed, add more conditions // { user_id: user_id }, ], }, }); console.log(`opportunitiesToDelete====${opportunitiesToDelete}`); opportunitiesToDelete.map(async (item) => { await db.tblVehicle.update( { lane_id: null }, { opportunity_id: item.opportunity_id } ); }); result = await db.tblOpportunity.destroy({ where: { [Op.and]: [ { auctioneer_id: item, }, { week_id: weekId, }, // will be added later { user_id: user_id }, ], }, }); }); await Promise.all(promises); return res.json({ status: 200, data: result }); } catch (error) { return res.json(error.message); } }; const deleteUserAuctioneerTesting = async (req, res) => { try { const { auctioneer_ids, weekId, user_id } = req.body; const deletePromises = auctioneer_ids.map(async (item) => { // Find opportunities to be deleted const opportunitiesToDelete = await db.tblOpportunity.findAll({ attributes: ["opportunity_id"], where: { auctioneer_id: item, week_id: weekId, user_id: user_id, // If needed, add more conditions }, }); // Extract opportunity IDs const opportunityIds = opportunitiesToDelete.map( (opportunity) => opportunity.opportunity_id ); const vehiclesResult = await db.tblVehicle.findAll({ where: { opportunity_id: opportunityIds }, }); const vehicleIds = vehiclesResult.map((item) => item.vehicle_id); await db.tblVehicleRun.update( { lane_id: null }, { where: { vehicle_id: vehicleIds } } ); // Update tblVehicle records await db.tblVehicle.update( { opportunity_id: null }, { where: { opportunity_id: opportunityIds } } ); // Delete opportunities const deleteResult = await db.tblOpportunity.destroy({ where: { auctioneer_id: item, week_id: weekId, user_id: user_id, // will be added later }, }); return { auctioneer_id: item, deletedOpportunities: opportunityIds, deleteResult, }; }); const results = await Promise.all(deletePromises); return res.json({ status: 200, data: results }); } catch (error) { return res.status(500).json({ error: `Error Message :${error.message}` }); } }; module.exports = { getUserProfile, updateUserProfile, userAuctioneerListById, getAllAuctioneerList, updateUserAuctioneerList, getAllCarsByAuctioneerId, getAllCarsWithStatus, deleteUserAuctioneer, getAllSubscribedAuctioneerList, deleteUserAuctioneerTesting, };
Copyright ©2k19 -
Hexid
|
Tex7ure