From 9ddc77415c33da214d637edf3d233a41f770e6b7 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Wed, 4 Nov 2026 18:10:45 +0800 Subject: [PATCH] =?UTF-8?q?ArtList=20=E5=BA=95=E5=BA=A7=E4=B8=8E=E5=AE=89?= =?UTF-8?q?=E5=85=A8=EF=BC=9A=E6=8E=A5=E5=85=A5=20Flyway=20=E5=9F=BA?= =?UTF-8?q?=E7=BA=BF=E3=80=81=E4=B8=8B=E7=BA=BF=20mock=20=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E3=80=81Redis=20=E4=BC=9A=E8=AF=9D=E9=9A=94=E7=A6=BB?= =?UTF-8?q?=E5=B9=B6=E6=B8=85=E7=90=86=E6=AD=BB=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JC-ArtList-Core/pom.xml | 9 + .../core/config/MyBatisPlusConfig.java | 1 - .../controller/front/DashboardController.java | 450 ---- .../service/OperationsAnalyticsService.java | 7 - .../analytics/service/WorkbenchService.java | 7 - .../impl/OperationsAnalyticsServiceImpl.java | 66 - .../service/impl/WorkbenchServiceImpl.java | 145 -- .../analytics/vo/DashboardStatsVO.java | 89 - .../analytics/vo/OperationsAnalyticsVO.java | 18 - .../analytics/vo/RecentActivityVO.java | 37 - .../analytics/vo/StoreWorkbenchVO.java | 19 - .../modules/artist/dto/ArtistScheduleDTO.java | 19 - .../dto/ArtistScheduleExceptionDTO.java | 17 - .../artist/dto/ArtistScheduleRuleDTO.java | 18 - .../artist/service/ArtistScheduleService.java | 24 - .../impl/ArtistScheduleServiceImpl.java | 423 --- .../artist/vo/ArtistScheduleExceptionVO.java | 20 - .../vo/ArtistScheduleRuleSettingVO.java | 11 - .../artist/vo/ArtistScheduleRuleVO.java | 21 - .../modules/artist/vo/ArtistScheduleVO.java | 22 - .../inventory/dto/InventoryAdjustDTO.java | 12 - .../inventory/dto/InventoryItemDTO.java | 16 - .../inventory/entity/InventoryItemDO.java | 33 - .../inventory/entity/InventoryRecordDO.java | 31 - .../inventory/mapper/InventoryItemMapper.java | 9 - .../mapper/InventoryRecordMapper.java | 9 - .../inventory/service/InventoryService.java | 14 - .../service/impl/InventoryServiceImpl.java | 99 - .../modules/inventory/vo/InventoryItemVO.java | 18 - .../manager/dto/ManagerCustomerCreateDTO.java | 17 - .../controller/front/PaymentController.java | 6 - .../payment/service/PaymentService.java | 2 - .../service/impl/PaymentServiceImpl.java | 28 - .../dto/PlanningAppointmentCreateDTO.java | 28 - .../dto/PlanningAppointmentMoveDTO.java | 13 - .../dto/PlanningAppointmentStatusDTO.java | 8 - .../planning/service/PlanningService.java | 22 - .../service/impl/PlanningServiceImpl.java | 901 ------- .../support/PlanningCalendarSupport.java | 83 - .../planning/vo/PlanningAppointmentVO.java | 33 - .../planning/vo/PlanningArtistCountVO.java | 13 - .../modules/planning/vo/PlanningArtistVO.java | 18 - .../planning/vo/PlanningCalendarVO.java | 16 - .../planning/vo/PlanningDaySummaryVO.java | 13 - .../planning/vo/PlanningScheduleVO.java | 17 - .../user/controller/front/UserController.java | 1 - .../user/service/impl/UserServiceImpl.java | 1 - .../support/security/UserSessionService.java | 4 +- .../V1__ArtList基线冻结_20261104.sql | 2275 +++++++++++++++++ JC-ArtList-Frontend/src/api/order.ts | 3 - .../src/views/OrderDetailView.vue | 11 - JC-ArtList-Frontend/src/views/OrderView.vue | 14 - JC-ArtList-WeChat/api/payment.js | 8 - JC-ArtList-WeChat/api/vnext.test.js | 10 +- JC-ArtList-WeChat/app.json | 3 - .../pages/artist-calendar/index.js | 76 - .../pages/artist-calendar/index.json | 5 - .../pages/artist-calendar/index.wxml | 37 - .../pages/artist-calendar/index.wxss | 49 - .../pages/artist-orders/index.js | 92 - .../pages/artist-orders/index.json | 5 - .../pages/artist-orders/index.wxml | 47 - .../pages/artist-orders/index.wxss | 70 - .../pages/artist-profile/index.js | 136 - .../pages/artist-profile/index.json | 4 - .../pages/artist-profile/index.wxml | 98 - .../pages/artist-profile/index.wxss | 336 --- JC-ArtList-WeChat/pages/orders/index.js | 17 +- JC-ArtList-WeChat/utils/navigation.js | 8 - .../jayucloud-artlist/DEFAULT_GROUP/core.yaml | 11 + .../DEFAULT_GROUP/infra.yaml | 2 +- 71 files changed, 2301 insertions(+), 3904 deletions(-) delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java delete mode 100644 JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java create mode 100644 JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql delete mode 100644 JC-ArtList-WeChat/pages/artist-calendar/index.js delete mode 100644 JC-ArtList-WeChat/pages/artist-calendar/index.json delete mode 100644 JC-ArtList-WeChat/pages/artist-calendar/index.wxml delete mode 100644 JC-ArtList-WeChat/pages/artist-calendar/index.wxss delete mode 100644 JC-ArtList-WeChat/pages/artist-orders/index.js delete mode 100644 JC-ArtList-WeChat/pages/artist-orders/index.json delete mode 100644 JC-ArtList-WeChat/pages/artist-orders/index.wxml delete mode 100644 JC-ArtList-WeChat/pages/artist-orders/index.wxss delete mode 100644 JC-ArtList-WeChat/pages/artist-profile/index.js delete mode 100644 JC-ArtList-WeChat/pages/artist-profile/index.json delete mode 100644 JC-ArtList-WeChat/pages/artist-profile/index.wxml delete mode 100644 JC-ArtList-WeChat/pages/artist-profile/index.wxss diff --git a/JC-ArtList-Core/pom.xml b/JC-ArtList-Core/pom.xml index 6cf3f2e1..b21a25c6 100644 --- a/JC-ArtList-Core/pom.xml +++ b/JC-ArtList-Core/pom.xml @@ -110,6 +110,15 @@ mysql-connector-j runtime + + + org.flywaydb + flyway-core + + + org.flywaydb + flyway-mysql + com.baomidou mybatis-plus-boot-starter diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java index 59e35b0f..394c1b78 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyBatisPlusConfig.java @@ -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", diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java deleted file mode 100644 index e6884f79..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/controller/front/DashboardController.java +++ /dev/null @@ -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 result consumed by the caller or returned to the frontend - */ - public Result 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() { - }, - () -> buildDashboardStats(currentUser, shopIdScope) - ); - return Result.success(stats); - } - - @GetMapping("/analytics") - @RequirePermission("analytics:view") - public Result 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().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 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 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 listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { - LambdaQueryWrapper 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 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 listOrderIdsByArtist(Long artistId) { - List items = orderItemMapper.selectList(new LambdaQueryWrapper() - .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 result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); - return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - } else { - // 管理员查询所有订单 - java.util.Map 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 result consumed by the caller or returned to the frontend - */ - private List getHotProducts(Long shopId) { - // 通过订单商品表统计每个商品的订单数量,按订单数量排序 - // 使用SQL查询获取商品及其订单数量 - List> productOrderCounts = orderItemMapper.selectMaps( - new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper() - .select("product_id, COUNT(*) as order_count") - .groupBy("product_id") - .orderByDesc("order_count") - .last("LIMIT 5") - ); - - List hotProducts = new ArrayList<>(); - - // 遍历查询结果,获取商品详情 - for (Map 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 wrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - wrapper.eq(ProductDO::getShopId, shopId); - } - wrapper.orderByDesc(ProductDO::getLikeCount) - .last("LIMIT 5"); - List 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 result consumed by the caller or returned to the frontend - */ - private List getRecentActivities(Long shopId) { - List activities = new ArrayList<>(); - - LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - List 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 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 productWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - productWrapper.eq(ProductDO::getShopId, shopId); - } - productWrapper.orderByDesc(ProductDO::getCreateTime) - .last("LIMIT 2"); - List 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 commentWrapper = new LambdaQueryWrapper<>(); - if (shopId != null) { - commentWrapper.eq(CommentDO::getShopId, shopId); - } - commentWrapper.orderByDesc(CommentDO::getCreateTime) - .last("LIMIT 2"); - List 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()); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java deleted file mode 100644 index 2927c955..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/OperationsAnalyticsService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java deleted file mode 100644 index 2be03c97..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/WorkbenchService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java deleted file mode 100644 index 72a022a6..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java +++ /dev/null @@ -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 orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId != null) { - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .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() - .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() - .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() - .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); - vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() - .eq(UserGrowthRecordDO::getSourceType, "REBOOK"))); - vo.setTotalAmount(orders.stream() - .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - return vo; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java deleted file mode 100644 index 7641e43d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/service/impl/WorkbenchServiceImpl.java +++ /dev/null @@ -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 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 scopedOrders(Long shopId, Long artistId) { - List orders = orderMapper.selectList(new LambdaQueryWrapper() - .eq(shopId != null, OrderDO::getShopId, shopId) - .eq(OrderDO::getIsDelete, 0)); - if (artistId == null) { - return orders; - } - Set orderIds = new HashSet<>(); - orderItemMapper.selectList(new LambdaQueryWrapper() - .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() - .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() - .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() - .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() - .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() - .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); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java deleted file mode 100644 index edc5acc4..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/DashboardStatsVO.java +++ /dev/null @@ -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): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List hotProducts; - /** - * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. - */ - private List recentActivities; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java deleted file mode 100644 index e794124c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/OperationsAnalyticsVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java deleted file mode 100644 index bebca37f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/RecentActivityVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java deleted file mode 100644 index 8839fc77..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/analytics/vo/StoreWorkbenchVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java deleted file mode 100644 index 28da0150..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java deleted file mode 100644 index 7f43bf77..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleExceptionDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java deleted file mode 100644 index b4d1f4ce..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/dto/ArtistScheduleRuleDTO.java +++ /dev/null @@ -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 workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java deleted file mode 100644 index 5ad05a63..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/ArtistScheduleService.java +++ /dev/null @@ -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 listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate); - - ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId); - - ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); - - ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java deleted file mode 100644 index d68ee7d1..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java +++ /dev/null @@ -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 listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .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() - .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() - .eq(ArtistScheduleExceptionDO::getShopId, shopId) - .eq(ArtistScheduleExceptionDO::getArtistId, artistId) - .eq(ArtistScheduleExceptionDO::getWorkDate, workDate) - .eq(ArtistScheduleExceptionDO::getIsDelete, 0) - .last("LIMIT 1")); - } - - private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { - return exceptionMapper.selectList(new LambdaQueryWrapper() - .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 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 resolveWorkDays(List inputWorkDays, String presetType) { - List 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 normalized = new LinkedHashSet<>(); - for (Integer day : presetDays == null ? List.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 workDays) { - return workDays.stream() - .sorted() - .map(String::valueOf) - .collect(Collectors.joining(",")); - } - - private List 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) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java deleted file mode 100644 index 2833e5e7..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleExceptionVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java deleted file mode 100644 index fdf82f63..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java +++ /dev/null @@ -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 exceptions; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java deleted file mode 100644 index 89096f7c..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleRuleVO.java +++ /dev/null @@ -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 workDays; - private LocalTime startTime; - private LocalTime endTime; - private Integer status; - private String remark; - private LocalDateTime createTime; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java deleted file mode 100644 index 2e2a9091..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/artist/vo/ArtistScheduleVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java deleted file mode 100644 index 362ba0fd..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryAdjustDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java deleted file mode 100644 index c8213b4f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/dto/InventoryItemDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java deleted file mode 100644 index e6bc0072..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryItemDO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java deleted file mode 100644 index 7e035965..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/entity/InventoryRecordDO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java deleted file mode 100644 index 6fecd165..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryItemMapper.java +++ /dev/null @@ -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 { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java deleted file mode 100644 index 8e9c7022..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/mapper/InventoryRecordMapper.java +++ /dev/null @@ -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 { -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java deleted file mode 100644 index c3b7931e..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/InventoryService.java +++ /dev/null @@ -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 listItems(Long shopId, Integer page, Integer size); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java deleted file mode 100644 index 52f9bcec..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/service/impl/InventoryServiceImpl.java +++ /dev/null @@ -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 listItems(Long shopId, Integer page, Integer size) { - int current = page == null || page < 1 ? 1 : page; - int pageSize = size == null || size < 1 ? 10 : size; - LambdaQueryWrapper wrapper = new LambdaQueryWrapper() - .eq(InventoryItemDO::getIsDelete, 0) - .orderByDesc(InventoryItemDO::getCreateTime); - if (shopId != null) { - wrapper.eq(InventoryItemDO::getShopId, shopId); - } - Page result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper); - PageResultVO 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; - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java deleted file mode 100644 index 79c35fc2..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/inventory/vo/InventoryItemVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java deleted file mode 100644 index 977f35b8..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/manager/dto/ManagerCustomerCreateDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java index 4bdbc341..33a973eb 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/controller/front/PaymentController.java @@ -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 mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java index 87ed325a..76f019f8 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/PaymentService.java @@ -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); } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java index b31d0ad3..6960caff 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/payment/service/impl/PaymentServiceImpl.java @@ -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) { diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java deleted file mode 100644 index adbf959a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java deleted file mode 100644 index c3b5aafb..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentMoveDTO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java deleted file mode 100644 index 12d8b336..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/dto/PlanningAppointmentStatusDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.xiaowang.jayucloud.artlist.core.modules.planning.dto; - -import lombok.Data; - -@Data -public class PlanningAppointmentStatusDTO { - private Integer status; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java deleted file mode 100644 index e1de78fa..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/PlanningService.java +++ /dev/null @@ -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); -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java deleted file mode 100644 index e8e19b27..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/service/impl/PlanningServiceImpl.java +++ /dev/null @@ -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 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 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 artists = listArtists(shopId, artistId); - List schedules = listSchedules(shopId, start, end, artistId); - List 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 appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists); - Map 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 artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - Map 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 listArtists(Long shopId, Long artistId) { - QueryWrapper 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 artists = userMapper.selectList(wrapper); - if (artists == null || artists.isEmpty()) { - return List.of(); - } - Set artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new)); - Map infoMap = loadArtistInfo(artistIds); - List 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 loadArtistInfo(Set artistIds) { - if (artistIds == null || artistIds.isEmpty()) { - return Map.of(); - } - QueryWrapper 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 listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) { - QueryWrapper 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 artists) { - Map 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 listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd, - Long artistId, List artists) { - QueryWrapper 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 reservations = appointmentReservationMapper.selectList(reservationWrapper); - - QueryWrapper 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 fallbackItems = orderItemMapper.selectList(itemWrapper); - - return buildAppointmentList(shopId, reservations, fallbackItems, artists); - } - - private List buildAppointmentList(Long shopId, List reservations, - List fallbackItems, List artists) { - Set itemIds = new HashSet<>(); - Set 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 itemMap = loadOrderItems(itemIds); - Map orderMap = loadOrders(orderIds); - Set productIds = itemMap.values().stream() - .map(OrderItemDO::getProductId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Set customerIds = orderMap.values().stream() - .map(OrderDO::getUserId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - Map productMap = loadProducts(productIds); - Map customerMap = loadUsers(customerIds); - Map artistMap = artists.stream() - .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - - List result = new ArrayList<>(); - Set 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 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 buildDaySummaries(LocalDate start, LocalDate end, List artists, - List schedules, List appointments) { - Map> appointmentsByDate = appointments.stream() - .filter(appointment -> appointment.getDate() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); - Map> schedulesByDate = schedules.stream() - .filter(schedule -> schedule.getWorkDate() != null) - .collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString())); - - List summaries = new ArrayList<>(); - LocalDate cursor = start; - while (!cursor.isAfter(end)) { - String date = cursor.toString(); - List dayAppointments = appointmentsByDate.getOrDefault(date, List.of()); - Map countByArtist = dayAppointments.stream() - .filter(appointment -> appointment.getArtistId() != null) - .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); - List daySchedules = schedulesByDate.getOrDefault(date, List.of()); - Map scheduleByArtist = daySchedules.stream() - .collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a)); - - List 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 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 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 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 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 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 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 loadOrderItems(Set 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 loadOrders(Set 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 loadProducts(Set 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 loadUsers(Set 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 List safeList(List 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(); - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java deleted file mode 100644 index 4301d134..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/support/PlanningCalendarSupport.java +++ /dev/null @@ -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) { - } -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java deleted file mode 100644 index f5186a2a..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningAppointmentVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java deleted file mode 100644 index 8f20d1e5..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistCountVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java deleted file mode 100644 index 5b64ebc9..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningArtistVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java deleted file mode 100644 index a91048ff..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningCalendarVO.java +++ /dev/null @@ -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 artists; - private List schedules; - private List appointments; - private List daySummaries; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java deleted file mode 100644 index ca253a1f..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningDaySummaryVO.java +++ /dev/null @@ -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 artistCounts; - private String dayStatus; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java deleted file mode 100644 index 924cb55d..00000000 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/planning/vo/PlanningScheduleVO.java +++ /dev/null @@ -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; -} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java index c5feab86..1c5cbacf 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java @@ -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.*; diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java index 18d98347..52695f45 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java @@ -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.*; diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java index 70c3feae..9afbc2b8 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/UserSessionService.java @@ -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. diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql new file mode 100644 index 00000000..94e1ed7d --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V1__ArtList基线冻结_20261104.sql @@ -0,0 +1,2275 @@ +-- ============================================================ +-- ArtList 基线冻结(Flyway V1) +-- 来源:docs/scripts/sql/init/jayucloud-artlist.sql +-- +-- 语义: +-- 1. 空库首次初始化:Flyway 从 V1 开始执行,建立全部基础表、索引与种子数据。 +-- 2. 已存在业务数据的库:由 spring.flyway.baseline-on-migrate=true + +-- baseline-version=1 自动 baseline 到版本 1,只执行 V2 及以后的迁移, +-- 不会重放本文件。 +-- 3. 本文件本身可安全重放:建表使用 IF NOT EXISTS,索引经存储过程幂等创建, +-- 种子数据使用 ON DUPLICATE KEY UPDATE / WHERE NOT EXISTS。 +-- +-- 规范化处理(相对初始化脚本): +-- - 移除 CREATE DATABASE / USE,库名由 Flyway schemas 配置决定; +-- - 建表统一 CREATE TABLE IF NOT EXISTS; +-- - 独立 CREATE INDEX / CREATE UNIQUE INDEX 改为 sp_add_index_if_not_exists / +-- sp_add_unique_index_if_not_exists 调用,保留原索引名、表名与列顺序, +-- 丢弃索引 COMMENT(MySQL 索引注释仅为元数据); +-- - 删除重复 DDL:t_order_artist_review、t_order_artist_change_request 各只保留一份; +-- - 修复原脚本中孤立字符导致的语法错误('索引';s); +-- - 不包含手机号加密、订单镜像字段等业务改造,后续按版本增量迁移。 +-- ============================================================ + +-- 幂等辅助存储过程(建表/索引重放时复用) +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_change_time', '(change_time)'); + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +CALL sp_add_index_if_not_exists('t_cart', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +CALL sp_add_index_if_not_exists('t_comment', 'idx_parent_comment_id', '(parent_comment_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_product_id', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_comment', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_status', '(status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +CALL sp_add_index_if_not_exists('t_coupon_tag', 'idx_coupon_id', '(coupon_id)'); + +CALL sp_add_index_if_not_exists('t_coupon_tag', 'idx_tag_id', '(tag_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +CALL sp_add_index_if_not_exists('t_effect_diagram', 'idx_product_id', '(product_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +CALL sp_add_index_if_not_exists('t_login_identity', 'idx_login_method', '(login_method)'); + +CALL sp_add_index_if_not_exists('t_login_identity', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +CALL sp_add_index_if_not_exists('t_wechat_mini_binding', 'idx_wechat_mini_unionid', '(unionid)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_user_id', '(user_id)'); + +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(participate_production, status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(backup_upload_status, primary_upload_status, status)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned not null comment '关联用户表主键', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +CALL sp_add_index_if_not_exists('t_order', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_order', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +CALL sp_add_index_if_not_exists('t_order_item', 'idx_order_id', '(order_id)'); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(order_item_id, is_delete)'); + +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(customer_id, status, create_time)'); + +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(artist_id, status)'); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(customer_id, status, create_time)'); + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(from_artist_id, to_artist_id, status)'); + +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(shop_id, status, create_time)'); + +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(pending_key)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +CALL sp_add_index_if_not_exists('t_product', 'idx_price', '(price)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_tags', '(tags)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_title', '(title)'); + +CALL sp_add_index_if_not_exists('t_product', 'idx_t_product_front_visible', '(shop_id, front_visible, source_type)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +CALL sp_add_index_if_not_exists('t_product_like', 'idx_product_id_like', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_product_like', 'idx_user_id_like', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_shop_name', '(shop_name)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(50) not null comment '用户账号(登录用)', + phone varchar(50) null comment '手机号', + contact_phone varchar(50) null comment '联系电话', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) not null comment '用户密码(加密存储)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_account + unique (account) comment '用户账号唯一索引' +) + comment '系统用户信息表'; + +CALL sp_add_index_if_not_exists('t_user', 'idx_email', '(email)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_phone', '(phone)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_shop_id', '(shop_id)'); + +CALL sp_add_index_if_not_exists('t_user', 'idx_type', '(type)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +CALL sp_add_index_if_not_exists('t_user_coupon', 'idx_status', '(status)'); + +CALL sp_add_index_if_not_exists('t_user_coupon', 'idx_user_id', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +CALL sp_add_index_if_not_exists('t_user_permission', 'idx_permission_id', '(permission_id)'); + +CALL sp_add_index_if_not_exists('t_user_permission', 'idx_user_id', '(user_id)'); + +CREATE TABLE IF NOT EXISTS t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +CALL sp_add_index_if_not_exists('t_system_message', 'idx_t_system_message_publish_time', '(publish_time)'); + +CALL sp_add_index_if_not_exists('t_system_message', 'idx_t_system_message_target', '(target_type, status)'); + +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(idempotency_key)'); + +CREATE TABLE IF NOT EXISTS t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +CALL sp_add_index_if_not_exists('t_system_message_user_state', 'idx_t_system_message_user_state_user', '(user_id, read_status, popup_shown)'); + +CREATE TABLE IF NOT EXISTS t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +CALL sp_add_index_if_not_exists('t_announcement', 'idx_t_announcement_target', '(target_type, status)'); + +CALL sp_add_index_if_not_exists('t_announcement', 'idx_t_announcement_sort_time', '(sort_order, publish_time)'); + +CREATE TABLE IF NOT EXISTS t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +CALL sp_add_index_if_not_exists('t_vip_recharge_plan', 'idx_t_vip_recharge_plan_shop_status', '(shop_id, status, sort_order)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_required_vip_level', '(required_vip_level)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_vip_level', '(vip_level)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_sort', '(user_id, sort_order, create_time)'); + +CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_user', '(user_id)'); + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_product_id', '(product_id)'); + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_user_id', '(user_id)'); + +CALL sp_add_index_if_not_exists('t_wishlist', 'idx_t_wishlist_user_group_sort', '(user_id, group_id, sort_order, create_time)'); + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); + +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-artlist' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='JayuCloud ArtList按业务场景投递MessageHub的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136626, 'home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + (313931273555136627, 'dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + (313931273555136628, 'user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + (313931273555136629, 'user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + (313931273555136630, 'user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + (313931273555136631, 'user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + (313931273555136632, 'user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + (313931273555136633, 'user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + (313931273555136634, 'user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + (313931273555136635, 'user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + (313931273555136636, 'user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + (313931273555136637, 'user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + (313931273555136638, 'product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + (313931273555136639, 'product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + (313931273555136640, 'product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + (313931273555136641, 'product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + (313931273555136642, 'product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + (313931273555136643, 'shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + (313931273555136644, 'shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + (313931273555136645, 'shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + (313931273555136646, 'shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + (313931273555136647, 'shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + (313931273555136648, 'permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + (313931273555136649, 'permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + (313931273555136650, 'permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + (313931273555136651, 'permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + (313931273555136652, 'permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + (313931273555136653, 'tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + (313931273555136654, 'tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + (313931273555136655, 'tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + (313931273555136656, 'tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + (313931273555136657, 'tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + (313931273555136658, 'coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + (313931273555136659, 'coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + (313931273555136660, 'coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + (313931273555136661, 'coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + (313931273555136662, 'coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + (313931273555136663, 'comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + (313931273555136664, 'comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + (313931273555136665, 'order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + (313931273555136666, 'order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + (313931273555136667, 'order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + (313931273555136668, 'order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + (313931273555136669, 'nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + (313931273555136670, 'nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + (313931273555136671, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (313931273555136672, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (313931273555136673, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + (313931273555136674, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (313931273555136675, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (313931273555136676, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES (313931273555136677, 'order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$3ZC5HHVK6EYIfkjcU9IHZulGXwNZhy.6LU85HRJC9A.3LHm0IEdMO', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NOT NULL COMMENT '用户ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + device_id varchar(128) NULL COMMENT '设备ID', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + device_id varchar(128) NULL COMMENT '设备ID', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +-- 排班规则与例外 +CREATE TABLE IF NOT EXISTS t_artist_schedule_rule ( + id bigint unsigned NOT NULL COMMENT '排班规则ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', preset_type varchar(32) NOT NULL COMMENT '预设类型', work_days varchar(32) NOT NULL COMMENT '工作星期,1-7逗号分隔', start_time time NOT NULL COMMENT '常规开始时间', end_time time NOT NULL COMMENT '常规结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1启用,0停用', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_rule_artist (shop_id, artist_id, is_delete), KEY idx_artist_schedule_rule_shop_status (shop_id, status, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师常规排班规则表'; +CREATE TABLE IF NOT EXISTS t_artist_schedule_exception ( + id bigint unsigned NOT NULL COMMENT '排班例外ID', shop_id bigint unsigned NOT NULL COMMENT '店铺ID', artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', work_date date NOT NULL COMMENT '例外日期', exception_type varchar(32) NOT NULL COMMENT '例外类型:REST/EXTRA_WORK/CHANGE_SHIFT', start_time time NULL COMMENT '例外开始时间', end_time time NULL COMMENT '例外结束时间', slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟', capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量', remark varchar(255) NULL COMMENT '备注', create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除', PRIMARY KEY (id), UNIQUE KEY uk_artist_schedule_exception_date (shop_id, artist_id, work_date, is_delete), KEY idx_artist_schedule_exception_artist_date (artist_id, work_date, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师排班例外表'; + +-- 历史命名兼容修正:整合已部署库迁移所需的数据修正,空库执行时无副作用。 +START TRANSACTION; +UPDATE t_messagehub_push_config +SET source_system = 'jayucloud-artlist' +WHERE source_system IN ('fingertipdesigner', 'fingertip-designer', 'FingertipDesigner'); +UPDATE t_legal_agreement +SET content = REPLACE(content, 'Fingertip Designer', 'JayuCloud ArtList') +WHERE content LIKE '%Fingertip Designer%'; +ALTER TABLE t_messagehub_push_config +COMMENT = 'JayuCloud ArtList 按业务场景投递 MessageHub 的配置'; +COMMIT; diff --git a/JC-ArtList-Frontend/src/api/order.ts b/JC-ArtList-Frontend/src/api/order.ts index 015c9875..e4a09dae 100644 --- a/JC-ArtList-Frontend/src/api/order.ts +++ b/JC-ArtList-Frontend/src/api/order.ts @@ -158,9 +158,6 @@ export interface GrowthSummaryVO { export const paymentApi = { prepareOrderPayment: async (orderId: IdType): Promise => { return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO - }, - mockSuccess: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO } } diff --git a/JC-ArtList-Frontend/src/views/OrderDetailView.vue b/JC-ArtList-Frontend/src/views/OrderDetailView.vue index 1367717a..5531b08e 100644 --- a/JC-ArtList-Frontend/src/views/OrderDetailView.vue +++ b/JC-ArtList-Frontend/src/views/OrderDetailView.vue @@ -37,7 +37,6 @@ const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status)) const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending' const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID' const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value)) -const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING') const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value))) const timeline = computed(() => { @@ -206,15 +205,6 @@ const preparePayment = async () => { message.success('支付单已准备') } -const mockPay = async () => { - if (!order.value?.id) return - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.value.id) - await loadOrder() - }) - message.success('模拟支付成功') -} - const cancelOrder = () => { if (!order.value?.id) return Modal.confirm({ @@ -358,7 +348,6 @@ onMounted(loadOrder)
准备支付 - 模拟支付 申请售后 取消订单
diff --git a/JC-ArtList-Frontend/src/views/OrderView.vue b/JC-ArtList-Frontend/src/views/OrderView.vue index b765db9c..37a08fad 100644 --- a/JC-ArtList-Frontend/src/views/OrderView.vue +++ b/JC-ArtList-Frontend/src/views/OrderView.vue @@ -201,7 +201,6 @@
- @@ -471,7 +470,6 @@ const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.p const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID' const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order) const canPreparePayment = (order: any) => orderNeedsPayment(order) && orderPaymentStatus(order) !== 'PAYING' -const canMockPay = (order: any) => Number(order.status) === 1 && orderPaymentStatus(order) === 'PAYING' const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && (Number(order.status) === 2 || isOrderPaid(order)) /** @@ -779,18 +777,6 @@ const preparePayment = async (order: any) => { } } -const mockPay = async (order: any) => { - try { - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.id) - await loadOrders() - }) - message.success('支付成功') - } catch (error: any) { - message.error(error?.message || '支付失败') - } -} - const submitQuoteReply = async (order: any) => { const key = quoteOrderKey(order) const remark = String(quoteReplyForms[key] || '').trim() diff --git a/JC-ArtList-WeChat/api/payment.js b/JC-ArtList-WeChat/api/payment.js index b551479f..89caf52d 100644 --- a/JC-ArtList-WeChat/api/payment.js +++ b/JC-ArtList-WeChat/api/payment.js @@ -7,13 +7,5 @@ module.exports = { method: 'POST', data: {} }) - }, - - mockOrderPaymentSuccess(orderId) { - return request({ - url: `/payment/order/${orderId}/mock-success`, - method: 'POST', - data: {} - }) } } diff --git a/JC-ArtList-WeChat/api/vnext.test.js b/JC-ArtList-WeChat/api/vnext.test.js index 95d3a12a..154b78bc 100644 --- a/JC-ArtList-WeChat/api/vnext.test.js +++ b/JC-ArtList-WeChat/api/vnext.test.js @@ -19,7 +19,6 @@ const afterSaleApi = require('./after-sale') const growthApi = require('./growth') paymentApi.prepareOrderPayment(12) -paymentApi.mockOrderPaymentSuccess(12) afterSaleApi.applyAfterSale({ orderId: 12, reason: 'need refund' }) afterSaleApi.getMyAfterSales({ page: 2, size: 5 }) growthApi.getGrowthSummary() @@ -32,19 +31,14 @@ assert.deepStrictEqual(calls[0], { data: {} }) assert.deepStrictEqual(calls[1], { - url: '/payment/order/12/mock-success', - method: 'POST', - data: {} -}) -assert.deepStrictEqual(calls[2], { url: '/after-sale/apply', method: 'POST', data: { orderId: 12, reason: 'need refund' } }) -assert.deepStrictEqual(calls[3], { +assert.deepStrictEqual(calls[2], { url: '/after-sale/my', params: { page: 2, size: 5 } }) -assert.deepStrictEqual(calls[4], { +assert.deepStrictEqual(calls[3], { url: '/growth/summary' }) diff --git a/JC-ArtList-WeChat/app.json b/JC-ArtList-WeChat/app.json index 945da678..64a16f58 100644 --- a/JC-ArtList-WeChat/app.json +++ b/JC-ArtList-WeChat/app.json @@ -7,7 +7,6 @@ "pages/profile/index", "pages/auth/index", "pages/product-detail/index", - "pages/artist-profile/index", "pages/shop-detail/index", "pages/orders/index", "pages/order-detail/index", @@ -15,8 +14,6 @@ "pages/after-sale-apply/index", "pages/service-progress/index", "pages/help/index", - "pages/artist-orders/index", - "pages/artist-calendar/index", "pages/account-settings/index", "pages/password-settings/index", "pages/wishlist/index", diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.js b/JC-ArtList-WeChat/pages/artist-calendar/index.js deleted file mode 100644 index 5d32fb83..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.js +++ /dev/null @@ -1,76 +0,0 @@ -const orderApi = require('../../api/order') -const auth = require('../../utils/auth') -const navigation = require('../../utils/navigation') -const theme = require('../../utils/theme') -const { formatDateTime, formatPrice } = require('../../utils/format') -const { runWithLoading } = require('../../utils/loading') - -function safeList(value) { - return Array.isArray(value) ? value : [] -} - -function formatClock(value) { - return value ? String(value).replace('T', ' ').slice(11, 16) : '--' -} - -function formatAppointment(item) { - return { - ...item, - dayText: String(item.appointmentStartTime || '').slice(5, 10), - timeText: `${formatClock(item.appointmentStartTime)}-${formatClock(item.appointmentEndTime)}`, - amountText: `¥${formatPrice(item.actualAmount || item.totalAmount)}`, - dateTimeText: formatDateTime(item.appointmentStartTime) - } -} - -Page({ - data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), { - loading: false, - isLoggedIn: false, - appointments: [] - }), - - onShow() { - this.loadAppointments() - }, - - handleBack() { - navigation.goBack('/pages/artist-orders/index') - }, - - async loadAppointments() { - const isLoggedIn = auth.isLoggedIn() - this.setData({ isLoggedIn }) - if (!isLoggedIn) { - navigation.openAuth(navigation.getCurrentPageUrl()) - return - } - this.setData({ loading: true }) - try { - const list = safeList(await orderApi.getArtistCalendarRecent(7)) - this.setData({ - appointments: list.map(formatAppointment) - }) - } catch (error) { - wx.showToast({ title: error.message || '预约日历加载失败', icon: 'none' }) - } finally { - this.setData({ loading: false }) - } - }, - - openArtistOrders() { - navigation.navigate('/pages/artist-orders/index') - }, - - async completeOrder(event) { - const orderId = event.currentTarget.dataset.orderId - if (!orderId) return - try { - await runWithLoading(() => orderApi.completeArtistOrder(orderId)) - wx.showToast({ title: '服务已完成', icon: 'none' }) - await this.loadAppointments() - } catch (error) { - wx.showToast({ title: error.message || '完成服务失败', icon: 'none' }) - } - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.json b/JC-ArtList-WeChat/pages/artist-calendar/index.json deleted file mode 100644 index 8632c9b0..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "usingComponents": { - "navigation-bar": "/components/navigation-bar/navigation-bar" - } -} diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.wxml b/JC-ArtList-WeChat/pages/artist-calendar/index.wxml deleted file mode 100644 index 52ab222e..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.wxml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - 未来 7 天 - {{appointments.length}} 个预约 - 按时间查看即将服务的客户与项目 - - 订单列表 - - - - - 正在加载日历 - - - - - - {{item.dayText}} - {{item.timeText}} - - - {{item.customerNickname || '客户'}} · {{item.productTitle}} - {{item.orderStatusText}} · {{item.shopName || '门店'}} - {{item.amountText}} - 完成服务 - - - - - - 未来 7 天暂无预约 - - - diff --git a/JC-ArtList-WeChat/pages/artist-calendar/index.wxss b/JC-ArtList-WeChat/pages/artist-calendar/index.wxss deleted file mode 100644 index 77c57625..00000000 --- a/JC-ArtList-WeChat/pages/artist-calendar/index.wxss +++ /dev/null @@ -1,49 +0,0 @@ -.appointment-card { - display: flex; - gap: 18rpx; - margin-top: 22rpx; - padding: 24rpx; -} - -.day-box { - width: 136rpx; - flex: 0 0 auto; - display: flex; - flex-direction: column; - justify-content: center; - gap: 8rpx; - padding: 20rpx 12rpx; - border-radius: 24rpx; - background: var(--theme-primary-soft); - color: var(--theme-primary); - text-align: center; - font-weight: 800; -} - -.appointment-main { - flex: 1; - min-width: 0; -} - -.appointment-title, -.appointment-line { - display: block; -} - -.appointment-title { - color: var(--text-primary); - font-size: 29rpx; - font-weight: 800; - line-height: 1.45; -} - -.appointment-line { - margin-top: 8rpx; - color: #504444; - font-size: 24rpx; - line-height: 1.6; -} - -.ghost-btn { - margin-top: 16rpx; -} diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.js b/JC-ArtList-WeChat/pages/artist-orders/index.js deleted file mode 100644 index 6142f28b..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.js +++ /dev/null @@ -1,92 +0,0 @@ -const orderApi = require('../../api/order') -const auth = require('../../utils/auth') -const navigation = require('../../utils/navigation') -const theme = require('../../utils/theme') -const { resolveLegacyImage } = require('../../utils/file') -const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format') -const { runWithLoading } = require('../../utils/loading') - -function safeList(value) { - return Array.isArray(value) ? value : [] -} - -async function formatOrder(order) { - return { - ...order, - statusText: getOrderStatusText(order), - statusClass: getOrderStatusClass(order), - amountText: `¥${formatPrice(order && order.actualAmount)}`, - items: await Promise.all(safeList(order && order.items).map(async item => ({ - ...item, - productImageUrl: await resolveLegacyImage(item.productImage), - priceText: `¥${formatPrice(item.price)}`, - appointmentText: formatDateTime(item.appointmentTime) - }))) - } -} - -Page({ - data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), { - loading: false, - isLoggedIn: false, - orders: [], - focusOrderId: '' - }), - - onLoad(options) { - this.setData({ - focusOrderId: (options && options.orderId) || '' - }) - }, - - onShow() { - this.loadOrders() - }, - - handleBack() { - navigation.goBack('/pages/profile/index') - }, - - async loadOrders() { - const isLoggedIn = auth.isLoggedIn() - this.setData({ isLoggedIn }) - if (!isLoggedIn) { - navigation.openAuth(navigation.getCurrentPageUrl()) - return - } - this.setData({ loading: true }) - try { - const list = safeList(await orderApi.getArtistOrders()) - const orders = await Promise.all(list.map(formatOrder)) - this.setData({ orders }) - } catch (error) { - wx.showToast({ title: error.message || '美甲师订单加载失败', icon: 'none' }) - } finally { - this.setData({ loading: false }) - } - }, - - openCalendar() { - navigation.navigate('/pages/artist-calendar/index') - }, - - async completeOrder(event) { - const orderId = event.currentTarget.dataset.orderId - if (!orderId) return - const confirmed = await new Promise(resolve => { - wx.showModal({ - title: '完成服务', - content: '确认这笔订单已经完成服务吗?', - success: res => resolve(Boolean(res.confirm)) - }) - }) - if (!confirmed) return - try { - await runWithLoading(() => orderApi.completeArtistOrder(orderId)) - wx.showToast({ title: '服务已完成', icon: 'none' }) - await this.loadOrders() - } catch (error) { - wx.showToast({ title: error.message || '完成订单失败', icon: 'none' }) - } - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.json b/JC-ArtList-WeChat/pages/artist-orders/index.json deleted file mode 100644 index 8632c9b0..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "usingComponents": { - "navigation-bar": "/components/navigation-bar/navigation-bar" - } -} diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.wxml b/JC-ArtList-WeChat/pages/artist-orders/index.wxml deleted file mode 100644 index 777e3522..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.wxml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - 服务订单 - {{orders.length}} 笔相关订单 - 查看客户预约、项目和服务完成状态 - - 预约日历 - - - - - 正在加载订单 - - - - - - - {{item.orderNo}} - {{item.customerNickname || '客户'}} {{item.customerPhoneMasked || ''}} - - {{item.statusText}} - - - - - {{orderItem.productTitle}} - {{orderItem.priceText}} x {{orderItem.quantity}} - 预约:{{orderItem.appointmentText}} - - - - {{item.amountText}} - 完成服务 - - - - - - 暂无相关订单 - 有客户预约你服务的项目后会出现在这里 - - - diff --git a/JC-ArtList-WeChat/pages/artist-orders/index.wxss b/JC-ArtList-WeChat/pages/artist-orders/index.wxss deleted file mode 100644 index 8e46a19c..00000000 --- a/JC-ArtList-WeChat/pages/artist-orders/index.wxss +++ /dev/null @@ -1,70 +0,0 @@ -.order-card { - margin-top: 22rpx; - padding: 26rpx; -} - -.order-card.focus-target { - border-color: var(--theme-primary); -} - -.order-head, -.order-foot { - display: flex; - align-items: center; - justify-content: space-between; - gap: 18rpx; -} - -.order-no, -.order-line, -.order-amount { - display: block; -} - -.order-no { - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} - -.order-line { - margin-top: 8rpx; - color: #504444; - font-size: 24rpx; - line-height: 1.6; -} - -.item-row { - display: flex; - gap: 18rpx; - margin-top: 22rpx; -} - -.item-thumb { - width: 116rpx; - height: 116rpx; - border-radius: 22rpx; - background: var(--theme-primary-soft); -} - -.item-main { - flex: 1; - min-width: 0; -} - -.item-title { - display: block; - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} - -.order-foot { - margin-top: 24rpx; -} - -.order-amount { - color: var(--text-primary); - font-size: 28rpx; - font-weight: 800; -} diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.js b/JC-ArtList-WeChat/pages/artist-profile/index.js deleted file mode 100644 index 848d8c7b..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.js +++ /dev/null @@ -1,136 +0,0 @@ -const nailArtistApi = require('../../api/nail-artist') -const navigation = require('../../utils/navigation') -const { DEFAULT_PRODUCT_IMAGE } = require('../../utils/config') - -function formatPrice(price) { - const value = Number(price || 0) - return value > 0 ? `¥${value.toFixed(2)}` : '到店确认' -} - -function formatDateTime(value) { - if (!value) { - return '' - } - return String(value).replace('T', ' ').slice(0, 16) -} - -Page({ - data: { - loading: true, - loadError: '', - artistId: '', - profile: null, - works: [], - reviews: [], - availability: [], - heroImage: DEFAULT_PRODUCT_IMAGE, - artistName: '美甲师', - artistDesc: '专注细节与稳定出品', - shopName: '门店待确认', - styleTags: [], - ratingText: '0.0', - serviceCountText: '0', - workTimeText: '到店确认' - }, - - onLoad(options) { - this.setData({ - artistId: options && options.id ? options.id : '' - }) - this.loadArtistProfile() - }, - - async onPullDownRefresh() { - await this.loadArtistProfile() - wx.stopPullDownRefresh() - }, - - async loadArtistProfile() { - if (!this.data.artistId) { - this.setData({ - loading: false, - loadError: '缺少美甲师信息' - }) - return - } - - this.setData({ - loading: true, - loadError: '' - }) - - try { - const [profile, availability, reviews] = await Promise.all([ - nailArtistApi.getPublicProfile(this.data.artistId), - nailArtistApi.getAvailability(this.data.artistId), - nailArtistApi.listReviews(this.data.artistId) - ]) - const works = (profile.works || []).map(work => ({ - ...work, - title: work.title || '美甲作品', - coverImageUrl: work.coverImageUrl || DEFAULT_PRODUCT_IMAGE, - priceText: formatPrice(work.price) - })) - const formattedReviews = (reviews || profile.reviews || []).map(review => ({ - ...review, - customerName: review.customerName || '匿名用户', - content: review.content || '这位用户没有填写文字评价', - submittedAtText: formatDateTime(review.submittedAt), - ratingText: Number(review.rating || 0).toFixed(1) - })) - const start = profile.workStartTime ? String(profile.workStartTime).slice(0, 5) : '' - const end = profile.workEndTime ? String(profile.workEndTime).slice(0, 5) : '' - - this.setData({ - profile, - works, - reviews: formattedReviews, - availability: availability || profile.availability || [], - heroImage: (works.find(work => work.coverImageUrl) || {}).coverImageUrl || DEFAULT_PRODUCT_IMAGE, - artistName: profile.artistName || '美甲师', - artistDesc: profile.identity || profile.signature || '专注细节与稳定出品', - shopName: profile.shopName || '门店待确认', - styleTags: (profile.styleTags || []).filter(Boolean), - ratingText: Number(profile.rating || 0).toFixed(1), - serviceCountText: String(profile.serviceCount || 0), - workTimeText: start && end ? `${start}-${end}` : '到店确认' - }) - } catch (error) { - this.setData({ - loadError: error.message || '美甲师个人页加载失败' - }) - } finally { - this.setData({ - loading: false - }) - } - }, - - handleBack() { - navigation.goBack('/pages/home/index') - }, - - handleRetry() { - this.loadArtistProfile() - }, - - handleOpenShop() { - const profile = this.data.profile - if (!profile || !profile.shopId) { - return - } - wx.navigateTo({ - url: `/pages/shop-detail/index?id=${profile.shopId}` - }) - }, - - handleOpenWork(event) { - const id = event.currentTarget.dataset.id - if (!id) { - return - } - wx.navigateTo({ - url: `/pages/product-detail/index?id=${id}` - }) - } -}) diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.json b/JC-ArtList-WeChat/pages/artist-profile/index.json deleted file mode 100644 index b16ef3e3..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "navigationStyle": "custom", - "usingComponents": {} -} diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.wxml b/JC-ArtList-WeChat/pages/artist-profile/index.wxml deleted file mode 100644 index 8386784f..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.wxml +++ /dev/null @@ -1,98 +0,0 @@ - - - ‹ - {{artistName}} - - - - - 加载中... - - - - 暂时无法查看个人页 - {{loadError}} - 重试 - - - - - - - - - 艺 - - {{artistName}} - {{artistDesc}} - {{shopName}} - - - - - - - 评分 - {{ratingText}} - - - 服务 - {{serviceCountText}} - - - 工时 - {{workTimeText}} - - - - - 擅长风格 - - {{item}} - - 暂未设置风格标签 - - - - 近期可预约 - - - {{item.dateText}} - {{item.timeText}} - - - 近期暂未放出可预约时间 - - - - 作品 - - - - {{item.title}} - {{item.priceText}} - - - 作品正在整理中 - - - - 评价 {{reviews.length}} - - - - - 客 - - {{item.customerName}} - {{item.submittedAtText}} - - {{item.ratingText}} - - {{item.content}} - - - 还没有公开评价 - - - diff --git a/JC-ArtList-WeChat/pages/artist-profile/index.wxss b/JC-ArtList-WeChat/pages/artist-profile/index.wxss deleted file mode 100644 index 5c153ac2..00000000 --- a/JC-ArtList-WeChat/pages/artist-profile/index.wxss +++ /dev/null @@ -1,336 +0,0 @@ -.artist-page { - min-height: 100vh; - background: #f6f7fb; - color: #1f2933; -} - -.page-header { - position: sticky; - top: 0; - z-index: 5; - display: flex; - align-items: center; - justify-content: space-between; - height: 96rpx; - padding: 0 24rpx; - background: rgba(255, 255, 255, 0.95); - border-bottom: 1rpx solid #e6e9ef; -} - -.back-btn, -.header-spacer { - width: 64rpx; - height: 64rpx; - line-height: 58rpx; - text-align: center; - font-size: 48rpx; -} - -.page-title { - flex: 1; - overflow: hidden; - text-align: center; - font-size: 32rpx; - font-weight: 700; - text-overflow: ellipsis; - white-space: nowrap; -} - -.content-scroll { - height: calc(100vh - 96rpx); -} - -.state-box { - display: flex; - min-height: 60vh; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 20rpx; - padding: 40rpx; - color: #65717f; -} - -.state-title { - color: #1f2933; - font-size: 34rpx; - font-weight: 700; -} - -.state-desc { - text-align: center; - line-height: 1.6; -} - -.primary-btn { - padding: 18rpx 36rpx; - color: #fff; - background: var(--theme-primary-action); - border-radius: 12rpx; -} - -.hero { - position: relative; - height: 520rpx; - margin: 20rpx; - overflow: hidden; - background: #222831; - border-radius: 16rpx; -} - -.hero-image, -.hero-mask { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - width: 100%; - height: 100%; -} - -.hero-mask { - background: linear-gradient(180deg, rgba(10, 14, 20, 0.08), rgba(10, 14, 20, 0.72)); -} - -.artist-card { - position: absolute; - right: 28rpx; - bottom: 28rpx; - left: 28rpx; - display: flex; - gap: 22rpx; - align-items: center; - color: #fff; -} - -.avatar { - width: 112rpx; - height: 112rpx; - flex: 0 0 auto; - overflow: hidden; - border: 3rpx solid rgba(255, 255, 255, 0.8); - border-radius: 56rpx; -} - -.placeholder { - display: flex; - align-items: center; - justify-content: center; - background: #d8dde6; - color: #5f6b7a; - font-weight: 700; -} - -.artist-main { - min-width: 0; -} - -.artist-name, -.artist-desc, -.shop-link { - display: block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.artist-name { - font-size: 44rpx; - font-weight: 800; -} - -.artist-desc { - margin-top: 10rpx; - color: rgba(255, 255, 255, 0.88); - font-size: 26rpx; -} - -.shop-link { - max-width: 440rpx; - margin-top: 16rpx; - padding: 12rpx 18rpx; - background: rgba(255, 255, 255, 0.18); - border: 1rpx solid rgba(255, 255, 255, 0.28); - border-radius: 12rpx; -} - -.metrics { - display: grid; - grid-template-columns: repeat(3, 1fr); - gap: 16rpx; - margin: 0 20rpx 20rpx; -} - -.metric-item { - display: flex; - min-height: 132rpx; - flex-direction: column; - justify-content: center; - gap: 10rpx; - padding: 20rpx; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 16rpx; -} - -.metric-item text:first-child { - color: #65717f; - font-size: 24rpx; -} - -.metric-value { - overflow-wrap: anywhere; - font-size: 34rpx; - font-weight: 800; -} - -.section { - margin: 20rpx; - padding: 28rpx; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 16rpx; -} - -.section-head { - margin-bottom: 20rpx; - font-size: 32rpx; - font-weight: 800; -} - -.tag-list { - display: flex; - flex-wrap: wrap; - gap: 14rpx; -} - -.tag { - padding: 10rpx 18rpx; - color: #394554; - background: #eef1f5; - border-radius: 999rpx; -} - -.empty-text { - color: #7b8794; - line-height: 1.6; -} - -.slot-grid, -.work-grid { - display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); - gap: 16rpx; -} - -.slot { - display: flex; - min-height: 104rpx; - flex-direction: column; - justify-content: center; - gap: 8rpx; - padding: 18rpx; - background: #f6f7fb; - border: 1rpx solid #dfe4ea; - border-radius: 14rpx; -} - -.slot text:first-child { - color: #65717f; - font-size: 24rpx; -} - -.slot-time { - font-size: 32rpx; - font-weight: 800; -} - -.work-card { - overflow: hidden; - background: #fff; - border: 1rpx solid #e6e9ef; - border-radius: 14rpx; -} - -.work-card image { - width: 100%; - height: 210rpx; - background: #eef1f5; -} - -.work-title, -.work-price { - display: block; - overflow: hidden; - padding: 0 16rpx; - text-overflow: ellipsis; - white-space: nowrap; -} - -.work-title { - margin-top: 14rpx; - font-weight: 700; -} - -.work-price { - margin: 8rpx 0 16rpx; - color: var(--theme-primary-action); - font-weight: 800; -} - -.review-list { - display: flex; - flex-direction: column; - gap: 18rpx; -} - -.review-card { - padding: 22rpx; - background: #f8fafc; - border: 1rpx solid #e6e9ef; - border-radius: 14rpx; -} - -.review-top { - display: flex; - align-items: center; - gap: 16rpx; -} - -.review-avatar { - width: 72rpx; - height: 72rpx; - border-radius: 36rpx; -} - -.review-meta { - flex: 1; - min-width: 0; -} - -.review-meta text { - display: block; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.review-meta text:last-child { - margin-top: 4rpx; - color: #7b8794; - font-size: 22rpx; -} - -.review-score { - color: var(--theme-primary-action); - font-weight: 800; -} - -.review-content { - display: block; - margin-top: 18rpx; - color: #3f4a56; - line-height: 1.7; - white-space: pre-wrap; -} diff --git a/JC-ArtList-WeChat/pages/orders/index.js b/JC-ArtList-WeChat/pages/orders/index.js index f2a444cd..c92e8e46 100644 --- a/JC-ArtList-WeChat/pages/orders/index.js +++ b/JC-ArtList-WeChat/pages/orders/index.js @@ -862,23 +862,8 @@ Page({ await runWithLoading(() => paymentApi.prepareOrderPayment(orderId), { title: '准备支付' }) - const confirmed = await new Promise(resolve => { - wx.showModal({ - title: '模拟支付', - content: `本次需支付 ${order.paymentInfo.amountText},确认模拟支付成功吗?`, - confirmText: '确认支付', - success: res => resolve(Boolean(res.confirm)), - fail: () => resolve(false) - }) - }) - if (!confirmed) { - return - } - await runWithLoading(() => paymentApi.mockOrderPaymentSuccess(orderId), { - title: '确认支付' - }) wx.showToast({ - title: '支付已确认', + title: '支付单已准备,请完成支付', icon: 'none' }) await this.loadOrders() diff --git a/JC-ArtList-WeChat/utils/navigation.js b/JC-ArtList-WeChat/utils/navigation.js index 46ca891c..8b823d0e 100644 --- a/JC-ArtList-WeChat/utils/navigation.js +++ b/JC-ArtList-WeChat/utils/navigation.js @@ -113,14 +113,6 @@ function normalizeActionPath(value) { return `/pages/help/index${query}` } - if (pathOnly === '/artist-orders') { - return `/pages/artist-orders/index${query}` - } - - if (pathOnly === '/artist-calendar') { - return `/pages/artist-calendar/index${query}` - } - if (pathOnly === '/settings/account') { return `/pages/account-settings/index${query}` } diff --git a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml index f23915fa..8d436cea 100644 --- a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -1,6 +1,17 @@ spring: datasource: url: jdbc:mysql://192.168.5.15:3306/jayucloud_artlist?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + flyway: + enabled: true + locations: classpath:db/migration + schemas: [jayucloud_artlist] + default-schema: jayucloud_artlist + create-schemas: false + baseline-on-migrate: true + baseline-version: 1 + validate-on-migrate: true + clean-disabled: true + out-of-order: false servlet: multipart: max-file-size: 5MB diff --git a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/infra.yaml b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/infra.yaml index c9fdb859..796a415f 100644 --- a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/infra.yaml +++ b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/infra.yaml @@ -2,7 +2,7 @@ spring: redis: host: 192.168.5.15 port: 6379 - database: 0 + database: 1 rabbitmq: addresses: 192.168.5.15:5672 virtual-host: /jayucloud-artlist-dev