Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
12053 lines (10364 loc) · 443 KB
/
Copy pathapp.js
File metadata and controls
12053 lines (10364 loc) · 443 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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import session from 'express-session';
import { engine } from 'express-handlebars';
import DataModel from './app/model/index.js';
import crypto from 'crypto';
import { v4 as uuidv4 } from 'uuid';
import mongoose from 'mongoose';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { v2 as cloudinary } from 'cloudinary';
import dotenv from 'dotenv';
dotenv.config();
// Connect to MongoDB
mongoose.connect(process.env.MongoDB_URL).then(() => {
console.log('✅ Connected to MongoDB');
})
.catch(err => {
console.error('❌ MongoDB Connection Error:', err.message);
});
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const app = express();
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
// Map legacy `/images` URL path to actual `public/image` folder
app.use('/images', express.static(path.join(process.cwd(), 'public', 'image')));
// Session middleware
app.use(session({
secret: process.env.SESSION_SECRET || 'vntechwebsecret2024',
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Handlebars setup
app.engine('handlebars', engine({
defaultLayout: 'AdminMain',
helpers: {
eq: (a, b) => a === b,
gt: (a, b) => a > b,
json: (context) => {
return JSON.stringify(context);
},
formatNumber: (price) => {
return new Intl.NumberFormat('vi-VN').format(price);
},
formatDate: (dateString) => {
if (!dateString) return 'N/A';
const date = new Date(dateString);
return date.toLocaleDateString('vi-VN');
},
getCategoryNameById: (categoryId, categories) => {
const category = categories.find(cat => cat._id.toString() === categoryId.toString());
return category ? category.ten_danh_muc : 'Không tìm thấy';
},
formatCurrency: (amount) => {
if (typeof amount !== 'number') {
amount = parseFloat(amount) || 0;
}
return new Intl.NumberFormat('vi-VN', {
style: 'currency',
currency: 'VND'
}).format(amount);
},
countProperties: (obj) => {
if (!obj) return 0;
return Object.keys(obj).length;
},
}
}));
app.set('view engine', 'handlebars');
app.set('views', './views');
const toObjectId = (id) => {
if (!id) return null;
return mongoose.Types.ObjectId.isValid(id) ? new mongoose.Types.ObjectId(id) : null;
};
const mongoApiRouter = express.Router();
mongoApiRouter.get('/regions', async (req, res) => {
try {
const regions = await DataModel.RegionModel.find({ trang_thai: 1 }).sort({ ma_vung: 1 }).lean();
res.json(regions);
} catch (error) {
res.status(500).json({ message: 'Lỗi khi lấy danh sách vùng: ' + error.message });
}
});
mongoApiRouter.get('/thuonghieu', async (req, res) => {
try {
const brands = await DataModel.BrandModel.find({}).sort({ ngay_tao: -1 }).lean();
res.json(brands);
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/danhmuc', async (req, res) => {
try {
const categories = await DataModel.CategoryModel.find({}).sort({ thu_tu: 1, ngay_tao: -1 }).lean();
res.json(categories);
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/sanpham', async (req, res) => {
try {
const { vung_id } = req.query;
const filter = {};
if (vung_id) filter.site_created = vung_id;
const products = await DataModel.ProductModel.find(filter)
.populate('thuong_hieu_id', 'ten_thuong_hieu logo_url')
.populate('danh_muc_id', 'ten_danh_muc')
.sort({ ngay_tao: -1 })
.lean();
const ids = products.map((p) => p._id);
const variants = await DataModel.ProductVariantModel.find({ san_pham_id: { $in: ids } }).lean();
const byProduct = new Map();
variants.forEach((variant) => {
const key = String(variant.san_pham_id);
if (!byProduct.has(key)) byProduct.set(key, []);
byProduct.get(key).push(variant);
});
const payload = products.map((product) => {
const list = byProduct.get(String(product._id)) || [];
const active = list.filter((v) => v.trang_thai === 1);
const giaBan = active.map((v) => v.gia_ban || 0);
const giaNiemYet = active.map((v) => v.gia_niem_yet || 0);
return {
...product,
id: product._id,
ten_thuong_hieu: product.thuong_hieu_id?.ten_thuong_hieu || '',
ten_danh_muc: product.danh_muc_id?.ten_danh_muc || '',
brand_logo: product.thuong_hieu_id?.logo_url || '',
variants: list,
so_bien_the: list.length,
so_bien_the_active: active.length,
so_bien_the_vung: active.length,
gia_ban_min: giaBan.length ? Math.min(...giaBan) : product.gia_ban || 0,
gia_ban_max: giaBan.length ? Math.max(...giaBan) : product.gia_ban || 0,
gia_niem_yet_min: giaNiemYet.length ? Math.min(...giaNiemYet) : product.gia_niem_yet || 0,
gia_niem_yet_max: giaNiemYet.length ? Math.max(...giaNiemYet) : product.gia_niem_yet || 0,
tong_ton_kho: active.reduce((sum, v) => sum + (v.so_luong_ton_kho || 0), 0),
tong_luot_ban: active.reduce((sum, v) => sum + (v.luot_ban || 0), 0),
chi_tiet: {}
};
});
res.json({
success: true,
data: {
sanphams: payload,
totalProducts: payload.length,
totalVariants: variants.length
}
});
} catch (error) {
res.status(500).json({ success: false, message: 'Đã xảy ra lỗi khi lấy dữ liệu sản phẩm', error: error.message });
}
});
mongoApiRouter.get('/variants', async (req, res) => {
try {
const { site_origin } = req.query;
const productFilter = site_origin ? { site_created: site_origin } : {};
const products = await DataModel.ProductModel.find(productFilter).select('_id ten_san_pham link_anh_dai_dien').lean();
const ids = products.map((p) => p._id);
const query = { trang_thai: 1 };
if (site_origin) query.san_pham_id = { $in: ids };
const variants = await DataModel.ProductVariantModel.find(query).sort({ ngay_tao: -1 }).lean();
const productMap = new Map(products.map((p) => [String(p._id), p]));
const data = variants.map((variant) => {
const product = productMap.get(String(variant.san_pham_id));
return {
...variant,
ten_san_pham: product?.ten_san_pham || '',
san_pham_anh: product?.link_anh_dai_dien || ''
};
});
res.json({ success: true, data, total: data.length });
} catch (error) {
res.status(500).json({ success: false, message: 'Lỗi server khi lấy danh sách variants', error: error.message });
}
});
mongoApiRouter.get('/products/:productId/variants', async (req, res) => {
try {
const variants = await DataModel.ProductVariantModel.find({ san_pham_id: req.params.productId }).sort({ ngay_tao: -1 }).lean();
res.json({ success: true, data: variants });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/flashsales', async (req, res) => {
try {
const flashSales = await DataModel.FlashSaleModel.find({}).sort({ ngay_tao: -1 }).lean();
res.json({ success: true, data: flashSales });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/flashsales/:id/items', async (req, res) => {
try {
const items = await DataModel.FlashSaleItemModel.find({ flash_sale_id: req.params.id }).sort({ thu_tu: 1, ngay_tao: -1 }).lean();
res.json({ success: true, data: items });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/provinces', async (req, res) => {
try {
const { vung_id } = req.query;
const filter = {};
if (vung_id) filter.vung_id = vung_id;
const provinces = await DataModel.ProvinceModel.find(filter).sort({ ten_tinh: 1 }).lean();
res.json({ success: true, data: provinces });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/wards', async (req, res) => {
try {
const { tinh_thanh_id } = req.query;
const filter = {};
if (tinh_thanh_id) filter.tinh_thanh_id = tinh_thanh_id;
const wards = await DataModel.WardModel.find(filter).sort({ ten_phuong_xa: 1 }).lean();
res.json({ success: true, data: wards });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/users', async (req, res) => {
try {
const users = await DataModel.UserModel.find({}).sort({ ngay_dang_ky: -1 }).lean();
res.json({ success: true, data: users });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/user-addresses/:userId', async (req, res) => {
try {
const addresses = await DataModel.UserAddressModel.find({ user_id: req.params.userId, trang_thai: { $ne: 0 } })
.populate('phuong_xa_id')
.sort({ is_default: -1, ngay_tao: -1 })
.lean();
res.json({ success: true, data: addresses });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/inventory', async (req, res) => {
try {
const inventory = await DataModel.InventoryModel.find({})
.populate('variant_id')
.populate('kho_id')
.sort({ ngay_tao: -1 })
.lean();
res.json({ success: true, data: inventory });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/warehouses', async (req, res) => {
try {
const warehouses = await DataModel.WarehouseModel.find({}).sort({ ngay_tao: -1 }).lean();
res.json({ success: true, data: warehouses });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/warehouses/by-region/:regionId', async (req, res) => {
try {
const warehouses = await DataModel.WarehouseModel.find({ vung_id: req.params.regionId, trang_thai: { $ne: 0 } }).lean();
res.json({ success: true, data: warehouses });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/shipping-methods', async (req, res) => {
try {
const shippingMethods = await DataModel.ShippingMethodModel.find({}).sort({ chi_phi_co_ban: 1 }).lean();
res.json({ success: true, data: shippingMethods });
} catch (error) {
res.status(500).json({ success: false, message: 'Lỗi khi lấy danh sách phương thức vận chuyển' });
}
});
mongoApiRouter.get('/shipping-methods/by-region/:regionId', async (req, res) => {
try {
const rows = await DataModel.ShippingMethodRegionModel.find({ region_id: req.params.regionId, trang_thai: 1 })
.populate('shipping_method_id')
.lean();
const data = rows.map((row) => ({
...row,
ten_phuong_thuc: row.shipping_method_id?.ten_phuong_thuc || '',
mo_ta: row.shipping_method_id?.mo_ta || '',
chi_phi_co_ban: row.shipping_method_id?.chi_phi_co_ban || 0
}));
res.json({ success: true, data });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/shipping-method-regions', async (req, res) => {
try {
const rows = await DataModel.ShippingMethodRegionModel.find({}).populate('shipping_method_id').lean();
res.json({ success: true, data: rows });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/vouchers', async (req, res) => {
try {
const { page = 1, limit = 10, loai_giam_gia, search, trang_thai } = req.query;
const filter = {};
if (loai_giam_gia) filter.loai_giam_gia = loai_giam_gia;
if (search) {
filter.$or = [
{ ma_voucher: { $regex: search, $options: 'i' } },
{ ten_voucher: { $regex: search, $options: 'i' } }
];
}
const now = new Date();
if (trang_thai === 'active') {
filter.ngay_bat_dau = { $lte: now };
filter.ngay_ket_thuc = { $gte: now };
} else if (trang_thai === 'expired') {
filter.ngay_ket_thuc = { $lt: now };
}
const vouchers = await DataModel.VoucherModel.find(filter).sort({ ngay_tao: -1 }).lean();
const pageNum = parseInt(page, 10);
const limitNum = parseInt(limit, 10);
const start = (pageNum - 1) * limitNum;
const rows = vouchers.slice(start, start + limitNum);
res.json({
success: true,
vouchers: rows,
currentPage: pageNum,
totalPages: Math.ceil(vouchers.length / limitNum),
total: vouchers.length
});
} catch (error) {
res.status(500).json({ success: false, message: 'Lỗi khi lấy danh sách voucher: ' + error.message });
}
});
mongoApiRouter.get('/vouchers/:id/products', async (req, res) => {
try {
const links = await DataModel.VoucherProductModel.find({ voucher_id: req.params.id }).populate('san_pham_id').lean();
res.json({ success: true, data: links });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.post('/vouchers/validate', async (req, res) => {
try {
const { ma_voucher, tong_tien_hang = 0 } = req.body;
const now = new Date();
const voucher = await DataModel.VoucherModel.findOne({ ma_voucher }).lean();
if (!voucher) {
return res.status(404).json({ success: false, message: 'Voucher không tồn tại' });
}
if (voucher.ngay_bat_dau && now < new Date(voucher.ngay_bat_dau)) {
return res.status(400).json({ success: false, message: 'Voucher chưa đến thời gian sử dụng' });
}
if (voucher.ngay_ket_thuc && now > new Date(voucher.ngay_ket_thuc)) {
return res.status(400).json({ success: false, message: 'Voucher đã hết hạn' });
}
if ((tong_tien_hang || 0) < (voucher.dieu_kien_ap_dung || 0)) {
return res.status(400).json({ success: false, message: 'Đơn hàng chưa đủ điều kiện áp dụng voucher' });
}
let giaTriGiam = 0;
if (voucher.loai_giam_gia === 'phan_tram') {
giaTriGiam = Math.floor((tong_tien_hang * voucher.gia_tri_giam) / 100);
if (voucher.gia_tri_giam_toi_da) {
giaTriGiam = Math.min(giaTriGiam, voucher.gia_tri_giam_toi_da);
}
} else {
giaTriGiam = voucher.gia_tri_giam;
}
return res.json({ success: true, data: { voucher, gia_tri_giam: giaTriGiam } });
} catch (error) {
return res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/orders', async (req, res) => {
try {
const { userId } = req.query;
const filter = {};
if (userId) filter.nguoi_dung_id = userId;
const orders = await DataModel.OrderModel.find(filter)
.populate('dia_chi_giao_hang_id')
.populate('voucher_id')
.sort({ ngay_tao: -1 })
.lean();
res.json({ success: true, data: orders });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/orders/:orderId', async (req, res) => {
try {
const order = await DataModel.OrderModel.findById(req.params.orderId)
.populate('dia_chi_giao_hang_id')
.populate('voucher_id')
.lean();
if (!order) {
return res.status(404).json({ success: false, message: 'Không tìm thấy đơn hàng' });
}
const details = await DataModel.OrderDetailModel.find({ don_hang_id: order._id })
.populate('variant_id')
.populate('warehouse_id')
.populate('flash_sale_item_id')
.lean();
res.json({ success: true, data: { order, details } });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.put('/orders/:orderId/cancel', async (req, res) => {
try {
const order = await DataModel.OrderModel.findByIdAndUpdate(
req.params.orderId,
{ trang_thai: 'huy' },
{ new: true }
).lean();
if (!order) {
return res.status(404).json({ success: false, message: 'Không tìm thấy đơn hàng' });
}
res.json({ success: true, data: order });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/donhang', async (req, res) => {
try {
const orders = await DataModel.OrderModel.find({}).sort({ ngay_tao: -1 }).lean();
res.json({ success: true, data: orders });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.get('/donhang/:id', async (req, res) => {
try {
const order = await DataModel.OrderModel.findById(req.params.id).lean();
if (!order) return res.status(404).json({ success: false, message: 'Không tìm thấy đơn hàng' });
const details = await DataModel.OrderDetailModel.find({ don_hang_id: order._id }).lean();
res.json({ success: true, data: { order, details } });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
mongoApiRouter.put('/donhang/:id/status', async (req, res) => {
try {
const { trang_thai, ghi_chu, nguoi_thao_tac } = req.body;
const oldOrder = await DataModel.OrderModel.findById(req.params.id).lean();
if (!oldOrder) return res.status(404).json({ success: false, message: 'Không tìm thấy đơn hàng' });
const updated = await DataModel.OrderModel.findByIdAndUpdate(req.params.id, { trang_thai }, { new: true }).lean();
await DataModel.OrderStatusHistoryModel.create({
don_hang_id: updated._id,
trang_thai_cu: oldOrder.trang_thai,
trang_thai_moi: trang_thai,
ghi_chu: ghi_chu || '',
nguoi_thao_tac: toObjectId(nguoi_thao_tac) || oldOrder.nguoi_dung_id
});
res.json({ success: true, data: updated });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
app.use('/api', mongoApiRouter);
// Global middleware để load data cho header (categories)
app.use(async (req, res, next) => {
try {
// Load categories cho tất cả các view - dùng .lean() để trả về plain objects
const categories = await DataModel.CategoryModel.find({}).lean();
// Map _id thành id để Handlebars có thể truy cập
res.locals.categories = categories.map(c => ({ ...c, id: c._id }));
next();
} catch (error) {
console.error('❌ Error loading global data:', error);
// Vẫn tiếp tục render page ngay cả khi lỗi
res.locals.categories = [];
next();
}
});
// =============================================
// MULTER CONFIGURATION FOR FILE UPLOAD
// =============================================
// Tạo thư mục upload tạm
const tempUploadDir = path.join(process.cwd(), 'temp_uploads');
if (!fs.existsSync(tempUploadDir)) {
fs.mkdirSync(tempUploadDir, { recursive: true });
}
// Cấu hình storage cho multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, tempUploadDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const ext = path.extname(file.originalname);
const name = path.basename(file.originalname, ext);
cb(null, name + '-' + uniqueSuffix + ext);
}
});
// File filter
const fileFilter = (req, file, cb) => {
const allowedImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
const allowedVideoTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/quicktime', 'video/webm'];
// Cho phép cả ảnh và video
if (allowedImageTypes.includes(file.mimetype) || allowedVideoTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error(`Định dạng file không được hỗ trợ: ${file.mimetype}. Chỉ chấp nhận JPG, PNG, GIF, WebP, MP4, MOV, AVI, WebM`), false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
limits: {
fileSize: 10 * 1024 * 1024, // 10MB
}
});
// Middleware xử lý lỗi upload
const handleUploadError = (err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
const isVideo = req.originalUrl.includes('video');
const maxSize = isVideo ? '100MB' : '10MB';
return res.status(400).json({
success: false,
message: `Kích thước file quá lớn. Tối đa ${maxSize}`
});
}
if (err.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({
success: false,
message: 'Quá nhiều file được chọn'
});
}
}
// Xử lý lỗi file filter
if (err.message.includes('Định dạng file không được hỗ trợ')) {
return res.status(400).json({
success: false,
message: err.message
});
}
res.status(400).json({
success: false,
message: err.message
});
};
// =============================================
// CLOUDINARY UTILITY FUNCTIONS
// ============================================
10BC8
=
// Hàm upload ảnh lên Cloudinary
const uploadToCloudinary = async (filePath, folder = 'products') => {
try {
const result = await cloudinary.uploader.upload(filePath, {
folder: `webPhone/${folder}`,
resource_type: 'image',
quality: 'auto:good',
fetch_format: 'auto'
});
// Xóa file tạm sau khi upload
fs.unlinkSync(filePath);
return result;
} catch (error) {
// Vẫn xóa file tạm dù upload thất bại
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
throw new Error(`Cloudinary upload failed: ${error.message}`);
}
};
// Hàm xóa ảnh từ Cloudinary
const deleteFromCloudinary = async (imageUrl) => {
try {
if (!imageUrl || !imageUrl.includes('cloudinary.com')) {
return { result: 'not_cloudinary' };
}
// Extract public_id từ URL Cloudinary
const publicId = extractPublicIdFromUrl(imageUrl);
if (!publicId) {
throw new Error('Could not extract public_id from URL');
}
const result = await cloudinary.uploader.destroy(publicId);
return result;
} catch (error) {
console.error('❌ Cloudinary delete failed:', error);
throw error;
}
};
// Hàm extract public_id từ Cloudinary URL
const extractPublicIdFromUrl = (url) => {
try {
// Ví dụ: https://res.cloudinary.com/cloudname/image/upload/v1234567/karaoke/products/image.jpg
// Hoặc: https://res.cloudinary.com/cloudname/video/upload/v1234567/karaoke/products/video.mp4
const matches = url.match(/\/upload\/(?:v\d+\/)?(.+)\.(?:jpg|jpeg|png|gif|webp|mp4|mov|avi|webm)/i);
return matches ? matches[1] : null;
} catch (error) {
console.error('Error extracting public_id:', error);
return null;
}
};
// =============================================
// UPLOAD ROUTES FOR BRAND, CATEGORY, PRODUCT
// =============================================
// Upload brand logo
app.post('/api/upload/brand-logo', upload.single('brandLogo'), handleUploadError, async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({
success: false,
message: 'Vui lòng chọn file logo'
});
}
// Kiểm tra nếu có oldImageUrl trong body thì xóa ảnh cũ
const { oldImageUrl } = req.body;
if (oldImageUrl) {
try {
await deleteFromCloudinary(oldImageUrl);
} catch (deleteError) {
console.warn('⚠️ Could not delete old image:', deleteError.message);
}
}
// Upload ảnh mới lên Cloudinary
const result = await uploadToCloudinary(req.file.path, 'brands');
res.json({
success: true,
message: 'Upload logo thành công',
data: {
url: result.secure_url,
public_id: result.public_id,
format: result.format,
bytes: result.bytes
}
});
} catch (error) {
console.error('❌ Brand logo upload error:', error);
res.status(500).json({
success: false,
message: 'Lỗi server khi upload logo: ' + error.message
});
}
});
// Upload category image
app.post('/api/upload/category-image', upload.single('categoryImage'), handleUploadError, async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({
success: false,
message: 'Vui lòng chọn file ảnh'
});
}
// Kiểm tra nếu có oldImageUrl trong body thì xóa ảnh cũ
const { oldImageUrl } = req.body;
if (oldImageUrl) {
try {
await deleteFromCloudinary(oldImageUrl);
} catch (deleteError) {
console.warn('⚠️ Could not delete old image:', deleteError.message);
}
}
// Upload ảnh mới lên Cloudinary
const result = await uploadToCloudinary(req.file.path, 'categories');
res.json({
success: true,
message: 'Upload ảnh danh mục thành công',
data: {
url: result.secure_url,
public_id: result.public_id,
format: result.format,
bytes: result.bytes
}
});
} catch (error) {
console.error('❌ Category image upload error:', error);
res.status(500).json({
success: false,
message: 'Lỗi server khi upload ảnh danh mục: ' + error.message
});
}
});
// Upload product main image
app.post('/api/upload/product-main-image', upload.single('productMainImage'), handleUploadError, async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({
success: false,
message: 'Vui lòng chọn file ảnh chính'
});
}
// Lấy folder name từ frontend (đã được format: ten-san-pham-productId)
const { productId, oldImageUrl } = req.body;
// Tạo đường dẫn: products/{ten-san-pham-productId}/images
const folderPath = productId ? `products/${productId}/images` : 'products/default/images';
// Kiểm tra nếu có oldImageUrl trong body thì xóa ảnh cũ
if (oldImageUrl) {
try {
await deleteFromCloudinary(oldImageUrl);
} catch (deleteError) {
console.warn('⚠️ Could not delete old image:', deleteError.message);
}
}
// Upload ảnh mới lên Cloudinary
const result = await uploadToCloudinary(req.file.path, folderPath);
res.json({
success: true,
message: 'Upload ảnh chính thành công',
data: {
url: result.secure_url,
public_id: result.public_id,
format: result.format,
bytes: result.bytes
}
});
} catch (error) {
console.error('❌ Product main image upload error:', error);
res.status(500).json({
success: false,
message: 'Lỗi server khi upload ảnh chính: ' + error.message
});
}
});
// Upload multiple product additional images
app.post('/api/upload/product-additional-images', upload.array('productAdditionalImages', 10), handleUploadError, async (req, res) => {
try {
if (!req.files || req.files.length === 0) {
return res.status(400).json({
success: false,
message: 'Vui lòng chọn file ảnh'
});
}
// Lấy folder name từ frontend (đã được format: ten-san-pham-productId)
const { productId } = req.body;
// Tạo đường dẫn: products/{ten-san-pham-productId}/images
const folderPath = productId ? `products/${productId}/images` : 'products/default/images';
const uploadPromises = req.files.map(file =>
uploadToCloudinary(file.path, folderPath)
);
const results = await Promise.all(uploadPromises);
const uploadedImages = results.map(result => ({
url: result.secure_url,
public_id: result.public_id,
format: result.format,
bytes: result.bytes
}));
res.json({
success: true,
message: `Upload ${uploadedImages.length} ảnh thành công`,
data: uploadedImages
});
} catch (error) {
console.error('❌ Product additional images upload error:', error);
res.status(500).json({
success: false,
message: 'Lỗi server khi upload ảnh phụ: ' + error.message
});
}
});
// API để xóa ảnh từ Cloudinary
app.delete('/api/upload/image', async (req, res) => {
try {
const { imageUrl } = req.body;
if (!imageUrl) {
return res.status(400).json({
success: false,
message: 'Thiếu URL ảnh'
});
}
const result = await deleteFromCloudinary(imageUrl);
res.json({
success: true,
message: 'Xóa ảnh thành công',
data: result
});
} catch (error) {
console.error('❌ Image delete error:', error);
res.status(500).json({
success: false,
message: 'Lỗi khi xóa ảnh: ' + error.message
});
}
});
///////////////////////////////
// GET ROUTES //
///////////////////////////////
//Trang chủ
app.get('/', async (req, res) => {
try {
const sanphams = await DataModel.ProductModel.find({}).lean();
const brands = await DataModel.BrandModel.find({}).lean();
const provinces = await DataModel.ProvinceModel.find({}).lean();
const allFlashSales = await DataModel.FlashSaleModel.find({}).sort({ ngay_bat_dau: 1 }).lean();
const now = new Date();
const flashSaleEvents = [];
for (const flashSale of allFlashSales) {
const startDate = new Date(flashSale.ngay_bat_dau);
const endDate = new Date(flashSale.ngay_ket_thuc);
const computedStatus = endDate < now ? 'da_ket_thuc' : (startDate <= now ? 'dang_dien_ra' : 'sap_dien_ra');
const items = await DataModel.FlashSaleItemModel.find({ flash_sale_id: flashSale._id, trang_thai: { $ne: 'dung_ban' } }).lean();
const enrichedItems = [];
for (const item of items) {
const variant = await DataModel.ProductVariantModel.findById(item.variant_id).lean();
if (!variant) continue;
const product = await DataModel.ProductModel.findById(variant.san_pham_id).lean();
if (!product) continue;
const phan_tram_giam = item.gia_goc > 0 ? Math.round((1 - item.gia_flash_sale / item.gia_goc) * 100) : 0;
const so_luong_ton = item.so_luong_ton || 0;
const da_ban = item.da_ban || 0;
const con_lai = so_luong_ton - da_ban;
const da_ban_percent = so_luong_ton > 0 ? Math.round((da_ban / so_luong_ton) * 100) : 0;
enrichedItems.push({
id: item.variant_id,
product_id: variant.san_pham_id,
flash_sale_item_id: item._id,
ten_san_pham: product.ten_san_pham,
ten_variant: `${product.ten_san_pham} - ${variant.ten_hien_thi || 'Mặc định'}`,
variant_name: variant.ten_hien_thi || 'Mặc định',
link_anh: variant.anh_dai_dien || product.link_anh_dai_dien || '/image/default-product.png',
sku: variant.ma_sku,
gia_goc: item.gia_goc,
gia_flash_sale: item.gia_flash_sale,
gia_ban_formatted: new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(item.gia_flash_sale),
gia_goc_formatted: new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(item.gia_goc),
phan_tram_giam,
so_luong_ton,
da_ban,
con_lai,
da_ban_percent,
ton_kho_variant: variant.so_luong_ton_kho || 0,
gioi_han_mua: item.gioi_han_mua,
is_hot: da_ban_percent > 50,
is_low_stock: con_lai < 10 && con_lai > 0
});
}
flashSaleEvents.push({
info: {
id: flashSale._id,
ten_flash_sale: flashSale.ten_flash_sale,
mo_ta: flashSale.mo_ta,
ngay_bat_dau: flashSale.ngay_bat_dau,
ngay_ket_thuc: flashSale.ngay_ket_thuc,
trang_thai: computedStatus,
is_active: computedStatus === 'dang_dien_ra',
is_upcoming: computedStatus === 'sap_dien_ra',
is_ended: computedStatus === 'da_ket_thuc'
},
items: enrichedItems
});
}
const flashSaleProductIds = new Set();
flashSaleEvents.forEach(event => {
event.items.forEach(item => {
if (item.product_id) {
flashSaleProductIds.add(String(item.product_id));
}
});
});
const formattedProducts = sanphams.map(product => {
const hasFlashSale = flashSaleProductIds.has(String(product._id));
return {
...product,
id: product._id,
has_flash_sale: hasFlashSale,
gia_ban_formatted: new Intl.NumberFormat('vi-VN', {
style: 'currency',
currency: 'VND'
}).format(product.gia_ban || 0),
gia_niem_yet_formatted: product.gia_niem_yet ? new Intl.NumberFormat('vi-VN', {
style: 'currency',
currency: 'VND'
}).format(product.gia_niem_yet) : null,
giam_gia_formatted: product.gia_niem_yet ? new Intl.NumberFormat('vi-VN', {