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;
data.business_email = data.business_email?.toLowerCase();
if (req.body.password) {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
data.password = hashedPassword;
}
try {
let result = await db.tblUser.update(data, {
where: {
user_id: user_id,
},
});
return res.json({
status: 200,
message: "profile updated successfully.",
});
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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" });
}
let { password, ...formattedResult } = result;
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 removeUser = async (req, res) => {
const { business_email } = req.body;
let transaction;
try {
transaction = await db.sequelize.transaction(); // Start a new transaction
const user = await db.tblUser.findOne({
where: { business_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 removeUserTest = async (req, res) => {
const { business_email } = req.body;
let transaction;
try {
transaction = await db.sequelize.transaction(); // Start a new transaction
const user = await db.tblAuction.destroy({
where: { auction_id: 1 },
});
return res.status(200).json({
message: "Auction successfully deleted.",
});
} 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",
"trim",
],
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,
trim: item.trim,
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: ["firstname"],
},
],
where: { opportunity_id },
});
if (opportunity && opportunity.tblAuctioneer) {
return opportunity.tblAuctioneer.firstname;
} else {
return null;
}
};
const getSelectedDate = async (opportunity_id) => {
const opportunity = await db.tblOpportunity.findOne({
attributes: ["date"],
where: { opportunity_id },
});
if (opportunity) {
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",
[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: ["firstname"],
},
],
},
],
},
],
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 || {};
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,
opportunity_id: vehicle.opportunity_id,
user_id: vehicle.user_id,
status: adminIdsInUsers.has(vehicle.get().opportunity_id) || false,
weekId: opportunity.week_id || null,
auctioneer_name: auctioneer.firstname || null,
selected_date: opportunity.date || null,
};
});
return res.json({
status: 200,
message: "Success",
data: formattedVehicles,
});
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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: ["firstname", "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 formattedResult = 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,
business_name: item.tblAuctioneer.business_name,
};
});
return res.json({
status: 200,
message: "Success",
filter_type: "auctioneer",
data: formattedResult,
});
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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, message: "Success", data: data });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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, message: "Success", data: data });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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, message: "Success", data: result });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: error.message,
});
}
};
const removeUserAuctioneer = async (req, res) => {
try {
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 },
],
},
});
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, message: "Success", data: result });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: 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 vehicleRunsResult = await db.tblVehicleRun.findAll({
attributes: ["vehicle_run_id"],
where: { opportunity_id: opportunityIds },
});
const vehicleRunIds = vehicleRunsResult.map(
(item) => item.vehicle_run_id
);
await db.tblVehicleRunFee.destroy({
where: {
vehicle_run_id: vehicleRunIds,
},
});
await db.tblVehicleRun.destroy({
where: { vehicle_run_id: vehicleRunIds },
});
const deleteResult = await db.tblOpportunity.destroy({
where: {
auctioneer_id: item,
week_id: weekId,
user_id: user_id,
},
});
return {
auctioneer_id: item,
deletedOpportunities: opportunityIds,
deleteResult,
};
});
const results = await Promise.all(deletePromises);
return res.json({ status: 200, message: "Success", data: results });
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: error.message,
});
}
};
//Hamza Ali
const exportByAuctioneer = async (req, res) => {
try {
let {
timeRange = "currentweek",
userId,
weekId,
sortBy,
orderDirection,
} = req.body;
const result = await db.tblOpportunity.findAll({
attributes: ["opportunity_id"],
where: {
week_id: weekId,
user_id: userId,
},
include: [
{
model: db.tblAuctioneer,
attributes: [
"auctioneer_id",
"firstname",
"lastname",
"business_name",
],
},
{
model: db.tblVehicleRun,
include: [
{
model: db.tblVehicle,
},
{
model: db.tblAuctionLane,
attributes: ["lane_id", "name"],
include: [
{
model: db.tblAuction,
attributes: ["auction_id", "name"],
},
],
},
],
},
],
});
// return res.json(result);
const formattedData = result.map((item) => ({
auctioneer_id: item.tblAuctioneer.auctioneer_id,
firstname: item.tblAuctioneer.firstname,
lastname: item.tblAuctioneer.lastname,
business_name: item.tblAuctioneer.business_name,
tblVehicles: item.tblVehicleRuns.map((vehicleRun) => {
const vehicle = vehicleRun.tblVehicle || {};
const auctionLane = vehicleRun.tblAuctionLane || {
lane_id: null,
name: null,
tblAuction: {
auction_id: null,
name: null,
},
};
const auction = auctionLane.tblAuction;
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 || null,
details: vehicle.details || null,
condition_light: vehicleRun.condition_light,
announcements: vehicleRun.announcements,
reserve: vehicleRun.reserve,
sale_price: vehicleRun.sale_price,
vehicle_total_fee: vehicleRun.vehicle_total_fee || null,
net_proceeds: vehicleRun.net_proceeds || null,
sale_status: vehicleRun.sale_status,
run_no: vehicleRun.run_no,
lane_id: auctionLane.lane_id,
lane_name: auctionLane.name,
auction_name: auction.name,
};
}),
}));
return res.json({
status: 200,
message: "Success",
filter_type: "auctioneer",
data: formattedData,
});
} catch (error) {
return res.status(500).json({
status: 500,
message: "Internal Server Error",
error: error.message,
});
}
};
module.exports = {
getUserProfile,
updateUserProfile,
updateUserPassword,
removeUser,
removeUserTest,
userAddedAuctioneerListById,
getAllAuctioneerList,
addUserAuctioneerToOpportunity,
getAllAssignedVehicles,
getAllVehiclesWithStatus,
getAllSubscribedAuctioneerList,
removeUserAuctioneer,
removeUserAuctioneerTesting,
exportByAuctioneer,
};
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists