tenderizer / src /controllers /adminController.js
ismizo's picture
Upload 28 files
0ba1efd verified
Raw History Blame Contribute Delete
11.2 kB
import User from '../models/User.js';
import ActivityLog from '../models/ActivityLog.js';
import Tender from '../models/Tender.js';
import Transaction from '../models/Transaction.js';
// @desc Get all users (paginated)
// @route GET /api/admin/users
export const getAllUsers = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const skip = (page - 1) * limit;
const search = req.query.search || '';
const query = search
? { email: { $regex: search, $options: 'i' } }
: {};
const [users, total] = await Promise.all([
User.find(query)
.select('-loginCode -loginCodeExpires')
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit),
User.countDocuments(query)
]);
// Enrich with tender/transaction counts
const enriched = await Promise.all(users.map(async (user) => {
const [tenderCount, txCount] = await Promise.all([
Tender.countDocuments({ user: user._id }),
Transaction.countDocuments({ user: user._id, status: { $in: ['completed', 'SUCCESS', 'SETTLED'] } })
]);
return {
...user.toObject(),
tenderCount,
successfulPayments: txCount
};
}));
res.json({
users: enriched,
total,
page,
pages: Math.ceil(total / limit)
});
} catch (error) {
console.error("Admin Get Users Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Get activity logs (paginated, filterable)
// @route GET /api/admin/logs
export const getActivityLogs = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 50;
const skip = (page - 1) * limit;
const action = req.query.action || '';
const email = req.query.email || '';
const query = {};
if (action) query.action = action;
if (email) query.userEmail = { $regex: email, $options: 'i' };
const [logs, total] = await Promise.all([
ActivityLog.find(query)
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit),
ActivityLog.countDocuments(query)
]);
res.json({
logs,
total,
page,
pages: Math.ceil(total / limit)
});
} catch (error) {
console.error("Admin Get Logs Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Get dashboard stats
// @route GET /api/admin/stats
export const getStats = async (req, res) => {
try {
const [
totalUsers,
bannedUsers,
totalTenders,
completedTenders,
totalTransactions,
successfulTransactions,
recentLogs
] = await Promise.all([
User.countDocuments(),
User.countDocuments({ isBanned: true }),
Tender.countDocuments(),
Tender.countDocuments({ status: 'completed' }),
Transaction.countDocuments(),
Transaction.countDocuments({ status: { $in: ['completed', 'SUCCESS', 'SETTLED'] } }),
ActivityLog.find().sort({ createdAt: -1 }).limit(10)
]);
// Revenue: sum of completed transactions
const revenueResult = await Transaction.aggregate([
{ $match: { status: { $in: ['completed', 'SUCCESS', 'SETTLED'] } } },
{ $group: { _id: null, total: { $sum: '$amount' } } }
]);
const totalRevenueTZS = revenueResult.length > 0 ? revenueResult[0].total : 0;
// New users in last 7 days
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const newUsersThisWeek = await User.countDocuments({ createdAt: { $gte: sevenDaysAgo } });
res.json({
totalUsers,
bannedUsers,
newUsersThisWeek,
totalTenders,
completedTenders,
totalTransactions,
successfulTransactions,
totalRevenueTZS,
recentLogs
});
} catch (error) {
console.error("Admin Stats Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Ban a user
// @route POST /api/admin/users/:id/ban
export const banUser = async (req, res) => {
try {
const { reason } = req.body;
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
if (user.isAdmin) return res.status(403).json({ message: 'Cannot ban an admin user' });
user.isBanned = true;
user.banReason = reason || 'Violated terms of service';
await user.save();
await ActivityLog.create({
user: req.user._id,
userEmail: req.user.email,
action: 'USER_LOGIN', // reuse existing enum - we log the ban action
details: {
action: 'BAN_USER',
bannedUserId: user._id,
bannedUserEmail: user.email,
reason: user.banReason
}
});
res.json({ message: `User ${user.email} has been banned`, user });
} catch (error) {
console.error("Ban User Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Unban a user
// @route POST /api/admin/users/:id/unban
export const unbanUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
user.isBanned = false;
user.banReason = null;
await user.save();
res.json({ message: `User ${user.email} has been unbanned`, user });
} catch (error) {
console.error("Unban User Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Manually adjust a user's credits
// @route POST /api/admin/users/:id/credits
export const adjustCredits = async (req, res) => {
try {
const { credits, reason } = req.body;
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
const oldCredits = user.credits;
user.credits = Math.max(0, user.credits + parseInt(credits));
await user.save();
await ActivityLog.create({
user: req.user._id,
userEmail: req.user.email,
action: 'WELCOME_CREDITS_GRANTED',
details: {
action: 'ADMIN_CREDIT_ADJUSTMENT',
targetUserId: user._id,
targetUserEmail: user.email,
creditsBefore: oldCredits,
creditsAfter: user.credits,
adjustment: parseInt(credits),
reason: reason || 'Manual admin adjustment'
}
});
res.json({ message: `Credits adjusted for ${user.email}`, newCredits: user.credits });
} catch (error) {
console.error("Adjust Credits Error:", error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Get pending M-Pesa manual payments (for admin review)
// @route GET /api/admin/mpesa-payments
export const getPendingMpesa = async (req, res) => {
try {
const status = req.query.status || 'pending_review';
const transactions = await Transaction
.find({ paymentMethod: 'mpesa_manual', status })
.populate('user', 'email credits')
.sort({ createdAt: -1 })
.limit(100);
res.json(transactions);
} catch (error) {
console.error('getPendingMpesa Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Approve a manual M-Pesa payment and grant credits
// @route POST /api/admin/mpesa-payments/:id/approve
export const approveMpesaPayment = async (req, res) => {
try {
const { note } = req.body;
const transaction = await Transaction.findById(req.params.id).populate('user', 'email credits');
if (!transaction) return res.status(404).json({ message: 'Transaction not found' });
if (transaction.status !== 'pending_review') {
return res.status(400).json({ message: `Transaction is already ${transaction.status}` });
}
transaction.status = 'completed';
transaction.reviewNote = note || 'Approved by admin';
transaction.reviewedBy = req.user.email;
transaction.reviewedAt = new Date();
await transaction.save();
const user = await User.findById(transaction.user._id || transaction.user);
if (user) {
user.credits += transaction.creditsPurchased;
await user.save();
}
await ActivityLog.create({
user: req.user._id,
userEmail: req.user.email,
action: 'PAYMENT_SUCCESS',
details: {
action: 'MPESA_APPROVED',
transactionId: transaction._id,
reference: transaction.reference,
amount: transaction.amount,
credits: transaction.creditsPurchased,
targetUser: user?.email,
note
}
});
res.json({ message: `Approved. ${transaction.creditsPurchased} credits added to ${user?.email}`, transaction });
} catch (error) {
console.error('approveMpesaPayment Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};
// @desc Reject a manual M-Pesa payment
// @route POST /api/admin/mpesa-payments/:id/reject
export const rejectMpesaPayment = async (req, res) => {
try {
const { note } = req.body;
const transaction = await Transaction.findById(req.params.id);
if (!transaction) return res.status(404).json({ message: 'Transaction not found' });
if (transaction.status !== 'pending_review') {
return res.status(400).json({ message: `Transaction is already ${transaction.status}` });
}
transaction.status = 'rejected';
transaction.reviewNote = note || 'Rejected by admin';
transaction.reviewedBy = req.user.email;
transaction.reviewedAt = new Date();
await transaction.save();
await ActivityLog.create({
user: req.user._id,
userEmail: req.user.email,
action: 'PAYMENT_FAILED',
details: { action: 'MPESA_REJECTED', transactionId: transaction._id, reference: transaction.reference, note }
});
res.json({ message: 'Payment rejected', transaction });
} catch (error) {
console.error('rejectMpesaPayment Error:', error);
res.status(500).json({ message: 'Server Error' });
}
};