完善代码

This commit is contained in:
2026-05-22 21:37:51 +08:00
parent fdcc187384
commit ca38ec4f60
13 changed files with 225 additions and 72 deletions

View File

@@ -445,7 +445,7 @@ public class AdminController {
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "商品删除成功");
response.put("message", "商品已下架");
return ResponseEntity.ok(response);
} catch (Exception e) {

View File

@@ -1,7 +1,6 @@
package com.org.flashsalesystem.controller;
import com.org.flashsalesystem.dto.FlashSaleDTO;
import com.org.flashsalesystem.dto.ProductDTO;
import com.org.flashsalesystem.entity.Product;
import com.org.flashsalesystem.repository.ProductRepository;
import com.org.flashsalesystem.service.FlashSaleService;
@@ -18,7 +17,10 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API控制器 - 为Vue前端提供REST接口
@@ -47,7 +49,7 @@ public class ApiController {
try {
// 获取前N个商品作为热门商品
Pageable pageable = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "id"));
Page<Product> productPage = productRepository.findAll(pageable);
Page<Product> productPage = productRepository.findByStatus(1, pageable);
List<Map<String, Object>> products = new ArrayList<>();
for (Product product : productPage.getContent()) {
@@ -175,7 +177,7 @@ public class ApiController {
try {
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "id"));
Page<Product> productPage = productRepository.findAll(pageable);
Page<Product> productPage = productRepository.findByStatus(1, pageable);
List<Map<String, Object>> products = new ArrayList<>();
for (Product product : productPage.getContent()) {
@@ -227,4 +229,4 @@ public class ApiController {
return ResponseEntity.ok(response);
}
}
}

View File

@@ -288,9 +288,23 @@ public class OrderController {
* 获取订单统计信息
*/
@GetMapping("/statistics")
public ResponseEntity<Map<String, Object>> getOrderStatistics() {
public ResponseEntity<Map<String, Object>> getOrderStatistics(@RequestParam(required = false) Long userId,
HttpServletRequest request) {
try {
OrderDTO.StatisticsDTO statistics = orderService.getOrderStatistics();
UserDTO currentUser = getCurrentUser(request);
if (currentUser == null) {
return createUnauthorizedResponse();
}
if (userId != null && !userId.equals(currentUser.getId()) && !"ADMIN".equalsIgnoreCase(currentUser.getRole())) {
Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "无权限查看此用户订单统计");
return ResponseEntity.status(403).body(response);
}
Long targetUserId = userId != null ? userId : currentUser.getId();
OrderDTO.StatisticsDTO statistics = orderService.getUserOrderStatistics(targetUserId);
Map<String, Object> response = new HashMap<>();
response.put("success", true);
@@ -528,15 +542,27 @@ public class OrderController {
}
private UserDTO getCurrentUser(HttpServletRequest request) {
String token = null;
HttpSession session = request.getSession(false);
if (session == null) {
return null;
if (session != null) {
token = (String) session.getAttribute("token");
}
if (token == null || token.trim().isEmpty()) {
token = resolveBearerToken(request);
}
String token = (String) session.getAttribute("token");
return userService.getUserByToken(token);
}
private String resolveBearerToken(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer ")) {
return null;
}
return authorization.substring("Bearer ".length()).trim();
}
/**
* 获取当前用户ID
*/

View File

@@ -244,7 +244,7 @@ public class ProductController {
Map<String, Object> response = new HashMap<>();
response.put("success", success);
response.put("message", success ? "商品删除成功" : "商品删除失败");
response.put("message", success ? "商品已下架" : "商品下架失败");
return ResponseEntity.ok(response);
} catch (Exception e) {

View File

@@ -788,14 +788,12 @@ public class AdminService {
try {
Optional<Product> productOpt = productRepository.findById(id);
if (productOpt.isPresent()) {
Product product = productOpt.get();
// 清理磁盘上的图片文件
fileUploadService.deleteProductImage(product.getImageUrl());
productService.invalidateProductCaches(id);
productService.removeProductStockCache(id);
// 清除关联的限时活动缓存
invalidateFlashSaleCacheByProductId(id);
productRepository.deleteById(id);
boolean deleted = productService.deleteProduct(id);
if (!deleted) {
throw new RuntimeException("商品删除失败");
}
} else {
throw new RuntimeException("商品不存在");
}

View File

@@ -7,11 +7,7 @@ import com.org.flashsalesystem.entity.GroupBuyingGroup;
import com.org.flashsalesystem.entity.Order;
import com.org.flashsalesystem.entity.OrderItem;
import com.org.flashsalesystem.entity.UserAddress;
import com.org.flashsalesystem.repository.GroupBuyingGroupRepository;
import com.org.flashsalesystem.repository.OrderItemRepository;
import com.org.flashsalesystem.repository.OrderRepository;
import com.org.flashsalesystem.repository.ProductRepository;
import com.org.flashsalesystem.repository.UserAddressRepository;
import com.org.flashsalesystem.repository.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -588,6 +584,61 @@ public class OrderService {
return statistics;
}
/**
* 获取用户订单统计信息
*/
public OrderDTO.StatisticsDTO getUserOrderStatistics(Long userId) {
if (userId == null) {
throw new RuntimeException("用户ID不能为空");
}
List<Order> userOrders = orderRepository.findByUserId(userId);
OrderDTO.StatisticsDTO statistics = new OrderDTO.StatisticsDTO();
statistics.setTotalOrders((long) userOrders.size());
statistics.setPendingPaymentOrders(countOrdersByStatus(userOrders, 1));
statistics.setPaidOrders(countOrdersByStatus(userOrders, 2));
statistics.setShippedOrders(countOrdersByStatus(userOrders, 3));
statistics.setCompletedOrders(countOrdersByStatus(userOrders, 4));
statistics.setCancelledOrders(countOrdersByStatus(userOrders, 5));
statistics.setRefundingOrders(countOrdersByStatus(userOrders, 6));
statistics.setRefundedOrders(countOrdersByStatus(userOrders, 7));
statistics.setNormalOrders(countOrdersByType(userOrders, 1));
statistics.setFlashSaleOrders(countOrdersByType(userOrders, 2));
statistics.setGroupBuyingOrders(countOrdersByType(userOrders, 3));
BigDecimal totalAmount = userOrders.stream()
.map(Order::getTotalPrice)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
statistics.setTotalAmount(totalAmount);
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
LocalDateTime todayEnd = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
BigDecimal todayAmount = userOrders.stream()
.filter(order -> order.getCreatedAt() != null)
.filter(order -> !order.getCreatedAt().isBefore(todayStart) && !order.getCreatedAt().isAfter(todayEnd))
.map(Order::getTotalPrice)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
statistics.setTodayAmount(todayAmount);
return statistics;
}
private Long countOrdersByStatus(List<Order> orders, Integer status) {
return orders.stream()
.filter(order -> Objects.equals(order.getStatus(), status))
.count();
}
private Long countOrdersByType(List<Order> orders, Integer orderType) {
return orders.stream()
.filter(order -> Objects.equals(order.getOrderType(), orderType))
.count();
}
private void createOrderItem(Order order, ProductDTO product, Integer quantity) {
OrderItem orderItem = new OrderItem();
orderItem.setOrderId(order.getId());

View File

@@ -31,6 +31,7 @@ public class ProductService {
private static final String PRODUCT_STOCK_PREFIX = "product_stock:";
private static final String PRODUCT_SALES_RANK = "product_sales_rank";
private static final String HOT_PRODUCTS_CACHE = "hot_products";
private static final String ACTIVE_FLASH_SALES_CACHE = "active_flashsales";
@Autowired
private ProductRepository productRepository;
@Autowired
@@ -474,7 +475,7 @@ public class ProductService {
*/
private void clearProductListCache() {
Set<String> listCacheKeys = redisService.keys(PRODUCT_LIST_CACHE_PREFIX + "*");
if (!listCacheKeys.isEmpty()) {
if (listCacheKeys != null && !listCacheKeys.isEmpty()) {
redisService.delete(listCacheKeys);
}
redisService.delete(HOT_PRODUCTS_CACHE);
@@ -495,8 +496,15 @@ public class ProductService {
log.info("删除商品: {}", productId);
try {
// 删除数据库记录
productRepository.deleteById(productId);
Optional<Product> productOpt = productRepository.findById(productId);
if (!productOpt.isPresent()) {
log.warn("删除商品失败,商品不存在: {}", productId);
return false;
}
Product product = productOpt.get();
product.setStatus(0);
productRepository.save(product);
// 删除相关缓存
String productCacheKey = PRODUCT_CACHE_PREFIX + productId;
@@ -509,8 +517,9 @@ public class ProductService {
// 清除商品列表缓存
clearProductListCache();
redisService.delete(ACTIVE_FLASH_SALES_CACHE);
log.info("商品删除成功: {}", productId);
log.info("商品已下架: {}", productId);
return true;
} catch (Exception e) {
log.error("删除商品失败: {}", productId, e);