-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadminController.js
More file actions
278 lines (228 loc) · 7.66 KB
/
adminController.js
File metadata and controls
278 lines (228 loc) · 7.66 KB
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
const User = require("./../models/userModel");
const Order = require("./../models/orderModel");
const Product = require("./../models/productModel"); // ✅ Add this import
// @route GET /api/admin/users
// @desc Get All Users (Admin Only)
exports.getAllUsers = async (req, res) => {
try {
const users = await User.find({}).select('-password');
res.json({
success: true,
users
});
} catch (error) {
console.error('Get users error:', error);
res.status(500).json({ success: false, message: "Server Error" });
}
};
// @route POST /api/admin/users
// @desc Create New User (Admin Only)
exports.addUser = async (req, res) => {
try {
const { name, email, password, role } = req.body;
console.log('📥 Creating user:', { name, email, role });
// Validation
if (!name || !email || !password) {
return res.status(400).json({
success: false,
message: "Please provide name, email, and password"
});
}
// Check if user already exists
const existingUser = await User.findOne({ email: email.toLowerCase() });
if (existingUser) {
return res.status(400).json({
success: false,
message: "User with this email already exists"
});
}
// Create new user (password will be hashed by pre-save hook in model)
const user = await User.create({
name,
email: email.toLowerCase(),
password,
role: role || "customer",
});
console.log('✅ User created:', user._id);
res.status(201).json({
success: true,
message: "User created successfully!",
user: {
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
createdAt: user.createdAt,
}
});
} catch (error) {
console.error('❌ Create user error:', error);
if (error.code === 11000) {
return res.status(400).json({
success: false,
message: "User with this email already exists"
});
}
res.status(500).json({ success: false, message: error.message || "Server Error" });
}
};
// @route PUT /api/admin/users/:id
// @desc Update User Role (Admin Only)
exports.updateUserRole = async (req, res) => {
try {
const { id } = req.params;
const { role, name, email } = req.body;
console.log('📥 Updating user:', id, { role, name, email });
const user = await User.findById(id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found"
});
}
// Update fields
if (name) user.name = name;
if (email) user.email = email;
if (role) user.role = role;
await user.save();
console.log('✅ User updated:', user._id);
res.status(200).json({
success: true,
message: "User updated successfully",
user: {
_id: user._id,
name: user.name,
email: user.email,
role: user.role,
}
});
} catch (error) {
console.error('❌ Update user error:', error);
res.status(500).json({ success: false, message: error.message || "Server Error" });
}
};
// @route DELETE /api/admin/users/:id
// @desc Delete User (Admin Only)
exports.deleteUser = async (req, res) => {
try {
const { id } = req.params;
console.log('📥 Deleting user:', id);
const user = await User.findById(id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found"
});
}
await User.findByIdAndDelete(id);
console.log('✅ User deleted:', id);
res.status(200).json({
success: true,
message: "User deleted successfully",
userId: id
});
} catch (error) {
console.error('❌ Delete user error:', error);
res.status(500).json({ success: false, message: error.message || "Server Error" });
}
};
// @route PUT /api/admin/orders/:id
// @desc Update Order Status (Admin Only)
exports.updateOrderStatus = async (req, res) => {
try {
const { id } = req.params;
const { status } = req.body;
console.log('📥 Updating order:', id, 'Status:', status);
const order = await Order.findById(id);
if (!order) {
return res.status(404).json({
success: false,
message: "Order not found"
});
}
// Update status
order.status = status;
// If delivered, set deliveredAt
if (status === 'Delivered') {
order.isDelivered = true;
order.deliveredAt = Date.now();
}
await order.save();
// ✅ Fetch the updated order WITH user populated
const updatedOrder = await Order.findById(id).populate('user', 'name email');
console.log('✅ Order updated:', updatedOrder._id);
res.status(200).json({
success: true,
message: "Order status updated",
order: updatedOrder
});
} catch (error) {
console.error('❌ Update order error:', error);
res.status(500).json({
success: false,
message: error.message || "Server Error"
});
}
};
// ✅ ADD THIS - Delete Product (Admin Only)
// @route DELETE /api/admin/products/:id
// @desc Delete Product (Admin Only)
exports.deleteProduct = async (req, res) => {
try {
const { id } = req.params;
console.log('🗑️ Deleting product:', id);
const product = await Product.findById(id);
if (!product) {
return res.status(404).json({
success: false,
message: "Product not found"
});
}
await Product.findByIdAndDelete(id);
console.log('✅ Product deleted:', id);
res.status(200).json({
success: true,
message: "Product deleted successfully",
productId: id
});
} catch (error) {
console.error('❌ Delete product error:', error);
res.status(500).json({
success: false,
message: error.message || "Server Error"
});
}
};
// @route PUT /api/admin/products/:id
// @desc Update Product (Admin Only)
exports.updateProduct = async (req, res) => {
try {
const { id } = req.params;
const updateData = req.body;
console.log('📥 Updating product:', id);
const product = await Product.findById(id);
if (!product) {
return res.status(404).json({
success: false,
message: "Product not found"
});
}
// Update fields
Object.keys(updateData).forEach(key => {
product[key] = updateData[key];
});
const updatedProduct = await product.save();
console.log('✅ Product updated:', updatedProduct._id);
res.status(200).json({
success: true,
message: "Product updated successfully",
product: updatedProduct
});
} catch (error) {
console.error('❌ Update product error:', error);
res.status(500).json({
success: false,
message: error.message || "Server Error"
});
}
};