ArtList 底座与安全:接入 Flyway 基线、下线 mock 支付、Redis 会话隔离并清理死代码

This commit is contained in:
2026-11-04 18:10:45 +08:00
parent 3c28fe5544
commit 9ddc77415c
71 changed files with 2301 additions and 3904 deletions
@@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration;
"com.xiaowang.jayucloud.artlist.core.modules.content.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.file.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.integration.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.marketing.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.message.mapper",
"com.xiaowang.jayucloud.artlist.core.modules.order.mapper",
@@ -1,450 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.controller.front;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.jayucloud.artlist.core.annotation.RequirePermission;
import com.xiaowang.jayucloud.artlist.core.common.Result;
import com.xiaowang.jayucloud.artlist.core.config.AppCacheProperties;
import com.xiaowang.jayucloud.artlist.core.modules.content.entity.CommentDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.content.mapper.CommentMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.artlist.core.support.cache.MultiLevelCacheService;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.DashboardStatsVO;
import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.RecentActivityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/admin/dashboard")
@RequiredArgsConstructor
/**
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class DashboardController {
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
/**
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductMapper productMapper;
/**
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ShopMapper shopMapper;
/**
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentMapper commentMapper;
/**
* Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderMapper orderMapper;
/**
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderItemMapper orderItemMapper;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MultiLevelCacheService multiLevelCacheService;
/**
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AppCacheProperties appCacheProperties;
private final OperationsAnalyticsService operationsAnalyticsService;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<DashboardStatsVO> result consumed by the caller or returned to the frontend
*/
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope);
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
DashboardStatsVO stats = multiLevelCacheService.getOrLoad(
"cache:dashboard:stats:" + cacheScope,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<DashboardStatsVO>() {
},
() -> buildDashboardStats(currentUser, shopIdScope)
);
return Result.success(stats);
}
@GetMapping("/analytics")
@RequirePermission("analytics:view")
public Result<OperationsAnalyticsVO> getAnalytics(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope));
}
/**
* Run business method `buildDashboardStats`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @param shopIdScope parameter `shopIdScope` supplied by the caller
* @return private DashboardStatsVO result consumed by the caller or returned to the frontend
*/
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
if (currentUser != null) {
// 根据用户类型显示不同的数据
if (currentUser.getType() == 4) { // 管理员
stats.setTotalUsers(userMapper.selectCount(null));
stats.setTotalProducts(productMapper.selectCount(null));
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
stats.setTotalCustomers(countUsers(null, 0, null, null));
stats.setTotalArtists(countUsers(null, 3, null, null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
stats.setTotalArtists(countUsers(shopId, 3, null, null));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
}
} else {
// 无法获取用户信息的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime weekStart = todayStart.minusDays(6);
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null);
long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null);
stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders);
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null));
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
return stats;
}
/**
* Run business method `resolveShopScope`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveShopScope(UserDO currentUser) {
if (currentUser == null || currentUser.getType() == 4) {
return null;
}
return currentUser.getShopId();
}
/**
* Purpose: countUsers supports DashboardController.java by holding or executing the count users business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
if (type != null) {
wrapper.eq(UserDO::getType, type);
}
if (from != null) {
wrapper.ge(UserDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(UserDO::getCreateTime, to);
}
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return 0L;
}
wrapper.in(UserDO::getId, userIds);
}
return userMapper.selectCount(wrapper);
}
/**
* Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
}
/**
* Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
return listScopedOrders(shopId, artistId, null, from, to).stream()
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(OrderDO::getShopId, shopId);
}
if (status != null) {
wrapper.eq(OrderDO::getStatus, status);
}
if (from != null) {
wrapper.ge(OrderDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(OrderDO::getCreateTime, to);
}
if (artistId != null) {
Set<Long> orderIds = listOrderIdsByArtist(artistId);
if (orderIds.isEmpty()) {
return Collections.emptyList();
}
wrapper.in(OrderDO::getId, orderIds);
}
return orderMapper.selectList(wrapper);
}
/**
* Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Set<Long> listOrderIdsByArtist(Long artistId) {
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.select(OrderItemDO::getOrderId)
.eq(OrderItemDO::getArtistId, artistId));
return items.stream()
.map(OrderItemDO::getOrderId)
.filter(id -> id != null)
.collect(Collectors.toCollection(HashSet::new));
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long getTodayOrders(Long shopId) {
// 获取今天的开始时间
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
if (shopId != null) {
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
} else {
// 管理员查询所有订单
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
}
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<HotProductVO> result consumed by the caller or returned to the frontend
*/
private List<HotProductVO> getHotProducts(Long shopId) {
// 通过订单商品表统计每个商品的订单数量,按订单数量排序
// 使用SQL查询获取商品及其订单数量
List<Map<String, Object>> productOrderCounts = orderItemMapper.selectMaps(
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemDO>()
.select("product_id, COUNT(*) as order_count")
.groupBy("product_id")
.orderByDesc("order_count")
.last("LIMIT 5")
);
List<HotProductVO> hotProducts = new ArrayList<>();
// 遍历查询结果,获取商品详情
for (Map<String, Object> map : productOrderCounts) {
Long productId = Long.valueOf(map.get("product_id").toString());
ProductDO product = productMapper.selectById(productId);
if (product != null && (shopId == null || shopId.equals(product.getShopId()))) {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
hotProducts.add(vo);
}
}
// 如果按订单数量查询没有结果,使用点赞数作为备选
if (hotProducts.isEmpty()) {
LambdaQueryWrapper<ProductDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
wrapper.orderByDesc(ProductDO::getLikeCount)
.last("LIMIT 5");
List<ProductDO> products = productMapper.selectList(wrapper);
hotProducts = products.stream().map(product -> {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
return vo;
}).collect(Collectors.toList());
}
return hotProducts;
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<RecentActivityVO> result consumed by the caller or returned to the frontend
*/
private List<RecentActivityVO> getRecentActivities(Long shopId) {
List<RecentActivityVO> activities = new ArrayList<>();
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
userWrapper.eq(UserDO::getId, -1L);
} else {
userWrapper.in(UserDO::getId, userIds);
}
}
userWrapper.orderByDesc(UserDO::getCreateTime)
.last("LIMIT 3");
List<UserDO> recentUsers = userMapper.selectList(userWrapper);
for (UserDO user : recentUsers) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(user.getId());
vo.setType("user");
vo.setTitle("新用户注册");
vo.setDescription("用户\"" + user.getNickname() + "\"注册成功");
vo.setTime(user.getCreateTime());
vo.setColor("");
activities.add(vo);
}
LambdaQueryWrapper<ProductDO> productWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
productWrapper.eq(ProductDO::getShopId, shopId);
}
productWrapper.orderByDesc(ProductDO::getCreateTime)
.last("LIMIT 2");
List<ProductDO> recentProducts = productMapper.selectList(productWrapper);
for (ProductDO product : recentProducts) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(product.getId());
vo.setType("product");
vo.setTitle("新品上架");
vo.setDescription("新品\"" + product.getTitle() + "\"已上架");
vo.setTime(product.getCreateTime());
vo.setColor("blue");
activities.add(vo);
}
LambdaQueryWrapper<CommentDO> commentWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
commentWrapper.eq(CommentDO::getShopId, shopId);
}
commentWrapper.orderByDesc(CommentDO::getCreateTime)
.last("LIMIT 2");
List<CommentDO> recentComments = commentMapper.selectList(commentWrapper);
for (CommentDO comment : recentComments) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(comment.getId());
vo.setType("comment");
vo.setTitle("用户评论");
String content = comment.getCommentContent();
if (content != null && content.length() > 20) {
content = content.substring(0, 20) + "...";
}
vo.setDescription(content != null ? content : "用户发表了评论");
vo.setTime(comment.getCreateTime());
vo.setColor("green");
activities.add(vo);
}
activities.sort((a, b) -> b.getTime().compareTo(a.getTime()));
return activities.stream().limit(5).collect(Collectors.toList());
}
}
@@ -1,7 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
public interface OperationsAnalyticsService {
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
}
@@ -1,7 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO;
public interface WorkbenchService {
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
}
@@ -1,66 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserGrowthRecordDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserGrowthRecordMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.OperationsAnalyticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final UserGrowthRecordMapper userGrowthRecordMapper;
@Override
public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId != null) {
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
OperationsAnalyticsVO vo = new OperationsAnalyticsVO();
vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setCartCount(0L);
vo.setOrderCount((long) orders.size());
vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count());
vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REVIEW")));
vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REBOOK")));
vo.setTotalAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
}
@@ -1,145 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.AfterSaleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.service.WorkbenchService;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.analytics.vo.StoreWorkbenchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class WorkbenchServiceImpl implements WorkbenchService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final AfterSaleMapper afterSaleMapper;
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
private final InventoryItemMapper inventoryItemMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final OrderArtistReviewMapper orderArtistReviewMapper;
@Override
public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) {
LocalDateTime todayStart = LocalDate.now().atStartOfDay();
LocalDateTime tomorrowStart = todayStart.plusDays(1);
List<OrderDO> orders = scopedOrders(shopId, artistId);
StoreWorkbenchVO vo = new StoreWorkbenchVO();
vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count());
vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count());
vo.setPendingAfterSaleCount(countAfterSales(shopId));
vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId));
vo.setLowStockItemCount(countLowStock(shopId));
vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate()));
vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart));
vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setServiceAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
vo.setAverageRating(resolveRating(artistId));
return vo;
}
private boolean isActionableOrder(OrderDO order) {
if (order == null || order.getStatus() == null) {
return false;
}
return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())
|| Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus());
}
private List<OrderDO> scopedOrders(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId == null) {
return orders;
}
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
return orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
private long countAfterSales(Long shopId) {
return afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(shopId != null, AfterSaleDO::getShopId, shopId)
.eq(AfterSaleDO::getStatus, "PENDING")
.eq(AfterSaleDO::getIsDelete, 0));
}
private long countArtistChanges(Long shopId, Long artistId) {
return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId)
.eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId)
.eq(OrderArtistChangeRequestDO::getStatus, "PENDING")
.eq(OrderArtistChangeRequestDO::getIsDelete, 0));
}
private long countLowStock(Long shopId) {
return inventoryItemMapper.selectList(new LambdaQueryWrapper<InventoryItemDO>()
.eq(shopId != null, InventoryItemDO::getShopId, shopId)
.eq(InventoryItemDO::getIsDelete, 0))
.stream()
.filter(item -> item.getStockQuantity() != null
&& item.getWarningThreshold() != null
&& item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0)
.count();
}
private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) {
return artistScheduleMapper.selectCount(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(shopId != null, ArtistScheduleDO::getShopId, shopId)
.eq(artistId != null, ArtistScheduleDO::getArtistId, artistId)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(3))
.eq(ArtistScheduleDO::getIsDelete, 0));
}
private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) {
if (artistId == null) {
return 0L;
}
return orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.ge(OrderItemDO::getAppointmentTime, todayStart)
.lt(OrderItemDO::getAppointmentTime, tomorrowStart)
.eq(OrderItemDO::getIsDelete, 0))
.size();
}
private BigDecimal resolveRating(Long artistId) {
if (artistId == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP);
}
private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) {
return value != null && !value.isBefore(start) && value.isBefore(end);
}
}
@@ -1,89 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import com.xiaowang.jayucloud.artlist.core.modules.product.vo.HotProductVO;
@Data
/**
* DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class DashboardStatsVO {
/**
* Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalUsers;
/**
* Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalProducts;
/**
* Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalShops;
/**
* Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long todayOrders;
/**
* Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal totalOrderAmount;
/**
* Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal todayOrderAmount;
/**
* Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal weekOrderAmount;
/**
* Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalCustomers;
/**
* Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalArtists;
/**
* Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomersToday;
/**
* Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomers7Days;
/**
* Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newOrders7Days;
/**
* Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long pendingOrders;
/**
* Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long completedOrders;
/**
* Field `hotProducts` (List<HotProductVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<HotProductVO> hotProducts;
/**
* Field `recentActivities` (List<RecentActivityVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<RecentActivityVO> recentActivities;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class OperationsAnalyticsVO {
private Long viewCount;
private Long favoriteCount;
private Long cartCount;
private Long orderCount;
private Long paidOrderCount;
private Long completedOrderCount;
private Long reviewCount;
private Long rebookCount;
private BigDecimal totalAmount;
}
@@ -1,37 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
/**
* RecentActivityVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class RecentActivityVO {
/**
* Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long id;
/**
* Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String type;
/**
* Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String title;
/**
* Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String description;
/**
* Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime time;
/**
* Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String color;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class StoreWorkbenchVO {
private Long todayOrderCount;
private Long pendingOrderCount;
private Long pendingAfterSaleCount;
private Long pendingArtistChangeCount;
private Long lowStockItemCount;
private Long scheduleReminderCount;
private Long todayServiceCount;
private Long completedServiceCount;
private BigDecimal serviceAmount;
private BigDecimal averageRating;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleDTO {
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
}
@@ -1,24 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.service;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleVO;
import java.time.LocalDate;
import java.util.List;
public interface ArtistScheduleService {
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId);
ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto);
ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto);
}
@@ -1,423 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ArtistScheduleServiceImpl implements ArtistScheduleService {
private static final int GENERATED_DAYS = 60;
private static final int DEFAULT_SLOT_MINUTES = 60;
private static final int DEFAULT_CAPACITY = 1;
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE";
private static final String PRESET_LATE_SHIFT = "LATE_SHIFT";
private static final String PRESET_CUSTOM = "CUSTOM";
private static final String EXCEPTION_REST = "REST";
private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK";
private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT";
private final ArtistScheduleMapper artistScheduleMapper;
private final ArtistScheduleRuleMapper ruleMapper;
private final ArtistScheduleExceptionMapper exceptionMapper;
private final AppointmentReservationMapper reservationMapper;
@Override
@Transactional
public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null
|| dto.getStartTime() == null || dto.getEndTime() == null) {
throw new RuntimeException("排班信息不完整");
}
ArtistScheduleDO schedule = new ArtistScheduleDO();
BeanUtils.copyProperties(dto, schedule);
schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes());
schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity());
schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
schedule.setIsDelete(0);
ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime());
if (existing == null) {
artistScheduleMapper.insert(schedule);
} else {
schedule.setId(existing.getId());
artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(),
schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark());
}
return toVO(schedule);
}
@Override
public List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) {
LambdaQueryWrapper<ArtistScheduleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getIsDelete, 0)
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime);
if (shopId != null) {
wrapper.eq(ArtistScheduleDO::getShopId, shopId);
}
if (artistId != null) {
wrapper.eq(ArtistScheduleDO::getArtistId, artistId);
}
if (startDate != null) {
wrapper.ge(ArtistScheduleDO::getWorkDate, startDate);
}
if (endDate != null) {
wrapper.le(ArtistScheduleDO::getWorkDate, endDate);
}
return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList();
}
private ArtistScheduleVO toVO(ArtistScheduleDO schedule) {
ArtistScheduleVO vo = new ArtistScheduleVO();
BeanUtils.copyProperties(schedule, vo);
return vo;
}
@Override
public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) {
if (shopId == null || artistId == null) {
throw new RuntimeException("排班规则查询参数不完整");
}
ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO();
ArtistScheduleRuleDO rule = selectRule(shopId, artistId);
setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule));
setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L))
.stream()
.map(this::toExceptionVO)
.toList());
return setting;
}
@Override
@Transactional
public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) {
ArtistScheduleRuleDO normalized = normalizeRule(dto);
ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId());
if (existing == null) {
ruleMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
ruleMapper.updateById(normalized);
}
refreshGeneratedSchedules(normalized);
return toRuleVO(normalized);
}
@Override
@Transactional
public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) {
ArtistScheduleExceptionDO normalized = normalizeException(dto);
ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId());
if (rule == null) {
rule = defaultRule(normalized.getShopId(), normalized.getArtistId());
}
ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate());
if (existing == null) {
exceptionMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
exceptionMapper.updateById(normalized);
}
refreshScheduleForDate(rule, normalized, normalized.getWorkDate());
return toExceptionVO(normalized);
}
private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) {
throw new RuntimeException("排班规则信息不完整");
}
String presetType = normalizePresetType(dto.getPresetType());
LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime();
LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime();
validateTimeRange(startTime, endTime);
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(dto.getShopId());
rule.setArtistId(dto.getArtistId());
rule.setPresetType(presetType);
rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType)));
rule.setStartTime(startTime);
rule.setEndTime(endTime);
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
rule.setRemark(trimText(dto.getRemark()));
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) {
throw new RuntimeException("排班例外信息不完整");
}
String exceptionType = normalizeExceptionType(dto.getExceptionType());
LocalTime startTime = dto.getStartTime();
LocalTime endTime = dto.getEndTime();
if (!EXCEPTION_REST.equals(exceptionType)) {
if (startTime == null || endTime == null) {
throw new RuntimeException("临时上班或改班必须填写开始和结束时间");
}
validateTimeRange(startTime, endTime);
}
ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO();
exception.setShopId(dto.getShopId());
exception.setArtistId(dto.getArtistId());
exception.setWorkDate(dto.getWorkDate());
exception.setExceptionType(exceptionType);
exception.setStartTime(startTime);
exception.setEndTime(endTime);
exception.setSlotMinutes(DEFAULT_SLOT_MINUTES);
exception.setCapacity(DEFAULT_CAPACITY);
exception.setRemark(trimText(dto.getRemark()));
exception.setIsDelete(0);
return exception;
}
private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) {
return ruleMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleRuleDO>()
.eq(ArtistScheduleRuleDO::getShopId, shopId)
.eq(ArtistScheduleRuleDO::getArtistId, artistId)
.eq(ArtistScheduleRuleDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) {
return exceptionMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getWorkDate, workDate)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private List<ArtistScheduleExceptionDO> listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) {
return exceptionMapper.selectList(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.between(ArtistScheduleExceptionDO::getWorkDate, start, end)
.orderByAsc(ArtistScheduleExceptionDO::getWorkDate));
}
private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) {
LocalDate start = LocalDate.now();
LocalDate end = start.plusDays(GENERATED_DAYS - 1L);
Map<LocalDate, ArtistScheduleExceptionDO> exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end)
.stream()
.collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a));
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor);
cursor = cursor.plusDays(1L);
}
}
private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate);
if (!generated.working()) {
assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate);
upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark());
return;
}
assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime());
upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark());
}
private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
if (exception != null) {
if (EXCEPTION_REST.equals(exception.getExceptionType())) {
return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception));
}
if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) {
return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception));
}
}
boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue());
return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班");
}
private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime,
Integer slotMinutes, Integer capacity, Integer status, String remark) {
ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate);
if (schedule == null) {
schedule = new ArtistScheduleDO();
schedule.setShopId(rule.getShopId());
schedule.setArtistId(rule.getArtistId());
schedule.setWorkDate(workDate);
schedule.setStartTime(startTime);
schedule.setEndTime(endTime);
schedule.setSlotMinutes(slotMinutes);
schedule.setCapacity(capacity);
schedule.setStatus(status);
schedule.setRemark(remark);
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
return;
}
artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark);
}
private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) {
int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate);
if (count > 0) {
throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count);
}
}
private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime);
if (count > 0) {
throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count);
}
}
private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) {
return toRuleVO(defaultRule(shopId, artistId));
}
private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(shopId);
rule.setArtistId(artistId);
rule.setPresetType(PRESET_DOUBLE_REST);
rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5)));
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) {
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
BeanUtils.copyProperties(rule, vo);
vo.setWorkDays(decodeWorkDays(rule.getWorkDays()));
return vo;
}
private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) {
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
BeanUtils.copyProperties(exception, vo);
return vo;
}
private String normalizePresetType(String presetType) {
String value = trimText(presetType);
if (value == null || value.isBlank()) {
return PRESET_CUSTOM;
}
return value;
}
private String normalizeExceptionType(String exceptionType) {
String value = trimText(exceptionType);
if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) {
return value;
}
throw new RuntimeException("不支持的排班例外类型:" + value);
}
private List<Integer> resolveWorkDays(List<Integer> inputWorkDays, String presetType) {
List<Integer> presetDays = switch (presetType) {
case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5);
case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6);
default -> inputWorkDays;
};
Set<Integer> normalized = new LinkedHashSet<>();
for (Integer day : presetDays == null ? List.<Integer>of() : presetDays) {
if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) {
normalized.add(day);
}
}
if (normalized.isEmpty()) {
throw new RuntimeException("请至少选择一个工作日");
}
return normalized.stream().sorted().toList();
}
private String encodeWorkDays(List<Integer> workDays) {
return workDays.stream()
.sorted()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
private List<Integer> decodeWorkDays(String workDays) {
if (workDays == null || workDays.isBlank()) {
return new ArrayList<>();
}
return List.of(workDays.split(",")).stream()
.map(String::trim)
.filter(value -> !value.isBlank())
.map(Integer::valueOf)
.sorted()
.toList();
}
private LocalTime presetStartTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(9, 0);
}
return LocalTime.of(10, 0);
}
private LocalTime presetEndTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(17, 0);
}
return LocalTime.of(22, 0);
}
private void validateTimeRange(LocalTime startTime, LocalTime endTime) {
if (startTime == null || endTime == null || !startTime.isBefore(endTime)) {
throw new RuntimeException("排班开始时间必须早于结束时间");
}
}
private String trimText(String value) {
return value == null ? null : value.trim();
}
private String exceptionRemark(ArtistScheduleExceptionDO exception) {
if (exception.getRemark() != null && !exception.getRemark().isBlank()) {
return exception.getRemark();
}
return "例外排班:" + exception.getExceptionType();
}
private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes,
Integer capacity, String remark) {
}
}
@@ -1,20 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
private LocalDateTime createTime;
}
@@ -1,11 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.util.List;
@Data
public class ArtistScheduleRuleSettingVO {
private ArtistScheduleRuleVO rule;
private List<ArtistScheduleExceptionVO> exceptions;
}
@@ -1,21 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleVO {
private Long id;
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -1,22 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -1,12 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryAdjustDTO {
private String changeType;
private BigDecimal changeQuantity;
private String remark;
}
@@ -1,16 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryItemDTO {
private Long shopId;
private String category;
private String itemName;
private String unit;
private BigDecimal stockQuantity;
private BigDecimal warningThreshold;
private Integer status;
}
@@ -1,33 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_inventory_item")
public class InventoryItemDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("category")
private String category;
@TableField("item_name")
private String itemName;
@TableField("unit")
private String unit;
@TableField("stock_quantity")
private BigDecimal stockQuantity;
@TableField("warning_threshold")
private BigDecimal warningThreshold;
@TableField("status")
private Integer status;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,31 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_inventory_record")
public class InventoryRecordDO extends BaseEntity {
@TableField("inventory_item_id")
private Long inventoryItemId;
@TableField("shop_id")
private Long shopId;
@TableField("change_type")
private String changeType;
@TableField("change_quantity")
private BigDecimal changeQuantity;
@TableField("before_quantity")
private BigDecimal beforeQuantity;
@TableField("after_quantity")
private BigDecimal afterQuantity;
@TableField("operator_id")
private Long operatorId;
@TableField("remark")
private String remark;
}
@@ -1,9 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface InventoryItemMapper extends BaseMapper<InventoryItemDO> {
}
@@ -1,9 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface InventoryRecordMapper extends BaseMapper<InventoryRecordDO> {
}
@@ -1,14 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.service;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO;
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
public interface InventoryService {
InventoryItemVO saveItem(InventoryItemDTO dto);
InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto);
PageResultVO<InventoryItemVO> listItems(Long shopId, Integer page, Integer size);
}
@@ -1,99 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryAdjustDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.InventoryItemDTO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.entity.InventoryRecordDO;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.mapper.InventoryRecordMapper;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.service.InventoryService;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.vo.InventoryItemVO;
import com.xiaowang.jayucloud.artlist.core.common.vo.PageResultVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
@RequiredArgsConstructor
public class InventoryServiceImpl implements InventoryService {
private final InventoryItemMapper inventoryItemMapper;
private final InventoryRecordMapper inventoryRecordMapper;
@Override
@Transactional
public InventoryItemVO saveItem(InventoryItemDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getItemName() == null || dto.getItemName().isBlank()) {
throw new RuntimeException("库存物料信息不完整");
}
InventoryItemDO item = new InventoryItemDO();
BeanUtils.copyProperties(dto, item);
item.setStockQuantity(dto.getStockQuantity() == null ? BigDecimal.ZERO : dto.getStockQuantity());
item.setWarningThreshold(dto.getWarningThreshold() == null ? BigDecimal.ZERO : dto.getWarningThreshold());
item.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
item.setIsDelete(0);
inventoryItemMapper.insert(item);
return toVO(item);
}
@Override
@Transactional
public InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto) {
InventoryItemDO item = inventoryItemMapper.selectById(itemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("库存物料不存在");
}
BigDecimal before = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity();
BigDecimal delta = dto == null || dto.getChangeQuantity() == null ? BigDecimal.ZERO : dto.getChangeQuantity();
BigDecimal after = before.add(delta);
if (after.compareTo(BigDecimal.ZERO) < 0) {
throw new RuntimeException("库存不能小于 0");
}
item.setStockQuantity(after);
inventoryItemMapper.updateById(item);
InventoryRecordDO record = new InventoryRecordDO();
record.setInventoryItemId(item.getId());
record.setShopId(item.getShopId());
record.setChangeType(dto == null ? null : dto.getChangeType());
record.setChangeQuantity(delta);
record.setBeforeQuantity(before);
record.setAfterQuantity(after);
record.setOperatorId(operatorId);
record.setRemark(dto == null ? null : dto.getRemark());
inventoryRecordMapper.insert(record);
return toVO(item);
}
@Override
public PageResultVO<InventoryItemVO> listItems(Long shopId, Integer page, Integer size) {
int current = page == null || page < 1 ? 1 : page;
int pageSize = size == null || size < 1 ? 10 : size;
LambdaQueryWrapper<InventoryItemDO> wrapper = new LambdaQueryWrapper<InventoryItemDO>()
.eq(InventoryItemDO::getIsDelete, 0)
.orderByDesc(InventoryItemDO::getCreateTime);
if (shopId != null) {
wrapper.eq(InventoryItemDO::getShopId, shopId);
}
Page<InventoryItemDO> result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper);
PageResultVO<InventoryItemVO> vo = new PageResultVO<>();
vo.setList(result.getRecords().stream().map(this::toVO).toList());
vo.setTotal(result.getTotal());
vo.setPage(current);
vo.setSize(pageSize);
return vo;
}
private InventoryItemVO toVO(InventoryItemDO item) {
InventoryItemVO vo = new InventoryItemVO();
BeanUtils.copyProperties(item, vo);
BigDecimal stock = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity();
BigDecimal warning = item.getWarningThreshold() == null ? BigDecimal.ZERO : item.getWarningThreshold();
vo.setWarning(stock.compareTo(warning) <= 0);
return vo;
}
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.inventory.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class InventoryItemVO {
private Long id;
private Long shopId;
private String category;
private String itemName;
private String unit;
private BigDecimal stockQuantity;
private BigDecimal warningThreshold;
private Boolean warning;
private Integer status;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.manager.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
@Data
public class ManagerCustomerCreateDTO {
@NotBlank(message = "客户姓名不能为空")
private String nickname;
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
}
@@ -23,10 +23,4 @@ public class PaymentController {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.prepareOrderPayment(userId, orderId));
}
@PostMapping("/order/{orderId}/mock-success")
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
}
}
@@ -6,7 +6,5 @@ import com.xiaowang.jayucloud.artlist.core.modules.payment.vo.RefundOrderVO;
public interface PaymentService {
PaymentOrderVO prepareOrderPayment(Long userId, Long orderId);
PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark);
RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark);
}
@@ -60,34 +60,6 @@ public class PaymentServiceImpl implements PaymentService {
return toVO(payment);
}
@Override
@Transactional
public PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark) {
OrderDO order = requirePayableOrder(null, orderId);
PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId);
if (payment == null) {
prepareOrderPayment(order.getUserId(), orderId);
payment = paymentOrderMapper.selectLatestByOrderId(orderId);
}
if (payment == null) {
throw new RuntimeException("支付单创建失败");
}
payment.setStatus(STATUS_PAID);
payment.setPaidAmount(payment.getPayAmount());
payment.setPayTime(LocalDateTime.now());
payment.setOperatorId(operatorId);
payment.setRemark(remark);
paymentOrderMapper.updateById(payment);
order.setPaymentStatus(STATUS_PAID);
order.setPaidAmount(payment.getPayAmount());
order.setPayTime(payment.getPayTime());
order.setPaymentMethod(payment.getChannel());
order.setPaymentOrderNo(payment.getPayNo());
orderMapper.updateById(order);
return toVO(payment);
}
@Override
@Transactional
public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) {
@@ -1,28 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class PlanningAppointmentCreateDTO {
private Long customerUserId;
private String customerName;
private String phone;
private Long productId;
private Integer quantity;
private Long artistId;
private String appointmentDate;
private String appointmentTime;
private String appointmentStartTime;
private Integer durationMinutes;
private String manualProductTitle;
private BigDecimal manualProductPrice;
private String manualProductDescription;
private String manualProductTags;
private String manualProductTargetAudience;
private String manualProductPrecautions;
private String manualProductImageFileIds;
private String remark;
private String clientRequestId;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
@Data
public class PlanningAppointmentMoveDTO {
private Long artistId;
private String appointmentDate;
private String appointmentTime;
private String appointmentStartTime;
private Integer durationMinutes;
private String clientRequestId;
}
@@ -1,8 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.dto;
import lombok.Data;
@Data
public class PlanningAppointmentStatusDTO {
private Integer status;
}
@@ -1,22 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.service;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningCalendarVO;
import java.time.LocalDate;
public interface PlanningService {
PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId);
PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto);
PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId);
PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto);
Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto);
}
@@ -1,901 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentCreateDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentMoveDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.dto.PlanningAppointmentStatusDTO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.entity.AppointmentReservationDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jayucloud.artlist.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jayucloud.artlist.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.artlist.core.modules.planning.service.AppointmentCapacityService;
import com.xiaowang.jayucloud.artlist.core.modules.order.service.OrderService;
import com.xiaowang.jayucloud.artlist.core.modules.planning.service.PlanningService;
import com.xiaowang.jayucloud.artlist.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.artlist.core.modules.order.support.OrderStatus;
import com.xiaowang.jayucloud.artlist.core.modules.planning.support.PlanningCalendarSupport;
import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistCountVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningArtistVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningCalendarVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningDaySummaryVO;
import com.xiaowang.jayucloud.artlist.core.modules.planning.vo.PlanningScheduleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
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.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PlanningServiceImpl implements PlanningService {
private static final int DEFAULT_SLOT_MINUTES = 30;
private static final int DEFAULT_DURATION_MINUTES = 60;
private static final int MONTH_AVAILABLE_MINUTES = 90;
private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE";
private static final String RESERVATION_CONFIRMED = "CONFIRMED";
private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT";
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW";
private static final List<String> ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED);
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final List<String> ARTIST_COLORS = List.of(
"#7BA7C7", "#8FB89A", "#A894C7", "#D7A86E", "#D98DA5", "#79A6A3", "#B9A16B", "#9BA9C8"
);
private final AdminScopeHelper adminScopeHelper;
private final UserMapper userMapper;
private final NailArtistInfoMapper nailArtistInfoMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final AppointmentReservationMapper appointmentReservationMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final ShopMapper shopMapper;
private final AppointmentCapacityService appointmentCapacityService;
private final OrderService orderService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Override
public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) {
LocalDate start = startDate == null ? LocalDate.now() : startDate;
LocalDate end = endDate == null ? start : endDate;
if (end.isBefore(start)) {
end = start;
}
if (start.plusDays(61).isBefore(end)) {
end = start.plusDays(61);
}
Long shopId = requirePlanningShopId(currentUser);
ShopDO shop = shopMapper.selectById(shopId);
PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours(
shop == null ? null : shop.getBusinessHours()
);
List<PlanningArtistVO> artists = listArtists(shopId, artistId);
List<ArtistScheduleDO> schedules = listSchedules(shopId, start, end, artistId);
List<PlanningScheduleVO> scheduleVos = schedules.stream()
.map(schedule -> toScheduleVO(schedule, artists))
.sorted(Comparator.comparing(PlanningScheduleVO::getDate)
.thenComparing(PlanningScheduleVO::getStartTime)
.thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo)))
.toList();
LocalDateTime rangeStart = start.atStartOfDay();
LocalDateTime rangeEnd = end.plusDays(1).atStartOfDay();
List<PlanningAppointmentVO> appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists);
Map<Long, Long> countByArtist = appointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting()));
artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue()));
PlanningCalendarVO vo = new PlanningCalendarVO();
vo.setBusinessStartTime(businessHours.start().toString());
vo.setBusinessEndTime(businessHours.end().toString());
vo.setSlotMinutes(DEFAULT_SLOT_MINUTES);
vo.setArtists(artists);
vo.setSchedules(scheduleVos);
vo.setAppointments(appointments);
vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments));
return vo;
}
@Override
@Transactional
public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) {
if (dto == null) {
throw new RuntimeException("预约信息不能为空");
}
if (Integer.valueOf(3).equals(currentUser.getType())) {
throw new RuntimeException("美甲师账号只能查看预约,不能新建预约");
}
Long shopId = requirePlanningShopId(currentUser);
requireAppointmentDuration(dto.getDurationMinutes());
ProductDO product = resolveAppointmentProduct(dto, shopId);
UserDO artist = requireActiveArtist(dto.getArtistId(), shopId);
UserDO customer = resolveCustomer(shopId, dto);
int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity();
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity;
LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime());
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
ensureWithinBusinessHours(shopId, startTime, endTime);
BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice();
BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity));
OrderDO order = new OrderDO();
order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString());
order.setUserId(customer.getId());
order.setShopId(shopId);
order.setTotalAmount(amount);
order.setActualAmount(amount);
order.setCustomerRemark(trimToNull(dto.getRemark()));
order.setQuoteStatus("CONFIRMED");
order.setQuoteUserConfirmed(1);
order.setQuoteShopConfirmed(1);
order.setQuoteConfirmedTime(LocalDateTime.now());
order.setPaymentStatus("UNPAID");
order.setPayAmount(amount);
order.setPaidAmount(BigDecimal.ZERO);
order.setStatus(OrderStatus.PENDING_SERVICE.getCode());
order.setIsDelete(0);
orderMapper.insert(order);
OrderItemDO item = new OrderItemDO();
item.setOrderId(order.getId());
item.setProductId(product.getId());
item.setQuantity(quantity);
item.setPrice(unitPrice);
item.setArtistId(artist.getId());
item.setAppointmentTime(startTime);
item.setIsDelete(0);
orderItemMapper.insert(item);
appointmentCapacityService.reserveConfirmedOrThrow(
order.getId(),
item.getId(),
shopId,
artist.getId(),
product.getTitle(),
startTime,
endTime,
trimToNull(dto.getClientRequestId())
);
return getAppointment(currentUser, item.getId());
}
@Override
public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) {
if (orderItemId == null) {
throw new RuntimeException("预约ID不能为空");
}
OrderItemDO item = orderItemMapper.selectById(orderItemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("预约不存在");
}
OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId());
ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId());
AppointmentReservationDO reservation = findActiveReservation(orderItemId);
Map<Long, PlanningArtistVO> artistMap = listArtists(order.getShopId(), item.getArtistId()).stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a));
Map<Long, UserDO> customerMap = loadUsers(Set.of(order.getUserId()));
return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap);
}
@Override
@Transactional
public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) {
if (orderItemId == null || dto == null) {
throw new RuntimeException("改派信息不能为空");
}
OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId);
if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) {
throw new RuntimeException("预约不存在");
}
OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId());
ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId());
Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId();
UserDO artist = requireActiveArtist(targetArtistId, order.getShopId());
int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) *
Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity());
LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime())
? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime())
: item.getAppointmentTime();
if (startTime == null) {
throw new RuntimeException("预约时间不能为空");
}
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
ensureWithinBusinessHours(order.getShopId(), startTime, endTime);
appointmentCapacityService.moveReservationForArtistChange(
order.getId(),
item.getId(),
order.getShopId(),
item.getArtistId(),
artist.getId(),
product.getTitle(),
startTime,
endTime
);
item.setArtistId(artist.getId());
item.setAppointmentTime(startTime);
orderItemMapper.updateById(item);
return getAppointment(currentUser, item.getId());
}
@Override
@Transactional
public Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto) {
if (orderId == null || dto == null || dto.getStatus() == null) {
throw new RuntimeException("预约状态不能为空");
}
OrderDO order = requireAccessibleOrder(currentUser, orderId);
int targetStatus = dto.getStatus();
if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) {
if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode());
}
return true;
}
orderService.processOrder(orderId, targetStatus);
return true;
}
private Long requirePlanningShopId(UserDO currentUser) {
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
if (shopId == null || shopId <= 0) {
throw new RuntimeException("请先选择店铺后再查看规划");
}
return shopId;
}
private List<PlanningArtistVO> listArtists(Long shopId, Long artistId) {
QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
wrapper.eq("shop_id", shopId)
.eq("type", 3)
.eq("is_delete", 0)
.orderByAsc("id");
if (artistId != null && artistId > 0) {
wrapper.eq("id", artistId);
}
List<UserDO> artists = userMapper.selectList(wrapper);
if (artists == null || artists.isEmpty()) {
return List.of();
}
Set<Long> artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new));
Map<Long, NailArtistInfoDO> infoMap = loadArtistInfo(artistIds);
List<PlanningArtistVO> result = new ArrayList<>();
for (int i = 0; i < artists.size(); i++) {
UserDO user = artists.get(i);
NailArtistInfoDO info = infoMap.get(user.getId());
PlanningArtistVO vo = new PlanningArtistVO();
vo.setId(user.getId());
vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1)));
vo.setShortName(PlanningCalendarSupport.shortName(vo.getName()));
vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), ""));
vo.setAvatar(user.getAvatar());
vo.setColor(colorForArtist(user.getId(), i));
vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus());
vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约");
vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString());
vo.setWorkEndTime(info == null || info.getWorkEndTime() == null ? null : info.getWorkEndTime().toString());
vo.setRangeCount(0);
result.add(vo);
}
return result;
}
private Map<Long, NailArtistInfoDO> loadArtistInfo(Set<Long> artistIds) {
if (artistIds == null || artistIds.isEmpty()) {
return Map.of();
}
QueryWrapper<NailArtistInfoDO> wrapper = new QueryWrapper<>();
wrapper.in("user_id", artistIds).eq("is_delete", 0);
return nailArtistInfoMapper.selectList(wrapper).stream()
.collect(Collectors.toMap(NailArtistInfoDO::getUserId, Function.identity(), (a, b) -> a));
}
private List<ArtistScheduleDO> listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) {
QueryWrapper<ArtistScheduleDO> wrapper = new QueryWrapper<>();
wrapper.eq("shop_id", shopId)
.between("work_date", start, end)
.eq("is_delete", 0)
.orderByAsc("work_date")
.orderByAsc("start_time");
if (artistId != null && artistId > 0) {
wrapper.eq("artist_id", artistId);
}
return artistScheduleMapper.selectList(wrapper);
}
private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List<PlanningArtistVO> artists) {
Map<Long, String> artistNames = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a));
PlanningScheduleVO vo = new PlanningScheduleVO();
vo.setId(schedule.getId());
vo.setArtistId(schedule.getArtistId());
vo.setArtistName(artistNames.get(schedule.getArtistId()));
vo.setDate(schedule.getWorkDate() == null ? null : schedule.getWorkDate().toString());
vo.setStartTime(schedule.getStartTime() == null ? null : schedule.getStartTime().toString());
vo.setEndTime(schedule.getEndTime() == null ? null : schedule.getEndTime().toString());
vo.setCapacity(schedule.getCapacity());
vo.setStatus(schedule.getStatus());
vo.setStatusText(Integer.valueOf(1).equals(schedule.getStatus()) ? "可预约" : "请假");
vo.setRemark(schedule.getRemark());
return vo;
}
private List<PlanningAppointmentVO> listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd,
Long artistId, List<PlanningArtistVO> artists) {
QueryWrapper<AppointmentReservationDO> reservationWrapper = new QueryWrapper<>();
reservationWrapper.eq("shop_id", shopId)
.eq("is_delete", 0)
.in("status", ACTIVE_RESERVATION_STATUS)
.lt("appointment_start_time", rangeEnd)
.gt("appointment_end_time", rangeStart)
.orderByAsc("appointment_start_time");
if (artistId != null && artistId > 0) {
reservationWrapper.eq("artist_id", artistId);
}
List<AppointmentReservationDO> reservations = appointmentReservationMapper.selectList(reservationWrapper);
QueryWrapper<OrderItemDO> itemWrapper = new QueryWrapper<>();
itemWrapper.eq("is_delete", 0)
.isNotNull("appointment_time")
.ge("appointment_time", rangeStart)
.lt("appointment_time", rangeEnd)
.orderByAsc("appointment_time");
if (artistId != null && artistId > 0) {
itemWrapper.eq("artist_id", artistId);
}
List<OrderItemDO> fallbackItems = orderItemMapper.selectList(itemWrapper);
return buildAppointmentList(shopId, reservations, fallbackItems, artists);
}
private List<PlanningAppointmentVO> buildAppointmentList(Long shopId, List<AppointmentReservationDO> reservations,
List<OrderItemDO> fallbackItems, List<PlanningArtistVO> artists) {
Set<Long> itemIds = new HashSet<>();
Set<Long> orderIds = new HashSet<>();
for (AppointmentReservationDO reservation : safeList(reservations)) {
if (reservation.getOrderItemId() != null) {
itemIds.add(reservation.getOrderItemId());
}
if (reservation.getOrderId() != null) {
orderIds.add(reservation.getOrderId());
}
}
for (OrderItemDO item : safeList(fallbackItems)) {
if (item.getId() != null) {
itemIds.add(item.getId());
}
if (item.getOrderId() != null) {
orderIds.add(item.getOrderId());
}
}
Map<Long, OrderItemDO> itemMap = loadOrderItems(itemIds);
Map<Long, OrderDO> orderMap = loadOrders(orderIds);
Set<Long> productIds = itemMap.values().stream()
.map(OrderItemDO::getProductId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<Long> customerIds = orderMap.values().stream()
.map(OrderDO::getUserId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<Long, ProductDO> productMap = loadProducts(productIds);
Map<Long, UserDO> customerMap = loadUsers(customerIds);
Map<Long, PlanningArtistVO> artistMap = artists.stream()
.collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a));
List<PlanningAppointmentVO> result = new ArrayList<>();
Set<Long> reservationItemIds = new HashSet<>();
for (AppointmentReservationDO reservation : safeList(reservations)) {
OrderItemDO item = itemMap.get(reservation.getOrderItemId());
OrderDO order = orderMap.get(reservation.getOrderId());
if (!isVisibleOrder(order, shopId)) {
continue;
}
ProductDO product = item == null ? null : productMap.get(item.getProductId());
UserDO customer = customerMap.get(order.getUserId());
result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap));
if (reservation.getOrderItemId() != null) {
reservationItemIds.add(reservation.getOrderItemId());
}
}
for (OrderItemDO item : safeList(fallbackItems)) {
if (item.getId() != null && reservationItemIds.contains(item.getId())) {
continue;
}
OrderDO order = orderMap.get(item.getOrderId());
if (!isVisibleOrder(order, shopId)) {
continue;
}
ProductDO product = productMap.get(item.getProductId());
UserDO customer = customerMap.get(order.getUserId());
result.add(toAppointmentVO(null, item, order, product, customer, artistMap));
}
result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo))
.thenComparing(PlanningAppointmentVO::getArtistName, Comparator.nullsLast(String::compareTo)));
return result;
}
private PlanningAppointmentVO toAppointmentVO(AppointmentReservationDO reservation, OrderItemDO item, OrderDO order,
ProductDO product, UserDO customer, Map<Long, PlanningArtistVO> artistMap) {
LocalDateTime start = reservation == null ? null : reservation.getAppointmentStartTime();
if (start == null && item != null) {
start = item.getAppointmentTime();
}
int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity());
LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime();
if (end == null && start != null) {
end = start.plusMinutes(durationMinutes);
}
Long artistId = reservation != null && reservation.getArtistId() != null
? reservation.getArtistId()
: item == null ? null : item.getArtistId();
PlanningArtistVO artist = artistId == null ? null : artistMap.get(artistId);
PlanningAppointmentVO vo = new PlanningAppointmentVO();
vo.setOrderId(order == null ? null : order.getId());
vo.setOrderNo(order == null ? null : order.getOrderNo());
vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId());
vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId());
vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户"));
vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""));
vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId());
vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle())
? reservation.getProductTitle()
: product == null ? "预约作品" : product.getTitle());
vo.setArtistId(artistId);
vo.setArtistName(artist == null ? "未分配" : artist.getName());
vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor());
vo.setDate(start == null ? null : start.toLocalDate().toString());
vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start));
vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end));
vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60);
vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes()));
vo.setStatus(order == null ? null : order.getStatus());
vo.setStatusText(statusText(order == null ? null : order.getStatus()));
String occupancyStatus = resolveOccupancyStatus(reservation, order);
vo.setOccupancyStatus(occupancyStatus);
vo.setCanEdit(canEditAppointment(order, occupancyStatus));
vo.setCanCancel(canCancelAppointment(order, occupancyStatus));
vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus));
vo.setAmount(order == null ? null : order.getActualAmount());
vo.setRemark(order == null ? null : order.getCustomerRemark());
return vo;
}
private List<PlanningDaySummaryVO> buildDaySummaries(LocalDate start, LocalDate end, List<PlanningArtistVO> artists,
List<ArtistScheduleDO> schedules, List<PlanningAppointmentVO> appointments) {
Map<String, List<PlanningAppointmentVO>> appointmentsByDate = appointments.stream()
.filter(appointment -> appointment.getDate() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getDate));
Map<String, List<ArtistScheduleDO>> schedulesByDate = schedules.stream()
.filter(schedule -> schedule.getWorkDate() != null)
.collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString()));
List<PlanningDaySummaryVO> summaries = new ArrayList<>();
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
String date = cursor.toString();
List<PlanningAppointmentVO> dayAppointments = appointmentsByDate.getOrDefault(date, List.of());
Map<Long, Long> countByArtist = dayAppointments.stream()
.filter(appointment -> appointment.getArtistId() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting()));
List<ArtistScheduleDO> daySchedules = schedulesByDate.getOrDefault(date, List.of());
Map<Long, ArtistScheduleDO> scheduleByArtist = daySchedules.stream()
.collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a));
List<PlanningArtistCountVO> artistCounts = new ArrayList<>();
int workingArtistCount = 0;
int fullWorkingArtistCount = 0;
for (PlanningArtistVO artist : artists) {
int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue();
ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId());
List<PlanningAppointmentVO> artistAppointments = dayAppointments.stream()
.filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId()))
.toList();
String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments);
if (!"rest".equals(artistStatus)) {
workingArtistCount++;
if ("full".equals(artistStatus)) {
fullWorkingArtistCount++;
}
}
PlanningArtistCountVO countVO = new PlanningArtistCountVO();
countVO.setArtistId(artist.getId());
countVO.setArtistName(artist.getName());
countVO.setShortName(artist.getShortName());
countVO.setColor(artist.getColor());
countVO.setCount(count);
countVO.setStatus(artistStatus);
artistCounts.add(countVO);
}
int total = dayAppointments.size();
boolean hasWorkingSchedule = workingArtistCount > 0;
boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount;
PlanningDaySummaryVO summary = new PlanningDaySummaryVO();
summary.setDate(date);
summary.setTotalCount(total);
summary.setArtistCounts(artistCounts);
summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull));
summaries.add(summary);
cursor = cursor.plusDays(1);
}
return summaries;
}
private String resolveArtistDayStatus(PlanningArtistVO artist, ArtistScheduleDO schedule, List<PlanningAppointmentVO> appointments) {
if (schedule != null && !Integer.valueOf(1).equals(schedule.getStatus())) {
return "rest";
}
if (schedule == null || Integer.valueOf(0).equals(artist.getStatus())) {
return "rest";
}
if (hasContinuousFreeWindow(schedule, appointments, MONTH_AVAILABLE_MINUTES)) {
return appointments.isEmpty() ? "free" : "working";
}
return "full";
}
private boolean hasContinuousFreeWindow(ArtistScheduleDO schedule, List<PlanningAppointmentVO> appointments, int requiredMinutes) {
if (schedule == null || schedule.getStartTime() == null || schedule.getEndTime() == null || requiredMinutes <= 0) {
return false;
}
int startMinute = schedule.getStartTime().toSecondOfDay() / 60;
int endMinute = schedule.getEndTime().toSecondOfDay() / 60;
if (endMinute - startMinute < requiredMinutes) {
return false;
}
int cursor = startMinute;
List<TimeRange> ranges = appointments.stream()
.map(this::toTimeRange)
.filter(Objects::nonNull)
.filter(range -> range.endMinute() > startMinute && range.startMinute() < endMinute)
.map(range -> new TimeRange(Math.max(range.startMinute(), startMinute), Math.min(range.endMinute(), endMinute)))
.sorted(Comparator.comparing(TimeRange::startMinute).thenComparing(TimeRange::endMinute))
.toList();
for (TimeRange range : ranges) {
if (range.startMinute() - cursor >= requiredMinutes) {
return true;
}
cursor = Math.max(cursor, range.endMinute());
}
return endMinute - cursor >= requiredMinutes;
}
private TimeRange toTimeRange(PlanningAppointmentVO appointment) {
if (appointment == null) {
return null;
}
Integer startMinute = appointment.getStartMinute();
Integer durationMinutes = appointment.getDurationMinutes();
if (startMinute == null || durationMinutes == null || durationMinutes <= 0) {
return null;
}
return new TimeRange(startMinute, startMinute + durationMinutes);
}
private record TimeRange(int startMinute, int endMinute) {
}
private ProductDO requireActiveProduct(Long productId, Long shopId) {
if (productId == null) {
throw new RuntimeException("请选择预约作品");
}
ProductDO product = productMapper.selectById(productId);
if (product == null || Integer.valueOf(1).equals(product.getIsDelete()) || !shopId.equals(product.getShopId())) {
throw new RuntimeException("预约作品不存在或不属于当前店铺");
}
return product;
}
private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
if (dto.getProductId() != null) {
return requireActiveProduct(dto.getProductId(), shopId);
}
return createManualAppointmentProduct(dto, shopId);
}
private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) {
String title = trimToNull(dto.getManualProductTitle());
if (!hasText(title)) {
throw new RuntimeException("请选择预约作品或填写手动作品名称");
}
BigDecimal price = dto.getManualProductPrice();
if (price == null || price.compareTo(BigDecimal.ZERO) < 0) {
throw new RuntimeException("手动作品价格不能小于0");
}
int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes());
ProductDO product = new ProductDO();
product.setShopId(shopId);
product.setTitle(title);
product.setDescription(trimToNull(dto.getManualProductDescription()));
product.setTags(trimToNull(dto.getManualProductTags()));
product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience()));
product.setPrecautions(trimToNull(dto.getManualProductPrecautions()));
product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds()));
product.setPrice(price);
product.setLikeCount(0);
product.setCollectCount(0);
product.setApproximateDuration(durationMinutes + "分钟");
product.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId()));
product.setFrontVisible(0);
product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT);
product.setIsDelete(0);
productMapper.insert(product);
return product;
}
private int requireAppointmentDuration(Integer durationMinutes) {
if (durationMinutes == null || durationMinutes <= 0) {
throw new RuntimeException("预约时长不能为空且必须大于0分钟");
}
return durationMinutes;
}
private UserDO requireActiveArtist(Long artistId, Long shopId) {
if (artistId == null) {
throw new RuntimeException("请选择美甲师");
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())
|| !Integer.valueOf(3).equals(artist.getType()) || !shopId.equals(artist.getShopId())) {
throw new RuntimeException("美甲师不存在或不属于当前店铺");
}
return artist;
}
private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) {
if (dto.getCustomerUserId() != null) {
UserDO customer = userMapper.selectById(dto.getCustomerUserId());
if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) {
throw new RuntimeException("客户不存在");
}
return customer;
}
if (!hasText(dto.getPhone())) {
throw new RuntimeException("客户手机号不能为空");
}
QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
wrapper.eq("is_delete", 0)
.and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone()))
.last("LIMIT 1");
UserDO existing = userMapper.selectOne(wrapper);
if (existing != null) {
return existing;
}
UserDO customer = new UserDO();
customer.setShopId(shopId);
customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone()));
customer.setPhone(dto.getPhone());
customer.setContactPhone(dto.getPhone());
customer.setAccount(dto.getPhone());
customer.setPassword(ENCODED_UNSET_PASSWORD);
customer.setType(0);
customer.setStatus(1);
customer.setIsDelete(0);
userMapper.insert(customer);
return customer;
}
private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) {
OrderDO order = orderMapper.selectById(orderId);
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("订单不存在");
}
adminScopeHelper.ensureShopAccessible(currentUser, order.getShopId(), "无权访问其他店铺预约");
return order;
}
private AppointmentReservationDO findActiveReservation(Long orderItemId) {
QueryWrapper<AppointmentReservationDO> wrapper = new QueryWrapper<>();
wrapper.eq("order_item_id", orderItemId)
.eq("is_delete", 0)
.in("status", ACTIVE_RESERVATION_STATUS)
.orderByDesc("id")
.last("LIMIT 1");
return appointmentReservationMapper.selectOne(wrapper);
}
private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) {
ShopDO shop = shopMapper.selectById(shopId);
PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours());
LocalTime start = startTime.toLocalTime();
LocalTime end = endTime.toLocalTime();
if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) {
throw new RuntimeException("预约时间超出店铺营业时间");
}
}
private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) {
if (hasText(appointmentStartTime)) {
String normalized = appointmentStartTime.trim().replace('T', ' ');
if (normalized.length() == 16) {
normalized = normalized + ":00";
}
try {
return LocalDateTime.parse(normalized, DATE_TIME_FORMATTER);
} catch (DateTimeParseException ignored) {
return LocalDateTime.parse(appointmentStartTime.trim());
}
}
if (!hasText(appointmentDate) || !hasText(appointmentTime)) {
throw new RuntimeException("请选择预约日期和时间");
}
LocalDate date = LocalDate.parse(appointmentDate.trim());
LocalTime time = LocalTime.parse(appointmentTime.trim().length() == 5 ? appointmentTime.trim() + ":00" : appointmentTime.trim());
return LocalDateTime.of(date, time);
}
private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) {
if (overrideMinutes != null && overrideMinutes > 0) {
return overrideMinutes;
}
return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES);
}
private boolean isVisibleOrder(OrderDO order, Long shopId) {
return order != null
&& !Integer.valueOf(1).equals(order.getIsDelete())
&& shopId.equals(order.getShopId())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private Map<Long, OrderItemDO> loadOrderItems(Set<Long> itemIds) {
if (itemIds == null || itemIds.isEmpty()) {
return Map.of();
}
return orderItemMapper.selectBatchIds(itemIds).stream()
.collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, OrderDO> loadOrders(Set<Long> orderIds) {
if (orderIds == null || orderIds.isEmpty()) {
return Map.of();
}
return orderMapper.selectBatchIds(orderIds).stream()
.collect(Collectors.toMap(OrderDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, ProductDO> loadProducts(Set<Long> productIds) {
if (productIds == null || productIds.isEmpty()) {
return Map.of();
}
return productMapper.selectBatchIds(productIds).stream()
.collect(Collectors.toMap(ProductDO::getId, Function.identity(), (a, b) -> a));
}
private Map<Long, UserDO> loadUsers(Set<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return Map.of();
}
return userMapper.selectBatchIds(userIds).stream()
.collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a));
}
private String colorForArtist(Long artistId, int index) {
if (artistId == null) {
return ARTIST_COLORS.get(index % ARTIST_COLORS.size());
}
int colorIndex = Math.abs(artistId.hashCode()) % ARTIST_COLORS.size();
return ARTIST_COLORS.get(colorIndex);
}
private String statusText(Integer status) {
if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(status)) {
return "已确认";
}
if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) {
return "已完成";
}
if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) {
return "已取消";
}
if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) {
return "待确认";
}
return "未知";
}
private String resolveOccupancyStatus(AppointmentReservationDO reservation, OrderDO order) {
if (reservation != null && hasText(reservation.getStatus())) {
return reservation.getStatus();
}
if (order != null && Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) {
return RESERVATION_PENDING_QUOTE;
}
if (order != null && Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
return RESERVATION_CONFIRMED;
}
if (order != null && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) {
return "CANCELLED";
}
if (order != null && Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) {
return "COMPLETED";
}
return "UNKNOWN";
}
private Boolean canEditAppointment(OrderDO order, String occupancyStatus) {
return order != null
&& (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus))
&& !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) {
return order != null
&& (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus))
&& !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())
&& !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus());
}
private String resolveAppointmentConflictReason(String occupancyStatus) {
if (RESERVATION_PENDING_QUOTE.equals(occupancyStatus)) {
return "该时段已有待报价预约占用";
}
if (RESERVATION_CONFIRMED.equals(occupancyStatus)) {
return "该时段已有已确认预约占用";
}
return null;
}
private <T> List<T> safeList(List<T> list) {
return list == null ? List.of() : list;
}
private String firstNonBlank(String... values) {
for (String value : values) {
if (hasText(value)) {
return value.trim();
}
}
return "";
}
private String trimToNull(String value) {
return hasText(value) ? value.trim() : null;
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
}
@@ -1,83 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.support;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class PlanningCalendarSupport {
private static final LocalTime DEFAULT_START = LocalTime.of(10, 0);
private static final LocalTime DEFAULT_END = LocalTime.of(22, 0);
private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)");
private PlanningCalendarSupport() {
}
public static String shortName(String name) {
if (name == null || name.trim().isEmpty()) {
return "?";
}
String normalized = name.trim();
if (normalized.startsWith("小") && normalized.length() > 1) {
return normalized.substring(1, 2);
}
if (normalized.endsWith("老师") && normalized.length() > 2) {
return normalized.substring(0, 1);
}
return normalized.substring(0, 1).toUpperCase();
}
public static BusinessHours parseBusinessHours(String businessHours) {
if (businessHours == null || businessHours.trim().isEmpty()) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
String[] parts = businessHours.trim().split("-");
if (parts.length != 2) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
try {
LocalTime start = LocalTime.parse(parts[0].trim());
LocalTime end = LocalTime.parse(parts[1].trim());
if (!start.isBefore(end)) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
return new BusinessHours(start, end);
} catch (RuntimeException ignored) {
return new BusinessHours(DEFAULT_START, DEFAULT_END);
}
}
public static int parseDurationMinutes(String durationText, int defaultMinutes) {
if (durationText == null || durationText.trim().isEmpty()) {
return defaultMinutes;
}
Matcher matcher = NUMBER_PATTERN.matcher(durationText.trim());
if (!matcher.find()) {
return defaultMinutes;
}
BigDecimal amount = new BigDecimal(matcher.group(1));
if (durationText.contains("小时") || durationText.toLowerCase().contains("hour")) {
amount = amount.multiply(BigDecimal.valueOf(60));
}
int minutes = amount.setScale(0, RoundingMode.HALF_UP).intValue();
return minutes > 0 ? minutes : defaultMinutes;
}
public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) {
if (!hasWorkingSchedule) {
return "rest";
}
if (allWorkingArtistsBusy) {
return "full";
}
if (totalCount <= 0) {
return "free";
}
return "working";
}
public record BusinessHours(LocalTime start, LocalTime end) {
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class PlanningAppointmentVO {
private Long orderId;
private String orderNo;
private Long orderItemId;
private Long customerId;
private String customerName;
private String customerPhone;
private Long productId;
private String productTitle;
private Long artistId;
private String artistName;
private String artistColor;
private String date;
private String startTime;
private String endTime;
private Integer startMinute;
private Integer durationMinutes;
private Integer status;
private String statusText;
private String occupancyStatus;
private Boolean canEdit;
private Boolean canCancel;
private String conflictReason;
private BigDecimal amount;
private String remark;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningArtistCountVO {
private Long artistId;
private String artistName;
private String shortName;
private String color;
private Integer count;
private String status;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningArtistVO {
private Long id;
private String name;
private String shortName;
private String phone;
private String avatar;
private String color;
private Integer status;
private String statusText;
private String workStartTime;
private String workEndTime;
private Integer rangeCount;
}
@@ -1,16 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.util.List;
@Data
public class PlanningCalendarVO {
private String businessStartTime;
private String businessEndTime;
private Integer slotMinutes;
private List<PlanningArtistVO> artists;
private List<PlanningScheduleVO> schedules;
private List<PlanningAppointmentVO> appointments;
private List<PlanningDaySummaryVO> daySummaries;
}
@@ -1,13 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
import java.util.List;
@Data
public class PlanningDaySummaryVO {
private String date;
private Integer totalCount;
private List<PlanningArtistCountVO> artistCounts;
private String dayStatus;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jayucloud.artlist.core.modules.planning.vo;
import lombok.Data;
@Data
public class PlanningScheduleVO {
private Long id;
private Long artistId;
private String artistName;
private String date;
private String startTime;
private String endTime;
private Integer capacity;
private Integer status;
private String statusText;
private String remark;
}
@@ -9,7 +9,6 @@ import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*;
@@ -12,7 +12,6 @@ import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.content.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.file.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.integration.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.inventory.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.marketing.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.message.dto.*;
import com.xiaowang.jayucloud.artlist.core.modules.order.dto.*;
@@ -28,12 +28,12 @@ public class UserSessionService {
* Purpose: SESSION_KEY_PREFIX supports UserSessionService.java by holding or executing the session key prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String SESSION_KEY_PREFIX = "auth:session:";
private static final String SESSION_KEY_PREFIX = "artlist:auth:session:";
/**
* Purpose: USER_SESSION_SET_PREFIX supports UserSessionService.java by holding or executing the user session set prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:";
private static final String USER_SESSION_SET_PREFIX = "artlist:auth:user:sessions:";
/**
* Purpose: stringRedisTemplate supports UserSessionService.java by holding or executing the string redis template business role.