修复:收口下单防重与成功提示
This commit is contained in:
@@ -94,7 +94,8 @@ Page({
|
||||
subtotalText: '¥0.00',
|
||||
discountAmountText: '¥0.00',
|
||||
totalAmountText: '¥0.00',
|
||||
checkoutIssues: []
|
||||
checkoutIssues: [],
|
||||
submittingOrder: false
|
||||
},
|
||||
|
||||
onShow() {
|
||||
@@ -457,6 +458,10 @@ Page({
|
||||
},
|
||||
|
||||
async handleCheckout() {
|
||||
if (this.data.submittingOrder) {
|
||||
return
|
||||
}
|
||||
|
||||
const selectedItems = this.getSelectedItems()
|
||||
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
|
||||
if (checkoutIssues.length) {
|
||||
@@ -467,6 +472,10 @@ Page({
|
||||
return
|
||||
}
|
||||
|
||||
this.setData({
|
||||
submittingOrder: true
|
||||
})
|
||||
|
||||
try {
|
||||
const selectedCoupon = this.getSelectedCoupon()
|
||||
await runWithLoading(() => orderApi.createOrder({
|
||||
@@ -479,18 +488,36 @@ Page({
|
||||
appointmentTime: item.appointmentValue
|
||||
}))
|
||||
}))
|
||||
|
||||
let successToast = '订单创建成功'
|
||||
try {
|
||||
await getApp().updateCartBadge()
|
||||
await this.loadCartItems()
|
||||
} catch (followupError) {
|
||||
console.error('订单创建后刷新页面失败:', followupError)
|
||||
successToast = '订单已创建,但页面刷新失败,请前往订单页查看'
|
||||
}
|
||||
|
||||
try {
|
||||
await navigation.navigate('/pages/orders/index')
|
||||
} catch (navigationError) {
|
||||
console.error('订单创建后跳转订单页失败:', navigationError)
|
||||
successToast = '订单已创建,但跳转订单页失败,请手动前往订单页查看'
|
||||
}
|
||||
|
||||
wx.showToast({
|
||||
title: '订单创建成功',
|
||||
title: successToast,
|
||||
icon: 'none'
|
||||
})
|
||||
await getApp().updateCartBadge()
|
||||
await this.loadCartItems()
|
||||
navigation.navigate('/pages/orders/index')
|
||||
} catch (error) {
|
||||
wx.showToast({
|
||||
title: error.message || '订单创建失败',
|
||||
icon: 'none'
|
||||
})
|
||||
} finally {
|
||||
this.setData({
|
||||
submittingOrder: false
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -15,4 +15,21 @@ public interface CartMapper extends BaseMapper<CartDO> {
|
||||
|
||||
@Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND product_id = #{productId} AND is_delete = 0")
|
||||
CartDO selectByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT * FROM t_cart",
|
||||
"WHERE user_id = #{userId}",
|
||||
"AND is_delete = 0",
|
||||
"AND product_id IN",
|
||||
"<foreach collection='productIds' item='productId' open='(' separator=',' close=')'>",
|
||||
"#{productId}",
|
||||
"</foreach>",
|
||||
"FOR UPDATE",
|
||||
"</script>"
|
||||
})
|
||||
List<CartDO> selectByUserIdAndProductIdsForUpdate(
|
||||
@Param("userId") Long userId,
|
||||
@Param("productIds") List<Long> productIds
|
||||
);
|
||||
}
|
||||
|
||||
+319
-11
@@ -28,11 +28,17 @@ 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.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -40,13 +46,20 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Collections;
|
||||
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;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
public class OrderServiceImpl implements OrderService {
|
||||
@@ -56,6 +69,13 @@ public class OrderServiceImpl implements OrderService {
|
||||
private static final String COUPON_SOURCE_NONE = "NONE";
|
||||
private static final String COUPON_SOURCE_USER = "USER_COUPON";
|
||||
private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP";
|
||||
private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:";
|
||||
private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:";
|
||||
private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15);
|
||||
private static final long ORDER_CREATE_LOCK_TTL_MILLIS = ORDER_CREATE_LOCK_TTL.toMillis();
|
||||
private static final long ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS = 5000L;
|
||||
private static final long ARTIST_LOCK_RETRY_INTERVAL_MILLIS = 150L;
|
||||
private static final long ARTIST_LOCK_WAIT_TIMEOUT_MILLIS = 1500L;
|
||||
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"),
|
||||
@@ -65,6 +85,25 @@ public class OrderServiceImpl implements OrderService {
|
||||
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;
|
||||
private static final DefaultRedisScript<Long> RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>();
|
||||
private static final DefaultRedisScript<Long> RENEW_LOCK_SCRIPT = new DefaultRedisScript<>();
|
||||
private static final ScheduledExecutorService LOCK_RENEW_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new LockRenewThreadFactory());
|
||||
|
||||
static {
|
||||
RELEASE_LOCK_SCRIPT.setScriptText(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
|
||||
"return redis.call('del', KEYS[1]) " +
|
||||
"else return 0 end"
|
||||
);
|
||||
RELEASE_LOCK_SCRIPT.setResultType(Long.class);
|
||||
|
||||
RENEW_LOCK_SCRIPT.setScriptText(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then " +
|
||||
"return redis.call('pexpire', KEYS[1], ARGV[2]) " +
|
||||
"else return 0 end"
|
||||
);
|
||||
RENEW_LOCK_SCRIPT.setResultType(Long.class);
|
||||
}
|
||||
|
||||
@Resource
|
||||
private OrderMapper orderMapper;
|
||||
@@ -102,13 +141,62 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@Resource
|
||||
private TransactionTemplate transactionTemplate;
|
||||
|
||||
@PreDestroy
|
||||
public void shutdownOrderLockRenewExecutor() {
|
||||
LOCK_RENEW_EXECUTOR.shutdownNow();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public OrderVO createOrder(Long userId, OrderDTO orderDTO) {
|
||||
if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
|
||||
throw new RuntimeException("订单项不能为空");
|
||||
}
|
||||
|
||||
String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId;
|
||||
String userLockToken = UUID.randomUUID().toString();
|
||||
if (!tryAcquireOrderLock(userLockKey, userLockToken)) {
|
||||
throw new RuntimeException("订单正在提交中,请勿重复点击");
|
||||
}
|
||||
|
||||
LockLease userLockLease = startOrderLockRenewal(userLockKey, userLockToken);
|
||||
|
||||
String artistLockKey = null;
|
||||
String artistLockToken = null;
|
||||
LockLease artistLockLease = null;
|
||||
try {
|
||||
Long artistId = resolveRequestedArtistId(orderDTO.getItems());
|
||||
artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId;
|
||||
artistLockToken = UUID.randomUUID().toString();
|
||||
if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) {
|
||||
throw new RuntimeException("当前美甲师预约繁忙,请稍后再试");
|
||||
}
|
||||
|
||||
artistLockLease = startOrderLockRenewal(artistLockKey, artistLockToken);
|
||||
|
||||
OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO));
|
||||
if (orderVO == null) {
|
||||
throw new RuntimeException("订单创建失败,请稍后重试");
|
||||
}
|
||||
return orderVO;
|
||||
} finally {
|
||||
stopOrderLockRenewal(artistLockLease);
|
||||
releaseOrderLock(artistLockKey, artistLockToken);
|
||||
stopOrderLockRenewal(userLockLease);
|
||||
releaseOrderLock(userLockKey, userLockToken);
|
||||
}
|
||||
}
|
||||
|
||||
private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) {
|
||||
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<>();
|
||||
@@ -118,6 +206,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
Set<String> selectedTagNames = new LinkedHashSet<>();
|
||||
Long shopId = null;
|
||||
Long selectedArtistId = null;
|
||||
Map<Long, Integer> requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs);
|
||||
List<Long> requestedProductIds = new ArrayList<>(requestedQuantityByProductId.keySet());
|
||||
Map<Long, CartDO> lockedCartItemMap = loadLockedCartItems(userId, requestedProductIds);
|
||||
|
||||
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
|
||||
validateOrderQuantity(orderItemDTO.getQuantity());
|
||||
@@ -128,11 +219,12 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
productCache.put(product.getId(), product);
|
||||
|
||||
CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, orderItemDTO.getProductId());
|
||||
CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId());
|
||||
if (cartItem == null) {
|
||||
throw new RuntimeException("请先将商品加入购物车后再结算");
|
||||
}
|
||||
if (cartItem.getQuantity() == null || cartItem.getQuantity() < orderItemDTO.getQuantity()) {
|
||||
Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId());
|
||||
if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) {
|
||||
throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试");
|
||||
}
|
||||
|
||||
@@ -140,6 +232,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
|
||||
if (shopId == null) {
|
||||
shopId = product.getShopId();
|
||||
validateUserCanCreateOrderInShop(userId, shopId);
|
||||
} else if (!shopId.equals(product.getShopId())) {
|
||||
throw new RuntimeException("跨店铺商品请分开下单");
|
||||
}
|
||||
@@ -237,13 +330,11 @@ public class OrderServiceImpl implements OrderService {
|
||||
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);
|
||||
}
|
||||
QueryWrapper<CartDO> cartWrapper = new QueryWrapper<>();
|
||||
cartWrapper.eq("user_id", userId)
|
||||
.eq("is_delete", 0)
|
||||
.in("product_id", requestedProductIds);
|
||||
cartMapper.delete(cartWrapper);
|
||||
|
||||
return buildOrderVO(order);
|
||||
}
|
||||
@@ -368,6 +459,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
|
||||
private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) {
|
||||
OrderVO orderVO = new OrderVO();
|
||||
Map<Long, UserDO> userCache = new HashMap<>();
|
||||
orderVO.setId(order.getId());
|
||||
orderVO.setOrderNo(order.getOrderNo());
|
||||
orderVO.setUserId(order.getUserId());
|
||||
@@ -377,6 +469,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
orderVO.setCouponId(order.getCouponId());
|
||||
orderVO.setUserCouponId(order.getUserCouponId());
|
||||
orderVO.setCouponSourceType(order.getCouponSourceType());
|
||||
UserDO customer = getUserFromCache(order.getUserId(), userCache);
|
||||
orderVO.setCustomerNickname(resolveCustomerNickname(customer));
|
||||
orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone()));
|
||||
orderVO.setStatus(order.getStatus());
|
||||
|
||||
switch (order.getStatus()) {
|
||||
@@ -438,7 +533,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
|
||||
if (item.getArtistId() != null) {
|
||||
itemVO.setArtistId(item.getArtistId());
|
||||
UserDO artist = userMapper.selectById(item.getArtistId());
|
||||
UserDO artist = getUserFromCache(item.getArtistId(), userCache);
|
||||
if (artist != null) {
|
||||
itemVO.setArtistName(artist.getNickname());
|
||||
itemVO.setArtistAvatar(artist.getAvatar());
|
||||
@@ -456,6 +551,171 @@ public class OrderServiceImpl implements OrderService {
|
||||
return orderVO;
|
||||
}
|
||||
|
||||
private Map<Long, Integer> buildRequestedQuantityMap(List<OrderItemDTO> orderItemDTOs) {
|
||||
Map<Long, Integer> requestedQuantityByProductId = new HashMap<>();
|
||||
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
|
||||
if (orderItemDTO == null || orderItemDTO.getProductId() == null) {
|
||||
throw new RuntimeException("订单商品信息不完整");
|
||||
}
|
||||
requestedQuantityByProductId.merge(
|
||||
orderItemDTO.getProductId(),
|
||||
orderItemDTO.getQuantity() == null ? 0 : orderItemDTO.getQuantity(),
|
||||
Integer::sum
|
||||
);
|
||||
}
|
||||
return requestedQuantityByProductId;
|
||||
}
|
||||
|
||||
private Map<Long, CartDO> loadLockedCartItems(Long userId, List<Long> requestedProductIds) {
|
||||
if (requestedProductIds == null || requestedProductIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
List<CartDO> lockedCartItems = cartMapper.selectByUserIdAndProductIdsForUpdate(userId, requestedProductIds);
|
||||
Map<Long, CartDO> lockedCartItemMap = new HashMap<>();
|
||||
for (CartDO cartDO : lockedCartItems) {
|
||||
if (cartDO != null && cartDO.getProductId() != null) {
|
||||
lockedCartItemMap.put(cartDO.getProductId(), cartDO);
|
||||
}
|
||||
}
|
||||
return lockedCartItemMap;
|
||||
}
|
||||
|
||||
private void validateUserCanCreateOrderInShop(Long userId, Long shopId) {
|
||||
if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) {
|
||||
throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试");
|
||||
}
|
||||
}
|
||||
|
||||
private Long resolveRequestedArtistId(List<OrderItemDTO> orderItemDTOs) {
|
||||
Long artistId = null;
|
||||
for (OrderItemDTO orderItemDTO : orderItemDTOs) {
|
||||
if (orderItemDTO == null || orderItemDTO.getArtistId() == null) {
|
||||
throw new RuntimeException("请为每个商品选择美甲师");
|
||||
}
|
||||
if (artistId == null) {
|
||||
artistId = orderItemDTO.getArtistId();
|
||||
continue;
|
||||
}
|
||||
if (!artistId.equals(orderItemDTO.getArtistId())) {
|
||||
throw new RuntimeException("不同美甲师的项目请分开下单");
|
||||
}
|
||||
}
|
||||
if (artistId == null) {
|
||||
throw new RuntimeException("请为每个商品选择美甲师");
|
||||
}
|
||||
return artistId;
|
||||
}
|
||||
|
||||
private boolean tryAcquireOrderLock(String lockKey, String lockToken) {
|
||||
return Boolean.TRUE.equals(
|
||||
stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL)
|
||||
);
|
||||
}
|
||||
|
||||
private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) {
|
||||
long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS;
|
||||
while (System.currentTimeMillis() <= deadline) {
|
||||
if (tryAcquireOrderLock(lockKey, lockToken)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(ARTIST_LOCK_RETRY_INTERVAL_MILLIS);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。
|
||||
private LockLease startOrderLockRenewal(String lockKey, String lockToken) {
|
||||
if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
LockLease lockLease = new LockLease(lockKey, lockToken);
|
||||
ScheduledFuture<?> future = LOCK_RENEW_EXECUTOR.scheduleWithFixedDelay(
|
||||
() -> renewOrderLock(lockLease),
|
||||
ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS,
|
||||
ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
lockLease.attachFuture(future);
|
||||
return lockLease;
|
||||
}
|
||||
|
||||
private void renewOrderLock(LockLease lockLease) {
|
||||
if (lockLease == null || !lockLease.isActive()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Long renewResult = stringRedisTemplate.execute(
|
||||
RENEW_LOCK_SCRIPT,
|
||||
Collections.singletonList(lockLease.getLockKey()),
|
||||
lockLease.getLockToken(),
|
||||
String.valueOf(ORDER_CREATE_LOCK_TTL_MILLIS)
|
||||
);
|
||||
if (!Long.valueOf(1L).equals(renewResult)) {
|
||||
lockLease.cancel();
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private void stopOrderLockRenewal(LockLease lockLease) {
|
||||
if (lockLease == null) {
|
||||
return;
|
||||
}
|
||||
lockLease.cancel();
|
||||
}
|
||||
|
||||
private void releaseOrderLock(String lockKey, String lockToken) {
|
||||
if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) {
|
||||
return;
|
||||
}
|
||||
stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken);
|
||||
}
|
||||
|
||||
private UserDO getUserFromCache(Long userId, Map<Long, UserDO> userCache) {
|
||||
if (userId == null) {
|
||||
return null;
|
||||
}
|
||||
if (userCache.containsKey(userId)) {
|
||||
return userCache.get(userId);
|
||||
}
|
||||
UserDO userDO = userMapper.selectById(userId);
|
||||
userCache.put(userId, userDO);
|
||||
return userDO;
|
||||
}
|
||||
|
||||
private String resolveCustomerNickname(UserDO customer) {
|
||||
if (customer == null) {
|
||||
return "用户";
|
||||
}
|
||||
if (StringUtils.hasText(customer.getNickname())) {
|
||||
return customer.getNickname();
|
||||
}
|
||||
if (StringUtils.hasText(customer.getAccount())) {
|
||||
return customer.getAccount();
|
||||
}
|
||||
return "用户";
|
||||
}
|
||||
|
||||
private String maskPhone(String phone) {
|
||||
if (!StringUtils.hasText(phone)) {
|
||||
return null;
|
||||
}
|
||||
String normalizedPhone = phone.trim();
|
||||
if (normalizedPhone.length() < 7) {
|
||||
return normalizedPhone;
|
||||
}
|
||||
return normalizedPhone.substring(0, 3)
|
||||
+ "****"
|
||||
+ normalizedPhone.substring(normalizedPhone.length() - 4);
|
||||
}
|
||||
|
||||
private void validateOrderQuantity(Integer quantity) {
|
||||
if (quantity == null || quantity < 1) {
|
||||
throw new RuntimeException("订单商品数量必须大于 0");
|
||||
@@ -805,6 +1065,54 @@ public class OrderServiceImpl implements OrderService {
|
||||
couponMapper.updateById(couponDO);
|
||||
}
|
||||
|
||||
private static final class LockLease {
|
||||
private final String lockKey;
|
||||
private final String lockToken;
|
||||
private volatile ScheduledFuture<?> future;
|
||||
private volatile boolean active = true;
|
||||
|
||||
private LockLease(String lockKey, String lockToken) {
|
||||
this.lockKey = lockKey;
|
||||
this.lockToken = lockToken;
|
||||
}
|
||||
|
||||
private String getLockKey() {
|
||||
return lockKey;
|
||||
}
|
||||
|
||||
private String getLockToken() {
|
||||
return lockToken;
|
||||
}
|
||||
|
||||
private boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
private void attachFuture(ScheduledFuture<?> future) {
|
||||
this.future = future;
|
||||
if (!active && future != null) {
|
||||
future.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancel() {
|
||||
active = false;
|
||||
ScheduledFuture<?> currentFuture = future;
|
||||
if (currentFuture != null) {
|
||||
currentFuture.cancel(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class LockRenewThreadFactory implements ThreadFactory {
|
||||
@Override
|
||||
public Thread newThread(Runnable runnable) {
|
||||
Thread thread = new Thread(runnable, "order-lock-renew");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class CouponSelection {
|
||||
private final String sourceType;
|
||||
private final Long couponId;
|
||||
|
||||
@@ -18,6 +18,8 @@ public class OrderVO {
|
||||
private Long userCouponId;
|
||||
private String couponSourceType;
|
||||
private String couponName;
|
||||
private String customerNickname;
|
||||
private String customerPhoneMasked;
|
||||
private Integer status;
|
||||
private String statusText;
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@@ -0,0 +1,912 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
</a-button>
|
||||
<h1>购物车</h1>
|
||||
<a-button type="text" @click="editing = !editing">
|
||||
{{ editing ? '完成' : '批量删除' }}
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<a-empty v-if="!cartItems.length" description="购物车还是空的">
|
||||
<a-button type="primary" @click="router.push('/products')">去逛作品</a-button>
|
||||
</a-empty>
|
||||
|
||||
<a-alert
|
||||
v-if="selectedCount && checkoutIssues.length && !editing"
|
||||
class="issue-alert"
|
||||
type="warning"
|
||||
show-icon
|
||||
:message="`还有 ${checkoutIssues.length} 项待完善`"
|
||||
:description="checkoutIssues.map(issue => issue.message).join(';')"
|
||||
>
|
||||
<template #action>
|
||||
<a-button size="small" @click="focusFirstIssue">定位问题</a-button>
|
||||
</template>
|
||||
</a-alert>
|
||||
|
||||
<a-card
|
||||
v-for="item in cartItems"
|
||||
:key="item.id"
|
||||
:ref="element => setItemRef(item.id, element)"
|
||||
class="item-card"
|
||||
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
|
||||
>
|
||||
<div class="item-row">
|
||||
<a-checkbox v-model:checked="item.selected" @change="handleToggleSelect" />
|
||||
<div class="thumb" @click="openProduct(item)">
|
||||
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
|
||||
<span v-else>{{ item.productTitle[0] }}</span>
|
||||
</div>
|
||||
<div class="item-main">
|
||||
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
|
||||
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
|
||||
|
||||
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
|
||||
<span class="label">美甲师</span>
|
||||
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
|
||||
<RightOutlined />
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="selector"
|
||||
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
|
||||
@click="openBookingModal(item)"
|
||||
>
|
||||
<span class="label">预约时间</span>
|
||||
<span class="value">
|
||||
{{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }}
|
||||
</span>
|
||||
<RightOutlined />
|
||||
</div>
|
||||
|
||||
<div v-if="item.approximateDuration" class="duration">预计时长:{{ item.approximateDuration }}</div>
|
||||
|
||||
<div class="actions">
|
||||
<div class="qty">
|
||||
<a-button size="small" :disabled="item.quantity <= 1" @click="changeQuantity(item, -1)">-</a-button>
|
||||
<span>{{ item.quantity }}</span>
|
||||
<a-button size="small" :disabled="item.quantity >= 99" @click="changeQuantity(item, 1)">+</a-button>
|
||||
</div>
|
||||
<a-popconfirm title="确认删除这件作品吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
|
||||
<a-button type="text" danger size="small">
|
||||
<DeleteOutlined />
|
||||
</a-button>
|
||||
</a-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
|
||||
<div class="coupon-row">
|
||||
<span>优惠方式</span>
|
||||
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }}</span>
|
||||
</div>
|
||||
<div v-if="selectedCoupon" class="coupon-extra">
|
||||
<span>{{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }}</span>
|
||||
<strong>-¥{{ discountAmount.toFixed(2) }}</strong>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="cartItems.length && !editing" class="summary-card">
|
||||
<div class="summary-row"><span>选中项目</span><span>{{ selectedCount }} 项</span></div>
|
||||
<div class="summary-row"><span>作品数量</span><span>{{ totalQuantity }} 件</span></div>
|
||||
<div class="summary-row"><span>小计</span><span>¥{{ subtotal.toFixed(2) }}</span></div>
|
||||
<div v-if="selectedCoupon" class="summary-row"><span>优惠</span><span>-¥{{ discountAmount.toFixed(2) }}</span></div>
|
||||
<div class="summary-row total"><span>合计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
|
||||
</a-card>
|
||||
</main>
|
||||
|
||||
<footer v-if="cartItems.length" class="footer">
|
||||
<a-button
|
||||
v-if="editing"
|
||||
danger
|
||||
size="large"
|
||||
block
|
||||
@click="removeSelectedItems"
|
||||
>
|
||||
删除已选中的 {{ selectedCount }} 项
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
type="primary"
|
||||
size="large"
|
||||
block
|
||||
:loading="submittingOrder"
|
||||
:disabled="submittingOrder"
|
||||
@click="checkout"
|
||||
>
|
||||
结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
|
||||
</a-button>
|
||||
</footer>
|
||||
|
||||
<a-modal v-model:open="showCouponModal" title="选择优惠方式" @ok="applyCouponSelection" @cancel="showCouponModal = false">
|
||||
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
|
||||
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
|
||||
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
|
||||
{{ formatCouponDisplay(coupon) }}
|
||||
</a-radio>
|
||||
</a-radio-group>
|
||||
<div class="coupon-tip">
|
||||
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
|
||||
</div>
|
||||
</a-modal>
|
||||
|
||||
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
|
||||
<div class="modal-section">
|
||||
<div class="section-title">美甲师</div>
|
||||
<div v-if="availableArtists.length" class="artist-list">
|
||||
<button
|
||||
v-for="artist in availableArtists"
|
||||
:key="artist.id"
|
||||
type="button"
|
||||
class="artist-option"
|
||||
:class="{ active: sameId(draftArtistId, artist.id) }"
|
||||
@click="draftArtistId = artist.id"
|
||||
>
|
||||
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
|
||||
<span>{{ artist.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<a-empty v-else description="暂无可预约美甲师" />
|
||||
</div>
|
||||
|
||||
<div class="modal-section">
|
||||
<div class="section-title">预约时间</div>
|
||||
<a-date-picker
|
||||
v-model:value="draftAppointmentTime"
|
||||
class="time-picker"
|
||||
style="width: 100%"
|
||||
format="YYYY-MM-DD HH:mm:ss"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
input-read-only
|
||||
:disabled-date="disablePastAppointmentDate"
|
||||
:disabled-time="disablePastAppointmentTime"
|
||||
:show-time="{ minuteStep: 30, secondStep: 60, hideDisabledOptions: true }"
|
||||
placeholder="请选择预约时间"
|
||||
/>
|
||||
<div class="helper">{{ bookingHelperText }}</div>
|
||||
</div>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { cartApi } from '../api/cart'
|
||||
import { couponApi, type UserCoupon } from '../api/coupon'
|
||||
import { fileApi } from '../api/index'
|
||||
import { orderApi } from '../api/order'
|
||||
import { shopApi } from '../api/shop'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { sameId, toOptionalIdString } from '@/utils/id'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
|
||||
const router = useRouter()
|
||||
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
|
||||
|
||||
const NO_COUPON_KEY = 'NONE'
|
||||
|
||||
interface ArtistOption {
|
||||
id: IdType
|
||||
name: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
interface CartItem {
|
||||
id: IdType
|
||||
productId: IdType
|
||||
shopId?: IdType
|
||||
productTitle: string
|
||||
productImage: string
|
||||
originalProductImage?: string
|
||||
price: number
|
||||
quantity: number
|
||||
totalPrice: number
|
||||
tags: string
|
||||
tagNames?: string
|
||||
approximateDuration?: string
|
||||
bookableArtists?: string
|
||||
availableBookableArtistCount?: number
|
||||
bookableArtistRestricted?: boolean
|
||||
availableArtists?: ArtistOption[]
|
||||
appointmentTime?: string
|
||||
selected: boolean
|
||||
artistId?: IdType
|
||||
artist?: ArtistOption
|
||||
}
|
||||
|
||||
interface CheckoutIssue {
|
||||
key: string
|
||||
message: string
|
||||
itemId?: IdType
|
||||
}
|
||||
|
||||
const cartItems = ref<CartItem[]>([])
|
||||
const imageIdCache = ref<Record<string, string>>({})
|
||||
const itemRefs = ref<Record<string, HTMLElement>>({})
|
||||
const availableCoupons = ref<UserCoupon[]>([])
|
||||
const selectedCoupon = ref<UserCoupon | null>(null)
|
||||
const couponSelectionKey = ref(NO_COUPON_KEY)
|
||||
const couponSelectionTouched = ref(false)
|
||||
const showCouponModal = ref(false)
|
||||
const showBookingModal = ref(false)
|
||||
const currentItem = ref<CartItem | null>(null)
|
||||
const availableArtists = ref<ArtistOption[]>([])
|
||||
const draftArtistId = ref<IdType>()
|
||||
const draftAppointmentTime = ref('')
|
||||
const currentShopHours = ref('')
|
||||
const editing = ref(false)
|
||||
const submittingOrder = ref(false)
|
||||
|
||||
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
|
||||
const selectedCount = computed(() => selectedItems.value.length)
|
||||
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
|
||||
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
|
||||
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
|
||||
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
|
||||
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
|
||||
const bookingHelperText = computed(() => {
|
||||
const texts: string[] = []
|
||||
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
|
||||
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
|
||||
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
|
||||
})
|
||||
|
||||
const getMinAppointmentDate = () => {
|
||||
const date = new Date()
|
||||
date.setSeconds(0, 0)
|
||||
date.setMinutes(date.getMinutes() + 5)
|
||||
return date
|
||||
}
|
||||
|
||||
const getDayBoundary = (date: Date) => {
|
||||
const boundary = new Date(date)
|
||||
boundary.setHours(0, 0, 0, 0)
|
||||
return boundary.getTime()
|
||||
}
|
||||
|
||||
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
|
||||
|
||||
const setItemRef = (itemId: IdType, element: unknown) => {
|
||||
const refKey = toOptionalIdString(itemId)
|
||||
if (!refKey) {
|
||||
return
|
||||
}
|
||||
if (element && (element as any).$el) {
|
||||
itemRefs.value[refKey] = (element as any).$el as HTMLElement
|
||||
return
|
||||
}
|
||||
if (element instanceof HTMLElement) {
|
||||
itemRefs.value[refKey] = element
|
||||
return
|
||||
}
|
||||
delete itemRefs.value[refKey]
|
||||
}
|
||||
|
||||
const formatCouponDisplay = (coupon: UserCoupon) => {
|
||||
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
|
||||
const benefit = coupon.couponType === 1
|
||||
? `${coupon.discountValue} 折`
|
||||
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
|
||||
return `${badge} ${coupon.couponName} ${benefit}`
|
||||
}
|
||||
|
||||
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
|
||||
if (!coupon || amount <= 0) {
|
||||
return 0
|
||||
}
|
||||
if (coupon.couponType === 1) {
|
||||
const discountValue = Number(coupon.discountValue || 0)
|
||||
return discountValue ? amount - amount * discountValue / 10 : 0
|
||||
}
|
||||
if (coupon.couponType === 2) {
|
||||
return Number(coupon.reduceAmount || 0)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
|
||||
return coupons
|
||||
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
|
||||
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
|
||||
}
|
||||
|
||||
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
|
||||
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
|
||||
|
||||
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
|
||||
|
||||
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
|
||||
const checkoutIssues = computed<CheckoutIssue[]>(() => {
|
||||
const items = selectedItems.value
|
||||
const issues: CheckoutIssue[] = []
|
||||
const firstMissingArtist = items.find(item => !item.artistId)
|
||||
if (firstMissingArtist) {
|
||||
issues.push({ key: 'artist', message: `请先为“${firstMissingArtist.productTitle}”选择美甲师`, itemId: firstMissingArtist.id })
|
||||
}
|
||||
|
||||
const firstMissingTime = items.find(item => !item.appointmentTime)
|
||||
if (firstMissingTime) {
|
||||
issues.push({ key: 'time', message: `请先为“${firstMissingTime.productTitle}”选择预约时间`, itemId: firstMissingTime.id })
|
||||
}
|
||||
|
||||
const firstExpiredTime = items.find(item => isPastAppointment(item.appointmentTime))
|
||||
if (firstExpiredTime) {
|
||||
issues.push({ key: 'expired', message: `“${firstExpiredTime.productTitle}”的预约时间已过期,请重新选择`, itemId: firstExpiredTime.id })
|
||||
}
|
||||
|
||||
const selectedShopIds = new Set(
|
||||
items
|
||||
.map(item => toOptionalIdString(item.shopId))
|
||||
.filter((shopId): shopId is string => Boolean(shopId))
|
||||
)
|
||||
if (selectedShopIds.size > 1) {
|
||||
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
const selectedArtistIds = new Set(
|
||||
items
|
||||
.map(item => toOptionalIdString(item.artistId))
|
||||
.filter((artistId): artistId is string => Boolean(artistId))
|
||||
)
|
||||
if (selectedArtistIds.size > 1) {
|
||||
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
return issues
|
||||
})
|
||||
|
||||
const scrollToIssue = (issue?: CheckoutIssue) => {
|
||||
const itemId = toOptionalIdString(issue?.itemId)
|
||||
if (!itemId) {
|
||||
return
|
||||
}
|
||||
const target = itemRefs.value[itemId]
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}
|
||||
|
||||
const focusFirstIssue = () => {
|
||||
scrollToIssue(checkoutIssues.value[0])
|
||||
}
|
||||
|
||||
const loadCartItems = async () => {
|
||||
const response = await cartApi.getCartList() as unknown as any[]
|
||||
cartItems.value = (response || []).map(item => ({
|
||||
...item,
|
||||
selected: true,
|
||||
originalProductImage: item.productImage,
|
||||
productImage: '',
|
||||
appointmentTime: item.appointmentTime
|
||||
}))
|
||||
couponSelectionTouched.value = false
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
selectedCoupon.value = null
|
||||
editing.value = false
|
||||
await Promise.all([loadProductImages(), loadAvailableCoupons()])
|
||||
}
|
||||
|
||||
const loadProductImages = async () => {
|
||||
for (const item of cartItems.value) {
|
||||
if (!item.originalProductImage) continue
|
||||
const match = item.originalProductImage.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
|
||||
if (!match?.[1]) continue
|
||||
const imageId = match[1]
|
||||
try {
|
||||
if (!imageIdCache.value[imageId]) {
|
||||
imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
|
||||
}
|
||||
item.productImage = imageIdCache.value[imageId] || ''
|
||||
} catch {
|
||||
item.productImage = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const loadAvailableCoupons = async () => {
|
||||
if (editing.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
|
||||
const selectedShopId = selectedItems.value[0]?.shopId
|
||||
|
||||
if (!selectedItems.value.length || subtotal.value <= 0) {
|
||||
availableCoupons.value = []
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 这里只做“最佳 VIP 自动券”兜底预选,普通用户券必须显式点选后才会消耗。
|
||||
const tags = new Set<string>()
|
||||
selectedItems.value.forEach(item => {
|
||||
item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => {
|
||||
if (tag) {
|
||||
tags.add(tag)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const data = await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value, selectedShopId) as unknown as UserCoupon[]
|
||||
availableCoupons.value = Array.isArray(data) ? data : []
|
||||
|
||||
const matchedCoupon = availableCoupons.value.find(coupon => getCouponKey(coupon) === currentSelectedKey) || null
|
||||
if (matchedCoupon) {
|
||||
selectedCoupon.value = matchedCoupon
|
||||
couponSelectionKey.value = getCouponKey(matchedCoupon)
|
||||
return
|
||||
}
|
||||
|
||||
if (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY) {
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
return
|
||||
}
|
||||
|
||||
couponSelectionTouched.value = false
|
||||
const defaultVipCoupon = findBestSystemVipCoupon(availableCoupons.value)
|
||||
if (defaultVipCoupon) {
|
||||
selectedCoupon.value = defaultVipCoupon
|
||||
couponSelectionKey.value = getCouponKey(defaultVipCoupon)
|
||||
} else {
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取可用优惠失败:', error)
|
||||
availableCoupons.value = []
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleSelect = async () => {
|
||||
await runWithGlobalLoading(() => loadAvailableCoupons())
|
||||
}
|
||||
|
||||
const changeQuantity = async (item: CartItem, delta: number) => {
|
||||
const next = item.quantity + delta
|
||||
if (next < 1 || next > 99) return
|
||||
item.quantity = next
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
|
||||
await loadAvailableCoupons()
|
||||
})
|
||||
await updateCartCount()
|
||||
} catch {
|
||||
item.quantity -= delta
|
||||
message.error('更新数量失败')
|
||||
}
|
||||
}
|
||||
|
||||
const removeItem = async (item: CartItem) => {
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await cartApi.removeFromCart(item.productId)
|
||||
cartItems.value = cartItems.value.filter(current => !sameId(current.id, item.id))
|
||||
await loadAvailableCoupons()
|
||||
})
|
||||
await updateCartCount()
|
||||
message.success('作品已删除')
|
||||
} catch {
|
||||
message.error('删除作品失败')
|
||||
}
|
||||
}
|
||||
|
||||
const removeSelectedItems = async () => {
|
||||
if (!selectedItems.value.length) {
|
||||
message.warning('请先勾选要删除的作品')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await runWithGlobalLoading(async () => {
|
||||
await Promise.all(selectedItems.value.map(item => cartApi.removeFromCart(item.productId)))
|
||||
await loadCartItems()
|
||||
})
|
||||
await updateCartCount()
|
||||
message.success('已删除选中的作品')
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error)
|
||||
message.error('批量删除失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const openProduct = (item: CartItem) => {
|
||||
router.push('/product/' + item.productId)
|
||||
}
|
||||
|
||||
const openBookingModal = async (item: CartItem) => {
|
||||
currentItem.value = item
|
||||
draftArtistId.value = item.artistId
|
||||
draftAppointmentTime.value = item.appointmentTime || ''
|
||||
showBookingModal.value = true
|
||||
await runWithGlobalLoading(() => Promise.all([loadArtists(item), loadShopHours(item.shopId)]))
|
||||
}
|
||||
|
||||
const loadArtists = async (item: CartItem) => {
|
||||
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
|
||||
availableArtists.value = Array.isArray(item.availableArtists)
|
||||
? item.availableArtists
|
||||
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
|
||||
.map(artist => ({
|
||||
id: artist.id,
|
||||
name: artist.name,
|
||||
avatar: artist.avatar
|
||||
}))
|
||||
: []
|
||||
|
||||
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
|
||||
draftArtistId.value = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const loadShopHours = async (shopId?: IdType) => {
|
||||
currentShopHours.value = ''
|
||||
if (!shopId) return
|
||||
try {
|
||||
const shop = await shopApi.getShopById(shopId) as any
|
||||
currentShopHours.value = shop?.businessHours || ''
|
||||
} catch {
|
||||
currentShopHours.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const disablePastAppointmentDate = (current: any) => {
|
||||
if (!current) return false
|
||||
return current.valueOf() < getDayBoundary(new Date())
|
||||
}
|
||||
|
||||
const disablePastAppointmentTime = (current: any) => {
|
||||
if (!current || typeof current.format !== 'function') {
|
||||
return {}
|
||||
}
|
||||
const minDate = getMinAppointmentDate()
|
||||
const minDateText = [
|
||||
minDate.getFullYear(),
|
||||
String(minDate.getMonth() + 1).padStart(2, '0'),
|
||||
String(minDate.getDate()).padStart(2, '0')
|
||||
].join('-')
|
||||
if (current.format('YYYY-MM-DD') !== minDateText) {
|
||||
return {}
|
||||
}
|
||||
const minHour = minDate.getHours()
|
||||
const minMinute = minDate.getMinutes()
|
||||
return {
|
||||
disabledHours: () => Array.from({ length: minHour }, (_, index) => index),
|
||||
disabledMinutes: (selectedHour: number) => selectedHour === minHour
|
||||
? Array.from({ length: minMinute }, (_, index) => index)
|
||||
: [],
|
||||
disabledSeconds: () => []
|
||||
}
|
||||
}
|
||||
|
||||
const closeBookingModal = () => {
|
||||
showBookingModal.value = false
|
||||
currentItem.value = null
|
||||
draftArtistId.value = undefined
|
||||
draftAppointmentTime.value = ''
|
||||
availableArtists.value = []
|
||||
currentShopHours.value = ''
|
||||
}
|
||||
|
||||
const confirmBooking = () => {
|
||||
if (!currentItem.value) return closeBookingModal()
|
||||
if (!draftArtistId.value) return message.warning('请先选择美甲师')
|
||||
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
|
||||
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
|
||||
currentItem.value.artistId = draftArtistId.value
|
||||
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
|
||||
currentItem.value.appointmentTime = draftAppointmentTime.value
|
||||
closeBookingModal()
|
||||
}
|
||||
|
||||
const openCouponModal = () => {
|
||||
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
|
||||
showCouponModal.value = true
|
||||
}
|
||||
|
||||
const applyCouponSelection = () => {
|
||||
couponSelectionTouched.value = true
|
||||
if (couponSelectionKey.value === NO_COUPON_KEY) {
|
||||
selectedCoupon.value = null
|
||||
} else {
|
||||
selectedCoupon.value = availableCoupons.value.find(coupon => getCouponKey(coupon) === couponSelectionKey.value) || null
|
||||
}
|
||||
showCouponModal.value = false
|
||||
}
|
||||
|
||||
const checkout = async () => {
|
||||
if (submittingOrder.value) {
|
||||
return
|
||||
}
|
||||
const items = selectedItems.value
|
||||
if (!items.length) {
|
||||
return message.warning('请先选择要结算的作品')
|
||||
}
|
||||
|
||||
const firstIssue = checkoutIssues.value[0]
|
||||
if (firstIssue) {
|
||||
message.warning(firstIssue.message)
|
||||
scrollToIssue(firstIssue)
|
||||
return
|
||||
}
|
||||
|
||||
submittingOrder.value = true
|
||||
try {
|
||||
await runWithGlobalLoading(() => orderApi.createOrder({
|
||||
couponId: selectedCoupon.value?.id,
|
||||
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
|
||||
items: items.map(item => ({
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
artistId: item.artistId,
|
||||
appointmentTime: item.appointmentTime
|
||||
}))
|
||||
}))
|
||||
message.success('订单创建成功')
|
||||
|
||||
let followupWarningShown = false
|
||||
try {
|
||||
await runWithGlobalLoading(() => loadCartItems())
|
||||
await updateCartCount()
|
||||
} catch (followupError) {
|
||||
followupWarningShown = true
|
||||
console.error('订单创建后刷新购物车失败:', followupError)
|
||||
message.warning('订单已创建,但购物车刷新失败,请前往订单页查看')
|
||||
}
|
||||
|
||||
try {
|
||||
await router.push('/orders')
|
||||
} catch (navigationError) {
|
||||
console.error('订单创建后跳转订单页失败:', navigationError)
|
||||
if (!followupWarningShown) {
|
||||
message.warning('订单已创建,但跳转订单页失败,请手动前往订单页查看')
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('创建订单失败:', error)
|
||||
message.error(error?.message || '创建订单失败')
|
||||
} finally {
|
||||
submittingOrder.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await loadCartItems()
|
||||
} catch {
|
||||
message.error('获取购物车数据失败')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding-top: 60px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.header,
|
||||
.footer {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: #fff;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.header {
|
||||
top: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 15px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.content {
|
||||
max-width: 980px;
|
||||
margin: 0 auto;
|
||||
padding: 16px 16px 140px;
|
||||
}
|
||||
|
||||
.issue-alert {
|
||||
margin-bottom: 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.item-card,
|
||||
.coupon-card,
|
||||
.summary-card {
|
||||
margin-bottom: 12px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.issue-card {
|
||||
border-color: #faad14;
|
||||
box-shadow: 0 8px 24px rgba(250, 173, 20, 0.12);
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.thumb {
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: #eef3ff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.item-main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.price {
|
||||
margin: 6px 0 10px;
|
||||
color: #ff4d4f;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
background: #f8f9ff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.selector.issue {
|
||||
border-color: #faad14;
|
||||
background: #fff7e6;
|
||||
}
|
||||
|
||||
.selector .label {
|
||||
min-width: 56px;
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.selector .value {
|
||||
flex: 1;
|
||||
color: #1677ff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.duration,
|
||||
.coupon-tip,
|
||||
.helper {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.actions,
|
||||
.qty,
|
||||
.coupon-row,
|
||||
.summary-row,
|
||||
.coupon-extra {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.qty {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.coupon-extra {
|
||||
margin-top: 10px;
|
||||
color: #666;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.summary-row {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-row.total {
|
||||
margin-bottom: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.footer {
|
||||
bottom: 60px;
|
||||
padding: 15px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.coupon-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.modal-section + .modal-section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin-bottom: 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.artist-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.artist-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.artist-option.active {
|
||||
border-color: #1677ff;
|
||||
color: #1677ff;
|
||||
background: #f0f9ff;
|
||||
}
|
||||
|
||||
.artist-option img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.content {
|
||||
padding: 15px 15px 140px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,64 @@
|
||||
# 2026-04-03 订单锁续租与下单成功提示修补
|
||||
|
||||
## 本轮目标
|
||||
|
||||
- 修补下单链路里“订单已创建但前端提示失败”的误导性提示。
|
||||
- 修补 Redis 下单锁固定 15 秒不续租带来的慢事务并发窗口。
|
||||
- 保持本轮只收口这 2 个确认过的问题,不扩散改动范围。
|
||||
|
||||
## 本轮改动
|
||||
|
||||
### 后端
|
||||
|
||||
- 在 `OrderServiceImpl` 中补全订单锁续租机制:
|
||||
- 用户锁 `order:create:user:{userId}`
|
||||
- 美甲师锁 `order:create:artist:{artistId}`
|
||||
- 拿到锁后立即启动续租任务,默认每 5 秒续租一次,续租时仍校验锁值是否属于当前请求。
|
||||
- 释放锁前先停止续租,避免释放后后台线程继续刷新 TTL。
|
||||
- 新增 `@PreDestroy` 清理续租线程池,避免服务关闭时残留后台任务。
|
||||
- 续租失败时自动取消当前 lease,避免无效任务持续占用线程。
|
||||
|
||||
### 网页端
|
||||
|
||||
- 购物车下单流程拆成两段:
|
||||
- 第一段只负责真实创建订单。
|
||||
- 第二段负责创建成功后的购物车刷新、徽标更新和跳转订单页。
|
||||
- 订单创建成功后会立即提示 `订单创建成功`。
|
||||
- 如果后置刷新失败,不再误报为“创建订单失败”,改为提示:
|
||||
- `订单已创建,但购物车刷新失败,请前往订单页查看`
|
||||
- 如果跳转订单页失败,改为提示:
|
||||
- `订单已创建,但跳转订单页失败,请手动前往订单页查看`
|
||||
- `submittingOrder` 改为统一在 `finally` 中收口,避免成功分支和失败分支重复维护。
|
||||
|
||||
### 小程序端
|
||||
|
||||
- 购物车下单流程同步拆成“创建订单”和“成功后刷新页面”两段。
|
||||
- 订单创建成功后,即使购物车徽标刷新或页面刷新失败,也不会再提示“订单创建失败”。
|
||||
- 刷新失败时改为中文明确提示:
|
||||
- `订单已创建,但页面刷新失败,请前往订单页查看`
|
||||
- 跳转订单页失败时改为中文明确提示:
|
||||
- `订单已创建,但跳转订单页失败,请手动前往订单页查看`
|
||||
- 提交态统一在 `finally` 中关闭,避免按钮状态残留。
|
||||
|
||||
## 影响文件
|
||||
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java`
|
||||
- `YumiNail-Frontend/src/views/CartView.vue`
|
||||
- `WeChatProgram/pages/cart/index.js`
|
||||
|
||||
## SQL 说明
|
||||
|
||||
- 本轮无数据库结构变更。
|
||||
- 本轮无新增初始化 SQL。
|
||||
|
||||
## 验证计划
|
||||
|
||||
- 后端执行 `mvn -q -DskipTests compile`
|
||||
- 网页端执行 `vue-tsc -b`
|
||||
- 网页端执行 `vite build`
|
||||
- 小程序页面脚本执行 `node --check WeChatProgram/pages/cart/index.js`
|
||||
|
||||
## 备注
|
||||
|
||||
- 本轮按已确认范围只修 2 个问题,没有改动美甲师多店铺相关逻辑。
|
||||
- 美甲师仍按你当前确认的业务前提处理:后台以美甲师身份工作,前台仍按普通用户身份下单。
|
||||
Reference in New Issue
Block a user