功能:补齐订单预约时间落库

This commit is contained in:
xiaowang
2026-03-19 20:19:41 +08:00
parent 8fd549d20e
commit de50394960
16 changed files with 1150 additions and 2151 deletions
@@ -4,7 +4,9 @@ import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.OrderDTO;
import com.xiaowang.yuminailcore.service.OrderService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.vo.OrderVO;
import com.xiaowang.yuminailcore.vo.UserVO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@@ -18,6 +20,9 @@ public class OrderController {
@Resource
private OrderService orderService;
@Resource
private UserService userService;
@PostMapping("/create")
public Result<OrderVO> createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
@@ -33,8 +38,9 @@ public class OrderController {
}
@GetMapping("/detail/{orderId}")
public Result<OrderVO> getOrderDetail(@PathVariable Long orderId) {
OrderVO orderVO = orderService.getOrderDetail(orderId);
public Result<OrderVO> getOrderDetail(@PathVariable Long orderId, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
OrderVO orderVO = orderService.getOrderDetail(orderId, userId);
return Result.success(orderVO);
}
@@ -48,23 +54,66 @@ public class OrderController {
// 后台管理接口
@RequirePermission("order:view")
@GetMapping("/admin/list")
public Result<List<OrderVO>> getAllOrders() {
public Result<List<OrderVO>> getAllOrders(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
Integer userType = (Integer) request.getAttribute("userType");
List<OrderVO> orderList = orderService.getAllOrders();
if (!Integer.valueOf(4).equals(userType)) {
UserVO currentUser = userService.getUserById(userId);
if (currentUser == null || currentUser.getShopId() == null) {
throw new RuntimeException("当前账号未绑定店铺");
}
orderList = orderList.stream()
.filter(order -> currentUser.getShopId().equals(order.getShopId()))
.toList();
}
return Result.success(orderList);
}
@RequirePermission("order:process")
@PutMapping("/admin/process/{orderId}")
public Result<Void> processOrder(@PathVariable Long orderId, @RequestParam Integer status) {
public Result<Void> processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
Integer userType = (Integer) request.getAttribute("userType");
if (!Integer.valueOf(4).equals(userType)) {
UserVO currentUser = userService.getUserById(userId);
if (currentUser == null || currentUser.getShopId() == null) {
throw new RuntimeException("当前账号未绑定店铺");
}
OrderVO orderVO = orderService.getAllOrders().stream()
.filter(order -> orderId.equals(order.getId()))
.findFirst()
.orElse(null);
if (orderVO == null || !currentUser.getShopId().equals(orderVO.getShopId())) {
throw new RuntimeException("无权处理其他店铺订单");
}
}
orderService.processOrder(orderId, status);
return Result.success();
}
// 美甲师查看自己的订单
@RequirePermission("order:view")
@GetMapping("/artist/list")
public Result<List<OrderVO>> getArtistOrders(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
Integer userType = (Integer) request.getAttribute("userType");
if (!Integer.valueOf(3).equals(userType)) {
throw new RuntimeException("仅美甲师可查看自己的订单");
}
List<OrderVO> orderList = orderService.getOrdersByArtistId(userId);
return Result.success(orderList);
}
}
@RequirePermission("order:process")
@PutMapping("/artist/complete/{orderId}")
public Result<Void> completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
Integer userType = (Integer) request.getAttribute("userType");
if (!Integer.valueOf(3).equals(userType)) {
throw new RuntimeException("仅美甲师可完成自己的订单");
}
orderService.completeArtistOrder(orderId, userId);
return Result.success();
}
}
@@ -26,4 +26,9 @@ public class OrderItemDTO {
* 美甲师ID
*/
private Long artistId;
/**
* 预约开始时间
*/
private String appointmentTime;
}
@@ -1,5 +1,6 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@@ -14,7 +15,11 @@ public class OrderItemDO extends BaseEntity {
private Integer quantity;
private BigDecimal price;
private Long artistId;
@TableField("appointment_time")
private LocalDateTime appointmentTime;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private Integer isDelete;
}
}
@@ -13,6 +13,15 @@ import java.util.List;
public interface OrderItemMapper extends BaseMapper<OrderItemDO> {
@Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}")
List<OrderItemDO> selectByOrderId(@Param("orderId") Long orderId);
@Select("SELECT oi.* FROM t_order_item oi " +
"INNER JOIN t_order o ON o.id = oi.order_id " +
"WHERE oi.artist_id = #{artistId} " +
"AND oi.is_delete = 0 " +
"AND o.is_delete = 0 " +
"AND o.status <> 3 " +
"AND oi.appointment_time IS NOT NULL")
List<OrderItemDO> selectActiveAppointmentItemsByArtistId(@Param("artistId") Long artistId);
@Select("SELECT COUNT(DISTINCT oi.order_id) as count FROM t_order_item oi " +
"JOIN t_product p ON oi.product_id = p.id " +
@@ -22,4 +31,4 @@ public interface OrderItemMapper extends BaseMapper<OrderItemDO> {
@Select("SELECT COUNT(DISTINCT id) as count FROM t_order WHERE create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND is_delete = 0")
java.util.Map<String, Object> countTodayOrders(@Param("todayStart") String todayStart);
}
}
@@ -8,9 +8,10 @@ import java.util.List;
public interface OrderService {
OrderVO createOrder(Long userId, OrderDTO orderDTO);
List<OrderVO> getOrderList(Long userId);
OrderVO getOrderDetail(Long orderId);
OrderVO getOrderDetail(Long orderId, Long userId);
void cancelOrder(Long orderId, Long userId);
void processOrder(Long orderId, Integer status);
void completeArtistOrder(Long orderId, Long artistId);
List<OrderVO> getAllOrders();
List<OrderVO> getOrdersByArtistId(Long artistId);
}
}
@@ -3,24 +3,65 @@ package com.xiaowang.yuminailcore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaowang.yuminailcore.dto.OrderDTO;
import com.xiaowang.yuminailcore.dto.OrderItemDTO;
import com.xiaowang.yuminailcore.entity.*;
import com.xiaowang.yuminailcore.mapper.*;
import com.xiaowang.yuminailcore.entity.CartDO;
import com.xiaowang.yuminailcore.entity.CouponDO;
import com.xiaowang.yuminailcore.entity.OrderDO;
import com.xiaowang.yuminailcore.entity.OrderItemDO;
import com.xiaowang.yuminailcore.entity.ProductDO;
import com.xiaowang.yuminailcore.entity.ShopDO;
import com.xiaowang.yuminailcore.entity.UserCouponDO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.CartMapper;
import com.xiaowang.yuminailcore.mapper.CouponMapper;
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
import com.xiaowang.yuminailcore.mapper.OrderMapper;
import com.xiaowang.yuminailcore.mapper.ProductMapper;
import com.xiaowang.yuminailcore.mapper.ShopMapper;
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.service.OrderService;
import com.xiaowang.yuminailcore.service.TagService;
import com.xiaowang.yuminailcore.vo.OrderItemVO;
import com.xiaowang.yuminailcore.vo.OrderVO;
import com.xiaowang.yuminailcore.vo.TagVO;
import com.xiaowang.yuminailcore.vo.UserCouponVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class OrderServiceImpl implements OrderService {
private static final DateTimeFormatter ORDER_NO_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private static final DateTimeFormatter APPOINTMENT_OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final List<DateTimeFormatter> APPOINTMENT_INPUT_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm")
);
private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)");
private static final Pattern BUSINESS_HOURS_PATTERN = Pattern.compile("^(\\d{1,2}:\\d{2})\\s*[-~至]\\s*(\\d{1,2}:\\d{2})$");
private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L;
@Resource
private OrderMapper orderMapper;
@@ -42,84 +83,96 @@ public class OrderServiceImpl implements OrderService {
@Resource
private UserMapper userMapper;
@Resource
private ShopMapper shopMapper;
@Resource
private CouponService couponService;
@Resource
private TagService tagService;
@Override
@Transactional
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
// 获取订单项列表
List<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
if (orderItemDTOs == null || orderItemDTOs.isEmpty()) {
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
throw new RuntimeException("订单项不能为空");
}
// 计算总金额
List<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
BigDecimal totalAmount = BigDecimal.ZERO;
List<OrderItemDO> orderItems = new ArrayList<>();
List<AppointmentSlot> requestedSlots = new ArrayList<>();
Map<Long, ProductDO> productCache = new HashMap<>();
Map<Long, ShopDO> shopCache = new HashMap<>();
Set<String> selectedTagNames = new LinkedHashSet<>();
Long shopId = null;
Long selectedArtistId = null;
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
validateOrderQuantity(orderItemDTO.getQuantity());
ProductDO product = productMapper.selectById(orderItemDTO.getProductId());
if (product == null || product.getIsDelete() == 1) {
if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) {
throw new RuntimeException("商品不存在或已下架");
}
productCache.put(product.getId(), product);
// 验证美甲师
if (orderItemDTO.getArtistId() != null) {
UserDO artist = userMapper.selectById(orderItemDTO.getArtistId());
if (artist == null || artist.getIsDelete() == 1) {
throw new RuntimeException("美甲师不存在或已删除");
}
if (artist.getType() != 3) {
throw new RuntimeException("指定的用户不是美甲师");
}
if (artist.getStatus() == 0) {
throw new RuntimeException("美甲师已被禁用");
}
// 验证商品是否可以被该美甲师预约
if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) {
String[] artistIds = product.getBookableArtists().split(",");
boolean isBookable = false;
for (String artistId : artistIds) {
if (artistId.trim().equals(orderItemDTO.getArtistId().toString())) {
isBookable = true;
break;
}
}
if (!isBookable) {
throw new RuntimeException("该美甲师无法预约此商品");
}
}
} else {
throw new RuntimeException("请为每个商品选择美甲师");
CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, orderItemDTO.getProductId());
if (cartItem == null) {
throw new RuntimeException("请先将商品加入购物车后再结算");
}
if (cartItem.getQuantity() == null || cartItem.getQuantity() < orderItemDTO.getQuantity()) {
throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试");
}
// 设置店铺ID(从第一个商品获取)
UserDO artist = validateArtistForProduct(product, orderItemDTO.getArtistId());
if (shopId == null) {
shopId = product.getShopId();
} else if (!shopId.equals(product.getShopId())) {
throw new RuntimeException("跨店铺商品请分开下单");
}
BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(orderItemDTO.getQuantity()));
if (selectedArtistId == null) {
selectedArtistId = artist.getId();
} else if (!selectedArtistId.equals(artist.getId())) {
throw new RuntimeException("不同美甲师的项目请分开下单");
}
LocalDateTime appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime());
validateAppointmentTime(appointmentTime, product.getTitle());
long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity();
LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes);
validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle());
requestedSlots.add(new AppointmentSlot(product.getTitle(), appointmentTime, appointmentEndTime));
collectTagNames(selectedTagNames, product.getTags());
BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()));
totalAmount = totalAmount.add(itemTotal);
// 创建订单商品
OrderItemDO orderItem = new OrderItemDO();
orderItem.setProductId(product.getId());
orderItem.setQuantity(orderItemDTO.getQuantity());
orderItem.setPrice(product.getPrice());
orderItem.setArtistId(orderItemDTO.getArtistId());
orderItem.setAppointmentTime(appointmentTime);
orderItems.add(orderItem);
}
validateRequestedSlotConflicts(requestedSlots);
validateArtistScheduleConflicts(selectedArtistId, requestedSlots, productCache);
if (totalAmount.compareTo(BigDecimal.ZERO) == 0) {
throw new RuntimeException("订单金额无效");
}
// 处理优惠券
BigDecimal actualAmount = totalAmount;
Long userCouponId = orderDTO.getCouponId();
Long couponId = null;
if (userCouponId != null && userCouponId > 0) {
// 检查优惠券是否存在且可用
UserCouponDO userCoupon = userCouponMapper.selectOne(
new QueryWrapper<UserCouponDO>()
.eq("id", userCouponId)
@@ -127,35 +180,45 @@ public class OrderServiceImpl implements OrderService {
.eq("status", 1)
);
if (userCoupon != null) {
couponId = userCoupon.getCouponId();
CouponDO coupon = couponMapper.selectById(couponId);
if (coupon != null && coupon.getStatus() == 1) {
// 计算优惠金额
if (coupon.getCouponType() == 1) { // 折扣券
actualAmount = totalAmount.multiply(coupon.getDiscountValue())
.divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP);
} else if (coupon.getCouponType() == 2) { // 满减券
if (totalAmount.compareTo(coupon.getMinAmount()) >= 0) {
actualAmount = totalAmount.subtract(coupon.getReduceAmount());
if (actualAmount.compareTo(BigDecimal.ZERO) < 0) {
actualAmount = BigDecimal.ZERO;
}
}
}
if (userCoupon == null) {
throw new RuntimeException("优惠券不存在或已失效");
}
// 更新优惠券状态
userCoupon.setStatus(2); // 已使用
userCoupon.setUseTime(LocalDateTime.now());
userCouponMapper.updateById(userCoupon);
String productTagNames = String.join(",", selectedTagNames);
boolean couponAvailable = couponService.getAvailableCoupons(userId, productTagNames, totalAmount.doubleValue()).stream()
.map(UserCouponVO::getId)
.anyMatch(id -> userCouponId.equals(id));
if (!couponAvailable) {
throw new RuntimeException("当前订单不可使用所选优惠券");
}
couponId = userCoupon.getCouponId();
CouponDO coupon = couponMapper.selectById(couponId);
if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete()) || coupon.getStatus() != 1) {
throw new RuntimeException("优惠券不存在或已失效");
}
if (shopId != null && coupon.getShopId() != null && !shopId.equals(coupon.getShopId())) {
throw new RuntimeException("该优惠券不适用于当前店铺");
}
if (coupon.getCouponType() == 1) {
actualAmount = totalAmount.multiply(coupon.getDiscountValue())
.divide(BigDecimal.valueOf(10), 2, BigDecimal.ROUND_HALF_UP);
} else if (coupon.getCouponType() == 2 && totalAmount.compareTo(coupon.getMinAmount()) >= 0) {
actualAmount = totalAmount.subtract(coupon.getReduceAmount());
if (actualAmount.compareTo(BigDecimal.ZERO) < 0) {
actualAmount = BigDecimal.ZERO;
}
}
userCoupon.setStatus(2);
userCoupon.setUseTime(LocalDateTime.now());
userCouponMapper.updateById(userCoupon);
}
// 生成订单号
String orderNo = "ORD" + LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
String orderNo = "ORD" + LocalDateTime.now().format(ORDER_NO_TIME_FORMATTER)
+ UUID.randomUUID().toString().substring(0, 8).toUpperCase();
// 创建订单
OrderDO order = new OrderDO();
order.setOrderNo(orderNo);
order.setUserId(userId);
@@ -163,18 +226,24 @@ public class OrderServiceImpl implements OrderService {
order.setTotalAmount(totalAmount);
order.setActualAmount(actualAmount);
order.setCouponId(couponId);
order.setStatus(1); // 待使用
order.setStatus(1);
order.setIsDelete(0);
orderMapper.insert(order);
// 创建订单商品
for (OrderItemDO item : orderItems) {
item.setOrderId(order.getId());
item.setIsDelete(0);
orderItemMapper.insert(item);
}
// 构建返回对象
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
QueryWrapper<CartDO> cartWrapper = new QueryWrapper<>();
cartWrapper.eq("user_id", userId)
.eq("product_id", orderItemDTO.getProductId())
.eq("is_delete", 0);
cartMapper.delete(cartWrapper);
}
return buildOrderVO(order);
}
@@ -182,23 +251,23 @@ public class OrderServiceImpl implements OrderService {
public List<OrderVO> getOrderList(Long userId) {
List<OrderDO> orderList = orderMapper.selectByUserId(userId);
List<OrderVO> orderVOList = new ArrayList<>();
for (OrderDO order : orderList) {
if (order.getIsDelete() == 0) {
if (!Integer.valueOf(1).equals(order.getIsDelete())) {
orderVOList.add(buildOrderVO(order));
}
}
return orderVOList;
}
@Override
public OrderVO getOrderDetail(Long orderId) {
public OrderVO getOrderDetail(Long orderId, Long userId) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || order.getIsDelete() == 1) {
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
if (!order.getUserId().equals(userId)) {
throw new RuntimeException("无权查看此订单");
}
return buildOrderVO(order);
}
@@ -206,38 +275,30 @@ public class OrderServiceImpl implements OrderService {
@Transactional
public void cancelOrder(Long orderId, Long userId) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || order.getIsDelete() == 1) {
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
if (!order.getUserId().equals(userId)) {
throw new RuntimeException("无权操作此订单");
}
if (order.getStatus() != 1) { // 只有待使用状态可以取消
if (order.getStatus() != 1) {
throw new RuntimeException("订单状态不允许取消");
}
// 更新订单状态
order.setStatus(3); // 已取消
order.setStatus(3);
orderMapper.updateById(order);
// 返还优惠券
if (order.getCouponId() != null && order.getCouponId() > 0) {
// 查询用户的已使用优惠券,找到与订单中couponId匹配的记录
List<UserCouponDO> userCoupons = userCouponMapper.selectList(
new QueryWrapper<UserCouponDO>()
.eq("user_id", userId)
.eq("coupon_id", order.getCouponId())
.eq("status", 2)
);
// 找到最近使用的优惠券
if (!userCoupons.isEmpty()) {
// 按使用时间倒序排序,取最近使用的
userCoupons.sort((a, b) -> b.getUseTime().compareTo(a.getUseTime()));
UserCouponDO userCoupon = userCoupons.get(0);
userCoupon.setStatus(1); // 未使用
userCoupon.setStatus(1);
userCoupon.setUseTime(null);
userCouponMapper.updateById(userCoupon);
}
@@ -248,53 +309,70 @@ public class OrderServiceImpl implements OrderService {
@Transactional
public void processOrder(Long orderId, Integer status) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || order.getIsDelete() == 1) {
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
if (status != 2 && status != 3) { // 只能设置为已完成或已取消
if (status != 2 && status != 3) {
throw new RuntimeException("无效的订单状态");
}
if (order.getStatus() != 1) { // 只有待使用状态可以处理
if (order.getStatus() != 1) {
throw new RuntimeException("订单状态不允许处理");
}
// 更新订单状态
order.setStatus(status);
orderMapper.updateById(order);
// 如果取消订单,返还优惠券
if (status == 3 && order.getCouponId() != null && order.getCouponId() > 0) {
// 查询用户的已使用优惠券,找到与订单中couponId匹配的记录
List<UserCouponDO> userCoupons = userCouponMapper.selectList(
new QueryWrapper<UserCouponDO>()
.eq("user_id", order.getUserId())
.eq("coupon_id", order.getCouponId())
.eq("status", 2)
);
// 找到最近使用的优惠券
if (!userCoupons.isEmpty()) {
// 按使用时间倒序排序,取最近使用的
userCoupons.sort((a, b) -> b.getUseTime().compareTo(a.getUseTime()));
UserCouponDO userCoupon = userCoupons.get(0);
userCoupon.setStatus(1); // 未使用
userCoupon.setStatus(1);
userCoupon.setUseTime(null);
userCouponMapper.updateById(userCoupon);
}
}
}
@Override
@Transactional
public void completeArtistOrder(Long orderId, Long artistId) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
if (order.getStatus() != 1) {
throw new RuntimeException("当前订单状态不允许完成");
}
List<OrderItemDO> activeItems = orderItemMapper.selectByOrderId(orderId).stream()
.filter(item -> !Integer.valueOf(1).equals(item.getIsDelete()))
.toList();
if (activeItems.isEmpty()) {
throw new RuntimeException("订单商品不存在");
}
boolean allBelongToArtist = activeItems.stream().allMatch(item -> artistId.equals(item.getArtistId()));
if (!allBelongToArtist) {
throw new RuntimeException("只能完成全部由自己承接的订单");
}
order.setStatus(2);
orderMapper.updateById(order);
}
@Override
public List<OrderVO> getAllOrders() {
List<OrderDO> orderList = orderMapper.selectList(new QueryWrapper<OrderDO>().eq("is_delete", 0));
List<OrderVO> orderVOList = new ArrayList<>();
for (OrderDO order : orderList) {
orderVOList.add(buildOrderVO(order));
}
return orderVOList;
}
@@ -302,15 +380,20 @@ public class OrderServiceImpl implements OrderService {
public List<OrderVO> getOrdersByArtistId(Long artistId) {
List<OrderDO> orderList = orderMapper.selectByArtistId(artistId);
List<OrderVO> orderVOList = new ArrayList<>();
for (OrderDO order : orderList) {
orderVOList.add(buildOrderVO(order));
OrderVO orderVO = buildOrderVO(order, artistId);
if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) {
orderVOList.add(orderVO);
}
}
return orderVOList;
}
private OrderVO buildOrderVO(OrderDO order) {
return buildOrderVO(order, null);
}
private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) {
OrderVO orderVO = new OrderVO();
orderVO.setId(order.getId());
orderVO.setOrderNo(order.getOrderNo());
@@ -321,7 +404,6 @@ public class OrderServiceImpl implements OrderService {
orderVO.setCouponId(order.getCouponId());
orderVO.setStatus(order.getStatus());
// 设置状态文本
switch (order.getStatus()) {
case 1:
orderVO.setStatusText("待使用");
@@ -332,10 +414,11 @@ public class OrderServiceImpl implements OrderService {
case 3:
orderVO.setStatusText("已取消");
break;
default:
orderVO.setStatusText("未知状态");
}
// 设置优惠券名称
if (order.getCouponId() != null && order.getCouponId() > 0) {
if (artistIdFilter == null && order.getCouponId() != null && order.getCouponId() > 0) {
CouponDO coupon = couponMapper.selectById(order.getCouponId());
if (coupon != null) {
orderVO.setCouponName(coupon.getCouponName());
@@ -344,44 +427,292 @@ public class OrderServiceImpl implements OrderService {
orderVO.setCreateTime(order.getCreateTime());
// 设置订单商品
List<OrderItemDO> orderItems = orderItemMapper.selectByOrderId(order.getId());
List<OrderItemVO> orderItemVOs = new ArrayList<>();
BigDecimal filteredTotal = BigDecimal.ZERO;
List<OrderItemDO> orderItems = orderItemMapper.selectByOrderId(order.getId());
for (OrderItemDO item : orderItems) {
if (item.getIsDelete() == 0) {
ProductDO product = productMapper.selectById(item.getProductId());
if (product != null) {
OrderItemVO itemVO = new OrderItemVO();
itemVO.setId(item.getId());
itemVO.setProductId(product.getId());
itemVO.setProductTitle(product.getTitle());
// 简单处理,取第一张图片
String imageFileIds = product.getImageFileIds();
if (imageFileIds != null && !imageFileIds.isEmpty()) {
String firstImageId = imageFileIds.split(",")[0];
itemVO.setProductImage("/api/file/get/" + firstImageId);
}
itemVO.setQuantity(item.getQuantity());
itemVO.setPrice(item.getPrice());
itemVO.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
// 设置美甲师信息
if (item.getArtistId() != null) {
itemVO.setArtistId(item.getArtistId());
UserDO artist = userMapper.selectById(item.getArtistId());
if (artist != null) {
itemVO.setArtistName(artist.getNickname());
itemVO.setArtistAvatar(artist.getAvatar());
}
}
orderItemVOs.add(itemVO);
if (Integer.valueOf(1).equals(item.getIsDelete())) {
continue;
}
if (artistIdFilter != null && !artistIdFilter.equals(item.getArtistId())) {
continue;
}
ProductDO product = productMapper.selectById(item.getProductId());
if (product == null) {
continue;
}
OrderItemVO itemVO = new OrderItemVO();
itemVO.setId(item.getId());
itemVO.setProductId(product.getId());
itemVO.setProductTitle(product.getTitle());
String imageFileIds = product.getImageFileIds();
if (imageFileIds != null && !imageFileIds.isEmpty()) {
String firstImageId = imageFileIds.split(",")[0];
itemVO.setProductImage("/api/file/get/" + firstImageId);
}
itemVO.setQuantity(item.getQuantity());
itemVO.setPrice(item.getPrice());
itemVO.setTotalPrice(item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
itemVO.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime()));
filteredTotal = filteredTotal.add(itemVO.getTotalPrice());
if (item.getArtistId() != null) {
itemVO.setArtistId(item.getArtistId());
UserDO artist = userMapper.selectById(item.getArtistId());
if (artist != null) {
itemVO.setArtistName(artist.getNickname());
itemVO.setArtistAvatar(artist.getAvatar());
}
}
orderItemVOs.add(itemVO);
}
orderVO.setItems(orderItemVOs);
if (artistIdFilter != null) {
orderVO.setTotalAmount(filteredTotal);
orderVO.setActualAmount(filteredTotal);
}
return orderVO;
}
}
private void validateOrderQuantity(Integer quantity) {
if (quantity == null || quantity < 1) {
throw new RuntimeException("订单商品数量必须大于 0");
}
}
private UserDO validateArtistForProduct(ProductDO product, Long artistId) {
if (artistId == null) {
throw new RuntimeException("请为每个商品选择美甲师");
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) {
throw new RuntimeException("美甲师不存在或已删除");
}
if (!Integer.valueOf(3).equals(artist.getType())) {
throw new RuntimeException("指定用户不是美甲师");
}
if (!Integer.valueOf(1).equals(artist.getStatus())) {
throw new RuntimeException("美甲师当前不可预约");
}
if (product.getShopId() != null && !product.getShopId().equals(artist.getShopId())) {
throw new RuntimeException("该美甲师不属于当前商品店铺");
}
if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) {
String[] artistIds = product.getBookableArtists().split(",");
boolean isBookable = false;
for (String currentArtistId : artistIds) {
if (currentArtistId.trim().equals(artistId.toString())) {
isBookable = true;
break;
}
}
if (!isBookable) {
throw new RuntimeException("该美甲师无法预约此商品");
}
}
return artist;
}
private void collectTagNames(Set<String> tagNames, String tags) {
if (tags == null || tags.isBlank()) {
return;
}
for (String tagId : tags.split(";")) {
if (tagId == null || tagId.isBlank()) {
continue;
}
try {
TagVO tagVO = tagService.getTagById(Long.parseLong(tagId.trim()));
if (tagVO != null && tagVO.getTagName() != null && !tagVO.getTagName().isBlank()) {
tagNames.add(tagVO.getTagName());
}
} catch (NumberFormatException ignored) {
}
}
}
private LocalDateTime parseAppointmentTime(String appointmentTime) {
if (appointmentTime == null || appointmentTime.isBlank()) {
throw new RuntimeException("请为每个商品选择预约时间");
}
String normalized = appointmentTime.trim();
for (DateTimeFormatter formatter : APPOINTMENT_INPUT_FORMATTERS) {
try {
return LocalDateTime.parse(normalized, formatter);
} catch (DateTimeParseException ignored) {
}
}
throw new RuntimeException("预约时间格式不正确");
}
private void validateAppointmentTime(LocalDateTime appointmentTime, String productTitle) {
if (!appointmentTime.isAfter(LocalDateTime.now())) {
throw new RuntimeException("商品「" + productTitle + "」的预约时间必须晚于当前时间");
}
}
private void validateBusinessHours(ShopDO shop, LocalDateTime appointmentTime, LocalDateTime appointmentEndTime, String productTitle) {
if (shop == null || shop.getBusinessHours() == null || shop.getBusinessHours().isBlank()) {
return;
}
String normalizedBusinessHours = shop.getBusinessHours()
.replace(':', ':')
.replace('-', '-')
.replace('—', '-')
.trim();
Matcher matcher = BUSINESS_HOURS_PATTERN.matcher(normalizedBusinessHours);
if (!matcher.matches()) {
return;
}
LocalTime openTime = LocalTime.parse(matcher.group(1), DateTimeFormatter.ofPattern("H:mm"));
LocalTime closeTime = LocalTime.parse(matcher.group(2), DateTimeFormatter.ofPattern("H:mm"));
if (!closeTime.isAfter(openTime)) {
return;
}
if (!appointmentTime.toLocalDate().equals(appointmentEndTime.toLocalDate())
|| appointmentTime.toLocalTime().isBefore(openTime)
|| appointmentEndTime.toLocalTime().isAfter(closeTime)) {
throw new RuntimeException("商品「" + productTitle + "」的预约时间超出门店营业时间");
}
}
private ShopDO getShopFromCache(Long shopId, Map<Long, ShopDO> shopCache) {
if (shopId == null) {
return null;
}
if (shopCache.containsKey(shopId)) {
return shopCache.get(shopId);
}
ShopDO shop = shopMapper.selectById(shopId);
if (shop != null && Integer.valueOf(1).equals(shop.getIsDelete())) {
shop = null;
}
shopCache.put(shopId, shop);
return shop;
}
private void validateRequestedSlotConflicts(List<AppointmentSlot> requestedSlots) {
if (requestedSlots.size() <= 1) {
return;
}
requestedSlots.sort(Comparator.comparing(AppointmentSlot::getStartTime));
for (int i = 1; i < requestedSlots.size(); i++) {
AppointmentSlot previous = requestedSlots.get(i - 1);
AppointmentSlot current = requestedSlots.get(i);
if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) {
throw new RuntimeException("所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间");
}
}
}
private void validateArtistScheduleConflicts(Long artistId, List<AppointmentSlot> requestedSlots, Map<Long, ProductDO> productCache) {
if (artistId == null || requestedSlots.isEmpty()) {
return;
}
List<OrderItemDO> existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId);
if (existingAppointments == null || existingAppointments.isEmpty()) {
return;
}
for (OrderItemDO existingItem : existingAppointments) {
if (existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) {
continue;
}
ProductDO existingProduct = getProductFromCache(existingItem.getProductId(), productCache);
if (existingProduct == null) {
continue;
}
long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * Math.max(1, existingItem.getQuantity());
LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes);
for (AppointmentSlot requestedSlot : requestedSlots) {
if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) {
throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择");
}
}
}
}
private ProductDO getProductFromCache(Long productId, Map<Long, ProductDO> productCache) {
if (productId == null) {
return null;
}
if (productCache.containsKey(productId)) {
return productCache.get(productId);
}
ProductDO product = productMapper.selectById(productId);
productCache.put(productId, product);
return product;
}
private long resolveServiceDurationMinutes(ProductDO product) {
if (product == null || product.getApproximateDuration() == null || product.getApproximateDuration().isBlank()) {
return DEFAULT_SERVICE_DURATION_MINUTES;
}
Matcher matcher = DURATION_PATTERN.matcher(product.getApproximateDuration());
if (matcher.find()) {
try {
return Math.max(1L, Long.parseLong(matcher.group(1)));
} catch (NumberFormatException ignored) {
}
}
return DEFAULT_SERVICE_DURATION_MINUTES;
}
private boolean hasOverlap(LocalDateTime startA, LocalDateTime endA, LocalDateTime startB, LocalDateTime endB) {
return startA.isBefore(endB) && startB.isBefore(endA);
}
private String formatAppointmentTime(LocalDateTime appointmentTime) {
if (appointmentTime == null) {
return null;
}
return appointmentTime.format(APPOINTMENT_OUTPUT_FORMATTER);
}
private static final class AppointmentSlot {
private final String productTitle;
private final LocalDateTime startTime;
private final LocalDateTime endTime;
private AppointmentSlot(String productTitle, LocalDateTime startTime, LocalDateTime endTime) {
this.productTitle = productTitle;
this.startTime = startTime;
this.endTime = endTime;
}
private String getProductTitle() {
return productTitle;
}
private LocalDateTime getStartTime() {
return startTime;
}
private LocalDateTime getEndTime() {
return endTime;
}
}
}
@@ -16,4 +16,5 @@ public class OrderItemVO {
private Long artistId;
private String artistName;
private String artistAvatar;
}
private String appointmentTime;
}