-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
296 lines (255 loc) · 11.7 KB
/
server.js
File metadata and controls
296 lines (255 loc) · 11.7 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const express = require('express');
const cors = require('cors');
const crypto = require('crypto');
const app = express();
const port = process.env.PORT || 8080;
app.use(cors());
app.use(express.json());
// In-memory DB (replace with real DB later)
let users = [];
let complaints = [];
let messages = [];
let notifications = [];
// Helper
const genId = () => crypto.randomBytes(8).toString('hex');
const genToken = () => crypto.randomBytes(16).toString('hex');
// Health
app.get('/health', (req, res) => res.json({status: 'OK'}));
// Auth middleware
const auth = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
const user = users.find(u => u.token === token);
if (!user) return res.status(401).json({error: 'Unauthorized'});
req.user = user;
next();
};
// ==================== AUTH ====================
// Register
app.post('/api/register', (req, res) => {
const { name, phone, password, role } = req.body;
if (!name || !phone || !password) return res.status(400).json({error: 'Missing fields'});
if (users.find(u => u.phone === phone)) return res.status(400).json({error: 'Phone already registered'});
const user = { id: genId(), name, phone, password, role: role || 'customer', token: null, emoCoins: 0, createdAt: new Date() };
users.push(user);
res.json({success: true, message: 'Registered successfully'});
});
// Login
app.post('/api/login', (req, res) => {
const { phone, password } = req.body;
const user = users.find(u => u.phone === phone && u.password === password);
if (!user) return res.status(401).json({error: 'Invalid credentials'});
user.token = genToken();
res.json({success: true, token: user.token, role: user.role, name: user.name, id: user.id});
});
// Profile
app.get('/api/user/profile', auth, (req, res) => {
const { password, token, ...safe } = req.user;
res.json(safe);
});
// ==================== COMPLAINTS ====================
// Register complaint
app.post('/api/complaints', auth, (req, res) => {
const { deviceName, imei, natureOfComplaint, bodyCondition, pickupAddress, location } = req.body;
if (!deviceName || !pickupAddress) return res.status(400).json({error: 'Missing fields'});
const complaint = {
id: genId(),
customerId: req.user.id,
customerName: req.user.name,
customerPhone: req.user.phone,
deviceName, imei, natureOfComplaint, bodyCondition, pickupAddress, location,
status: 'Registered',
deliveryBoyId: null,
serviceCentreId: null,
timeline: [{status: 'Complaint Registered', time: new Date()}],
images: { pickup: [], dropoff: [], received: [], returned: [] },
amount: null,
paymentMethod: null,
paymentDone: false,
createdAt: new Date()
};
complaints.push(complaint);
// Notify supervisors
users.filter(u => u.role === 'supervisor').forEach(sup => {
notifications.push({id: genId(), userId: sup.id, message: `New complaint from ${req.user.name}`, complaintId: complaint.id, read: false, time: new Date()});
});
res.json({success: true, complaint});
});
// Get my complaints (customer)
app.get('/api/complaints/my', auth, (req, res) => {
const myComplaints = complaints.filter(c => c.customerId === req.user.id);
res.json(myComplaints);
});
// Get all complaints (supervisor/admin)
app.get('/api/complaints', auth, (req, res) => {
if (!['supervisor','superadmin'].includes(req.user.role)) return res.status(403).json({error: 'Forbidden'});
res.json(complaints);
});
// Get complaints by status
app.get('/api/complaints/status/:status', auth, (req, res) => {
const filtered = complaints.filter(c => c.status === req.params.status);
res.json(filtered);
});
// Assign delivery boy + service centre (supervisor)
app.post('/api/complaints/:id/assign', auth, (req, res) => {
if (!['supervisor','superadmin'].includes(req.user.role)) return res.status(403).json({error: 'Forbidden'});
const complaint = complaints.find(c => c.id === req.params.id);
if (!complaint) return res.status(404).json({error: 'Not found'});
const { deliveryBoyId, serviceCentreId } = req.body;
complaint.deliveryBoyId = deliveryBoyId;
complaint.serviceCentreId = serviceCentreId;
complaint.status = 'Assigned';
complaint.timeline.push({status: 'Agent Assigned for Pickup', time: new Date()});
// Notify delivery boy
notifications.push({id: genId(), userId: deliveryBoyId, message: `New pickup assigned`, complaintId: complaint.id, read: false, time: new Date()});
// Notify customer
notifications.push({id: genId(), userId: complaint.customerId, message: `Agent assigned for your complaint`, complaintId: complaint.id, read: false, time: new Date()});
res.json({success: true, complaint});
});
// Update complaint status
app.post('/api/complaints/:id/status', auth, (req, res) => {
const complaint = complaints.find(c => c.id === req.params.id);
if (!complaint) return res.status(404).json({error: 'Not found'});
const { status, images } = req.body;
complaint.status = status;
complaint.timeline.push({status, time: new Date()});
if (images) Object.assign(complaint.images, images);
// Notify customer
notifications.push({id: genId(), userId: complaint.customerId, message: `Your complaint status: ${status}`, complaintId: complaint.id, read: false, time: new Date()});
res.json({success: true, complaint});
});
// Set repair amount
app.post('/api/complaints/:id/amount', auth, (req, res) => {
const complaint = complaints.find(c => c.id === req.params.id);
if (!complaint) return res.status(404).json({error: 'Not found'});
const { amount, quality } = req.body;
complaint.amount = amount;
complaint.quality = quality;
complaint.timeline.push({status: `Quote sent: AED ${amount}`, time: new Date()});
notifications.push({id: genId(), userId: complaint.customerId, message: `Repair quote: AED ${amount}`, complaintId: complaint.id, read: false, time: new Date()});
res.json({success: true});
});
// Accept/reject amount (customer)
app.post('/api/complaints/:id/accept', auth, (req, res) => {
const complaint = complaints.find(c => c.id === req.params.id);
if (!complaint) return res.status(404).json({error: 'Not found'});
const { accepted } = req.body;
if (accepted) {
complaint.status = 'Repair Started';
complaint.timeline.push({status: 'Customer Accepted Quote - Repair Started', time: new Date()});
} else {
complaint.status = 'Quote Rejected';
complaint.timeline.push({status: 'Customer Rejected Quote', time: new Date()});
}
res.json({success: true});
});
// Payment
app.post('/api/complaints/:id/payment', auth, (req, res) => {
const complaint = complaints.find(c => c.id === req.params.id);
if (!complaint) return res.status(404).json({error: 'Not found'});
const { method } = req.body;
complaint.paymentMethod = method;
complaint.paymentDone = true;
complaint.status = 'Payment Done';
complaint.timeline.push({status: `Payment received - ${method}`, time: new Date()});
// EmoCoins for customer
const customer = users.find(u => u.id === complaint.customerId);
if (customer) customer.emoCoins += 10;
res.json({success: true});
});
// ==================== DELIVERY BOY ====================
// Get my assigned complaints
app.get('/api/delivery/complaints', auth, (req, res) => {
if (req.user.role !== 'delivery') return res.status(403).json({error: 'Forbidden'});
const myJobs = complaints.filter(c => c.deliveryBoyId === req.user.id);
res.json(myJobs);
});
// ==================== SERVICE CENTRE ====================
// Get my assigned complaints
app.get('/api/service/complaints', auth, (req, res) => {
if (req.user.role !== 'service') return res.status(403).json({error: 'Forbidden'});
const myJobs = complaints.filter(c => c.serviceCentreId === req.user.id);
res.json(myJobs);
});
// ==================== CHAT ====================
// Send message
app.post('/api/chat', auth, (req, res) => {
const { complaintId, to, message } = req.body;
const msg = {id: genId(), complaintId, from: req.user.id, fromName: req.user.name, fromRole: req.user.role, to, message, time: new Date()};
messages.push(msg);
notifications.push({id: genId(), userId: to, message: `New message from ${req.user.name}`, complaintId, read: false, time: new Date()});
res.json({success: true, msg});
});
// Get messages for complaint
app.get('/api/chat/:complaintId', auth, (req, res) => {
const msgs = messages.filter(m => m.complaintId === req.params.complaintId);
res.json(msgs);
});
// ==================== NOTIFICATIONS ====================
app.get('/api/notifications', auth, (req, res) => {
const myNotifs = notifications.filter(n => n.userId === req.user.id);
res.json(myNotifs);
});
app.post('/api/notifications/read', auth, (req, res) => {
notifications.filter(n => n.userId === req.user.id).forEach(n => n.read = true);
res.json({success: true});
});
// ==================== SUPER ADMIN ====================
// Create staff profile
app.post('/api/admin/create', auth, (req, res) => {
if (req.user.role !== 'superadmin') return res.status(403).json({error: 'Forbidden'});
const { name, phone, email, role, location } = req.body;
if (users.find(u => u.phone === phone)) return res.status(400).json({error: 'Already exists'});
const tempPassword = genId().slice(0,8);
const user = {id: genId(), name, phone, email, password: tempPassword, role, location, token: null, emoCoins: 0, createdAt: new Date()};
users.push(user);
res.json({success: true, tempPassword, user: {id: user.id, name, phone, email, role}});
});
// Get all staff
app.get('/api/admin/staff', auth, (req, res) => {
if (!['supervisor','superadmin'].includes(req.user.role)) return res.status(403).json({error: 'Forbidden'});
const staff = users.filter(u => u.role !== 'customer').map(({password, token, ...s}) => s);
res.json(staff);
});
// Get delivery boys list
app.get('/api/admin/delivery', auth, (req, res) => {
if (!['supervisor','superadmin'].includes(req.user.role)) return res.status(403).json({error: 'Forbidden'});
const delivery = users.filter(u => u.role === 'delivery').map(({password, token, ...s}) => s);
res.json(delivery);
});
// Get service centres list
app.get('/api/admin/service', auth, (req, res) => {
if (!['supervisor','superadmin'].includes(req.user.role)) return res.status(403).json({error: 'Forbidden'});
const service = users.filter(u => u.role === 'service').map(({password, token, ...s}) => s);
res.json(service);
});
// ==================== EMOCOIN ====================
app.get('/api/emocoin/balance', auth, (req, res) => {
res.json({balance: req.user.emoCoins || 0});
});
app.post('/api/emocoin/daily', auth, (req, res) => {
req.user.emoCoins = (req.user.emoCoins || 0) + 2;
res.json({success: true, balance: req.user.emoCoins});
});
// ==================== EMOWALL AI ====================
app.post('/api/ai/chat', auth, async (req, res) => {
const { message } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) return res.json({reply: 'AI not configured'});
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
contents: [{parts: [{text: `You are Emowall AI assistant for Emobies mobile repair service. Help with repair queries and crypto/TheWall wallet questions. User: ${message}`}]}]
})
});
const data = await response.json();
const reply = data.candidates?.[0]?.content?.parts?.[0]?.text || 'Sorry, try again';
res.json({reply});
} catch(e) {
res.json({reply: 'AI error, try again'});
}
});
// Seed super admin
users.push({id: genId(), name: 'Divin K.K.', phone: '9847842172', password: 'Emobies@2026!', role: 'superadmin', token: null, emoCoins: 0, createdAt: new Date()});
app.listen(port, () => console.log('Emobies live on', port));