Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"cloudinary": "^2.4.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"date-fns": "^4.1.0",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"express-session": "^1.18.1",
Expand Down
98 changes: 98 additions & 0 deletions src/controllers/admin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { Request, Response } from "express";
import Admin from "../../models/Admin";
import { decodeAdminToken, generateAdminToken } from "../../helpers/jwt";

export const registerAdmin = async (req: Request, res: Response) => {
const { email, password } = req.body;

try {
const existingAdmin = await Admin.findOne({ email });
if (existingAdmin) {
return res.status(400).json({ message: "Admin already exists." });
}

const newAdmin = await Admin.create({ email, password });
return res.status(201).json({ message: "Admin registered successfully.", admin: newAdmin });
} catch (error) {
return res.status(500).json({ message: "An error occurred.", error });
}
};

export const loginAdmin = async (req: Request, res: Response) => {
const { email, password } = req.body;

try {
const admin = await Admin.findOne({ email });
if (!admin) {
return res.status(404).json({ message: "Admin not found." });
}

const isPasswordMatch = admin.password === password
if (!isPasswordMatch) {
return res.status(401).json({ message: "Invalid credentials." });
}

const token = generateAdminToken(admin)
return res.status(200).json({ message: "Login successful.", token,admin });
} catch (error) {
return res.status(500).json({ message: "An error occurred.", error });
}
};

export const deactivateAdmin = async (req: Request, res: Response) => {
const { id } = req.params;
try {
const admin = await Admin.findByIdAndUpdate(id, { isActive: false }, { new: true });
if (!admin) {
return res.status(404).json({ message: "Admin not found." });
}

return res.status(200).json({ message: "Admin deactivated successfully.", admin });
} catch (error) {
return res.status(500).json({ message: "An error occurred.", error });
}
};

export const activateAdmin = async (req: Request, res: Response) => {
const { id } = req.params;

try {
const admin = await Admin.findByIdAndUpdate(id, { isActive: true }, { new: true });
if (!admin) {
return res.status(404).json({ message: "Admin not found." });
}

return res.status(200).json({ message: "Admin activated successfully.", admin });
} catch (error) {
return res.status(500).json({ message: "An error occurred.", error });
}
};

export const getAdminInfo = async (req: Request, res: Response) => {
const token = req.headers.authorization?.split(" ")[1];

if (!token) {
return res.status(401).json({ message: "Authorization token missing." });
}

try {
const admin = await decodeAdminToken(token)

if (!admin) {
return res.status(404).json({ message: "Admin not found." });
}

return res.status(200).json(admin);
} catch (error) {
return res.status(401).json({ message: "Invalid or expired token.", error });
}
};

export const getAlladmins = async (req: Request, res: Response) => {
try {
const admins = await Admin.find();
return res.status(200).json(admins);
} catch (error) {
return res.status(500).json({ message: "An error occurred while fetching admins.", error });
}
}
50 changes: 50 additions & 0 deletions src/controllers/statistics/restricted-countries-statistics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Request, Response } from "express";
import SanctionedGeoBoundary from "../../models/misc/SanctionedGeoBoundary";

export const getRestrictedAreaStats = async (req: Request, res: Response) => {
try {
const restrictedAreas = await SanctionedGeoBoundary.find()
return res.status(200).json({
restrictedAreas
});
} catch (error) {
return res.status(500).json({
success: false,
message: "Error fetching restricted areas",
error: error
});
}
}

export const createSanctionedRegion = async (req: Request, res: Response) => {
try {
const { geometry, properties } = req.body;

const newSanctionedRegion = await SanctionedGeoBoundary.create({
type: "Feature",
geometry: {
type: "Polygon",
coordinates: geometry.coordinates
},
properties: {
shapeName: properties.shapeName,
shapeISO: properties.shapeISO,
shapeID: properties.shapeID,
shapeGroup: properties.shapeGroup,
shapeType: properties.shapeType
}
});

return res.status(201).json({
success: true,
message: "Sanctioned region created successfully",
data: newSanctionedRegion
});
} catch (error) {
return res.status(500).json({
success: false,
message: "Error creating sanctioned region",
error: error
});
}
}
83 changes: 83 additions & 0 deletions src/controllers/statistics/review-statistics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Request, Response } from "express";
import ReviewFeedback from "../../models/ReviewFeedback";
import User from "../../models/User";

export const getReviewStatistics = async (req: Request, res: Response) => {
try {
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 20;

const skip = (page - 1) * limit;
const totalReviews = await ReviewFeedback.countDocuments();
const reviews = await ReviewFeedback.find()
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit);

const totalPages = Math.ceil(totalReviews / limit);
const hasNextPage = page < totalPages;
const hasPrevPage = page > 1;

const mappedReviews = await Promise.all(
reviews.map(async (review) => {
const reviewerUser = await User.findOne({ pi_uid: review.review_giver_id });
const sellerUser = await User.findOne({ pi_uid: review.review_receiver_id });

return {
id: review._id,
reviewer: reviewerUser?.pi_username ||review.review_giver_id,
seller: sellerUser?.pi_username || review.review_receiver_id ,
rating: review.rating,
comment: review.comment,
date: review.review_date.toISOString().split("T")[0],
};
})
);


const mostReviewedUser = await ReviewFeedback.aggregate([
{ $group: { _id: "$review_receiver_id", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 1 },
]);

const user = await User.findOne({
pi_uid: mostReviewedUser[0]?._id,
});


const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const startOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);

const currentMonthReviews = await ReviewFeedback.countDocuments({
review_date: { $gte: startOfMonth, $lt: startOfNextMonth },
});

const currentMonthReviewPercentage =
totalReviews > 0
? ((currentMonthReviews / totalReviews) * 100).toFixed(2)
: "0.00";

res.status(200).json({
reviews:mappedReviews,
totalReviews,
mostReviewedUser: {
user: user || null,
count: mostReviewedUser[0]?.count || 0,
},
currentMonthReviews,
currentMonthReviewPercentage: `${currentMonthReviewPercentage}`,
pagination: {
currentPage: page,
totalPages,
hasNextPage,
hasPrevPage,
totalReviews
},
});
} catch (error) {
res.status(500).json({ message: "Failed to fetch review statistics", error });
}
};

130 changes: 130 additions & 0 deletions src/controllers/statistics/seller-statistics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@


import { Request, Response } from "express";
import Seller from "../../models/Seller";
// import logger from "../../config/loggingConfig";

export const getSellerStatistics = async (req: Request, res: Response) => {
try {
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 15;

const skip = (page - 1) * limit;
const totalSellers = await Seller.countDocuments();
const sellers = await Seller.find()
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit);

const totalPages = Math.ceil(totalSellers / limit);
const hasNextPage = page < totalPages;
const hasPrevPage = page > 1;


const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);

const activeSellersCount = await Seller.countDocuments({ seller_type: "activeSeller" });
const inactiveSellers = await Seller.countDocuments({ seller_type: "inactiveSeller" });
const testSellers = await Seller.countDocuments({ seller_type: "testSeller" });

const sellerGrowthThisMonth = await Seller.aggregate([
{
$match: {
createdAt: { $gte: startOfMonth, $lte: endOfMonth },
},
},
{
$group: {
_id: "$seller_type",
count: { $sum: 1 },
},
},
]);

const sellerGrowthByTypeThisMonth = sellerGrowthThisMonth.reduce((acc, item) => {
acc[item._id] = item.count;
return acc;
}, {});

const newSellersThisMonth = sellerGrowthThisMonth.reduce((sum, item) => sum + item.count, 0);

const percentageGrowthThisMonth =
totalSellers > 0 ? (newSellersThisMonth / totalSellers) * 100 : 0;

const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];

const sellerGrowth = await Seller.aggregate([
{
$group: {
_id: { $month: "$createdAt" },
count: { $sum: 1 },
},
},
{ $sort: { "_id": 1 } },
]);

const data = sellerGrowth.map((growth) => {
return {
month: months[growth._id - 1],
count: growth.count,
};
});

const shopDetails = sellers.map(seller => ({
name: seller.name,
owner: seller.seller_id,
category: seller.seller_type,
rating: parseFloat(seller.average_rating.toString()),
status: seller.order_online_enabled_pref ? "Active" : "Inactive",
address: seller.address,
coordinates: seller.sell_map_center.coordinates,
}));


const statistics = {
totalSellers,
sellers:shopDetails,
activeSellers: activeSellersCount,
inactiveSellers,
testSellers,
newSellersThisMonth,
percentageGrowthThisMonth: percentageGrowthThisMonth.toFixed(2),
sellerGrowthByTypeThisMonth: {
activeSeller: sellerGrowthByTypeThisMonth["activeSeller"] || 0,
inactiveSeller: sellerGrowthByTypeThisMonth["inactiveSeller"] || 0,
testSeller: sellerGrowthByTypeThisMonth["testSeller"] || 0,
},
sellerGrowth: data,
pagination: {
currentPage: page,
totalPages,
hasNextPage,
hasPrevPage,
},
};

// logger.info("Fetched seller statistics for the current month successfully", statistics);

return res.status(200).json(statistics);
} catch (error) {
// logger.error("Failed to fetch seller statistics:", error);
return res
.status(500)
.json({ message: "An error occurred while fetching seller statistics; please try again later." });
}
};
Loading