Skip to content

ft-Add Report API for User and Seller Statistics #221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
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
14 changes: 12 additions & 2 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion 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.2",
"jsonwebtoken": "^9.0.2",
Expand Down Expand Up @@ -56,4 +57,4 @@
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
}
}
}
89 changes: 89 additions & 0 deletions src/controllers/admin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
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 });
}
};
44 changes: 44 additions & 0 deletions src/controllers/statistics/restricted-countries-statistics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Request, Response } from "express";
import SanctionedRegion from "../../models/misc/SanctionedRegion";


export const getRestrictedAreaStats = async (req: Request, res: Response) => {
try {
const restrictedAreas = await SanctionedRegion.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 { location, boundary } = req.body;

const newSanctionedRegion = await SanctionedRegion.create({
location,
boundary: {
type: "Polygon",
coordinates: boundary
}
});

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 });
}
};

Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.