后台完成修复,初始化项目

This commit is contained in:
2025-07-01 17:18:04 +08:00
commit 5916f076b7
74 changed files with 17444 additions and 0 deletions

View File

@@ -0,0 +1,671 @@
package com.org.flashsalesystem.service;
import com.org.flashsalesystem.dto.UserDTO;
import com.org.flashsalesystem.entity.Order;
import com.org.flashsalesystem.entity.Product;
import com.org.flashsalesystem.entity.User;
import com.org.flashsalesystem.repository.FlashSaleRepository;
import com.org.flashsalesystem.repository.OrderRepository;
import com.org.flashsalesystem.repository.ProductRepository;
import com.org.flashsalesystem.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* 管理后台服务类
*/
@Service
@Slf4j
public class AdminService {
@Autowired
private UserRepository userRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private OrderRepository orderRepository;
@Autowired
private FlashSaleRepository flashSaleRepository;
@Autowired
private RedisService redisService;
/**
* 获取仪表盘统计数据
*/
public Map<String, Object> getDashboardStats() {
Map<String, Object> stats = new HashMap<>();
try {
// 总用户数
long totalUsers = userRepository.count();
stats.put("totalUsers", totalUsers);
// 总商品数
long totalProducts = productRepository.count();
stats.put("totalProducts", totalProducts);
// 活跃秒杀数
LocalDateTime now = LocalDateTime.now();
long activeFlashSales = flashSaleRepository.countByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now,
now);
stats.put("activeFlashSales", activeFlashSales);
// 今日订单数
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
long todayOrders = orderRepository.countByCreatedAtBetween(startOfDay, endOfDay);
stats.put("todayOrders", todayOrders);
// 总订单数
long totalOrders = orderRepository.count();
stats.put("totalOrders", totalOrders);
// 已支付订单数
Long paidOrdersCount = orderRepository.countByStatus(2); // 2-已支付
long paidOrders = paidOrdersCount != null ? paidOrdersCount : 0L;
stats.put("paidOrders", paidOrders);
// 待处理订单数
Long pendingOrdersCount = orderRepository.countByStatus(1); // 1-待支付
long pendingOrders = pendingOrdersCount != null ? pendingOrdersCount : 0L;
stats.put("pendingOrders", pendingOrders);
// 总交易额
BigDecimal totalAmount = orderRepository.sumTotalPriceByStatus(2); // 2-已支付
if (totalAmount == null) {
totalAmount = BigDecimal.ZERO;
}
stats.put("totalAmount", totalAmount);
log.info("获取仪表盘统计数据成功: {}", stats);
} catch (Exception e) {
log.error("获取仪表盘统计数据失败", e);
// 返回默认值
stats.put("totalUsers", 0L);
stats.put("totalProducts", 0L);
stats.put("activeFlashSales", 0L);
stats.put("todayOrders", 0L);
stats.put("totalOrders", 0L);
stats.put("paidOrders", 0L);
stats.put("pendingOrders", 0L);
stats.put("totalAmount", BigDecimal.ZERO);
}
return stats;
}
/**
* 获取用户统计数据
*/
public Map<String, Object> getUserStats() {
Map<String, Object> stats = new HashMap<>();
try {
// 总用户数
long totalUsers = userRepository.count();
stats.put("totalUsers", totalUsers);
// 活跃用户数最近7天登录
LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
long activeUsers = userRepository.countByLastLoginAfter(sevenDaysAgo);
stats.put("activeUsers", activeUsers);
// 新用户数(今天注册)
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
long newUsers = userRepository.countByCreatedAtBetween(startOfDay, endOfDay);
stats.put("newUsers", newUsers);
// 在线用户数从Redis获取
String onlineUsersKey = "online_users";
long onlineUsers = redisService.sCard(onlineUsersKey);
stats.put("onlineUsers", onlineUsers);
} catch (Exception e) {
log.error("获取用户统计数据失败", e);
stats.put("totalUsers", 0L);
stats.put("activeUsers", 0L);
stats.put("newUsers", 0L);
stats.put("onlineUsers", 0L);
}
return stats;
}
/**
* 获取订单统计数据
*/
public Map<String, Object> getOrderStats() {
Map<String, Object> stats = new HashMap<>();
try {
// 总订单数
long totalOrders = orderRepository.count();
stats.put("totalOrders", totalOrders);
// 已支付订单数
Long paidOrdersCount = orderRepository.countByStatus(2); // 2-已支付
long paidOrders = paidOrdersCount != null ? paidOrdersCount : 0L;
stats.put("paidOrders", paidOrders);
// 待处理订单数
Long pendingOrdersCount = orderRepository.countByStatus(1); // 1-待支付
long pendingOrders = pendingOrdersCount != null ? pendingOrdersCount : 0L;
stats.put("pendingOrders", pendingOrders);
// 已取消订单数
Long cancelledOrdersCount = orderRepository.countByStatus(5); // 5-已取消
long cancelledOrders = cancelledOrdersCount != null ? cancelledOrdersCount : 0L;
stats.put("cancelledOrders", cancelledOrders);
// 总交易额
BigDecimal totalAmount = orderRepository.sumTotalPriceByStatus(2); // 2-已支付
if (totalAmount == null) {
totalAmount = BigDecimal.ZERO;
}
stats.put("totalAmount", totalAmount);
// 今日订单数
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
long todayOrders = orderRepository.countByCreatedAtBetween(startOfDay, endOfDay);
stats.put("todayOrders", todayOrders);
} catch (Exception e) {
log.error("获取订单统计数据失败", e);
stats.put("totalOrders", 0L);
stats.put("paidOrders", 0L);
stats.put("pendingOrders", 0L);
stats.put("cancelledOrders", 0L);
stats.put("totalAmount", BigDecimal.ZERO);
stats.put("todayOrders", 0L);
}
return stats;
}
/**
* 获取商品统计数据
*/
public Map<String, Object> getProductStats() {
Map<String, Object> stats = new HashMap<>();
try {
// 总商品数
long totalProducts = productRepository.count();
stats.put("totalProducts", totalProducts);
// 上架商品数
long activeProducts = productRepository.countByStatus(1);
stats.put("activeProducts", activeProducts);
// 下架商品数
long inactiveProducts = productRepository.countByStatus(0);
stats.put("inactiveProducts", inactiveProducts);
// 库存不足商品数库存小于10
long lowStockProducts = productRepository.countByStockLessThan(10);
stats.put("lowStockProducts", lowStockProducts);
} catch (Exception e) {
log.error("获取商品统计数据失败", e);
stats.put("totalProducts", 0L);
stats.put("activeProducts", 0L);
stats.put("inactiveProducts", 0L);
stats.put("lowStockProducts", 0L);
}
return stats;
}
/**
* 获取秒杀统计数据
*/
public Map<String, Object> getFlashSaleStats() {
Map<String, Object> stats = new HashMap<>();
try {
LocalDateTime now = LocalDateTime.now();
// 总秒杀活动数
long totalFlashSales = flashSaleRepository.count();
stats.put("totalFlashSales", totalFlashSales);
// 活跃秒杀数
long activeFlashSales = flashSaleRepository.countByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now,
now);
stats.put("activeFlashSales", activeFlashSales);
// 即将开始的秒杀数
LocalDateTime oneHourLater = now.plusHours(1);
long upcomingFlashSales = flashSaleRepository.countByStartTimeBetween(now, oneHourLater);
stats.put("upcomingFlashSales", upcomingFlashSales);
// 已结束的秒杀数
long endedFlashSales = flashSaleRepository.countByEndTimeLessThan(now);
stats.put("endedFlashSales", endedFlashSales);
} catch (Exception e) {
log.error("获取秒杀统计数据失败", e);
stats.put("totalFlashSales", 0L);
stats.put("activeFlashSales", 0L);
stats.put("upcomingFlashSales", 0L);
stats.put("endedFlashSales", 0L);
}
return stats;
}
/**
* 获取最近订单列表
*/
public List<Map<String, Object>> getRecentOrders(int limit) {
try {
Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Order> orders = orderRepository.findAll(pageable);
return orders.getContent().stream().map(order -> {
Map<String, Object> orderMap = new HashMap<>();
orderMap.put("id", order.getId());
orderMap.put("username", order.getUser().getUsername());
orderMap.put("productName", order.getProduct().getName());
orderMap.put("quantity", order.getQuantity());
orderMap.put("totalAmount", order.getTotalPrice());
orderMap.put("status", order.getStatus());
orderMap.put("createdAt", order.getCreatedAt());
orderMap.put("isFlashSale", order.getOrderType() == 2); // 2表示秒杀订单
return orderMap;
}).collect(Collectors.toList());
} catch (Exception e) {
log.error("获取最近订单失败", e);
return new ArrayList<>();
}
}
/**
* 获取热门商品列表
*/
public List<Map<String, Object>> getHotProducts(int limit) {
try {
// 这里可以根据销量排序,暂时按创建时间排序
Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Product> products = productRepository.findAll(pageable);
return products.getContent().stream().map(product -> {
Map<String, Object> productMap = new HashMap<>();
productMap.put("id", product.getId());
productMap.put("name", product.getName());
productMap.put("price", product.getPrice());
productMap.put("stock", product.getStock());
productMap.put("sales", 0); // 暂时设为0后续可以添加销量统计
return productMap;
}).collect(Collectors.toList());
} catch (Exception e) {
log.error("获取热门商品失败", e);
return new ArrayList<>();
}
}
/**
* 获取用户列表
*/
public Map<String, Object> getUsers(int page, int size, String keyword, Integer status) {
try {
Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<User> userPage;
if (keyword != null && !keyword.trim().isEmpty()) {
userPage = userRepository.findByUsernameContainingOrEmailContaining(keyword, keyword, pageable);
} else if (status != null) {
userPage = userRepository.findByStatus(status, pageable);
} else {
userPage = userRepository.findAll(pageable);
}
List<UserDTO> userDTOs = userPage.getContent().stream().map(user -> {
UserDTO dto = new UserDTO();
BeanUtils.copyProperties(user, dto);
dto.setPassword(null); // 不返回密码
dto.setIsOnline(redisService.sIsMember("online_users", user.getId().toString()));
return dto;
}).collect(Collectors.toList());
Map<String, Object> result = new HashMap<>();
result.put("users", userDTOs);
result.put("total", userPage.getTotalElements());
result.put("totalPages", userPage.getTotalPages());
result.put("currentPage", page);
result.put("size", size);
return result;
} catch (Exception e) {
log.error("获取用户列表失败", e);
Map<String, Object> result = new HashMap<>();
result.put("users", new ArrayList<>());
result.put("total", 0L);
result.put("totalPages", 0);
result.put("currentPage", page);
result.put("size", size);
return result;
}
}
/**
* 获取订单列表
*/
public Map<String, Object> getOrders(int page, int size, String keyword, String status) {
try {
Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Order> orderPage;
if (keyword != null && !keyword.trim().isEmpty()) {
orderPage = orderRepository.findByIdContainingOrUserUsernameContaining(keyword, keyword, pageable);
} else if (status != null && !status.trim().isEmpty()) {
Integer statusInt = Integer.parseInt(status);
orderPage = orderRepository.findByStatus(statusInt, pageable);
} else {
orderPage = orderRepository.findAll(pageable);
}
List<Map<String, Object>> orders = orderPage.getContent().stream().map(order -> {
Map<String, Object> orderMap = new HashMap<>();
orderMap.put("id", order.getId());
orderMap.put("username", order.getUser().getUsername());
orderMap.put("productName", order.getProduct().getName());
orderMap.put("quantity", order.getQuantity());
orderMap.put("totalAmount", order.getTotalPrice());
orderMap.put("status", order.getStatus());
orderMap.put("createdAt", order.getCreatedAt());
orderMap.put("isFlashSale", order.getOrderType() == 2); // 2表示秒杀订单
return orderMap;
}).collect(Collectors.toList());
Map<String, Object> result = new HashMap<>();
result.put("orders", orders);
result.put("total", orderPage.getTotalElements());
result.put("totalPages", orderPage.getTotalPages());
result.put("currentPage", page);
result.put("size", size);
return result;
} catch (Exception e) {
log.error("获取订单列表失败", e);
Map<String, Object> result = new HashMap<>();
result.put("orders", new ArrayList<>());
result.put("total", 0L);
result.put("totalPages", 0);
result.put("currentPage", page);
result.put("size", size);
return result;
}
}
/**
* 获取商品列表
*/
public Object getProducts(int page, int size, String keyword, Integer status) {
try {
Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Product> productPage;
if (keyword != null && !keyword.trim().isEmpty() && status != null) {
// 同时按关键词和状态筛选
productPage = productRepository.findByNameContainingAndStatus(keyword, status, pageable);
} else if (keyword != null && !keyword.trim().isEmpty()) {
productPage = productRepository.findByNameContaining(keyword, pageable);
} else if (status != null) {
productPage = productRepository.findByStatus(status, pageable);
} else {
productPage = productRepository.findAll(pageable);
}
// 转换为DTO
List<Map<String, Object>> productList = productPage.getContent().stream().map(product -> {
Map<String, Object> productMap = new HashMap<>();
productMap.put("id", product.getId());
productMap.put("name", product.getName());
productMap.put("price", product.getPrice());
productMap.put("stock", product.getStock());
productMap.put("status", product.getStatus());
productMap.put("description", product.getDescription());
productMap.put("imageUrl", product.getImageUrl());
productMap.put("createdAt", product.getCreatedAt());
return productMap;
}).collect(Collectors.toList());
Map<String, Object> result = new HashMap<>();
result.put("products", productList);
result.put("total", productPage.getTotalElements());
result.put("totalPages", productPage.getTotalPages());
result.put("currentPage", page);
result.put("size", size);
return result;
} catch (Exception e) {
log.error("获取商品列表失败", e);
Map<String, Object> result = new HashMap<>();
result.put("products", new ArrayList<>());
result.put("total", 0L);
result.put("totalPages", 0);
result.put("currentPage", page);
result.put("size", size);
return result;
}
}
/**
* 获取系统状态
*/
public Object getSystemStatus() {
try {
Map<String, Object> systemStatus = new HashMap<>();
// 获取JVM内存使用情况
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long usedMemory = totalMemory - freeMemory;
double memoryUsage = (double) usedMemory / totalMemory * 100;
// 获取可用处理器数量模拟CPU使用率
int availableProcessors = runtime.availableProcessors();
double cpuUsage = Math.random() * 30 + 20; // 模拟20-50%的CPU使用率
// 模拟磁盘使用率
double diskUsage = Math.random() * 40 + 10; // 模拟10-50%的磁盘使用率
systemStatus.put("status", "正常");
systemStatus.put("cpuUsage", Math.round(cpuUsage));
systemStatus.put("memoryUsage", Math.round(memoryUsage));
systemStatus.put("diskUsage", Math.round(diskUsage));
systemStatus.put("availableProcessors", availableProcessors);
systemStatus.put("totalMemory", totalMemory / 1024 / 1024 + "MB");
systemStatus.put("usedMemory", usedMemory / 1024 / 1024 + "MB");
return systemStatus;
} catch (Exception e) {
log.error("获取系统状态失败", e);
Map<String, Object> errorStatus = new HashMap<>();
errorStatus.put("status", "异常");
errorStatus.put("cpuUsage", 0);
errorStatus.put("memoryUsage", 0);
errorStatus.put("diskUsage", 0);
return errorStatus;
}
}
/**
* 获取Redis状态
*/
public Object getRedisStatus() {
try {
List<Map<String, Object>> redisNodes = new ArrayList<>();
// 模拟Redis集群节点状态
String[] nodes = {
"42.192.62.91:7000", "42.192.62.91:7001", "42.192.62.91:7002",
"42.192.62.91:7003", "42.192.62.91:7004", "42.192.62.91:7005"
};
for (String node : nodes) {
Map<String, Object> nodeStatus = new HashMap<>();
nodeStatus.put("node", node);
nodeStatus.put("status", "正常");
nodeStatus.put("memory", (200 + (int) (Math.random() * 100)) + "MB");
nodeStatus.put("connections", 30 + (int) (Math.random() * 30));
redisNodes.add(nodeStatus);
}
return redisNodes;
} catch (Exception e) {
log.error("获取Redis状态失败", e);
return new ArrayList<>();
}
}
/**
* 获取单个商品详情
*/
public Object getProduct(Long id) {
try {
Optional<Product> productOpt = productRepository.findById(id);
if (productOpt.isPresent()) {
Product product = productOpt.get();
Map<String, Object> productMap = new HashMap<>();
productMap.put("id", product.getId());
productMap.put("name", product.getName());
productMap.put("price", product.getPrice());
productMap.put("stock", product.getStock());
productMap.put("status", product.getStatus());
productMap.put("description", product.getDescription());
productMap.put("imageUrl", product.getImageUrl());
productMap.put("createdAt", product.getCreatedAt());
productMap.put("updatedAt", product.getUpdatedAt());
// 添加统计信息(模拟数据,实际应该从统计表获取)
productMap.put("totalSales", 0); // 总销量
productMap.put("totalRevenue", 0.0); // 总收入
productMap.put("viewCount", 0); // 浏览次数
productMap.put("rating", 0.0); // 平均评分
return productMap;
} else {
throw new RuntimeException("商品不存在");
}
} catch (Exception e) {
log.error("获取商品详情失败", e);
throw new RuntimeException("获取商品详情失败");
}
}
/**
* 更新商品
*/
public void updateProduct(Long id, Map<String, Object> productData) {
try {
Optional<Product> productOpt = productRepository.findById(id);
if (productOpt.isPresent()) {
Product product = productOpt.get();
if (productData.containsKey("name")) {
product.setName((String) productData.get("name"));
}
if (productData.containsKey("price")) {
product.setPrice(new BigDecimal(productData.get("price").toString()));
}
if (productData.containsKey("stock")) {
product.setStock(Integer.parseInt(productData.get("stock").toString()));
}
if (productData.containsKey("status")) {
product.setStatus(Integer.parseInt(productData.get("status").toString()));
}
if (productData.containsKey("description")) {
product.setDescription((String) productData.get("description"));
}
if (productData.containsKey("imageUrl")) {
product.setImageUrl((String) productData.get("imageUrl"));
}
product.setUpdatedAt(LocalDateTime.now());
productRepository.save(product);
} else {
throw new RuntimeException("商品不存在");
}
} catch (Exception e) {
log.error("更新商品失败", e);
throw new RuntimeException("更新商品失败: " + e.getMessage());
}
}
/**
* 删除商品
*/
public void deleteProduct(Long id) {
try {
if (productRepository.existsById(id)) {
productRepository.deleteById(id);
} else {
throw new RuntimeException("商品不存在");
}
} catch (Exception e) {
log.error("删除商品失败", e);
throw new RuntimeException("删除商品失败: " + e.getMessage());
}
}
/**
* 添加商品
*/
public Object addProduct(Map<String, Object> productData) {
try {
Product product = new Product();
product.setName((String) productData.get("name"));
product.setPrice(new BigDecimal(productData.get("price").toString()));
product.setStock(Integer.parseInt(productData.get("stock").toString()));
product.setStatus(Integer.parseInt(productData.get("status").toString()));
product.setDescription((String) productData.get("description"));
product.setImageUrl((String) productData.get("imageUrl"));
product.setCreatedAt(LocalDateTime.now());
product.setUpdatedAt(LocalDateTime.now());
Product savedProduct = productRepository.save(product);
Map<String, Object> result = new HashMap<>();
result.put("id", savedProduct.getId());
result.put("name", savedProduct.getName());
result.put("price", savedProduct.getPrice());
result.put("stock", savedProduct.getStock());
result.put("status", savedProduct.getStatus());
result.put("description", savedProduct.getDescription());
result.put("imageUrl", savedProduct.getImageUrl());
result.put("createdAt", savedProduct.getCreatedAt());
return result;
} catch (Exception e) {
log.error("添加商品失败", e);
throw new RuntimeException("添加商品失败: " + e.getMessage());
}
}
}