Sindbad~EG File Manager
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 updateUserPassword = async (req, res) => {
try {
let { user_id, newPassword } = req.body;
if (newPassword) {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(newPassword, salt);
let result = await db.tblUser.update(
{ password: hashedPassword },
{ where: { user_id: user_id } }
);
return res.status(200).json({ status: 200, message: "Success" });
} else {
return res.json({ status: 400, message: "Please enter new password." });
}
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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 removeUser = async (req, res) => {
const { email } = req.body;
let transaction;
try {
transaction = await db.sequelize.transaction(); // Start a new transaction
const user = await db.tblUser.findOne({
where: { email },
transaction,
});
if (!user) {
await transaction.rollback(); // Ensure transaction is rolled back if user does not exist
return res.status(404).json({ status: 404, message: "User not found." });
}
const opportunities = await db.tblOpportunity.findAll({
where: { user_id: user.user_id },
transaction,
});
const opportunity_ids = opportunities.map(
(opportunity) => opportunity.opportunity_id
);
vehicle_run = await db.tblVehicleRun.findAll({
where: {
opportunity_id: {
[Op.in]: opportunity_ids, // Use the `Op.in` operator to look for any opportunity_id in the provided array
},
},
transaction,
});
const vehicle_run_ids = vehicle_run.map((item) => item.vehicle_run_id);
const vehicle_run_fee_deleted_count = await db.tblVehicleRunFee.destroy({
where: { vehicle_run_id: vehicle_run_ids },
transaction,
});
const vehicle_run_deleted_count = await db.tblVehicleRun.destroy({
where: { opportunity_id: opportunity_ids },
transaction,
});
const vehicle_deleted_count = await db.tblVehicle.destroy({
where: { user_id: user.user_id },
transaction,
});
const opportunity_deleted_count = await db.tblOpportunity.destroy({
where: { opportunity_id: opportunity_ids },
transaction,
});
const subscription_deleted_count = await db.tblUserSubAuctioneer.destroy({
where: { user_id: user.user_id },
transaction,
});
const user_deleted_count = await db.tblUser.destroy({
where: { user_id: user.user_id },
transaction,
});
await transaction.commit(); // Commit all changes
return res.status(200).json({
message: "User and related data successfully deleted.",
details: {
vehicle_runs: vehicle_run_deleted_count,
vehicle_runs_fee: vehicle_run_fee_deleted_count,
vehicle: vehicle_deleted_count,
opportunities: opportunity_deleted_count,
subscriptions: subscription_deleted_count,
user: user_deleted_count,
},
});
} catch (error) {
if (transaction) {
try {
// Additional safeguard to ensure that we do not call rollback on an already finished transaction.
if (!transaction.finished) {
await transaction.rollback();
}
} catch (rollbackError) {
console.error("Rollback error:", rollbackError);
}
}
return res.status(500).json({
message: "Internal Server Error",
error: error.message,
});
}
};
const getAllAssignedVehicles = 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";
}
const result = await db.tblVehicle.findAll({
attributes: [
"vehicle_id",
"vin",
"year",
"make",
"model",
"mileage",
"imageUrl",
],
include: [
{
model: db.tblVehicleRun,
where: {
opportunity_id: opportunity_id,
},
attributes: ["condition_light", "run_no", "sale_status", "lane_id"],
include: [
{
model: db.tblAuctionLane,
attributes: ["lane_id", "name"],
// as: "lane_details",
include: [
{
model: db.tblAuction,
attributes: ["name"],
// as: "auction_details",
},
],
},
],
},
],
where: {
user_id: user_id,
},
order: [[sortBy || "vehicle_id", orderDirection || "ASC"]],
});
// return res.json({ data: result });
const formattedResult = result.map((item) => {
const vehicleRun = item.tblVehicleRuns[0] || {};
const lane = vehicleRun.tblAuctionLane || {};
const auction = lane.tblAuction || {};
return {
vehicle_id: item.vehicle_id,
year: item.year,
make: item.make,
model: item.model,
vin: item.vin,
mileage: item.mileage,
imageUrl: item.imageUrl,
condition_light: vehicleRun?.condition_light || 4,
sale_status: vehicleRun?.sale_status || false,
lane_id: vehicleRun?.lane_id || null,
run_no: vehicleRun?.run_no || null,
lane_name: lane?.name || null,
auction_name: auction?.name || null,
};
});
return res.json({ status: 200, message: "Success", data: formattedResult });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: error.message,
});
}
};
const getAuctioneerName = async (opportunity_id) => {
const opportunity = await db.tblOpportunity.findOne({
attributes: [],
include: [
{
model: db.tblAuctioneer,
attributes: ["first_name"],
},
],
where: { opportunity_id },
});
if (opportunity && opportunity.tblAuctioneer) {
console.log(opportunity.tblAuctioneer.first_name);
return opportunity.tblAuctioneer.first_name;
} else {
return null;
}
};
const getSelectedDate = async (opportunity_id) => {
const opportunity = await db.tblOpportunity.findOne({
attributes: ["date"],
where: { opportunity_id },
});
if (opportunity) {
console.log(opportunity.date);
return opportunity.date;
} else {
return null;
}
};
const getWeekId = async (opportunity_id) => {
const opportunity = await db.tblOpportunity.findOne({
attributes: ["week_id"],
where: { opportunity_id },
});
if (opportunity) {
return opportunity.week_id;
} else {
return null;
}
};
const getAllVehiclesWithStatus = async (req, res) => {
try {
const { user_id, sortBy = "vehicle_id", orderDirection = "ASC" } = req.body;
const vehicles = await db.tblVehicle.findAll({
attributes: [
"vehicle_id",
"year",
"make",
"model",
"trim",
"vin",
"mileage",
"color",
"color_name",
"details",
"imageUrl",
[db.sequelize.col("tblVehicleRuns.opportunity_id"), "opportunity_id"],
],
where: { user_id },
include: [
{
model: db.tblVehicleRun,
// attributes: ["condition_light", "opportunity_id"], // Include opportunity_id here
include: [
{
model: db.tblOpportunity,
attributes: ["week_id", "date"],
include: [
{
model: db.tblAuctioneer,
attributes: ["first_name"],
},
],
},
],
},
],
order: [[sortBy, orderDirection]],
});
// return res.json(vehicles);
let resultTableAdminUsers = await db.tblOpportunity.findAll({});
const adminIdsInUsers = new Set(
resultTableAdminUsers.map((item) => item.opportunity_id)
);
const formattedVehicles = vehicles.map((vehicle) => {
const run = vehicle.tblVehicleRuns[0] || {};
const opportunity = run.tblOpportunity || {};
const auctioneer = opportunity.tblAuctioneer || {};
// console.log(vehicle.get().opportunity_id);
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,
/* condition_light: run.condition_light || 0,
announcements: run.announcements || null,
reserve: run.reserve || 0,
sale_price: run.sale_price || 0,
vehicle_total_fee: run.vehicle_total_fee || 0,
net_proceed: run.net_proceed || 0,
run_no: run.run_no || 0,
sale_status: run.sale_status || false,
lane_id: run.lane_id || null, */
status: adminIdsInUsers.has(vehicle.get().opportunity_id) || false,
weekId: opportunity.week_id || null,
auctioneer_name: auctioneer.first_name || null,
selected_date: opportunity.date || null,
};
});
return res.json({
status: 200,
message: "Success",
data: formattedVehicles,
});
} catch (error) {
console.error(error.message);
return res.status(500).json({ message: error.message });
}
};
const userAddedAuctioneerListById = 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("tblVehicleRuns.opportunity_id")
),
0
),
"units",
],
],
include: [
{
model: db.tblAuctioneer,
attributes: ["first_name", "business_name", "auctioneer_id"],
},
{
model: db.tblVehicleRun,
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.business_name,
};
});
return res.json({ status: 200, message: "Success", 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 addUserAuctioneerToOpportunity = 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 removeUserAuctioneer = 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 removeUserAuctioneerTesting = 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.tblVehicleRun.findAll({
where: { opportunity_id: opportunityIds },
});
const vehicleIds = vehiclesResult.map((item) => item.vehicle_id);
await db.tblVehicleRun.update(
{ lane_id: null, opportunity_id: null },
{ where: { vehicle_id: vehicleIds } }
);
console.log("Before");
// Delete opportunities
const deleteResult = await db.tblOpportunity.destroy({
where: {
auctioneer_id: item,
week_id: weekId,
user_id: user_id,
},
});
console.log("After");
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,
updateUserPassword,
updateUserProfile,
removeUser,
userAddedAuctioneerListById,
getAllAuctioneerList,
addUserAuctioneerToOpportunity,
getAllAssignedVehicles,
getAllVehiclesWithStatus,
getAllSubscribedAuctioneerList,
removeUserAuctioneer,
removeUserAuctioneerTesting,
};
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists