-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
676 lines (572 loc) · 21.3 KB
/
Copy pathserver.js
File metadata and controls
676 lines (572 loc) · 21.3 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const app = express();
const PORT = 3000;
// CORS тохиргоо - Live Server-тэй ажиллана
app.use(cors({
origin: '*', // Бүх domain-ээс зөвшөөрнө
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type']
}));
app.use(express.json());
// Serve static files (HTML, CSS, JS, images, fonts)
app.use(express.static(__dirname));
// Root route - serve index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// JSON файлуудын зам
const DATA_DIR = path.join(__dirname, 'data');
const FILES = {
USERS: path.join(DATA_DIR, 'users.json'),
PRODUCTS: path.join(DATA_DIR, 'products.json'),
CARTS: path.join(DATA_DIR, 'carts.json'),
ORDERS: path.join(DATA_DIR, 'orders.json')
};
// Ensure data directory exists
async function ensureDataDir() {
try {
await fs.mkdir(DATA_DIR, { recursive: true });
} catch (error) {
console.error('Error creating data directory:', error);
}
}
// Password хашлах
function hashPassword(password) {
return crypto.createHash('sha256').update(password).digest('hex');
}
// Generic file read function
async function readFile(filepath, defaultValue = []) {
try {
const data = await fs.readFile(filepath, 'utf8');
return JSON.parse(data);
} catch (error) {
return defaultValue;
}
}
// Generic file write function
async function writeFile(filepath, data) {
await fs.writeFile(filepath, JSON.stringify(data, null, 2));
}
// Initialize default data
async function initializeData() {
const defaultProducts = [
{
id: '1',
name: 'Surron Light Bee X Controller',
category: 'Electronics',
price: 899.99,
stock: 15,
image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=500',
description: 'High-performance controller for Surron Light Bee X. Advanced motor control with regenerative braking.'
},
{
id: '2',
name: 'Premium Battery Pack 60V',
category: 'Battery',
price: 1299.99,
stock: 8,
image: 'https://images.unsplash.com/photo-1609976699759-45cf02366b23?w=500',
description: '60V 32Ah Lithium-ion battery pack. Extended range up to 60 miles per charge.'
},
{
id: '3',
name: 'Front Suspension Fork',
category: 'Suspension',
price: 549.99,
stock: 12,
image: 'https://images.unsplash.com/photo-1532298229144-0ec0c57515c7?w=500',
description: 'DNM USD-8 inverted front fork. 43mm stanchions with adjustable compression and rebound.'
},
{
id: '4',
name: 'Rear Shock Absorber',
category: 'Suspension',
price: 399.99,
stock: 10,
image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=500',
description: 'DNM AO-38RC rear shock. 190mm eye-to-eye with lockout feature.'
},
{
id: '5',
name: 'Hydraulic Brake Set',
category: 'Brakes',
price: 279.99,
stock: 20,
image: 'https://images.unsplash.com/photo-1486262715619-67b85e0b08d3?w=500',
description: 'Front and rear hydraulic disc brakes. 180mm rotors with 4-piston calipers.'
},
{
id: '6',
name: 'Performance Tires Set',
category: 'Wheels',
price: 189.99,
stock: 25,
image: 'https://images.unsplash.com/photo-1624379329795-89eac93ecd3f?w=500',
description: 'Aggressive tread pattern tires. Excellent grip for off-road and street riding.'
},
{
id: '7',
name: 'LED Headlight Kit',
category: 'Accessories',
price: 129.99,
stock: 30,
image: 'https://images.unsplash.com/photo-1542838309-ab4f5d3c2a18?w=500',
description: 'Ultra-bright LED headlight with high and low beam. 2000 lumens output.'
},
{
id: '8',
name: 'Custom Seat',
category: 'Accessories',
price: 149.99,
stock: 18,
image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=500',
description: 'Ergonomic custom seat with enhanced padding. Weather-resistant material.'
}
];
const defaultUsers = [
{
id: '1',
username: 'gank',
email: 'gank@surron.mn',
password: hashPassword('Gank2024!'),
role: 'admin',
createdAt: new Date().toISOString()
}
];
const products = await readFile(FILES.PRODUCTS);
if (products.length === 0) {
await writeFile(FILES.PRODUCTS, defaultProducts);
console.log('✅ Default бүтээгдэхүүнүүд нэмэгдлээ');
}
const users = await readFile(FILES.USERS);
if (users.length === 0) {
await writeFile(FILES.USERS, defaultUsers);
console.log('✅ Default admin: gank / Gank2024!');
}
await readFile(FILES.CARTS);
await readFile(FILES.ORDERS);
}
// ==================== AUTH ====================
app.post('/api/auth/register', async (req, res) => {
try {
const { username, email, password } = req.body;
if (!username || !email || !password) {
return res.status(400).json({
success: false,
message: 'Бүх талбарыг бөглөнө үү'
});
}
const users = await readFile(FILES.USERS);
const exists = users.find(u => u.username === username || u.email === email);
if (exists) {
return res.status(400).json({
success: false,
message: 'Хэрэглэгч аль хэдийн бүртгэлтэй байна'
});
}
const newUser = {
id: Date.now().toString(),
username,
email,
password: hashPassword(password),
role: 'user',
createdAt: new Date().toISOString()
};
users.push(newUser);
await writeFile(FILES.USERS, users);
const { password: _, ...userWithoutPassword } = newUser;
res.status(201).json({
success: true,
message: 'Амжилттай бүртгэгдлээ',
data: { user: userWithoutPassword }
});
} catch (error) {
console.error('Register error:', error);
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({
success: false,
message: 'Нэр болон нууц үг оруулна уу'
});
}
const users = await readFile(FILES.USERS);
const user = users.find(u => u.username === username && u.password === hashPassword(password));
if (!user) {
return res.status(401).json({
success: false,
message: 'Нэр эсвэл нууц үг буруу байна'
});
}
const { password: _, ...userWithoutPassword } = user;
res.json({
success: true,
message: 'Амжилттай нэвтэрлээ',
data: { user: userWithoutPassword }
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
// ==================== PRODUCTS ====================
app.get('/api/products', async (req, res) => {
try {
const { category, search } = req.query;
let products = await readFile(FILES.PRODUCTS);
if (category && category !== 'All') {
products = products.filter(p => p.category === category);
}
if (search) {
const searchLower = search.toLowerCase();
products = products.filter(p =>
p.name.toLowerCase().includes(searchLower) ||
p.description.toLowerCase().includes(searchLower)
);
}
res.json({
success: true,
count: products.length,
data: products
});
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.get('/api/products/:id', async (req, res) => {
try {
const products = await readFile(FILES.PRODUCTS);
const product = products.find(p => p.id === req.params.id);
if (!product) {
return res.status(404).json({ success: false, message: 'Бүтээгдэхүүн олдсонгүй' });
}
res.json({ success: true, data: product });
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.post('/api/products', async (req, res) => {
try {
const products = await readFile(FILES.PRODUCTS);
const newProduct = {
id: Date.now().toString(),
...req.body,
createdAt: new Date().toISOString()
};
products.push(newProduct);
await writeFile(FILES.PRODUCTS, products);
res.status(201).json({
success: true,
message: 'Бүтээгдэхүүн амжилттай нэмэгдлээ',
data: newProduct
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.put('/api/products/:id', async (req, res) => {
try {
const products = await readFile(FILES.PRODUCTS);
const index = products.findIndex(p => p.id === req.params.id);
if (index === -1) {
return res.status(404).json({ success: false, message: 'Бүтээгдэхүүн олдсонгүй' });
}
products[index] = {
...products[index],
...req.body,
id: req.params.id,
updatedAt: new Date().toISOString()
};
await writeFile(FILES.PRODUCTS, products);
res.json({
success: true,
message: 'Бүтээгдэхүүн амжилттай шинэчлэгдлээ',
data: products[index]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.delete('/api/products/:id', async (req, res) => {
try {
let products = await readFile(FILES.PRODUCTS);
const initialLength = products.length;
products = products.filter(p => p.id !== req.params.id);
if (products.length === initialLength) {
return res.status(404).json({ success: false, message: 'Бүтээгдэхүүн олдсонгүй' });
}
await writeFile(FILES.PRODUCTS, products);
res.json({
success: true,
message: 'Бүтээгдэхүүн амжилттай устгагдлаа'
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
// ==================== CART ====================
app.get('/api/cart/:userId', async (req, res) => {
try {
const carts = await readFile(FILES.CARTS);
const cart = carts.find(c => c.userId === req.params.userId);
res.json({
success: true,
data: cart || { userId: req.params.userId, items: [] }
});
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.post('/api/cart/:userId/add', async (req, res) => {
try {
const { productId, quantity = 1 } = req.body;
const carts = await readFile(FILES.CARTS);
const products = await readFile(FILES.PRODUCTS);
const product = products.find(p => p.id === productId);
if (!product) {
return res.status(404).json({ success: false, message: 'Бүтээгдэхүүн олдсонгүй' });
}
let cartIndex = carts.findIndex(c => c.userId === req.params.userId);
if (cartIndex === -1) {
carts.push({
userId: req.params.userId,
items: [],
updatedAt: new Date().toISOString()
});
cartIndex = carts.length - 1;
}
const itemIndex = carts[cartIndex].items.findIndex(i => i.productId === productId);
if (itemIndex > -1) {
carts[cartIndex].items[itemIndex].quantity += quantity;
} else {
carts[cartIndex].items.push({
productId,
quantity,
addedAt: new Date().toISOString()
});
}
carts[cartIndex].updatedAt = new Date().toISOString();
await writeFile(FILES.CARTS, carts);
res.json({
success: true,
message: 'Сагсанд нэмэгдлээ',
data: carts[cartIndex]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.put('/api/cart/:userId/update', async (req, res) => {
try {
const { productId, quantity } = req.body;
const carts = await readFile(FILES.CARTS);
const cartIndex = carts.findIndex(c => c.userId === req.params.userId);
if (cartIndex === -1) {
return res.status(404).json({ success: false, message: 'Сагс олдсонгүй' });
}
const itemIndex = carts[cartIndex].items.findIndex(i => i.productId === productId);
if (itemIndex === -1) {
return res.status(404).json({ success: false, message: 'Бүтээгдэхүүн сагсанд байхгүй' });
}
if (quantity <= 0) {
carts[cartIndex].items.splice(itemIndex, 1);
} else {
carts[cartIndex].items[itemIndex].quantity = quantity;
}
carts[cartIndex].updatedAt = new Date().toISOString();
await writeFile(FILES.CARTS, carts);
res.json({
success: true,
message: 'Сагс шинэчлэгдлээ',
data: carts[cartIndex]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.delete('/api/cart/:userId/remove/:productId', async (req, res) => {
try {
const carts = await readFile(FILES.CARTS);
const cartIndex = carts.findIndex(c => c.userId === req.params.userId);
if (cartIndex === -1) {
return res.status(404).json({ success: false, message: 'Сагс олдсонгүй' });
}
carts[cartIndex].items = carts[cartIndex].items.filter(i => i.productId !== req.params.productId);
carts[cartIndex].updatedAt = new Date().toISOString();
await writeFile(FILES.CARTS, carts);
res.json({
success: true,
message: 'Бүтээгдэхүүн хасагдлаа',
data: carts[cartIndex]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.delete('/api/cart/:userId/clear', async (req, res) => {
try {
const carts = await readFile(FILES.CARTS);
const cartIndex = carts.findIndex(c => c.userId === req.params.userId);
if (cartIndex === -1) {
return res.status(404).json({ success: false, message: 'Сагс олдсонгүй' });
}
carts[cartIndex].items = [];
carts[cartIndex].updatedAt = new Date().toISOString();
await writeFile(FILES.CARTS, carts);
res.json({
success: true,
message: 'Сагс хоосон болгогдлоо',
data: carts[cartIndex]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
// ==================== ORDERS ====================
app.post('/api/orders', async (req, res) => {
try {
const { userId, items, totalAmount, shippingAddress } = req.body;
const orders = await readFile(FILES.ORDERS);
const products = await readFile(FILES.PRODUCTS);
for (const item of items) {
const product = products.find(p => p.id === item.productId);
if (!product || product.stock < item.quantity) {
return res.status(400).json({
success: false,
message: `${item.name || 'Бүтээгдэхүүн'} хангалттай нөөцгүй`
});
}
product.stock -= item.quantity;
}
await writeFile(FILES.PRODUCTS, products);
const newOrder = {
id: Date.now().toString(),
userId,
items,
totalAmount,
shippingAddress,
status: 'pending',
createdAt: new Date().toISOString()
};
orders.push(newOrder);
await writeFile(FILES.ORDERS, orders);
const carts = await readFile(FILES.CARTS);
const cartIndex = carts.findIndex(c => c.userId === userId);
if (cartIndex > -1) {
carts[cartIndex].items = [];
await writeFile(FILES.CARTS, carts);
}
res.status(201).json({
success: true,
message: 'Захиалга амжилттай үүсгэгдлээ',
data: newOrder
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.get('/api/orders', async (req, res) => {
try {
const { userId, role } = req.query;
let orders = await readFile(FILES.ORDERS);
if (role !== 'admin' && userId) {
orders = orders.filter(o => o.userId === userId);
}
orders.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
res.json({
success: true,
count: orders.length,
data: orders
});
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.get('/api/orders/:id', async (req, res) => {
try {
const orders = await readFile(FILES.ORDERS);
const order = orders.find(o => o.id === req.params.id);
if (!order) {
return res.status(404).json({ success: false, message: 'Захиалга олдсонгүй' });
}
res.json({ success: true, data: order });
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.put('/api/orders/:id/status', async (req, res) => {
try {
const { status } = req.body;
const orders = await readFile(FILES.ORDERS);
const index = orders.findIndex(o => o.id === req.params.id);
if (index === -1) {
return res.status(404).json({ success: false, message: 'Захиалга олдсонгүй' });
}
orders[index].status = status;
orders[index].updatedAt = new Date().toISOString();
await writeFile(FILES.ORDERS, orders);
res.json({
success: true,
message: 'Захиалгын төлөв шинэчлэгдлээ',
data: orders[index]
});
} catch (error) {
res.status(400).json({ success: false, message: 'Алдаа гарлаа' });
}
});
app.get('/api/orders/stats/dashboard', async (req, res) => {
try {
const orders = await readFile(FILES.ORDERS);
const products = await readFile(FILES.PRODUCTS);
const totalOrders = orders.length;
const pendingOrders = orders.filter(o => o.status === 'pending').length;
const totalRevenue = orders.reduce((sum, order) => sum + (order.totalAmount || 0), 0);
const productCount = products.length;
res.json({
success: true,
data: {
totalOrders,
pendingOrders,
totalRevenue,
productCount
}
});
} catch (error) {
res.status(500).json({ success: false, message: 'Серверийн алдаа' });
}
});
app.get('/', (req, res) => {
res.json({
message: '🚀 Surron API ажиллаж байна',
status: 'OK',
endpoints: {
auth: '/api/auth/*',
products: '/api/products/*',
cart: '/api/cart/*',
orders: '/api/orders/*'
}
});
});
// Initialize and start
(async () => {
await ensureDataDir();
await initializeData();
app.listen(PORT, () => {
console.log(`\n${'='.repeat(50)}`);
console.log(`🚀 СЕРВЕР АЖИЛЛАЖ БАЙНА`);
console.log(`${'='.repeat(50)}`);
console.log(`📡 URL: http://localhost:${PORT}`);
console.log(`📁 Data: ${DATA_DIR}`);
console.log(`✅ CORS: Enabled (бүх domain)`);
console.log(`👤 Admin: gank / Gank2024!`);
console.log(`${'='.repeat(50)}\n`);
});
})();