File size: 11,169 Bytes
1d3aceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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' });
    }
};