diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java index 6b5bec46..b4f21a31 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java @@ -54,10 +54,15 @@ public class WebMvcConfig implements WebMvcConfigurer { "/product/list/**", "/comment/list/product/**", "/api/comment/list/product/**", + "/nail-artist/profile/**", + "/nail-artist/*/availability", + "/nail-artist/*/reviews", "/shop/get/**", + "/shop/trust-profile/**", "/shop/list/public", "/shop/list/simple", "/tag/list/all", + "/tag/list/filter-options", "/file/get-signed-url/**", "/admin/auth/login", "/admin/auth/login-shops/**", diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/NailArtistController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/NailArtistController.java index 25d58f7f..67246b92 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/NailArtistController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/NailArtistController.java @@ -3,6 +3,9 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.service.NailArtistInfoService; +import com.xiaowang.yuminailcore.vo.NailArtistAvailabilityVO; +import com.xiaowang.yuminailcore.vo.NailArtistProfileVO; +import com.xiaowang.yuminailcore.vo.NailArtistReviewVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -42,4 +45,19 @@ public class NailArtistController { NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); return Result.success(nailArtistInfoDTO); } + + @GetMapping("/profile/{artistId}") + public Result getPublicProfile(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getPublicProfile(artistId)); + } + + @GetMapping("/{artistId}/availability") + public Result> getAvailability(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getAvailability(artistId)); + } + + @GetMapping("/{artistId}/reviews") + public Result> listPublicReviews(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.listPublicReviews(artistId)); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java index 6433bcd6..f5e55eed 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java @@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.CheckoutPreviewDTO; import com.xiaowang.yuminailcore.dto.OrderDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO; @@ -11,6 +12,7 @@ import com.xiaowang.yuminailcore.service.OrderService; import com.xiaowang.yuminailcore.service.UserService; import com.xiaowang.yuminailcore.support.SecurityAuditActions; import com.xiaowang.yuminailcore.support.SecurityAuditSupport; +import com.xiaowang.yuminailcore.vo.CheckoutPreviewVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO; import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO; @@ -68,6 +70,12 @@ public class OrderController { return Result.success(orderVO); } + @PostMapping("/checkout-preview") + public Result checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO)); + } + @GetMapping("/list") /** * Load data by the supplied parameter. @@ -349,6 +357,18 @@ public class OrderController { return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType)); } + @GetMapping("/{orderId}/artist-change/requests") + /** + * Purpose: listOrderArtistChangeRequests returns pending and processed artist-change records for one order. + * Usage: call it from order pages to build a timeline after the caller has an authenticated session. + */ + public Result> listOrderArtistChangeRequests(@PathVariable Long orderId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listOrderArtistChangeRequests(orderId, userId, userType)); + } + @PutMapping("/artist-change/{requestId}/approve") @OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") public Result approveArtistChange(@PathVariable Long requestId, diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java index 300d632d..d7b96fc3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java @@ -185,8 +185,9 @@ public class ProductController { @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = false) String keyword, - @RequestParam(required = false) String tag) { - return Result.success(productService.pagePublicProducts(page, size, keyword, tag, resolveOptionalCurrentShopId(request))); + @RequestParam(required = false) String tag, + @RequestParam(required = false) String tagIds) { + return Result.success(productService.pagePublicProducts(page, size, keyword, tag, tagIds, resolveOptionalCurrentShopId(request))); } /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java index 50810546..0a5f3ce1 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java @@ -7,6 +7,7 @@ import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.ShopService; import com.xiaowang.yuminailcore.support.AdminScopeHelper; import com.xiaowang.yuminailcore.vo.ShopSimpleVO; +import com.xiaowang.yuminailcore.vo.ShopTrustProfileVO; import com.xiaowang.yuminailcore.vo.ShopVO; import lombok.Data; import lombok.RequiredArgsConstructor; @@ -118,6 +119,17 @@ public class ShopController { return Result.success(shopVO); } + @GetMapping("/trust-profile/{id}") + /** + * Purpose: getShopTrustProfile returns public confidence signals for a shop detail page. + * Usage: anonymous clients can call this endpoint; phone data remains behind contact-info APIs. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShopTrustProfile(@PathVariable Long id) { + return Result.success(shopService.getShopTrustProfile(id)); + } + @GetMapping("/list/all") @RequirePermission("shop:view") /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java index 4d6a36c4..e9c8aa57 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java @@ -6,6 +6,7 @@ import com.xiaowang.yuminailcore.dto.TagDTO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.TagService; import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.TagFilterGroupVO; import com.xiaowang.yuminailcore.vo.TagVO; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @@ -117,6 +118,15 @@ public class TagController { return Result.success(tagVOs); } + /** + * Purpose: listFilterOptions exposes customer-facing grouped tag filters. + * Usage: call it from public product pages, optionally passing shopId for a shop-scoped filter bar. + */ + @GetMapping("/list/filter-options") + public Result> listFilterOptions(@RequestParam(required = false) Long shopId) { + return Result.success(tagService.listFilterOptions(shopId)); + } + /** * 根据店铺ID查询标签 * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java index d3554d48..bd74389d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java @@ -2,71 +2,99 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.WishlistAddWithGroupDTO; import com.xiaowang.yuminailcore.dto.WishlistDTO; +import com.xiaowang.yuminailcore.dto.WishlistGroupDTO; +import com.xiaowang.yuminailcore.dto.WishlistMoveDTO; import com.xiaowang.yuminailcore.service.WishlistService; import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; +import com.xiaowang.yuminailcore.vo.WishlistGroupVO; +import com.xiaowang.yuminailcore.vo.WishlistInspirationVO; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController @RequestMapping("/wishlist") -/** - * WishlistController 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 WishlistController { @Autowired - /** - * Purpose: wishlistService supports WishlistController.java by holding or executing the wishlist service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ private WishlistService wishlistService; @PostMapping("/add") @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Purpose: addToWishlist supports WishlistController.java by holding or executing the add to wishlist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - Long productId = request.get("productId"); - wishlistService.addToWishlist(userId, productId); - return Result.success("添加到收藏成功"); + wishlistService.addToWishlist(userId, request.get("productId")); + return Result.success("ok"); + } + + @PostMapping("/add-with-group") + @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { + wishlistService.addToWishlist(userId, request); + return Result.success("ok"); } @PostMapping("/remove") @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) - /** - * Purpose: removeFromWishlist supports WishlistController.java by holding or executing the remove from wishlist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { - Long productId = request.get("productId"); - wishlistService.removeFromWishlist(userId, productId); - return Result.success("从收藏中移除成功"); + wishlistService.removeFromWishlist(userId, request.get("productId")); + return Result.success("ok"); } @GetMapping("/check") - /** - * Purpose: checkWishlist supports WishlistController.java by holding or executing the check wishlist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { - boolean isInWishlist = wishlistService.isInWishlist(userId, productId); - return Result.success(isInWishlist); + return Result.success(wishlistService.isInWishlist(userId, productId)); } @GetMapping("/list") - /** - * Purpose: getWishlist supports WishlistController.java by holding or executing the get wishlist business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Result> getWishlist(@RequestAttribute("userId") Long userId) { - List wishlist = wishlistService.getWishlistByUserId(userId); - return Result.success(wishlist); + return Result.success(wishlistService.getWishlistByUserId(userId)); + } + + @GetMapping("/groups") + public Result> listGroups(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.listGroups(userId)); + } + + @PostMapping("/groups") + public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.createGroup(userId, request)); + } + + @PutMapping("/groups/{id}") + public Result updateGroup( + @PathVariable Long id, + @RequestBody WishlistGroupDTO request, + @RequestAttribute("userId") Long userId + ) { + return Result.success(wishlistService.updateGroup(userId, id, request)); + } + + @DeleteMapping("/groups/{id}") + public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.deleteGroup(userId, id)); + } + + @PostMapping("/move") + @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.moveWishlist(userId, request)); + } + + @GetMapping("/inspiration") + public Result getInspiration(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.getInspiration(userId)); } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CheckoutPreviewDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CheckoutPreviewDTO.java new file mode 100644 index 00000000..f219bced --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CheckoutPreviewDTO.java @@ -0,0 +1,27 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 结算预览请求,只做金额和优惠说明,不创建订单。 + */ +@Data +public class CheckoutPreviewDTO { + + /** + * 已选择的优惠选项ID:用户券传用户券ID,VIP自动券传券模板ID。 + */ + private Long couponId; + + /** + * 优惠来源:USER_COUPON、SYSTEM_VIP、NONE。 + */ + private String couponSourceType; + + /** + * 本次预览的商品列表。 + */ + private List items; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ProductDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ProductDTO.java index 4d7c29cd..2f93fc66 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ProductDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ProductDTO.java @@ -29,6 +29,16 @@ public class ProductDTO { */ private String description; + /** + * 适合人群说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String targetAudience; + + /** + * 注意事项说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String precautions; + /** * 图片文件ID集合,多个ID以逗号分隔 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/TagDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/TagDTO.java index db05008a..61a2b621 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/TagDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/TagDTO.java @@ -32,6 +32,30 @@ public class TagDTO { */ private String borderColor; + /** + * Purpose: sceneGroup groups tags into customer-facing scene filters. + * Usage: submit it from admin tag forms; empty values are treated as the default public group. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the short label customers see in filters. + * Usage: submit it from admin forms; empty values fall back to tagName. + */ + private String displayName; + + /** + * Purpose: sortOrder controls this tag's ordering inside its public filter group. + * Usage: lower values are shown first; omit it to use legacy ordering. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible marks whether the tag appears in public filter options. + * Usage: send 1 to show, 0 to hide; omitted values default to visible. + */ + private Integer frontVisible; + /** * 店铺ID */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistAddWithGroupDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistAddWithGroupDTO.java new file mode 100644 index 00000000..c13aa4bf --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistAddWithGroupDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +@Data +public class WishlistAddWithGroupDTO { + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistDTO.java index ffbd5d1d..9ba965ff 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistDTO.java @@ -28,6 +28,14 @@ public class WishlistDTO { */ private Long productId; + private Long groupId; + + private String groupName; + + private String note; + + private Integer sortOrder; + /** * 商品详细信息 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistGroupDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistGroupDTO.java new file mode 100644 index 00000000..1bd9b3ac --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistGroupDTO.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +@Data +public class WishlistGroupDTO { + private String name; + private Integer sortOrder; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistMoveDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistMoveDTO.java new file mode 100644 index 00000000..301234e6 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WishlistMoveDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +@Data +public class WishlistMoveDTO { + private Long wishlistId; + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ProductDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ProductDO.java index 80dd9ca5..2dc08934 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ProductDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ProductDO.java @@ -38,6 +38,18 @@ public class ProductDO extends BaseEntity { @TableField("description") private String description; + /** + * 适合人群说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("target_audience") + private String targetAudience; + + /** + * 注意事项说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("precautions") + private String precautions; + /** * 图片文件ID集合,多个ID以逗号分隔 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/TagDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/TagDO.java index 96c14d85..af51c986 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/TagDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/TagDO.java @@ -41,6 +41,34 @@ public class TagDO extends BaseEntity { @TableField("border_color") private String borderColor; + /** + * Purpose: sceneGroup stores the customer-facing filter group, such as style or occasion. + * Usage: set it from admin tag forms and read it from public filter-option APIs. + */ + @TableField("scene_group") + private String sceneGroup; + + /** + * Purpose: displayName stores the shorter public label shown in scene filters. + * Usage: leave it empty to fall back to tagName in frontend and mini-program filters. + */ + @TableField("display_name") + private String displayName; + + /** + * Purpose: sortOrder controls tag order inside public filter groups. + * Usage: lower numbers appear first; null uses the default legacy ordering. + */ + @TableField("sort_order") + private Integer sortOrder; + + /** + * Purpose: frontVisible decides whether this tag is visible in public scene filters. + * Usage: set to 1 for visible tags and 0 to hide admin-only/internal tags. + */ + @TableField("front_visible") + private Integer frontVisible; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java index d52f19f7..78aaa3d8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java @@ -19,6 +19,15 @@ public class WishlistDO extends BaseEntity { * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private Long productId; + + @TableField("group_id") + private Long groupId; + + @TableField("note") + private String note; + + @TableField("sort_order") + private Integer sortOrder; @TableField("is_delete") /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistGroupDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistGroupDO.java new file mode 100644 index 00000000..d6fd284e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistGroupDO.java @@ -0,0 +1,24 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_wishlist_group") +public class WishlistGroupDO extends BaseEntity { + + @TableField("user_id") + private Long userId; + + @TableField("name") + private String name; + + @TableField("sort_order") + private Integer sortOrder; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java index 259513b2..ed3197d4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java @@ -30,6 +30,9 @@ public interface OrderArtistChangeRequestMapper extends BaseMapper NOW()) ORDER BY create_time DESC, id DESC") List selectPendingByShopId(@Param("shopId") Long shopId); + @Select("SELECT * FROM t_order_artist_change_request WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); + @Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})") int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistGroupMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistGroupMapper.java new file mode 100644 index 00000000..452f0fd1 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistGroupMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.WishlistGroupDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WishlistGroupMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/NailArtistInfoService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/NailArtistInfoService.java index d7fa72ae..92d74b08 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/NailArtistInfoService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/NailArtistInfoService.java @@ -3,6 +3,9 @@ package com.xiaowang.yuminailcore.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; +import com.xiaowang.yuminailcore.vo.NailArtistAvailabilityVO; +import com.xiaowang.yuminailcore.vo.NailArtistProfileVO; +import com.xiaowang.yuminailcore.vo.NailArtistReviewVO; import java.util.List; @@ -42,4 +45,10 @@ public interface NailArtistInfoService extends IService { * @return 美甲师信息列表 */ List getAllAvailableNailArtists(); + + NailArtistProfileVO getPublicProfile(Long artistId); + + List getAvailability(Long artistId); + + List listPublicReviews(Long artistId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java index 89a2e564..be6caea8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java @@ -1,10 +1,12 @@ package com.xiaowang.yuminailcore.service; import com.xiaowang.yuminailcore.dto.OrderDTO; +import com.xiaowang.yuminailcore.dto.CheckoutPreviewDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO; import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO; import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.yuminailcore.vo.CheckoutPreviewVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO; import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO; @@ -25,6 +27,12 @@ public interface OrderService { * @return OrderVO result consumed by the caller or returned to the frontend */ OrderVO createOrder(Long userId, OrderDTO orderDTO); + + /** + * Preview checkout pricing and coupon explanations without creating an order. + */ + CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO); + /** * 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. @@ -112,6 +120,8 @@ public interface OrderService { List listMyPendingArtistChangeRequests(Long userId, Integer userType); + List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType); + OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType); OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java index 0c33e947..a17e3563 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java @@ -125,4 +125,10 @@ public interface ProductService extends IService { PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId); + + /** + * Purpose: pagePublicProducts filters public product pages by legacy tag text and grouped tag ids. + * Usage: pass comma/semicolon separated tagIds from scene filters; keep tag for backward-compatible name filtering. + */ + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java index b1b9a1a7..ceed5261 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java @@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService; import com.xiaowang.yuminailcore.entity.ShopDO; import com.xiaowang.yuminailcore.dto.ShopDTO; import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.ShopTrustProfileVO; import com.xiaowang.yuminailcore.vo.ShopVO; import java.util.List; @@ -50,6 +51,15 @@ public interface ShopService extends IService { */ ShopVO getShopById(Long id); + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals. + * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. + * + * @param id shop id to inspect + * @return public trust profile or null when the shop cannot be viewed + */ + ShopTrustProfileVO getShopTrustProfile(Long id); + /** * 查询所有店铺 * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/TagService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/TagService.java index f355e785..d3fef317 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/TagService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/TagService.java @@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xiaowang.yuminailcore.entity.TagDO; import com.xiaowang.yuminailcore.dto.TagDTO; +import com.xiaowang.yuminailcore.vo.TagFilterGroupVO; import com.xiaowang.yuminailcore.vo.TagVO; import java.util.List; @@ -71,4 +72,13 @@ public interface TagService extends IService { * @return 标签VO列表 */ List listTagsByShopId(Long shopId); + + /** + * Purpose: listFilterOptions returns public scene-filter groups for product browsing. + * Usage: call it from public Web or mini-program product pages, optionally scoped by shopId. + * + * @param shopId optional shop scope + * @return grouped public filter tags + */ + List listFilterOptions(Long shopId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java index 766c478c..a3f3966d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java @@ -1,8 +1,13 @@ package com.xiaowang.yuminailcore.service; import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.yuminailcore.dto.WishlistAddWithGroupDTO; import com.xiaowang.yuminailcore.dto.WishlistDTO; +import com.xiaowang.yuminailcore.dto.WishlistGroupDTO; +import com.xiaowang.yuminailcore.dto.WishlistMoveDTO; import com.xiaowang.yuminailcore.entity.WishlistDO; +import com.xiaowang.yuminailcore.vo.WishlistGroupVO; +import com.xiaowang.yuminailcore.vo.WishlistInspirationVO; import java.util.List; /** @@ -17,6 +22,7 @@ public interface WishlistService extends IService { * @param productId parameter `productId` supplied by the caller */ void addToWishlist(Long userId, Long productId); + void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO); /** * Remove a record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -39,4 +45,16 @@ public interface WishlistService extends IService { * @return List result consumed by the caller or returned to the frontend */ List getWishlistByUserId(Long userId); + + List listGroups(Long userId); + + Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO); + + boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO); + + boolean deleteGroup(Long userId, Long groupId); + + boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO); + + WishlistInspirationVO getInspiration(Long userId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java index c36f16da..f463b548 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java @@ -4,20 +4,48 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; +import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO; +import com.xiaowang.yuminailcore.entity.OrderDO; +import com.xiaowang.yuminailcore.entity.OrderItemDO; +import com.xiaowang.yuminailcore.entity.ProductDO; import com.xiaowang.yuminailcore.entity.ShopDO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper; +import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper; +import com.xiaowang.yuminailcore.mapper.OrderItemMapper; +import com.xiaowang.yuminailcore.mapper.OrderMapper; +import com.xiaowang.yuminailcore.mapper.ProductMapper; import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.service.NailArtistInfoService; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.vo.NailArtistAvailabilityVO; +import com.xiaowang.yuminailcore.vo.NailArtistProfileVO; +import com.xiaowang.yuminailcore.vo.NailArtistReviewVO; +import com.xiaowang.yuminailcore.vo.NailArtistWorkVO; +import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import com.xiaowang.yuminailcore.vo.ShopSimpleVO; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; @Service /** @@ -26,6 +54,14 @@ import java.util.List; */ public class NailArtistInfoServiceImpl extends ServiceImpl implements NailArtistInfoService { + private static final int REVIEW_STATUS_SUBMITTED = 1; + private static final int ORDER_STATUS_COMPLETED = 2; + private static final int AVAILABILITY_DAYS = 7; + private static final int SLOT_MINUTES = 60; + private static final int MAX_AVAILABILITY_SLOTS = 16; + private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; + private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm"); + @Autowired /** * Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role. @@ -47,6 +83,21 @@ public class NailArtistInfoServiceImpl extends ServiceImpl servedItems = loadArtistOrderItems(artistId, true); + List reviews = listPublicReviews(artistId); + NailArtistProfileVO profile = new NailArtistProfileVO(); + profile.setArtistId(artistId); + profile.setArtistName(resolveArtistName(artistInfo, artist)); + profile.setAvatar(artist.getAvatar()); + profile.setIdentity(artistInfo.getIdentity()); + profile.setSignature(artistInfo.getSignature()); + profile.setExperience(artistInfo.getExperience()); + profile.setStatus(artistInfo.getStatus()); + profile.setShopId(artistInfo.getShopId()); + profile.setShopName(artistInfo.getShopName()); + profile.setRating(resolvePublicRating(artistId, artistInfo)); + profile.setServiceCount(countServiceQuantity(servedItems)); + profile.setWorkStartTime(artistInfo.getWorkStartTime()); + profile.setWorkEndTime(artistInfo.getWorkEndTime()); + profile.setStyleTags(parseTextTokens(artistInfo.getSkills())); + profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 6)); + profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList())); + profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList())); + return profile; + } + + @Override + public List getAvailability(Long artistId) { + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (!Integer.valueOf(1).equals(artistInfo.getStatus())) { + return new ArrayList<>(); + } + + LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime(); + LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime(); + if (!workEnd.isAfter(workStart)) { + workStart = LocalTime.of(10, 0); + workEnd = LocalTime.of(20, 0); + } + + LocalDate today = LocalDate.now(); + LocalDateTime rangeStart = today.atStartOfDay(); + LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay(); + Set bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd); + LocalDateTime now = LocalDateTime.now(); + List slots = new ArrayList<>(); + + for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) { + LocalDate date = today.plusDays(dayOffset); + LocalTime cursor = workStart; + while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) { + LocalDateTime slotStart = date.atTime(cursor); + LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES); + if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) { + slots.add(buildAvailabilitySlot(slotStart, slotEnd)); + } + cursor = cursor.plusMinutes(SLOT_MINUTES); + } + } + return slots; + } + + @Override + public List listPublicReviews(Long artistId) { + if (artistId == null) { + return new ArrayList<>(); + } + List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getId)); + if (reviews == null || reviews.isEmpty()) { + return new ArrayList<>(); + } + + List limitedReviews = reviews.stream().limit(20).collect(Collectors.toList()); + Map customerMap = loadUsers(limitedReviews.stream() + .map(OrderArtistReviewDO::getCustomerId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Map productMap = loadProducts(limitedReviews.stream() + .map(OrderArtistReviewDO::getProductId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Set imageIds = new LinkedHashSet<>(); + for (OrderArtistReviewDO review : limitedReviews) { + imageIds.addAll(parseLongTokens(review.getImageFileIds())); + } + Map fileMap = loadFiles(imageIds); + + List result = new ArrayList<>(); + for (OrderArtistReviewDO review : limitedReviews) { + result.add(buildReviewVO(review, customerMap, productMap, fileMap)); + } + return result; + } + /** * Run business method `convertToDTO`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -248,4 +401,259 @@ public class NailArtistInfoServiceImpl extends ServiceImpl loadArtistOrderItems(Long artistId, boolean completedOnly) { + List orders = orderMapper.selectByArtistId(artistId); + if (orders == null || orders.isEmpty()) { + return new ArrayList<>(); + } + + Set allowedOrderIds = orders.stream() + .filter(order -> !isDeleted(order.getIsDelete())) + .filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus())) + .map(OrderDO::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (allowedOrderIds.isEmpty()) { + return new ArrayList<>(); + } + + List items = new ArrayList<>(); + for (Long orderId : allowedOrderIds) { + List orderItems = orderItemMapper.selectByOrderId(orderId); + if (orderItems == null) { + continue; + } + for (OrderItemDO item : orderItems) { + if (item != null + && artistId.equals(item.getArtistId()) + && !isDeleted(item.getIsDelete())) { + items.add(item); + } + } + } + return items; + } + + private long countServiceQuantity(List items) { + if (items == null || items.isEmpty()) { + return 0L; + } + long count = 0L; + for (OrderItemDO item : items) { + if (item == null) { + continue; + } + count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity(); + } + return count; + } + + private List buildWorks(String portfolio, List servedItems, int limit) { + LinkedHashSet productIds = new LinkedHashSet<>(parseLongTokens(portfolio)); + if (servedItems != null) { + servedItems.stream() + .sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .map(OrderItemDO::getProductId) + .filter(productId -> productId != null && productId > 0) + .forEach(productIds::add); + } + if (productIds.isEmpty()) { + return new ArrayList<>(); + } + + List limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList()); + Map productMap = loadProducts(new LinkedHashSet<>(limitedIds)); + Set fileIds = new LinkedHashSet<>(); + for (ProductDO product : productMap.values()) { + fileIds.addAll(parseLongTokens(product.getImageFileIds())); + } + Map fileMap = loadFiles(fileIds); + + List works = new ArrayList<>(); + for (Long productId : limitedIds) { + ProductDO product = productMap.get(productId); + if (product == null || isDeleted(product.getIsDelete())) { + continue; + } + works.add(buildWorkVO(product, fileMap)); + } + return works; + } + + private NailArtistWorkVO buildWorkVO(ProductDO product, Map fileMap) { + NailArtistWorkVO work = new NailArtistWorkVO(); + work.setId(product.getId()); + work.setTitle(product.getTitle()); + work.setDescription(product.getDescription()); + work.setPrice(product.getPrice()); + work.setTags(parseTextTokens(product.getTags())); + work.setLikeCount(product.getLikeCount()); + work.setCollectCount(product.getCollectCount()); + List imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap); + work.setImageUrls(imageUrls); + work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0)); + return work; + } + + private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review, + Map customerMap, + Map productMap, + Map fileMap) { + NailArtistReviewVO vo = new NailArtistReviewVO(); + vo.setId(review.getId()); + vo.setArtistId(review.getArtistId()); + vo.setCustomerId(review.getCustomerId()); + UserDO customer = customerMap.get(review.getCustomerId()); + vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname()); + vo.setCustomerAvatar(customer == null ? null : customer.getAvatar()); + vo.setProductId(review.getProductId()); + ProductDO product = productMap.get(review.getProductId()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setRating(review.getRatingScore()); + vo.setContent(review.getContent()); + List imageFileIds = parseLongTokens(review.getImageFileIds()); + vo.setImageFileIds(imageFileIds); + vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap)); + vo.setSubmittedAt(review.getSubmittedAt()); + return vo; + } + + private Set loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) { + List bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd); + if (bookedItems == null || bookedItems.isEmpty()) { + return new HashSet<>(); + } + return bookedItems.stream() + .map(OrderItemDO::getAppointmentTime) + .filter(appointmentTime -> appointmentTime != null) + .map(this::truncateToMinute) + .collect(Collectors.toSet()); + } + + private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) { + NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO(); + slot.setStartTime(startTime); + slot.setEndTime(endTime); + slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate())); + slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime())); + slot.setAvailable(true); + return slot; + } + + private Map loadProducts(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return new HashMap<>(); + } + List products = productMapper.selectBatchIds(productIds); + if (products == null || products.isEmpty()) { + return new HashMap<>(); + } + return products.stream() + .filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete())) + .collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new)); + } + + private Map loadUsers(Set userIds) { + if (userIds == null || userIds.isEmpty()) { + return new HashMap<>(); + } + List users = userMapper.selectBatchIds(new ArrayList<>(userIds)); + if (users == null || users.isEmpty()) { + return new HashMap<>(); + } + return users.stream() + .filter(user -> user != null && user.getId() != null) + .collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new)); + } + + private Map loadFiles(Set fileIds) { + if (fileIds == null || fileIds.isEmpty()) { + return new HashMap<>(); + } + Map files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + return files == null ? new HashMap<>() : files; + } + + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return new ArrayList<>(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(file.getFileUrl()); + } + } + return urls; + } + + private List parseLongTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet ids = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;\\s]+")) { + if (!StringUtils.hasText(token)) { + continue; + } + try { + ids.add(Long.parseLong(token.trim())); + } catch (NumberFormatException ignored) { + // Some legacy fields store tag names instead of ids. + } + } + return new ArrayList<>(ids); + } + + private List parseTextTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet tokens = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;、\\s]+")) { + if (StringUtils.hasText(token)) { + tokens.add(token.trim()); + } + } + return new ArrayList<>(tokens); + } + + private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) { + if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) { + return artistInfo.getNickname(); + } + if (artist != null && StringUtils.hasText(artist.getNickname())) { + return artist.getNickname(); + } + return "美甲师"; + } + + private boolean isDeleted(Integer isDelete) { + return Integer.valueOf(1).equals(isDelete); + } + + private LocalDateTime truncateToMinute(LocalDateTime value) { + return value == null ? null : value.withSecond(0).withNano(0); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java index cf243be2..9099deca 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java @@ -2,6 +2,7 @@ package com.xiaowang.yuminailcore.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.yuminailcore.dto.CheckoutPreviewDTO; import com.xiaowang.yuminailcore.dto.OrderDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO; import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO; @@ -42,6 +43,8 @@ import com.xiaowang.yuminailcore.support.OrderStatus; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.yuminailcore.vo.CheckoutCouponPreviewVO; +import com.xiaowang.yuminailcore.vo.CheckoutPreviewVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO; import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO; import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO; @@ -471,6 +474,50 @@ public class OrderServiceImpl implements OrderService { } } + @Override + public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO); + CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO); + List availableCouponOptions = couponService.getAvailableCoupons( + userId, + pricingContext.getProductTagNames(), + pricingContext.getTotalAmount().doubleValue(), + pricingContext.getShopId() + ); + if (availableCouponOptions == null) { + availableCouponOptions = List.of(); + } + + List availableCoupons = availableCouponOptions.stream() + .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) + .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() + .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) + .toList(); + + CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); + if (bestCoupon != null) { + bestCoupon.setBest(true); + } + + CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); + BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); + BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); + if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { + payableAmount = BigDecimal.ZERO; + } + + CheckoutPreviewVO preview = new CheckoutPreviewVO(); + preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); + preview.setSavedAmount(scaleMoney(savedAmount)); + preview.setPayableAmount(scaleMoney(payableAmount)); + preview.setBestCoupon(bestCoupon); + preview.setAvailableCoupons(availableCoupons); + preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); + preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); + preview.setSummaryText(buildCheckoutSummaryText(preview)); + return preview; + } + /** * Create a new record. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -704,6 +751,312 @@ public class OrderServiceImpl implements OrderService { return buildOrderVO(order); } + private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = new OrderDTO(); + if (checkoutPreviewDTO == null) { + return orderDTO; + } + orderDTO.setCouponId(checkoutPreviewDTO.getCouponId()); + orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + orderDTO.setItems(checkoutPreviewDTO.getItems()); + return orderDTO; + } + + private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + throw new RuntimeException("订单项不能为空"); + } + + List orderItemDTOs = orderDTO.getItems(); + Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); + BigDecimal totalAmount = BigDecimal.ZERO; + Set selectedTagNames = new LinkedHashSet<>(); + Long shopId = null; + + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + validateOrderQuantity(orderItemDTO.getQuantity()); + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + throw new RuntimeException("商品不存在或已下架"); + } + + CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); + Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); + if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { + throw new RuntimeException("请先将商品加入购物车后再结算"); + } + if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); + } + + if (shopId == null) { + shopId = product.getShopId(); + validateUserCanCreateOrderInShop(userId, shopId); + } else if (!shopId.equals(product.getShopId())) { + throw new RuntimeException("跨店铺商品请分开下单"); + } + + collectPreviewTagNames(selectedTagNames, product.getTags()); + BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); + } + + if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + throw new RuntimeException("订单金额无效"); + } + return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); + } + + private void collectPreviewTagNames(Set tagNames, String tags) { + if (tagNames == null || tags == null || tags.isBlank()) { + return; + } + for (String rawTag : tags.split("[,;]")) { + if (rawTag == null || rawTag.isBlank()) { + continue; + } + String tagText = rawTag.trim(); + try { + Long tagId = Long.parseLong(tagText); + if (tagService != null) { + TagVO tagVO = tagService.getTagById(tagId); + if (tagVO != null && StringUtils.hasText(tagVO.getTagName())) { + tagNames.add(tagVO.getTagName()); + } + } + } catch (NumberFormatException ignored) { + tagNames.add(tagText); + } + } + } + + private CheckoutCouponPreviewVO buildAvailableCouponPreview(UserCouponVO coupon, BigDecimal totalAmount) { + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getCouponId()); + preview.setUserCouponId(COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null); + preview.setSourceType(coupon.getSourceType()); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(parseMoney(coupon.getDiscountValue())); + preview.setMinAmount(parseMoney(coupon.getMinAmount())); + preview.setReduceAmount(parseMoney(coupon.getReduceAmount())); + preview.setDiscountAmount(capDiscount(calculateCouponDiscountAmount(coupon, totalAmount), totalAmount)); + preview.setAvailable(true); + preview.setBest(false); + preview.setVipAuto(COUPON_SOURCE_SYSTEM_VIP.equals(coupon.getSourceType())); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setSavingText(buildSavingText(preview.getDiscountAmount())); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private CheckoutCouponPreviewVO findBestCouponPreview(List availableCoupons) { + if (availableCoupons == null || availableCoupons.isEmpty()) { + return null; + } + return availableCoupons.stream() + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + } + + private CheckoutCouponPreviewVO resolvePreviewSelectedCoupon(CheckoutPreviewDTO checkoutPreviewDTO, + List availableCoupons, + CheckoutCouponPreviewVO bestCoupon) { + if (checkoutPreviewDTO != null + && checkoutPreviewDTO.getCouponId() == null + && COUPON_SOURCE_NONE.equalsIgnoreCase(checkoutPreviewDTO.getCouponSourceType())) { + return null; + } + if (checkoutPreviewDTO == null || checkoutPreviewDTO.getCouponId() == null || checkoutPreviewDTO.getCouponId() <= 0) { + return bestCoupon; + } + + String requestedSourceType = normalizeCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + return availableCoupons.stream() + .filter(coupon -> checkoutPreviewDTO.getCouponId().equals(coupon.getId())) + .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) + .findFirst() + .orElseThrow(() -> new RuntimeException("当前订单不可使用所选优惠券")); + } + + private List buildUnavailableCouponPreviews(List availableCoupons, + CheckoutPricingContext pricingContext) { + Set availableCouponIds = availableCoupons == null ? Collections.emptySet() : availableCoupons.stream() + .map(CheckoutCouponPreviewVO::getCouponId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + List coupons = couponMapper.selectList(new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0)); + if (coupons == null || coupons.isEmpty()) { + return List.of(); + } + + LocalDateTime now = LocalDateTime.now(); + return coupons.stream() + .filter(coupon -> coupon != null && coupon.getId() != null) + .filter(coupon -> !availableCouponIds.contains(coupon.getId())) + .map(coupon -> buildUnavailableCouponPreview(coupon, pricingContext, now)) + .filter(Objects::nonNull) + .toList(); + } + + private CheckoutCouponPreviewVO buildUnavailableCouponPreview(CouponDO coupon, + CheckoutPricingContext pricingContext, + LocalDateTime now) { + String reason = resolveUnavailableCouponReason(coupon, pricingContext, now); + if (!StringUtils.hasText(reason)) { + reason = "本单暂不可用"; + } + + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getId()); + preview.setSourceType(isVipAutoCoupon(coupon) ? COUPON_SOURCE_SYSTEM_VIP : COUPON_SOURCE_USER); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(coupon.getDiscountValue()); + preview.setMinAmount(coupon.getMinAmount()); + preview.setReduceAmount(coupon.getReduceAmount()); + preview.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + preview.setAvailable(false); + preview.setBest(false); + preview.setVipAuto(isVipAutoCoupon(coupon)); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setUnavailableReason(reason); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private String resolveUnavailableCouponReason(CouponDO coupon, CheckoutPricingContext pricingContext, LocalDateTime now) { + if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete())) { + return "优惠券已失效"; + } + if (coupon.getStatus() == null || coupon.getStatus() != 1) { + return "优惠券已失效"; + } + if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) { + return "还未到可用时间"; + } + if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) { + return "优惠券已过期"; + } + if (coupon.getShopId() != null + && pricingContext.getShopId() != null + && !coupon.getShopId().equals(pricingContext.getShopId())) { + return "仅限其他门店使用"; + } + if (Integer.valueOf(2).equals(coupon.getCouponType()) + && coupon.getMinAmount() != null + && coupon.getMinAmount().compareTo(pricingContext.getTotalAmount()) > 0) { + return "还差 " + formatMoney(coupon.getMinAmount().subtract(pricingContext.getTotalAmount())) + " 可用"; + } + return "本单商品暂不适用"; + } + + private String buildVipTip(Long userId, BigDecimal totalAmount, List availableCoupons) { + CheckoutCouponPreviewVO vipCoupon = availableCoupons == null ? null : availableCoupons.stream() + .filter(coupon -> Boolean.TRUE.equals(coupon.getVipAuto())) + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + UserDO userDO = userMapper.selectById(userId); + String vipLevel = userDO == null ? null : userDO.getLevel(); + if (vipCoupon != null && safeAmount(vipCoupon.getDiscountAmount()).compareTo(BigDecimal.ZERO) > 0) { + String levelText = StringUtils.hasText(vipLevel) ? vipLevel + "VIP" : "VIP"; + return levelText + "本单可省 " + formatMoney(vipCoupon.getDiscountAmount()) + ",已为你计算。"; + } + if (StringUtils.hasText(vipLevel) && !"普通".equals(vipLevel)) { + return vipLevel + "VIP暂无本单可用自动优惠,已为你保留其他可用优惠。"; + } + if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) { + return "开通VIP后,可在结算页自动匹配VIP优惠。"; + } + return null; + } + + private String buildCheckoutSummaryText(CheckoutPreviewVO preview) { + return "商品小计 " + formatMoney(preview.getSubtotalAmount()) + + ",已省 " + formatMoney(preview.getSavedAmount()) + + ",到手价 " + formatMoney(preview.getPayableAmount()) + "。"; + } + + private String buildCouponDisplayText(CheckoutCouponPreviewVO coupon) { + String prefix = Boolean.TRUE.equals(coupon.getVipAuto()) ? "VIP自动优惠" : "优惠券"; + String benefit; + if (Integer.valueOf(1).equals(coupon.getCouponType()) && coupon.getDiscountValue() != null) { + benefit = coupon.getDiscountValue().stripTrailingZeros().toPlainString() + "折"; + } else if (Integer.valueOf(2).equals(coupon.getCouponType())) { + benefit = "满" + formatMoneyValue(coupon.getMinAmount()) + "减" + formatMoneyValue(coupon.getReduceAmount()); + } else { + benefit = "优惠"; + } + return prefix + ":" + coupon.getCouponName() + "," + benefit; + } + + private String buildSavingText(BigDecimal discountAmount) { + BigDecimal amount = safeAmount(discountAmount); + if (amount.compareTo(BigDecimal.ZERO) <= 0) { + return "本单暂不省钱"; + } + return "本单可省 " + formatMoney(amount); + } + + private boolean isVipAutoCoupon(CouponDO coupon) { + return coupon != null + && Integer.valueOf(1).equals(coupon.getAutoMatch()) + && "VIP_AUTO".equals(coupon.getCouponScene()); + } + + private String resolveCouponTypeName(Integer couponType) { + if (Integer.valueOf(1).equals(couponType)) { + return "折扣券"; + } + if (Integer.valueOf(2).equals(couponType)) { + return "满减券"; + } + return "优惠券"; + } + + private BigDecimal parseMoney(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return new BigDecimal(value.trim()); + } catch (NumberFormatException exception) { + return null; + } + } + + private BigDecimal capDiscount(BigDecimal discountAmount, BigDecimal totalAmount) { + BigDecimal discount = safeAmount(discountAmount); + BigDecimal total = safeAmount(totalAmount); + if (discount.compareTo(total) > 0) { + return scaleMoney(total); + } + return scaleMoney(discount); + } + + private BigDecimal safeAmount(BigDecimal amount) { + return amount == null ? BigDecimal.ZERO : amount; + } + + private BigDecimal scaleMoney(BigDecimal amount) { + return safeAmount(amount).setScale(2, RoundingMode.HALF_UP); + } + + private String formatMoney(BigDecimal amount) { + return "¥" + scaleMoney(amount).toPlainString(); + } + + private String formatMoneyValue(BigDecimal amount) { + return scaleMoney(amount).stripTrailingZeros().toPlainString(); + } + @Override /** * Load data by the supplied parameter. @@ -1167,7 +1520,7 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("该订单项已有待处理改派申请"); } createArtistChangeMessage(order, request); - return buildArtistChangeRequestVO(request); + return buildArtistChangeRequestVO(request, item); } @Override @@ -1193,6 +1546,22 @@ public class OrderServiceImpl implements OrderService { .toList(); } + @Override + /** + * Purpose: listOrderArtistChangeRequests returns every artist-change request for one accessible order. + * Usage: call it from order detail/list pages to build a customer-facing order timeline with pending and historical changes. + */ + public List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType) { + expireDueArtistChangeRequests(); + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("[ORDER_ARTIST_CHANGE_FORBIDDEN] 无权查看该订单改派记录"); + } + return orderArtistChangeRequestMapper.selectByOrderId(orderId).stream() + .map(this::buildArtistChangeRequestVO) + .toList(); + } + @Override @Transactional /** @@ -1231,7 +1600,7 @@ public class OrderServiceImpl implements OrderService { request.setStatus(CHANGE_STATUS_APPROVED); request.setApprovedTime(approvedTime); request.setPendingKey(null); - return buildArtistChangeRequestVO(request); + return buildArtistChangeRequestVO(request, item); } @Override @@ -1647,6 +2016,14 @@ public class OrderServiceImpl implements OrderService { * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) { + return buildArtistChangeRequestVO(request, null); + } + + /** + * Purpose: buildArtistChangeRequestVO converts a change request plus optional order item into the client timeline payload. + * Usage: pass the locked/current order item when the caller already has it so the conversion does not issue extra reads. + */ + private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request, OrderItemDO requestItem) { if (request == null) { return null; } @@ -1677,6 +2054,19 @@ public class OrderServiceImpl implements OrderService { vo.setStatusText(resolveArtistChangeStatusText(request.getStatus())); vo.setReason(request.getReason()); vo.setRejectReason(request.getRejectReason()); + OrderItemDO item = requestItem != null ? requestItem : request.getOrderItemId() == null ? null : orderItemMapper.selectById(request.getOrderItemId()); + if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) { + vo.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + vo.setOriginalPrice(item.getPrice()); + vo.setNewPrice(item.getPrice()); + vo.setTimeAffected(false); + vo.setTimeImpactText("预约时间不变"); + vo.setPriceAffected(false); + vo.setPriceImpactText("订单价格不变"); + } else { + vo.setTimeImpactText("暂无法确认预约时间,请联系门店"); + vo.setPriceImpactText("暂无法确认订单价格,请联系门店"); + } vo.setReviewerId(request.getCustomerId()); vo.setMessageId(request.getMessageId()); vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime()); @@ -3165,6 +3555,30 @@ public class OrderServiceImpl implements OrderService { } } + private static final class CheckoutPricingContext { + private final BigDecimal totalAmount; + private final Long shopId; + private final String productTagNames; + + private CheckoutPricingContext(BigDecimal totalAmount, Long shopId, String productTagNames) { + this.totalAmount = totalAmount; + this.shopId = shopId; + this.productTagNames = productTagNames; + } + + private BigDecimal getTotalAmount() { + return totalAmount; + } + + private Long getShopId() { + return shopId; + } + + private String getProductTagNames() { + return productTagNames; + } + } + /** * Purpose: AppointmentSlot supports OrderServiceImpl.java by holding or executing the appointment slot business role. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java index 5181a4d3..5730c8d5 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java @@ -120,6 +120,8 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setShopId(productDTO.getShopId()); productDO.setTitle(productDTO.getTitle()); productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); productDO.setImageFileIds(productDTO.getImageFileIds()); productDO.setPrice(productDTO.getPrice()); productDO.setTags(productDTO.getTags()); @@ -152,6 +154,8 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setShopId(productDTO.getShopId()); productDO.setTitle(productDTO.getTitle()); productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); productDO.setImageFileIds(productDTO.getImageFileIds()); productDO.setPrice(productDTO.getPrice()); productDO.setTags(productDTO.getTags()); @@ -439,6 +443,8 @@ public class ProductServiceImpl extends ServiceImpl im productVO.setShopName(context.shopNames().get(productDO.getShopId())); productVO.setTitle(productDO.getTitle()); productVO.setDescription(productDO.getDescription()); + productVO.setTargetAudience(productDO.getTargetAudience()); + productVO.setPrecautions(productDO.getPrecautions()); productVO.setImageFileIds(productDO.getImageFileIds()); productVO.setPrice(productDO.getPrice()); productVO.setTags(productDO.getTags()); @@ -610,10 +616,20 @@ public class ProductServiceImpl extends ServiceImpl im * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId) { + return pagePublicProducts(page, size, keyword, tag, null, shopId); + } + + @Override + /** + * Purpose: pagePublicProducts supports grouped tag-id filters for public product browsing. + * Usage: pass tagIds from scene filter chips while keeping tag for legacy tag-name searches. + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId) { int normalizedPage = normalizePage(page); int normalizedSize = normalizePageSize(size); String normalizedKeyword = normalizeOptionalKeyword(keyword); String normalizedTag = normalizeOptionalKeyword(tag); + String normalizedTagIds = normalizeOptionalKeyword(tagIds); Long scopedShopId = normalizeShopId(shopId); AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword) ? appCacheProperties.getProductSearch() @@ -621,14 +637,15 @@ public class ProductServiceImpl extends ServiceImpl im String cacheKey = PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "page:" + normalizedPage + ":" + normalizedSize + ":" + normalizedKeyword.toLowerCase(Locale.ROOT) - + ":" + normalizedTag.toLowerCase(Locale.ROOT); + + ":" + normalizedTag.toLowerCase(Locale.ROOT) + + ":" + normalizedTagIds.toLowerCase(Locale.ROOT); return multiLevelCacheService.getOrLoad( cacheKey, Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), new TypeReference>() { }, - () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, scopedShopId) + () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, normalizedTagIds, scopedShopId) ); } @@ -828,6 +845,14 @@ public class ProductServiceImpl extends ServiceImpl im * @return private PageResultVO result consumed by the caller or returned to the frontend */ private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, Long shopId) { + return buildPublicProductPage(page, size, keyword, tag, null, shopId); + } + + /** + * Purpose: buildPublicProductPage creates the public product page with optional grouped tag ids. + * Usage: call from cache loaders after inputs have been normalized. + */ + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, String tagIds, Long shopId) { Set exactTagIds = null; if (StringUtils.hasText(tag)) { exactTagIds = findExactTagIds(tag); @@ -842,9 +867,10 @@ public class ProductServiceImpl extends ServiceImpl im return buildEmptyPageResult(page, size); } } + Set selectedTagIds = parseTagIdFilter(tagIds); Page pageParam = new Page<>(page, size); - Page productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, shopId)); + Page productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, selectedTagIds, shopId)); PageResultVO result = new PageResultVO<>(); result.setList(toProductVOList(productPage.getRecords())); result.setTotal(productPage.getTotal()); @@ -870,6 +896,14 @@ public class ProductServiceImpl extends ServiceImpl im * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Long shopId) { + return buildFrontQuery(keyword, tag, exactTagIds, null, shopId); + } + + /** + * Purpose: buildFrontQuery adds product search, legacy tag, grouped tag-id, and shop filters. + * Usage: pass selectedTagIds when users tap scene-filter chips. + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0); if (shopId != null) { @@ -886,6 +920,9 @@ public class ProductServiceImpl extends ServiceImpl im if (StringUtils.hasText(tag)) { applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds); } + if (selectedTagIds != null && !selectedTagIds.isEmpty()) { + applyTagIdConditions(wrapper, selectedTagIds); + } wrapper.orderByDesc(ProductDO::getCreateTime); return wrapper; } @@ -1019,6 +1056,28 @@ public class ProductServiceImpl extends ServiceImpl im return ids; } + /** + * Purpose: parseTagIdFilter converts scene-filter tag ids into a query-safe set. + * Usage: pass comma or semicolon separated frontend values; invalid chunks are ignored. + */ + private Set parseTagIdFilter(String rawValue) { + if (!StringUtils.hasText(rawValue)) { + return Collections.emptySet(); + } + return java.util.Arrays.stream(rawValue.split("[,;]")) + .map(String::trim) + .filter(StringUtils::hasText) + .filter(value -> { + try { + Long.parseLong(value); + return true; + } catch (NumberFormatException exception) { + return false; + } + }) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + /** * Run business method `findExactTagIds`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java index 08b90ca7..073e0c83 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java @@ -9,33 +9,46 @@ import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.dto.ShopDTO; import com.xiaowang.yuminailcore.entity.CouponDO; import com.xiaowang.yuminailcore.entity.CommentDO; +import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO; import com.xiaowang.yuminailcore.entity.ProductDO; import com.xiaowang.yuminailcore.entity.ShopDO; import com.xiaowang.yuminailcore.entity.TagDO; import com.xiaowang.yuminailcore.entity.UserCouponDO; import com.xiaowang.yuminailcore.mapper.CommentMapper; import com.xiaowang.yuminailcore.mapper.CouponMapper; +import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper; import com.xiaowang.yuminailcore.mapper.ProductMapper; import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.TagMapper; import com.xiaowang.yuminailcore.mapper.UserCouponMapper; import com.xiaowang.yuminailcore.service.CouponService; import com.xiaowang.yuminailcore.service.MapService; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.service.ShopService; import com.xiaowang.yuminailcore.support.ShopThemeSupport; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.ShopTrustProfileVO; import com.xiaowang.yuminailcore.vo.ShopVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; /** @@ -96,6 +109,14 @@ public class ShopServiceImpl extends ServiceImpl implements * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserCouponMapper userCouponMapper; + /** + * Variable `orderArtistReviewMapper`: Spring-injected collaborator used by this class to aggregate public shop review trust signals. + */ + private final OrderArtistReviewMapper orderArtistReviewMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to resolve public image URLs for trust cards. + */ + private final ObjectStorageFileService objectStorageFileService; /** * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -256,6 +277,62 @@ public class ShopServiceImpl extends ServiceImpl implements ); } + @Override + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. + * Usage: pass a valid shop id; the returned profile never exposes contact phone data. + */ + public ShopTrustProfileVO getShopTrustProfile(Long id) { + if (id == null || id <= 0) { + return null; + } + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + return null; + } + + long productCount = countActiveProducts(id); + List featuredProducts = listFeaturedProducts(id); + List recentReviews = listSubmittedReviews(id, 3); + BigDecimal averageRating = calculateAverageRating(id); + long reviewCount = countSubmittedReviews(id); + + Set fileIds = new LinkedHashSet<>(); + fileIds.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + fileIds.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + featuredProducts.forEach(product -> fileIds.addAll(parseLongIds(product.getImageFileIds(), ","))); + recentReviews.forEach(review -> fileIds.addAll(parseLongIds(review.getImageFileIds(), ","))); + Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + + ShopTrustProfileVO profile = new ShopTrustProfileVO(); + profile.setShopId(shopDO.getId()); + profile.setShopName(shopDO.getShopName()); + profile.setBusinessHoursText(StringUtils.hasText(shopDO.getBusinessHours()) ? shopDO.getBusinessHours() : "营业时间待补充"); + profile.setBusinessStatusText(Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) ? "正常营业" : "暂不可预约"); + boolean locationAvailable = shopDO.getLatitude() != null && shopDO.getLongitude() != null; + profile.setLocationAvailable(locationAvailable); + profile.setNavigationAvailable(locationAvailable); + profile.setDistanceCapabilityText(locationAvailable ? "开启定位后可查看距离" : "门店暂未设置地图位置"); + profile.setEnvironmentImages(resolveImageUrls(fileIdsForShop(shopDO), fileMap)); + + ShopTrustProfileVO.Stats stats = new ShopTrustProfileVO.Stats(); + stats.setProductCount(productCount); + stats.setReviewCount(reviewCount); + stats.setAverageRating(averageRating); + stats.setRecentReviewCount(recentReviews.size()); + profile.setStats(stats); + + profile.setFeaturedProducts(featuredProducts.stream() + .map(product -> buildFeaturedProduct(product, fileMap)) + .collect(Collectors.toList())); + profile.setRecentReviews(recentReviews.stream() + .map(review -> buildRecentReview(review, featuredProducts, fileMap)) + .collect(Collectors.toList())); + profile.setAvailabilitySummary(buildAvailabilitySummary(shopDO, productCount)); + profile.setContactSummary(buildContactSummary()); + return profile; + } + @Override /** * List records for the current query or current user scope. @@ -365,6 +442,255 @@ public class ShopServiceImpl extends ServiceImpl implements return result; } + /** + * Purpose: countActiveProducts counts products that can contribute to a public shop trust profile. + * Usage: call it with a valid shop id before rendering product trust metrics. + */ + private long countActiveProducts(Long shopId) { + Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + /** + * Purpose: listFeaturedProducts returns representative active products for shop detail trust cards. + * Usage: render at most three products and navigate to product detail when tapped. + */ + private List listFeaturedProducts(Long shopId) { + return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCollectCount) + .orderByDesc(ProductDO::getLikeCount) + .orderByDesc(ProductDO::getCreateTime) + .last("LIMIT 3")) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: listSubmittedReviews loads privacy-safe submitted review rows for the shop. + * Usage: only status=1 reviews should feed public trust display. + */ + private List listSubmittedReviews(Long shopId, int limit) { + return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getCreateTime) + .last("LIMIT " + Math.max(1, limit))) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: countSubmittedReviews counts reviews that are visible in public shop trust sections. + * Usage: render it beside average rating so customers can judge sample size. + */ + private long countSubmittedReviews(Long shopId) { + Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + /** + * Purpose: calculateAverageRating derives the public average rating for a shop. + * Usage: use submitted reviews only and return zero when no rating exists. + */ + private BigDecimal calculateAverageRating(Long shopId) { + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .isNotNull(OrderArtistReviewDO::getRatingScore)); + if (reviews == null || reviews.isEmpty()) { + return BigDecimal.ZERO; + } + BigDecimal total = reviews.stream() + .map(OrderArtistReviewDO::getRatingScore) + .filter(Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + long count = reviews.stream().map(OrderArtistReviewDO::getRatingScore).filter(Objects::nonNull).count(); + if (count == 0) { + return BigDecimal.ZERO; + } + return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); + } + + /** + * Purpose: buildFeaturedProduct converts a product row into a compact trust card. + * Usage: keep this card small and do not include unpublished product internals. + */ + private ShopTrustProfileVO.FeaturedProduct buildFeaturedProduct(ProductDO product, Map fileMap) { + ShopTrustProfileVO.FeaturedProduct featured = new ShopTrustProfileVO.FeaturedProduct(); + featured.setId(product.getId()); + featured.setTitle(product.getTitle()); + featured.setPrice(product.getPrice()); + featured.setLikeCount(product.getLikeCount() == null ? 0 : product.getLikeCount()); + featured.setCollectCount(product.getCollectCount() == null ? 0 : product.getCollectCount()); + int artistCount = countBookableArtists(product.getBookableArtists()); + featured.setAvailableBookableArtistCount(artistCount); + featured.setBookingHint(artistCount > 0 ? artistCount + " 位美甲师可预约" : "到店后由门店安排美甲师"); + featured.setImageUrl(resolveFirstImageUrl(product.getImageFileIds(), fileMap)); + return featured; + } + + /** + * Purpose: buildRecentReview converts a submitted review row into a privacy-safe card. + * Usage: never include customer phone, account, or full order identifiers here. + */ + private ShopTrustProfileVO.RecentReview buildRecentReview(OrderArtistReviewDO review, + List featuredProducts, + Map fileMap) { + ShopTrustProfileVO.RecentReview item = new ShopTrustProfileVO.RecentReview(); + item.setId(review.getId()); + item.setProductId(review.getProductId()); + item.setProductTitle(resolveProductTitle(review.getProductId(), featuredProducts)); + item.setRatingScore(review.getRatingScore()); + item.setContent(review.getContent()); + item.setSubmittedAt(review.getSubmittedAt() == null ? review.getCreateTime() : review.getSubmittedAt()); + item.setImageUrls(resolveImageUrls(parseLongIds(review.getImageFileIds(), ","), fileMap)); + return item; + } + + /** + * Purpose: buildAvailabilitySummary gives a coarse booking-readiness summary for the public page. + * Usage: clients must still rely on order creation for final schedule validation. + */ + private ShopTrustProfileVO.AvailabilitySummary buildAvailabilitySummary(ShopDO shopDO, long productCount) { + ShopTrustProfileVO.AvailabilitySummary summary = new ShopTrustProfileVO.AvailabilitySummary(); + boolean active = Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) && productCount > 0; + summary.setAvailable(active); + if (!Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus()))) { + summary.setSummaryText("门店暂不可预约"); + } else if (productCount <= 0) { + summary.setSummaryText("暂无可预约作品"); + } else { + summary.setSummaryText("当前有 " + productCount + " 个作品可预约,提交订单前会再次校验档期"); + summary.setNextSlots(buildCoarseSlotHints(shopDO.getBusinessHours())); + } + return summary; + } + + /** + * Purpose: buildContactSummary documents the explicit contact flow without public phone leakage. + * Usage: tests assert phoneExposed is false for the public trust endpoint. + */ + private ShopTrustProfileVO.ContactSummary buildContactSummary() { + ShopTrustProfileVO.ContactSummary contact = new ShopTrustProfileVO.ContactSummary(); + contact.setActionText("点击联系店长后获取联系方式"); + contact.setPhoneExposed(false); + contact.setPhone(null); + return contact; + } + + /** + * Purpose: buildCoarseSlotHints creates simple near-term booking hints from business hours. + * Usage: render these as guidance only, not as guaranteed appointment slots. + */ + private List buildCoarseSlotHints(String businessHours) { + String hours = StringUtils.hasText(businessHours) ? businessHours.trim() : "营业时间内"; + List hints = new ArrayList<>(); + hints.add("今天 " + hours); + hints.add("明天 " + hours); + hints.add("后天 " + hours); + return hints; + } + + /** + * Purpose: fileIdsForShop returns cover and environment image ids in display order. + * Usage: resolve these ids into environment image URLs for shop detail pages. + */ + private List fileIdsForShop(ShopDO shopDO) { + List ids = new ArrayList<>(); + ids.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + ids.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + return ids; + } + + /** + * Purpose: resolveFirstImageUrl returns the first available image URL from a delimited file id string. + * Usage: use it for compact product cards where only one thumbnail is needed. + */ + private String resolveFirstImageUrl(String fileIds, Map fileMap) { + return resolveImageUrls(parseLongIds(fileIds, ","), fileMap).stream().findFirst().orElse(null); + } + + /** + * Purpose: resolveImageUrls maps file ids to public URLs while preserving order. + * Usage: call it for shop environment, product thumbnails, and review thumbnails. + */ + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return Collections.emptyList(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(file.getFileUrl()); + } + } + return urls; + } + + /** + * Purpose: resolveProductTitle returns the title for a reviewed product. + * Usage: prefer already-loaded featured products and fall back to one product lookup. + */ + private String resolveProductTitle(Long productId, List featuredProducts) { + if (productId == null) { + return null; + } + for (ProductDO product : featuredProducts) { + if (product != null && productId.equals(product.getId())) { + return product.getTitle(); + } + } + ProductDO product = productMapper.selectById(productId); + return product == null || Integer.valueOf(1).equals(product.getIsDelete()) ? null : product.getTitle(); + } + + /** + * Purpose: parseLongIds parses comma or semicolon separated numeric ids. + * Usage: feed image/product/tag id strings into batch lookup helpers. + */ + private List parseLongIds(String value, String delimiter) { + if (!StringUtils.hasText(value)) { + return Collections.emptyList(); + } + List ids = new ArrayList<>(); + String regex = ",".equals(delimiter) ? "[,;]" : delimiter; + for (String part : value.split(regex)) { + if (!StringUtils.hasText(part)) { + continue; + } + try { + ids.add(Long.parseLong(part.trim())); + } catch (NumberFormatException ignored) { + // Ignore dirty historical file id fragments instead of failing the public shop page. + } + } + return ids; + } + + /** + * Purpose: countBookableArtists counts the configured artist ids for a product. + * Usage: render a compact availability hint without validating live schedules. + */ + private int countBookableArtists(String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return 0; + } + return (int) parseLongIds(bookableArtists, ",").stream().distinct().count(); + } + /** * 将 DO 转换为 VO * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java index ba337063..c3cb09ef 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java @@ -11,6 +11,7 @@ import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.TagMapper; import com.xiaowang.yuminailcore.service.TagService; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import com.xiaowang.yuminailcore.vo.TagFilterGroupVO; import com.xiaowang.yuminailcore.vo.TagVO; import lombok.RequiredArgsConstructor; import org.springframework.dao.DuplicateKeyException; @@ -18,7 +19,11 @@ import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; /** @@ -41,6 +46,11 @@ public class TagServiceImpl extends ServiceImpl implements Tag * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:"; + /** + * Purpose: DEFAULT_FILTER_GROUP is the public group used for legacy tags without a scene group. + * Usage: keep old tags visible in filters without requiring data migration edits. + */ + private static final String DEFAULT_FILTER_GROUP = "其他"; /** * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -83,6 +93,10 @@ public class TagServiceImpl extends ServiceImpl implements Tag tagDO.setTextColor(tagDTO.getTextColor()); tagDO.setBgColor(tagDTO.getBgColor()); tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); tagDO.setShopId(shopId); tagDO.setIsDelete(0); try { @@ -131,6 +145,10 @@ public class TagServiceImpl extends ServiceImpl implements Tag tagDO.setTextColor(tagDTO.getTextColor()); tagDO.setBgColor(tagDTO.getBgColor()); tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); tagDO.setShopId(shopId); try { boolean updated = tagMapper.updateById(tagDO) > 0; @@ -259,6 +277,24 @@ public class TagServiceImpl extends ServiceImpl implements Tag ); } + @Override + /** + * Purpose: listFilterOptions builds public scene-filter groups for customer browsing. + * Usage: call it from Web or mini-program product pages; pass shopId to limit groups to one shop. + */ + public List listFilterOptions(Long shopId) { + Long scopedShopId = shopId != null && shopId > 0 ? shopId : null; + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "filter:" + (scopedShopId == null ? "all" : scopedShopId), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildFilterOptions(scopedShopId) + ); + } + @Override /** * Load data by the supplied parameter. @@ -297,6 +333,10 @@ public class TagServiceImpl extends ServiceImpl implements Tag tagVO.setTextColor(tagDO.getTextColor()); tagVO.setBgColor(tagDO.getBgColor()); tagVO.setBorderColor(tagDO.getBorderColor()); + tagVO.setSceneGroup(resolveSceneGroup(tagDO.getSceneGroup())); + tagVO.setDisplayName(resolveDisplayName(tagDO)); + tagVO.setSortOrder(tagDO.getSortOrder()); + tagVO.setFrontVisible(normalizeFrontVisible(tagDO.getFrontVisible())); tagVO.setShopId(tagDO.getShopId()); tagVO.setShopName(resolveShopName(tagDO.getShopId())); tagVO.setCreateTime(tagDO.getCreateTime()); @@ -322,6 +362,73 @@ public class TagServiceImpl extends ServiceImpl implements Tag return tagName.trim(); } + /** + * Purpose: buildFilterOptions groups visible tags while preserving legacy tags in a default group. + * Usage: call it only through the cache-backed public listFilterOptions method. + */ + private List buildFilterOptions(Long shopId) { + List tags = tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(shopId != null, TagDO::getShopId, shopId) + ); + Map> groupedTags = new LinkedHashMap<>(); + tags.stream() + .filter(tagDO -> !Integer.valueOf(0).equals(tagDO.getFrontVisible())) + .sorted(Comparator + .comparing((TagDO tagDO) -> resolveSceneGroup(tagDO.getSceneGroup()).equals(DEFAULT_FILTER_GROUP) ? 1 : 0) + .thenComparing(tagDO -> resolveSceneGroup(tagDO.getSceneGroup())) + .thenComparing(tagDO -> tagDO.getSortOrder() == null ? Integer.MAX_VALUE : tagDO.getSortOrder()) + .thenComparing(TagDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(TagDO::getId, Comparator.nullsLast(Long::compareTo))) + .forEach(tagDO -> groupedTags + .computeIfAbsent(resolveSceneGroup(tagDO.getSceneGroup()), ignored -> new ArrayList<>()) + .add(convertToVO(tagDO))); + return groupedTags.entrySet().stream() + .map(entry -> { + TagFilterGroupVO groupVO = new TagFilterGroupVO(); + groupVO.setGroupName(entry.getKey()); + groupVO.setTags(entry.getValue()); + return groupVO; + }) + .collect(Collectors.toList()); + } + + /** + * Purpose: normalizeOptionalText trims optional tag metadata. + * Usage: call before persisting sceneGroup or displayName so blank strings become null. + */ + private String normalizeOptionalText(String value) { + return StringUtils.hasText(value) ? value.trim() : null; + } + + /** + * Purpose: resolveSceneGroup keeps legacy tags usable in scene filters. + * Usage: call when serializing or grouping tags for public clients. + */ + private String resolveSceneGroup(String sceneGroup) { + return StringUtils.hasText(sceneGroup) ? sceneGroup.trim() : DEFAULT_FILTER_GROUP; + } + + /** + * Purpose: resolveDisplayName decides the public label for one tag. + * Usage: call when building TagVO so clients can render displayName directly. + */ + private String resolveDisplayName(TagDO tagDO) { + if (tagDO == null) { + return null; + } + return StringUtils.hasText(tagDO.getDisplayName()) ? tagDO.getDisplayName().trim() : tagDO.getTagName(); + } + + /** + * Purpose: normalizeFrontVisible defaults old rows to visible. + * Usage: call when saving and serializing the public visibility flag. + */ + private Integer normalizeFrontVisible(Integer frontVisible) { + return frontVisible == null ? 1 : frontVisible; + } + /** * Run business method `requireShopId`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -430,7 +537,9 @@ public class TagServiceImpl extends ServiceImpl implements Tag } if (shopId != null) { multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:" + shopId); } multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all"); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:all"); } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java index 668c7b81..8b03c659 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java @@ -2,152 +2,354 @@ package com.xiaowang.yuminailcore.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.yuminailcore.dto.WishlistAddWithGroupDTO; import com.xiaowang.yuminailcore.dto.WishlistDTO; +import com.xiaowang.yuminailcore.dto.WishlistGroupDTO; +import com.xiaowang.yuminailcore.dto.WishlistMoveDTO; import com.xiaowang.yuminailcore.entity.ProductDO; import com.xiaowang.yuminailcore.entity.WishlistDO; -import com.xiaowang.yuminailcore.mapper.WishlistMapper; +import com.xiaowang.yuminailcore.entity.WishlistGroupDO; import com.xiaowang.yuminailcore.mapper.ProductMapper; -import com.xiaowang.yuminailcore.service.WishlistService; +import com.xiaowang.yuminailcore.mapper.WishlistGroupMapper; +import com.xiaowang.yuminailcore.mapper.WishlistMapper; import com.xiaowang.yuminailcore.service.ProductService; +import com.xiaowang.yuminailcore.service.WishlistService; import com.xiaowang.yuminailcore.vo.ProductVO; +import com.xiaowang.yuminailcore.vo.WishlistGroupVO; +import com.xiaowang.yuminailcore.vo.WishlistInspirationVO; +import lombok.RequiredArgsConstructor; import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; @Service -/** - * WishlistServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ +@RequiredArgsConstructor public class WishlistServiceImpl extends ServiceImpl implements WishlistService { - @Autowired - /** - * Purpose: productService supports WishlistServiceImpl.java by holding or executing the product service business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductService productService; + private static final List PRESET_GROUP_NAMES = List.of( + "\u6700\u8fd1\u60f3\u505a", + "\u5a5a\u793c\u6b3e", + "\u590f\u5929\u6b3e" + ); + private static final int DEFAULT_SORT_ORDER = 100; + private static final int NOTE_MAX_LENGTH = 500; - @Autowired - /** - * Purpose: productMapper supports WishlistServiceImpl.java by holding or executing the product mapper business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private ProductMapper productMapper; + private final WishlistMapper wishlistMapper; + private final WishlistGroupMapper wishlistGroupMapper; + private final ProductService productService; + private final ProductMapper productMapper; @Override @Transactional - /** - * Add a new record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ public void addToWishlist(Long userId, Long productId) { + WishlistAddWithGroupDTO dto = new WishlistAddWithGroupDTO(); + dto.setProductId(productId); + addToWishlist(userId, dto); + } + + @Override + @Transactional + public void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO) { + Long productId = wishlistDTO == null ? null : wishlistDTO.getProductId(); ProductDO product = getValidProduct(productId); if (product == null) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("商品不存在或已下架"); + throw new RuntimeException("\u5546\u54c1\u4e0d\u5b58\u5728\u6216\u5df2\u4e0b\u67b6"); } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getProductId, productId); - if (count(wrapper) == 0) { + WishlistGroupDO group = resolveTargetGroup(userId, wishlistDTO == null ? null : wishlistDTO.getGroupId()); + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { WishlistDO wishlistDO = new WishlistDO(); wishlistDO.setUserId(userId); wishlistDO.setProductId(productId); - /** - * Save submitted data. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wishlistDO parameter `wishlistDO` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - save(wishlistDO); - // 增加商品收藏数 + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistDTO == null ? null : wishlistDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistDTO == null ? null : wishlistDTO.getSortOrder())); + wishlistDO.setIsDelete(0); + wishlistMapper.insert(wishlistDO); productMapper.incrementCollectCount(productId); + return; } + + existing.setGroupId(group.getId()); + existing.setNote(normalizeNote(wishlistDTO.getNote())); + if (wishlistDTO.getSortOrder() != null) { + existing.setSortOrder(normalizeSortOrder(wishlistDTO.getSortOrder())); + } else if (existing.getSortOrder() == null) { + existing.setSortOrder(DEFAULT_SORT_ORDER); + } + wishlistMapper.updateById(existing); } @Override @Transactional - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - */ public void removeFromWishlist(Long userId, Long productId) { + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { + return; + } LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(WishlistDO::getUserId, userId); wrapper.eq(WishlistDO::getProductId, productId); - if (count(wrapper) > 0) { - /** - * Remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param wrapper parameter `wrapper` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - remove(wrapper); - // 减少商品收藏数 - if (getValidProduct(productId) != null) { - productMapper.decrementCollectCount(productId); - } + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.delete(wrapper); + if (getValidProduct(productId) != null) { + productMapper.decrementCollectCount(productId); } } @Override - /** - * Run business method `isInWishlist`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userId parameter `userId` supplied by the caller - * @param productId parameter `productId` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ public boolean isInWishlist(Long userId, Long productId) { if (getValidProduct(productId) == null) { return false; } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(WishlistDO::getUserId, userId); - wrapper.eq(WishlistDO::getProductId, productId); - return count(wrapper) > 0; + return findActiveWishlistByUserAndProduct(userId, productId) != null; } @Override - /** - * 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 userId parameter `userId` supplied by the caller - * @return List result consumed by the caller or returned to the frontend - */ public List getWishlistByUserId(Long userId) { + List groups = listGroups(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + return loadActiveWishlist(userId).stream() + .map(wishlistDO -> toWishlistDTO(wishlistDO, groupNames)) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public List listGroups(Long userId) { + return ensurePresetGroups(userId).stream() + .map(this::toGroupVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + return group.getId(); + } + + @Override + @Transactional + public boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean deleteGroup(Long userId, Long groupId) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(WishlistDO::getUserId, userId); - List wishlistDOList = list(wrapper); - return wishlistDOList.stream().map(wishlistDO -> { - WishlistDTO wishlistDTO = new WishlistDTO(); - BeanUtils.copyProperties(wishlistDO, wishlistDTO); - ProductVO productVO = productService.getProductById(wishlistDO.getProductId()); - wishlistDTO.setProduct(productVO); - return wishlistDTO; - }).filter(wishlistDTO -> wishlistDTO.getProduct() != null).collect(Collectors.toList()); + wrapper.eq(WishlistDO::getGroupId, groupId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.selectList(wrapper).forEach(wishlistDO -> { + wishlistDO.setGroupId(defaultGroup.getId()); + wishlistMapper.updateById(wishlistDO); + }); + group.setIsDelete(1); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + WishlistDO wishlistDO = findTargetWishlist(userId, wishlistMoveDTO); + if (wishlistDO == null) { + return false; + } + WishlistGroupDO group = resolveTargetGroup(userId, wishlistMoveDTO == null ? null : wishlistMoveDTO.getGroupId()); + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistMoveDTO == null ? null : wishlistMoveDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistMoveDTO == null ? null : wishlistMoveDTO.getSortOrder())); + return wishlistMapper.updateById(wishlistDO) > 0; + } + + @Override + @Transactional + public WishlistInspirationVO getInspiration(Long userId) { + List groups = listGroups(userId); + Map groupMap = new LinkedHashMap<>(); + groups.forEach(group -> groupMap.put(group.getId(), group)); + + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + + List items = loadActiveWishlist(userId).stream() + .map(wishlistDO -> { + if (wishlistDO.getGroupId() == null || !groupMap.containsKey(wishlistDO.getGroupId())) { + wishlistDO.setGroupId(defaultGroup.getId()); + } + return toWishlistDTO(wishlistDO, groupNames); + }) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + + items.forEach(item -> { + WishlistGroupVO group = groupMap.get(item.getGroupId()); + if (group != null) { + group.getItems().add(item); + } + }); + groups.forEach(group -> group.setItemCount(group.getItems().size())); + + WishlistInspirationVO inspirationVO = new WishlistInspirationVO(); + inspirationVO.setTotal(items.size()); + inspirationVO.setGroups(groups); + return inspirationVO; + } + + private WishlistDTO toWishlistDTO(WishlistDO wishlistDO, Map groupNames) { + WishlistDTO wishlistDTO = new WishlistDTO(); + BeanUtils.copyProperties(wishlistDO, wishlistDTO); + wishlistDTO.setGroupName(groupNames.get(wishlistDO.getGroupId())); + ProductVO productVO = productService.getProductById(wishlistDO.getProductId()); + wishlistDTO.setProduct(productVO); + return wishlistDTO; + } + + private WishlistGroupVO toGroupVO(WishlistGroupDO groupDO) { + WishlistGroupVO groupVO = new WishlistGroupVO(); + groupVO.setId(groupDO.getId()); + groupVO.setName(groupDO.getName()); + groupVO.setSortOrder(normalizeSortOrder(groupDO.getSortOrder())); + groupVO.setItemCount(0); + groupVO.setItems(new ArrayList<>()); + return groupVO; + } + + private WishlistDO findTargetWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + if (wishlistMoveDTO == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + if (wishlistMoveDTO.getWishlistId() != null) { + wrapper.eq(WishlistDO::getId, wishlistMoveDTO.getWishlistId()); + } else if (wishlistMoveDTO.getProductId() != null) { + wrapper.eq(WishlistDO::getProductId, wishlistMoveDTO.getProductId()); + } else { + return null; + } + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private WishlistDO findActiveWishlistByUserAndProduct(Long userId, Long productId) { + if (userId == null || productId == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getProductId, productId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private List loadActiveWishlist(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.orderByAsc(WishlistDO::getSortOrder); + wrapper.orderByDesc(WishlistDO::getCreateTime); + return wishlistMapper.selectList(wrapper); + } + + private List ensurePresetGroups(Long userId) { + List groups = loadActiveGroups(userId); + Map groupByName = groups.stream() + .collect(Collectors.toMap(WishlistGroupDO::getName, group -> group, (left, right) -> left)); + for (int index = 0; index < PRESET_GROUP_NAMES.size(); index++) { + String name = PRESET_GROUP_NAMES.get(index); + if (!groupByName.containsKey(name)) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(name); + group.setSortOrder((index + 1) * 10); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + groups.add(group); + groupByName.put(name, group); + } + } + return groups.stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + private WishlistGroupDO resolveDefaultGroup(Long userId) { + return ensurePresetGroups(userId).stream() + .filter(group -> PRESET_GROUP_NAMES.get(0).equals(group.getName())) + .findFirst() + .orElseThrow(() -> new RuntimeException("\u9ed8\u8ba4\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728")); + } + + private WishlistGroupDO resolveTargetGroup(Long userId, Long groupId) { + if (groupId == null) { + return resolveDefaultGroup(userId); + } + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728"); + } + return group; + } + + private WishlistGroupDO findOwnedGroup(Long userId, Long groupId) { + if (userId == null || groupId == null) { + return null; + } + WishlistGroupDO group = wishlistGroupMapper.selectById(groupId); + if (group == null || Integer.valueOf(1).equals(group.getIsDelete()) || !userId.equals(group.getUserId())) { + return null; + } + return group; + } + + private List loadActiveGroups(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistGroupDO::getUserId, userId); + wrapper.eq(WishlistGroupDO::getIsDelete, 0); + return wishlistGroupMapper.selectList(wrapper).stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); } - /** - * 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 productId parameter `productId` supplied by the caller - * @return private ProductDO result consumed by the caller or returned to the frontend - */ private ProductDO getValidProduct(Long productId) { if (productId == null) { return null; @@ -160,4 +362,23 @@ public class WishlistServiceImpl extends ServiceImpl return product; } + + private String normalizeGroupName(String name) { + if (!StringUtils.hasText(name)) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a"); + } + return name.trim(); + } + + private String normalizeNote(String note) { + if (!StringUtils.hasText(note)) { + return null; + } + String trimmedNote = note.trim(); + return trimmedNote.length() > NOTE_MAX_LENGTH ? trimmedNote.substring(0, NOTE_MAX_LENGTH) : trimmedNote; + } + + private Integer normalizeSortOrder(Integer sortOrder) { + return sortOrder == null ? DEFAULT_SORT_ORDER : sortOrder; + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutCouponPreviewVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutCouponPreviewVO.java new file mode 100644 index 00000000..116cbdfb --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutCouponPreviewVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 结算预览里的单张优惠说明。 + */ +@Data +public class CheckoutCouponPreviewVO { + + private Long id; + + private Long couponId; + + private Long userCouponId; + + private String sourceType; + + private String couponName; + + private Integer couponType; + + private String couponTypeName; + + private BigDecimal discountValue; + + private BigDecimal minAmount; + + private BigDecimal reduceAmount; + + private BigDecimal discountAmount; + + private Boolean available; + + private Boolean best; + + private Boolean vipAuto; + + private String displayText; + + private String savingText; + + private String unavailableReason; + + private LocalDateTime startTime; + + private LocalDateTime endTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutPreviewVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutPreviewVO.java new file mode 100644 index 00000000..f39892bf --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CheckoutPreviewVO.java @@ -0,0 +1,30 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * 结算页展示用预览结果。 + */ +@Data +public class CheckoutPreviewVO { + + private BigDecimal subtotalAmount = BigDecimal.ZERO; + + private BigDecimal savedAmount = BigDecimal.ZERO; + + private BigDecimal payableAmount = BigDecimal.ZERO; + + private CheckoutCouponPreviewVO bestCoupon; + + private List availableCoupons = new ArrayList<>(); + + private List unavailableCoupons = new ArrayList<>(); + + private String vipTip; + + private String summaryText; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistAvailabilityVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistAvailabilityVO.java new file mode 100644 index 00000000..21e2d80b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistAvailabilityVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class NailArtistAvailabilityVO { + private LocalDateTime startTime; + private LocalDateTime endTime; + private String dateText; + private String timeText; + private Boolean available; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistProfileVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistProfileVO.java new file mode 100644 index 00000000..54598090 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistProfileVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistProfileVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + private String artistName; + private String avatar; + private String identity; + private String signature; + private Integer experience; + private Integer status; + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + private String shopName; + private BigDecimal rating; + private Long serviceCount; + private LocalTime workStartTime; + private LocalTime workEndTime; + private List styleTags = new ArrayList<>(); + private List works = new ArrayList<>(); + private List reviews = new ArrayList<>(); + private List availability = new ArrayList<>(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistReviewVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistReviewVO.java new file mode 100644 index 00000000..5fdc3e00 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistReviewVO.java @@ -0,0 +1,30 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistReviewVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + @JsonSerialize(using = ToStringSerializer.class) + private Long customerId; + private String customerName; + private String customerAvatar; + @JsonSerialize(using = ToStringSerializer.class) + private Long productId; + private String productTitle; + private BigDecimal rating; + private String content; + private List imageFileIds = new ArrayList<>(); + private List imageUrls = new ArrayList<>(); + private LocalDateTime submittedAt; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistWorkVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistWorkVO.java new file mode 100644 index 00000000..378c5554 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/NailArtistWorkVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistWorkVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + private String title; + private String description; + private BigDecimal price; + private String coverImageUrl; + private List imageUrls = new ArrayList<>(); + private List tags = new ArrayList<>(); + private Integer likeCount; + private Integer collectCount; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java index 246b3427..b9f2d988 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java @@ -2,6 +2,7 @@ package com.xiaowang.yuminailcore.vo; import lombok.Data; +import java.math.BigDecimal; import java.time.LocalDateTime; @Data @@ -120,6 +121,41 @@ public class OrderArtistChangeRequestVO { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private String rejectReason; + /** + * Purpose: appointmentTime exposes the affected order-item appointment for customer-facing timelines. + * Usage: render this value beside the change request so users can confirm the change does not move their booking. + */ + private String appointmentTime; + /** + * Purpose: timeAffected tells clients whether the artist change modifies the booking time. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean timeAffected; + /** + * Purpose: timeImpactText gives ready-to-display wording for the time impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String timeImpactText; + /** + * Purpose: originalPrice records the original order-item unit price for impact display. + * Usage: compare it with newPrice when rendering customer-facing price impact copy. + */ + private BigDecimal originalPrice; + /** + * Purpose: newPrice records the post-change order-item unit price for impact display. + * Usage: show it only when priceAffected is true or when detailed impact wording is needed. + */ + private BigDecimal newPrice; + /** + * Purpose: priceAffected tells clients whether the artist change modifies the order amount. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean priceAffected; + /** + * Purpose: priceImpactText gives ready-to-display wording for the price impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String priceImpactText; /** * Purpose: reviewerId supports OrderArtistChangeRequestVO.java by holding or executing the reviewer id business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ProductVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ProductVO.java index 9d6776e3..6d6248e7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ProductVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ProductVO.java @@ -42,6 +42,16 @@ public class ProductVO { */ private String description; + /** + * 适合人群说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String targetAudience; + + /** + * 注意事项说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String precautions; + /** * 图片文件ID集合,多个ID以逗号分隔 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopTrustProfileVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopTrustProfileVO.java new file mode 100644 index 00000000..b7ad3208 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopTrustProfileVO.java @@ -0,0 +1,278 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page. + * Usage: return this VO from /shop/trust-profile/{shopId}; clients render it without exposing phone numbers. + */ +@Data +public class ShopTrustProfileVO { + /** + * Purpose: shopId identifies the shop whose trust profile is being rendered. + * Usage: clients use it to keep the profile matched to the visible shop. + */ + private Long shopId; + + /** + * Purpose: shopName gives the profile a stable display label. + * Usage: render it in accessibility labels or fallback section titles. + */ + private String shopName; + + /** + * Purpose: businessHoursText describes when the shop says it is open. + * Usage: show it near booking and navigation actions. + */ + private String businessHoursText; + + /** + * Purpose: businessStatusText summarizes whether the shop can currently be viewed and booked. + * Usage: display this short text in trust summary chips. + */ + private String businessStatusText; + + /** + * Purpose: locationAvailable reports whether map coordinates exist. + * Usage: hide navigation/distance affordances when false. + */ + private Boolean locationAvailable; + + /** + * Purpose: distanceCapabilityText explains whether distance can be calculated on the client. + * Usage: show this text until the client has user location permission. + */ + private String distanceCapabilityText; + + /** + * Purpose: navigationAvailable reports whether navigation URLs can be offered. + * Usage: clients use it to enable map buttons. + */ + private Boolean navigationAvailable; + + /** + * Purpose: stats contains public aggregate numbers for customer confidence. + * Usage: render as compact metrics on the shop detail page. + */ + private Stats stats = new Stats(); + + /** + * Purpose: environmentImages contains public shop environment image URLs. + * Usage: render thumbnails or a carousel; it must not include contact data. + */ + private List environmentImages = new ArrayList<>(); + + /** + * Purpose: featuredProducts lists representative products from this shop. + * Usage: render as quick inspection or booking entry cards. + */ + private List featuredProducts = new ArrayList<>(); + + /** + * Purpose: recentReviews lists recent submitted reviews only. + * Usage: show social proof while keeping customer identity private. + */ + private List recentReviews = new ArrayList<>(); + + /** + * Purpose: availabilitySummary gives a safe booking summary without reserving slots. + * Usage: render it near booking actions and keep final conflict checks in order creation. + */ + private AvailabilitySummary availabilitySummary = new AvailabilitySummary(); + + /** + * Purpose: contactSummary tells clients how to request contact details without exposing phone data. + * Usage: render the action hint and fetch phone only through the explicit contact endpoint. + */ + private ContactSummary contactSummary = new ContactSummary(); + + /** + * Purpose: Stats groups aggregate shop trust metrics. + * Usage: serialize inside ShopTrustProfileVO.stats for frontend summary cards. + */ + @Data + public static class Stats { + /** + * Purpose: averageRating is the submitted-review average for this shop. + * Usage: display with one decimal place when reviewCount is greater than zero. + */ + private BigDecimal averageRating = BigDecimal.ZERO; + + /** + * Purpose: reviewCount is the number of submitted, public reviews. + * Usage: render beside averageRating to avoid showing score without sample size. + */ + private Long reviewCount = 0L; + + /** + * Purpose: productCount is the number of active products in this shop. + * Usage: render as a confidence signal and empty-state condition. + */ + private Long productCount = 0L; + + /** + * Purpose: recentReviewCount is the number of review cards included in this response. + * Usage: clients use it for section labels and empty states. + */ + private Integer recentReviewCount = 0; + } + + /** + * Purpose: FeaturedProduct is a compact public product card for shop trust display. + * Usage: render these cards on shop detail pages without fetching full product detail first. + */ + @Data + public static class FeaturedProduct { + /** + * Purpose: id identifies the product for detail navigation. + * Usage: pass it to product detail routes when the customer taps the card. + */ + private Long id; + + /** + * Purpose: title names the featured product. + * Usage: render as the card title. + */ + private String title; + + /** + * Purpose: imageUrl provides the first public product image. + * Usage: render as a thumbnail and fall back gracefully when blank. + */ + private String imageUrl; + + /** + * Purpose: price carries the current product price. + * Usage: show it as a current quote, not as historical order price. + */ + private BigDecimal price; + + /** + * Purpose: likeCount is the current like count. + * Usage: render as a lightweight popularity signal. + */ + private Integer likeCount; + + /** + * Purpose: collectCount is the current wishlist count. + * Usage: render as a lightweight popularity signal. + */ + private Integer collectCount; + + /** + * Purpose: availableBookableArtistCount tells whether this product has available artists configured. + * Usage: show concise booking hints without exposing artist schedules. + */ + private Integer availableBookableArtistCount; + + /** + * Purpose: bookingHint is a customer-facing availability hint for this product. + * Usage: display below the product title. + */ + private String bookingHint; + } + + /** + * Purpose: RecentReview is a privacy-safe submitted review summary. + * Usage: render public review snippets without customer account or phone fields. + */ + @Data + public static class RecentReview { + /** + * Purpose: id identifies the review row. + * Usage: use it as a frontend list key. + */ + private Long id; + + /** + * Purpose: productId links the review to the reviewed product. + * Usage: optionally navigate to the product detail page. + */ + private Long productId; + + /** + * Purpose: productTitle names the product reviewed. + * Usage: display as context for the review. + */ + private String productTitle; + + /** + * Purpose: ratingScore is the submitted rating. + * Usage: render with one decimal place. + */ + private BigDecimal ratingScore; + + /** + * Purpose: content stores the submitted review text. + * Usage: display a short snippet and hide the section when blank if desired. + */ + private String content; + + /** + * Purpose: imageUrls contains public review image URLs. + * Usage: render thumbnails without exposing customer identity. + */ + private List imageUrls = new ArrayList<>(); + + /** + * Purpose: submittedAt records when the review was submitted. + * Usage: render relative or formatted review time. + */ + private LocalDateTime submittedAt; + } + + /** + * Purpose: AvailabilitySummary summarizes booking readiness for the shop. + * Usage: clients render it as guidance while final validation remains server-side on order creation. + */ + @Data + public static class AvailabilitySummary { + /** + * Purpose: available states whether the shop currently has active products to book. + * Usage: enable or soften booking entry copy. + */ + private Boolean available = false; + + /** + * Purpose: summaryText gives the customer a direct booking-readiness sentence. + * Usage: render as the availability card body. + */ + private String summaryText = "暂无可预约作品"; + + /** + * Purpose: nextSlots gives coarse upcoming booking hints when available. + * Usage: render as chips; clients must not treat these as reserved slots. + */ + private List nextSlots = new ArrayList<>(); + } + + /** + * Purpose: ContactSummary describes the explicit contact action without leaking phone data. + * Usage: render the action label and call contact-info only after the user taps contact. + */ + @Data + public static class ContactSummary { + /** + * Purpose: actionText is the label for the explicit contact action. + * Usage: render on the contact button or helper text. + */ + private String actionText = "点击联系店长后获取联系方式"; + + /** + * Purpose: phoneExposed records whether this public profile includes phone data. + * Usage: assert false in tests and use contact-info endpoint for phone data. + */ + private Boolean phoneExposed = false; + + /** + * Purpose: phone is intentionally null in this public profile. + * Usage: clients must ignore it and call the explicit contact endpoint instead. + */ + private String phone; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagFilterGroupVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagFilterGroupVO.java new file mode 100644 index 00000000..ae9ae889 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagFilterGroupVO.java @@ -0,0 +1,26 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: TagFilterGroupVO groups public tags for customer scene filters. + * Usage: return it from `/tag/list/filter-options` and render each group as one filter row. + */ +@Data +public class TagFilterGroupVO { + + /** + * Purpose: groupName is the customer-facing group title. + * Usage: display it above the group's tag chips. + */ + private String groupName; + + /** + * Purpose: tags holds visible tags in the current filter group. + * Usage: use each tag id for product filtering and displayName/tagName for chip text. + */ + private List tags = new ArrayList<>(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagVO.java index 143d7e9f..52615225 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/TagVO.java @@ -39,6 +39,30 @@ public class TagVO { */ private String borderColor; + /** + * Purpose: sceneGroup tells clients which public filter group this tag belongs to. + * Usage: read it from tag list APIs and group filter chips by this value. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the public-facing tag label. + * Usage: show this value in filters; fall back to tagName if it is empty. + */ + private String displayName; + + /** + * Purpose: sortOrder controls the public order inside a group. + * Usage: sort lower values before higher values when rendering grouped filters. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible indicates whether the tag should appear in public filters. + * Usage: public filter APIs only return visible tags; admin screens may still display it. + */ + private Integer frontVisible; + /** * 创建时间 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistGroupVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistGroupVO.java new file mode 100644 index 00000000..2822f608 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistGroupVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.yuminailcore.vo; + +import com.xiaowang.yuminailcore.dto.WishlistDTO; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistGroupVO { + private Long id; + private String name; + private Integer sortOrder; + private Integer itemCount; + private List items = new ArrayList<>(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistInspirationVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistInspirationVO.java new file mode 100644 index 00000000..9b52693c --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WishlistInspirationVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistInspirationVO { + private Integer total; + private List groups = new ArrayList<>(); +} diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index 7912bfca..e2e823cc 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -431,6 +431,8 @@ create table t_product 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个', @@ -527,6 +529,10 @@ create table t_tag 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-已删', @@ -772,6 +778,28 @@ create index idx_vip_level on t_vip_info (vip_level) comment '按VIP等级查询的索引'; +-- auto-generated definition +create table 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 '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + -- auto-generated definition create table t_wishlist ( @@ -779,6 +807,9 @@ create table t_wishlist 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-已删除', @@ -795,6 +826,10 @@ create index idx_user_id on t_wishlist (user_id) comment '按用户查询收藏的索引'; +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + -- ======================================== -- 首次部署整合区:用户资产 / VIP / 优惠券补丁 -- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql @@ -956,6 +991,14 @@ 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等级'''); @@ -1788,6 +1831,7 @@ 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'); diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/ProductControllerTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/ProductControllerTest.java index 2513d60b..29364434 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/ProductControllerTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/ProductControllerTest.java @@ -76,6 +76,15 @@ class ProductControllerTest { verify(productService, never()).listProductsByShopId(3L); } + @Test + void pagePublicProductsShouldPassGroupedTagIdsToService() { + MockHttpServletRequest request = new MockHttpServletRequest(); + + controller.pagePublicProducts(request, 1, 10, "", "", "11,22"); + + verify(productService).pagePublicProducts(1, 10, "", "", "11,22", null); + } + private MockHttpServletRequest authenticatedShopRequest(Long userId, Long shopId) { String token = "access-token"; MockHttpServletRequest request = new MockHttpServletRequest(); diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImplTest.java new file mode 100644 index 00000000..ebd1101b --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImplTest.java @@ -0,0 +1,227 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; +import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO; +import com.xiaowang.yuminailcore.entity.OrderDO; +import com.xiaowang.yuminailcore.entity.OrderItemDO; +import com.xiaowang.yuminailcore.entity.ProductDO; +import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper; +import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper; +import com.xiaowang.yuminailcore.mapper.OrderItemMapper; +import com.xiaowang.yuminailcore.mapper.OrderMapper; +import com.xiaowang.yuminailcore.mapper.ProductMapper; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.vo.NailArtistAvailabilityVO; +import com.xiaowang.yuminailcore.vo.NailArtistProfileVO; +import com.xiaowang.yuminailcore.vo.NailArtistReviewVO; +import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.when; + +class NailArtistInfoServiceImplTest { + + @Mock + private NailArtistInfoMapper nailArtistInfoMapper; + @Mock + private UserMapper userMapper; + @Mock + private ShopMapper shopMapper; + @Mock + private UserShopBindingSupport userShopBindingSupport; + @Mock + private ProductMapper productMapper; + @Mock + private OrderMapper orderMapper; + @Mock + private OrderItemMapper orderItemMapper; + @Mock + private OrderArtistReviewMapper orderArtistReviewMapper; + @Mock + private ObjectStorageFileService objectStorageFileService; + + private NailArtistInfoServiceImpl service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + service = new NailArtistInfoServiceImpl(); + ReflectionTestUtils.setField(service, "baseMapper", nailArtistInfoMapper); + ReflectionTestUtils.setField(service, "userMapper", userMapper); + ReflectionTestUtils.setField(service, "shopMapper", shopMapper); + ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport); + ReflectionTestUtils.setField(service, "productMapper", productMapper); + ReflectionTestUtils.setField(service, "orderMapper", orderMapper); + ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper); + ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper); + ReflectionTestUtils.setField(service, "objectStorageFileService", objectStorageFileService); + when(userShopBindingSupport.listShopOptionsByUserId(any(), anyBoolean(), anyBoolean())).thenReturn(List.of()); + } + + @Test + void getPublicProfileAggregatesArtistBasicsWorksReviewsAndAvailability() { + NailArtistInfoDO artistInfo = new NailArtistInfoDO(); + artistInfo.setId(11L); + artistInfo.setUserId(7L); + artistInfo.setIdentity("Yumi senior artist"); + artistInfo.setExperience(5); + artistInfo.setSkills("法式,猫眼"); + artistInfo.setRating(new BigDecimal("4.7")); + artistInfo.setStatus(1); + artistInfo.setPortfolio("31"); + artistInfo.setWorkStartTime(LocalTime.of(10, 0)); + artistInfo.setWorkEndTime(LocalTime.of(12, 0)); + artistInfo.setIsDelete(0); + when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo); + + UserDO artist = new UserDO(); + artist.setId(7L); + artist.setNickname("Mina"); + artist.setAvatar("https://img.test/mina.jpg"); + artist.setSignature("Clean lines and soft colors"); + artist.setType(3); + artist.setShopId(9L); + artist.setIsDelete(0); + when(userMapper.selectById(7L)).thenReturn(artist); + + ShopDO shop = new ShopDO(); + shop.setId(9L); + shop.setShopName("Yumi Test Shop"); + when(shopMapper.selectById(9L)).thenReturn(shop); + when(userShopBindingSupport.listShopOptionsByUserId(7L, true, true)).thenReturn(List.of()); + + ProductDO product = new ProductDO(); + product.setId(31L); + product.setShopId(9L); + product.setTitle("Soft French"); + product.setPrice(new BigDecimal("168.00")); + product.setImageFileIds("201"); + product.setTags("通勤;显白"); + product.setIsDelete(0); + when(productMapper.selectBatchIds(any())).thenReturn(List.of(product)); + + ObjectStorageFileVO productImage = new ObjectStorageFileVO(); + productImage.setId(201L); + productImage.setFileUrl("https://img.test/product.jpg"); + when(objectStorageFileService.getObjectStorageFileMapByIds(any())).thenReturn(Map.of(201L, productImage)); + + OrderDO completedOrder = new OrderDO(); + completedOrder.setId(41L); + completedOrder.setStatus(2); + completedOrder.setIsDelete(0); + when(orderMapper.selectByArtistId(7L)).thenReturn(List.of(completedOrder)); + + OrderItemDO servedItem = new OrderItemDO(); + servedItem.setId(51L); + servedItem.setOrderId(41L); + servedItem.setArtistId(7L); + servedItem.setProductId(31L); + servedItem.setQuantity(2); + servedItem.setIsDelete(0); + when(orderItemMapper.selectByOrderId(41L)).thenReturn(List.of(servedItem)); + when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of()); + + OrderArtistReviewDO submitted = new OrderArtistReviewDO(); + submitted.setId(61L); + submitted.setArtistId(7L); + submitted.setCustomerId(71L); + submitted.setProductId(31L); + submitted.setRatingScore(new BigDecimal("5.0")); + submitted.setContent("Lines are precise"); + submitted.setStatus(1); + submitted.setSubmittedAt(LocalDateTime.now().minusDays(1)); + submitted.setIsDelete(0); + when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted)); + when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(7L)).thenReturn(new BigDecimal("5.0")); + + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setNickname("Ava"); + when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer)); + + NailArtistProfileVO profile = service.getPublicProfile(7L); + + assertThat(profile.getArtistId()).isEqualTo(7L); + assertThat(profile.getArtistName()).isEqualTo("Mina"); + assertThat(profile.getShopName()).isEqualTo("Yumi Test Shop"); + assertThat(profile.getStyleTags()).containsExactly("法式", "猫眼"); + assertThat(profile.getRating()).isEqualByComparingTo("5.0"); + assertThat(profile.getServiceCount()).isEqualTo(2L); + assertThat(profile.getWorks()).hasSize(1); + assertThat(profile.getWorks().get(0).getCoverImageUrl()).isEqualTo("https://img.test/product.jpg"); + assertThat(profile.getReviews()).hasSize(1); + assertThat(profile.getReviews().get(0).getCustomerName()).isEqualTo("Ava"); + assertThat(profile.getAvailability()).isNotEmpty(); + } + + @Test + void listPublicReviewsReturnsSubmittedReviewsOnly() { + OrderArtistReviewDO submitted = new OrderArtistReviewDO(); + submitted.setId(61L); + submitted.setArtistId(7L); + submitted.setCustomerId(71L); + submitted.setRatingScore(new BigDecimal("4.5")); + submitted.setContent("Gentle and detailed"); + submitted.setStatus(1); + submitted.setSubmittedAt(LocalDateTime.now().minusHours(2)); + submitted.setIsDelete(0); + when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted)); + + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setNickname("Ava"); + when(userMapper.selectBatchIds(List.of(71L))).thenReturn(List.of(customer)); + + List reviews = service.listPublicReviews(7L); + + assertThat(reviews).hasSize(1); + assertThat(reviews.get(0).getRating()).isEqualByComparingTo("4.5"); + assertThat(reviews.get(0).getContent()).isEqualTo("Gentle and detailed"); + } + + @Test + void getAvailabilitySkipsBookedSlots() { + NailArtistInfoDO artistInfo = new NailArtistInfoDO(); + artistInfo.setUserId(7L); + artistInfo.setStatus(1); + artistInfo.setWorkStartTime(LocalTime.of(10, 0)); + artistInfo.setWorkEndTime(LocalTime.of(12, 0)); + artistInfo.setIsDelete(0); + when(nailArtistInfoMapper.selectOne(any())).thenReturn(artistInfo); + UserDO artist = new UserDO(); + artist.setId(7L); + artist.setType(3); + artist.setIsDelete(0); + when(userMapper.selectById(7L)).thenReturn(artist); + + OrderItemDO booked = new OrderItemDO(); + booked.setArtistId(7L); + booked.setAppointmentTime(LocalDateTime.now().plusDays(1).withHour(10).withMinute(0).withSecond(0).withNano(0)); + when(orderItemMapper.selectArtistCalendarItems(any(), any(), any())).thenReturn(List.of(booked)); + + List slots = service.getAvailability(7L); + + assertThat(slots).isNotEmpty(); + assertThat(slots) + .noneMatch(slot -> slot.getStartTime().toLocalDate().equals(booked.getAppointmentTime().toLocalDate()) + && slot.getStartTime().toLocalTime().equals(LocalTime.of(10, 0))); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplCheckoutPreviewTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplCheckoutPreviewTest.java new file mode 100644 index 00000000..b15cad46 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplCheckoutPreviewTest.java @@ -0,0 +1,161 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.xiaowang.yuminailcore.dto.CheckoutPreviewDTO; +import com.xiaowang.yuminailcore.dto.OrderItemDTO; +import com.xiaowang.yuminailcore.entity.CartDO; +import com.xiaowang.yuminailcore.entity.CouponDO; +import com.xiaowang.yuminailcore.entity.ProductDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.CartMapper; +import com.xiaowang.yuminailcore.mapper.CouponMapper; +import com.xiaowang.yuminailcore.mapper.ProductMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.service.CouponService; +import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.vo.CheckoutPreviewVO; +import com.xiaowang.yuminailcore.vo.UserCouponVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +class OrderServiceImplCheckoutPreviewTest { + + @Mock + private ProductMapper productMapper; + @Mock + private CartMapper cartMapper; + @Mock + private CouponMapper couponMapper; + @Mock + private UserMapper userMapper; + @Mock + private CouponService couponService; + @Mock + private UserShopBindingSupport userShopBindingSupport; + + private OrderServiceImpl service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + service = new OrderServiceImpl(); + ReflectionTestUtils.setField(service, "productMapper", productMapper); + ReflectionTestUtils.setField(service, "cartMapper", cartMapper); + ReflectionTestUtils.setField(service, "couponMapper", couponMapper); + ReflectionTestUtils.setField(service, "userMapper", userMapper); + ReflectionTestUtils.setField(service, "couponService", couponService); + ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport); + } + + @Test + void checkoutPreviewExplainsBestAvailableCouponAndUnavailableReasons() { + ProductDO product = product(100L, "温柔法式", "法式,通勤", new BigDecimal("100.00")); + CartDO cartItem = cartItem(100L, 2); + UserCouponVO vipCoupon = couponOption(300L, 300L, "SYSTEM_VIP", "黄金VIP自动90折券", 1, "9.0", null, null); + UserCouponVO userCoupon = couponOption(400L, 500L, "USER_COUPON", "满150减30", 2, null, "150.00", "30.00"); + + when(productMapper.selectById(100L)).thenReturn(product); + when(cartMapper.selectByUserIdAndProductId(20L, 100L)).thenReturn(cartItem); + when(userMapper.selectById(20L)).thenReturn(user("黄金")); + when(userShopBindingSupport.canUserAccessShop(20L, 9L, false, null)).thenReturn(true); + when(couponService.getAvailableCoupons(20L, "法式,通勤", 200.0, 9L)).thenReturn(List.of(userCoupon, vipCoupon)); + when(couponMapper.selectById(300L)).thenReturn(coupon(300L, "黄金VIP自动90折券", 1, new BigDecimal("9.0"), null, null, 9L)); + when(couponMapper.selectById(400L)).thenReturn(coupon(400L, "满150减30", 2, null, new BigDecimal("150.00"), new BigDecimal("30.00"), 9L)); + when(couponMapper.selectList(any())).thenReturn(List.of( + coupon(600L, "满300减80", 2, null, new BigDecimal("300.00"), new BigDecimal("80.00"), 9L), + coupon(700L, "其他门店券", 2, null, new BigDecimal("50.00"), new BigDecimal("5.00"), 10L) + )); + + CheckoutPreviewVO preview = service.checkoutPreview(20L, order(100L, 2)); + + assertThat(preview.getSubtotalAmount()).isEqualByComparingTo("200.00"); + assertThat(preview.getSavedAmount()).isEqualByComparingTo("30.00"); + assertThat(preview.getPayableAmount()).isEqualByComparingTo("170.00"); + assertThat(preview.getBestCoupon().getCouponName()).isEqualTo("满150减30"); + assertThat(preview.getAvailableCoupons()).extracting("couponName") + .containsExactly("满150减30", "黄金VIP自动90折券"); + assertThat(preview.getUnavailableCoupons()).extracting("couponName") + .containsExactly("满300减80", "其他门店券"); + assertThat(preview.getUnavailableCoupons()).extracting("unavailableReason") + .containsExactly("还差 ¥100.00 可用", "仅限其他门店使用"); + assertThat(preview.getVipTip()).isEqualTo("黄金VIP本单可省 ¥20.00,已为你计算。"); + assertThat(preview.getSummaryText()).isEqualTo("商品小计 ¥200.00,已省 ¥30.00,到手价 ¥170.00。"); + } + + private CheckoutPreviewDTO order(Long productId, Integer quantity) { + OrderItemDTO item = new OrderItemDTO(); + item.setProductId(productId); + item.setQuantity(quantity); + + CheckoutPreviewDTO dto = new CheckoutPreviewDTO(); + dto.setItems(List.of(item)); + return dto; + } + + private ProductDO product(Long id, String title, String tags, BigDecimal price) { + ProductDO product = new ProductDO(); + product.setId(id); + product.setTitle(title); + product.setTags(tags); + product.setPrice(price); + product.setShopId(9L); + product.setIsDelete(0); + return product; + } + + private CartDO cartItem(Long productId, Integer quantity) { + CartDO item = new CartDO(); + item.setUserId(20L); + item.setProductId(productId); + item.setQuantity(quantity); + item.setIsDelete(0); + return item; + } + + private UserDO user(String level) { + UserDO user = new UserDO(); + user.setId(20L); + user.setLevel(level); + user.setIsDelete(0); + return user; + } + + private CouponDO coupon(Long id, String name, Integer type, BigDecimal discountValue, BigDecimal minAmount, BigDecimal reduceAmount, Long shopId) { + CouponDO coupon = new CouponDO(); + coupon.setId(id); + coupon.setCouponName(name); + coupon.setCouponType(type); + coupon.setDiscountValue(discountValue); + coupon.setMinAmount(minAmount); + coupon.setReduceAmount(reduceAmount); + coupon.setShopId(shopId); + coupon.setStatus(1); + coupon.setStartTime(LocalDateTime.now().minusDays(1)); + coupon.setEndTime(LocalDateTime.now().plusDays(1)); + coupon.setIsDelete(0); + return coupon; + } + + private UserCouponVO couponOption(Long id, Long couponId, String sourceType, String name, Integer type, String discountValue, String minAmount, String reduceAmount) { + UserCouponVO coupon = new UserCouponVO(); + coupon.setId(id); + coupon.setCouponId(couponId); + coupon.setSourceType(sourceType); + coupon.setCouponName(name); + coupon.setCouponType(type); + coupon.setDiscountValue(discountValue); + coupon.setMinAmount(minAmount); + coupon.setReduceAmount(reduceAmount); + return coupon; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java index 7c2fe0c4..53fcdda6 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java @@ -401,6 +401,46 @@ class OrderServiceImplReviewChangeTest { verify(orderArtistChangeRequestMapper).selectPendingByUserId(2L); } + @Test + void listOrderArtistChangeRequestsExpiresDueRequestsAndReturnsHistoryForAccessibleOrder() { + OrderDO order = pendingOrder(); + OrderArtistChangeRequestDO approved = pendingChangeRequest(); + approved.setStatus("APPROVED"); + approved.setApprovedTime(LocalDateTime.now().minusHours(2)); + OrderArtistChangeRequestDO rejected = pendingChangeRequest(); + rejected.setId(501L); + rejected.setStatus("REJECTED"); + rejected.setRejectedTime(LocalDateTime.now().minusHours(1)); + rejected.setRejectReason("时间不合适"); + + when(orderMapper.selectById(1L)).thenReturn(order); + when(orderArtistChangeRequestMapper.selectByOrderId(1L)).thenReturn(List.of(approved, rejected)); + when(productMapper.selectById(20L)).thenReturn(product()); + when(userMapper.selectById(30L)).thenReturn(artist(30L)); + when(userMapper.selectById(31L)).thenReturn(artist(31L)); + + assertThat(service.listOrderArtistChangeRequests(1L, 2L, 0)) + .extracting("id") + .containsExactly(500L, 501L); + + verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class)); + verify(orderArtistChangeRequestMapper).selectByOrderId(1L); + } + + @Test + void listOrderArtistChangeRequestsRejectsInaccessibleOrder() { + OrderDO order = pendingOrder(); + when(orderMapper.selectById(1L)).thenReturn(order); + when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(orderItem())); + + assertThatThrownBy(() -> service.listOrderArtistChangeRequests(1L, 99L, 0)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("ORDER_ARTIST_CHANGE_FORBIDDEN"); + + verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class)); + verify(orderArtistChangeRequestMapper, never()).selectByOrderId(any()); + } + @Test void submitArtistReviewRequiresHalfPointRating() { OrderArtistReviewDO review = pendingReview(); diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImplTest.java new file mode 100644 index 00000000..da8021b8 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImplTest.java @@ -0,0 +1,120 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.xiaowang.yuminailcore.config.AppCacheProperties; +import com.xiaowang.yuminailcore.dto.ProductDTO; +import com.xiaowang.yuminailcore.entity.ProductDO; +import com.xiaowang.yuminailcore.mapper.CouponMapper; +import com.xiaowang.yuminailcore.mapper.ProductMapper; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.TagMapper; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.support.BookableArtistSupport; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import com.xiaowang.yuminailcore.vo.ProductVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.math.BigDecimal; +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ProductServiceImplTest { + + @Mock + private ProductMapper productMapper; + + @Mock + private ObjectStorageFileService objectStorageFileService; + + @Mock + private CouponMapper couponMapper; + + @Mock + private ShopMapper shopMapper; + + @Mock + private TagMapper tagMapper; + + @Mock + private BookableArtistSupport bookableArtistSupport; + + @Mock + private MultiLevelCacheService multiLevelCacheService; + + private ProductServiceImpl productService; + + @BeforeEach + void setUp() { + AppCacheProperties cacheProperties = new AppCacheProperties(); + productService = new ProductServiceImpl( + productMapper, + objectStorageFileService, + couponMapper, + shopMapper, + tagMapper, + bookableArtistSupport, + multiLevelCacheService, + cacheProperties + ); + } + + @Test + void createProductShouldPersistTargetAudienceAndPrecautions() { + ProductDTO dto = new ProductDTO(); + dto.setShopId(3L); + dto.setTitle("French cat eye"); + dto.setDescription("soft shimmer"); + dto.setPrice(new BigDecimal("168.00")); + dto.setTargetAudience("Short nails, daily office style"); + dto.setPrecautions("Avoid long hot baths within 24 hours"); + when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn(""); + when(productMapper.insert(any(ProductDO.class))).thenAnswer(invocation -> { + ProductDO product = invocation.getArgument(0); + product.setId(99L); + return 1; + }); + + productService.createProduct(dto); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ProductDO.class); + org.mockito.Mockito.verify(productMapper).insert(captor.capture()); + assertEquals("Short nails, daily office style", captor.getValue().getTargetAudience()); + assertEquals("Avoid long hot baths within 24 hours", captor.getValue().getPrecautions()); + } + + @Test + void getProductByIdShouldExposeTargetAudienceAndPrecautions() { + ProductDO product = new ProductDO(); + product.setId(99L); + product.setShopId(3L); + product.setTitle("French cat eye"); + product.setDescription("soft shimmer"); + product.setPrice(new BigDecimal("168.00")); + product.setTargetAudience("Short nails, daily office style"); + product.setPrecautions("Avoid long hot baths within 24 hours"); + product.setIsDelete(0); + when(productMapper.selectById(99L)).thenReturn(product); + when(bookableArtistSupport.filterValidBookableArtists(3L, null)).thenReturn(""); + when(multiLevelCacheService.getOrLoad( + anyString(), + any(Duration.class), + any(Duration.class), + any(), + any() + )).thenAnswer(invocation -> ((java.util.function.Supplier) invocation.getArgument(4)).get()); + + ProductVO productVO = productService.getProductById(99L); + + assertEquals("Short nails, daily office style", productVO.getTargetAudience()); + assertEquals("Avoid long hot baths within 24 hours", productVO.getPrecautions()); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java index 3a29a79f..2d85fc5a 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java @@ -2,23 +2,36 @@ package com.xiaowang.yuminailcore.service.impl; import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.dto.ShopDTO; +import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO; +import com.xiaowang.yuminailcore.entity.ProductDO; import com.xiaowang.yuminailcore.entity.ShopDO; import com.xiaowang.yuminailcore.mapper.CommentMapper; import com.xiaowang.yuminailcore.mapper.CouponMapper; +import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper; import com.xiaowang.yuminailcore.mapper.ProductMapper; import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.TagMapper; import com.xiaowang.yuminailcore.mapper.UserCouponMapper; import com.xiaowang.yuminailcore.service.CouponService; import com.xiaowang.yuminailcore.service.MapService; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; +import com.xiaowang.yuminailcore.vo.ShopTrustProfileVO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -40,6 +53,10 @@ class ShopServiceImplTest { @Mock private UserCouponMapper userCouponMapper; @Mock + private OrderArtistReviewMapper orderArtistReviewMapper; + @Mock + private ObjectStorageFileService objectStorageFileService; + @Mock private UserShopBindingSupport userShopBindingSupport; @Mock private MultiLevelCacheService multiLevelCacheService; @@ -61,6 +78,8 @@ class ShopServiceImplTest { tagMapper, commentMapper, userCouponMapper, + orderArtistReviewMapper, + objectStorageFileService, userShopBindingSupport, multiLevelCacheService, appCacheProperties, @@ -99,4 +118,79 @@ class ShopServiceImplTest { verify(shopMapper, never()).updateById(disabledShop); } + + @Test + void getShopTrustProfileAggregatesPublicTrustDataWithoutContactPhone() { + ShopDO shop = new ShopDO(); + shop.setId(9L); + shop.setShopName("Yumi Test Shop"); + shop.setStatus(1); + shop.setIsDelete(0); + shop.setBusinessHours("10:00-20:00"); + shop.setImageFileIds("101,102"); + shop.setCoverImageFileId("100"); + shop.setCreateTime(LocalDateTime.now().minusDays(10)); + when(shopMapper.selectById(9L)).thenReturn(shop); + + ProductDO featured = new ProductDO(); + featured.setId(31L); + featured.setShopId(9L); + featured.setTitle("琉璃猫眼"); + featured.setDescription("透亮显白"); + featured.setPrice(new BigDecimal("168.00")); + featured.setImageFileIds("201"); + featured.setLikeCount(5); + featured.setCollectCount(12); + featured.setBookableArtists("7,8"); + featured.setIsDelete(0); + featured.setCreateTime(LocalDateTime.now().minusDays(1)); + when(productMapper.selectCount(any())).thenReturn(1L); + when(productMapper.selectList(any())).thenReturn(List.of(featured)); + + OrderArtistReviewDO submitted = new OrderArtistReviewDO(); + submitted.setId(51L); + submitted.setShopId(9L); + submitted.setProductId(31L); + submitted.setRatingScore(new BigDecimal("4.5")); + submitted.setContent("环境干净,做得很细"); + submitted.setStatus(1); + submitted.setIsDelete(0); + submitted.setSubmittedAt(LocalDateTime.now().minusHours(3)); + OrderArtistReviewDO pending = new OrderArtistReviewDO(); + pending.setId(52L); + pending.setShopId(9L); + pending.setRatingScore(new BigDecimal("1.0")); + pending.setContent("待评价不应展示"); + pending.setStatus(0); + pending.setIsDelete(0); + when(orderArtistReviewMapper.selectList(any())).thenReturn(List.of(submitted)); + when(orderArtistReviewMapper.selectCount(any())).thenReturn(1L); + + ObjectStorageFileVO cover = new ObjectStorageFileVO(); + cover.setId(100L); + cover.setFileUrl("https://img.test/cover.jpg"); + ObjectStorageFileVO env = new ObjectStorageFileVO(); + env.setId(101L); + env.setFileUrl("https://img.test/env.jpg"); + ObjectStorageFileVO productImage = new ObjectStorageFileVO(); + productImage.setId(201L); + productImage.setFileUrl("https://img.test/product.jpg"); + when(objectStorageFileService.getObjectStorageFileMapByIds(any())) + .thenReturn(Map.of(100L, cover, 101L, env, 201L, productImage)); + + ShopTrustProfileVO profile = service.getShopTrustProfile(9L); + + assertThat(profile).isNotNull(); + assertThat(profile.getShopId()).isEqualTo(9L); + assertThat(profile.getStats().getProductCount()).isEqualTo(1L); + assertThat(profile.getStats().getReviewCount()).isEqualTo(1L); + assertThat(profile.getStats().getAverageRating()).isEqualByComparingTo("4.5"); + assertThat(profile.getEnvironmentImages()).contains("https://img.test/cover.jpg", "https://img.test/env.jpg"); + assertThat(profile.getFeaturedProducts()).hasSize(1); + assertThat(profile.getFeaturedProducts().get(0).getImageUrl()).isEqualTo("https://img.test/product.jpg"); + assertThat(profile.getRecentReviews()).hasSize(1); + assertThat(profile.getRecentReviews().get(0).getContent()).isEqualTo("环境干净,做得很细"); + assertThat(profile.getContactSummary().getPhoneExposed()).isFalse(); + assertThat(profile.getContactSummary().getPhone()).isNull(); + } } diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/TagServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/TagServiceImplTest.java new file mode 100644 index 00000000..06a2d3b0 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/TagServiceImplTest.java @@ -0,0 +1,73 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.yuminailcore.config.AppCacheProperties; +import com.xiaowang.yuminailcore.entity.TagDO; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.TagMapper; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import com.xiaowang.yuminailcore.vo.TagFilterGroupVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.function.Supplier; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class TagServiceImplTest { + + private TagMapper tagMapper; + private TagServiceImpl service; + + @BeforeEach + void setUp() { + tagMapper = mock(TagMapper.class); + ShopMapper shopMapper = mock(ShopMapper.class); + MultiLevelCacheService cacheService = mock(MultiLevelCacheService.class); + AppCacheProperties cacheProperties = new AppCacheProperties(); + when(cacheService.getOrLoad( + anyString(), + any(Duration.class), + any(Duration.class), + any(TypeReference.class), + any(Supplier.class) + )).thenAnswer(invocation -> ((Supplier) invocation.getArgument(4)).get()); + service = new TagServiceImpl(tagMapper, shopMapper, cacheService, cacheProperties); + } + + @Test + void listFilterOptionsGroupsOnlyFrontVisibleTagsAndKeepsLegacyDefaults() { + TagDO style = tag(1L, "日常", "风格", "通勤", 20, 1); + TagDO legacy = tag(2L, "显白", null, null, null, null); + TagDO hidden = tag(3L, "隐藏", "风格", "隐藏", 1, 0); + when(tagMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of(hidden, legacy, style)); + + List groups = service.listFilterOptions(null); + + assertThat(groups).hasSize(2); + assertThat(groups.get(0).getGroupName()).isEqualTo("风格"); + assertThat(groups.get(0).getTags()).extracting("displayName").containsExactly("通勤"); + assertThat(groups.get(1).getGroupName()).isEqualTo("其他"); + assertThat(groups.get(1).getTags()).extracting("displayName").containsExactly("显白"); + } + + private TagDO tag(Long id, String tagName, String sceneGroup, String displayName, Integer sortOrder, Integer frontVisible) { + TagDO tag = new TagDO(); + tag.setId(id); + tag.setShopId(8L); + tag.setTagName(tagName); + tag.setSceneGroup(sceneGroup); + tag.setDisplayName(displayName); + tag.setSortOrder(sortOrder); + tag.setFrontVisible(frontVisible); + tag.setIsDelete(0); + return tag; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImplTest.java new file mode 100644 index 00000000..0b6504d9 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImplTest.java @@ -0,0 +1,208 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.yuminailcore.dto.WishlistAddWithGroupDTO; +import com.xiaowang.yuminailcore.dto.WishlistMoveDTO; +import com.xiaowang.yuminailcore.dto.WishlistGroupDTO; +import com.xiaowang.yuminailcore.entity.ProductDO; +import com.xiaowang.yuminailcore.entity.WishlistDO; +import com.xiaowang.yuminailcore.entity.WishlistGroupDO; +import com.xiaowang.yuminailcore.mapper.ProductMapper; +import com.xiaowang.yuminailcore.mapper.WishlistGroupMapper; +import com.xiaowang.yuminailcore.mapper.WishlistMapper; +import com.xiaowang.yuminailcore.service.ProductService; +import com.xiaowang.yuminailcore.vo.ProductVO; +import com.xiaowang.yuminailcore.vo.WishlistGroupVO; +import com.xiaowang.yuminailcore.vo.WishlistInspirationVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.math.BigDecimal; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class WishlistServiceImplTest { + + private static final String RECENT_GROUP = "\u6700\u8fd1\u60f3\u505a"; + private static final String WEDDING_GROUP = "\u5a5a\u793c\u6b3e"; + private static final String SUMMER_GROUP = "\u590f\u5929\u6b3e"; + + private WishlistMapper wishlistMapper; + private WishlistGroupMapper wishlistGroupMapper; + private ProductMapper productMapper; + private ProductService productService; + private WishlistServiceImpl service; + + @BeforeEach + void setUp() { + wishlistMapper = mock(WishlistMapper.class); + wishlistGroupMapper = mock(WishlistGroupMapper.class); + productMapper = mock(ProductMapper.class); + productService = mock(ProductService.class); + service = new WishlistServiceImpl(wishlistMapper, wishlistGroupMapper, productService, productMapper); + } + + @Test + void listGroupsCreatesPresetGroupsForNewUser() { + when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of()); + + List groups = service.listGroups(88L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WishlistGroupDO.class); + verify(wishlistGroupMapper, org.mockito.Mockito.times(3)).insert(captor.capture()); + assertThat(captor.getAllValues()) + .extracting(WishlistGroupDO::getName) + .containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP); + assertThat(groups).extracting(WishlistGroupVO::getName) + .containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP); + } + + @Test + void addWithGroupCreatesWishlistEntryWithGroupMetadata() { + ProductDO product = new ProductDO(); + product.setId(9L); + product.setIsDelete(0); + when(productMapper.selectById(9L)).thenReturn(product); + when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20)); + when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(null); + + WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO(); + request.setProductId(9L); + request.setGroupId(3L); + request.setNote("Ask for pearl accent"); + request.setSortOrder(7); + service.addToWishlist(88L, request); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WishlistDO.class); + verify(wishlistMapper).insert(captor.capture()); + assertThat(captor.getValue().getUserId()).isEqualTo(88L); + assertThat(captor.getValue().getProductId()).isEqualTo(9L); + assertThat(captor.getValue().getGroupId()).isEqualTo(3L); + assertThat(captor.getValue().getNote()).isEqualTo("Ask for pearl accent"); + assertThat(captor.getValue().getSortOrder()).isEqualTo(7); + verify(productMapper).incrementCollectCount(9L); + } + + @Test + void addWithGroupUpdatesExistingWishlistWithoutIncrementingCollectCount() { + ProductDO product = new ProductDO(); + product.setId(9L); + product.setIsDelete(0); + WishlistDO existing = new WishlistDO(); + existing.setId(11L); + existing.setUserId(88L); + existing.setProductId(9L); + when(productMapper.selectById(9L)).thenReturn(product); + when(wishlistGroupMapper.selectById(3L)).thenReturn(group(3L, 88L, WEDDING_GROUP, 20)); + when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing); + + WishlistAddWithGroupDTO request = new WishlistAddWithGroupDTO(); + request.setProductId(9L); + request.setGroupId(3L); + request.setNote("Move to wedding board"); + service.addToWishlist(88L, request); + + assertThat(existing.getGroupId()).isEqualTo(3L); + assertThat(existing.getNote()).isEqualTo("Move to wedding board"); + verify(wishlistMapper).updateById(existing); + verify(productMapper, never()).incrementCollectCount(9L); + } + + @Test + void moveWishlistChangesGroupNoteAndOrder() { + WishlistDO existing = new WishlistDO(); + existing.setId(11L); + existing.setUserId(88L); + existing.setProductId(9L); + when(wishlistMapper.selectOne(any(Wrapper.class))).thenReturn(existing); + when(wishlistGroupMapper.selectById(2L)).thenReturn(group(2L, 88L, SUMMER_GROUP, 30)); + + WishlistMoveDTO request = new WishlistMoveDTO(); + request.setProductId(9L); + request.setGroupId(2L); + request.setNote("Try blue"); + request.setSortOrder(4); + service.moveWishlist(88L, request); + + assertThat(existing.getGroupId()).isEqualTo(2L); + assertThat(existing.getNote()).isEqualTo("Try blue"); + assertThat(existing.getSortOrder()).isEqualTo(4); + verify(wishlistMapper).updateById(existing); + } + + @Test + void inspirationGroupsWishlistItemsByGroupAndKeepsUngroupedInDefaultGroup() { + WishlistGroupDO recent = group(1L, 88L, RECENT_GROUP, 10); + WishlistGroupDO summer = group(2L, 88L, SUMMER_GROUP, 30); + WishlistDO grouped = wishlist(101L, 88L, 9L, 2L, "Try blue", 4); + WishlistDO legacy = wishlist(102L, 88L, 10L, null, null, 0); + when(wishlistGroupMapper.selectList(any(Wrapper.class))).thenReturn(List.of(recent, summer)); + when(wishlistMapper.selectList(any(Wrapper.class))).thenReturn(List.of(grouped, legacy)); + when(productService.getProductById(9L)).thenReturn(product(9L, "Ocean glass")); + when(productService.getProductById(10L)).thenReturn(product(10L, "Plain nude")); + + WishlistInspirationVO inspiration = service.getInspiration(88L); + + assertThat(inspiration.getTotal()).isEqualTo(2); + assertThat(inspiration.getGroups()).extracting(WishlistGroupVO::getName) + .containsExactly(RECENT_GROUP, WEDDING_GROUP, SUMMER_GROUP); + assertThat(inspiration.getGroups().get(0).getItems()) + .extracting(item -> item.getProduct().getTitle()) + .containsExactly("Plain nude"); + assertThat(inspiration.getGroups().get(1).getItems()).isEmpty(); + assertThat(inspiration.getGroups().get(2).getItems()) + .extracting(item -> item.getProduct().getTitle()) + .containsExactly("Ocean glass"); + } + + @Test + void createGroupNormalizesNameAndSortOrder() { + WishlistGroupDTO request = new WishlistGroupDTO(); + request.setName(" Bride ideas "); + + service.createGroup(88L, request); + + ArgumentCaptor captor = ArgumentCaptor.forClass(WishlistGroupDO.class); + verify(wishlistGroupMapper).insert(captor.capture()); + assertThat(captor.getValue().getName()).isEqualTo("Bride ideas"); + assertThat(captor.getValue().getSortOrder()).isEqualTo(100); + assertThat(captor.getValue().getIsDelete()).isZero(); + } + + private WishlistGroupDO group(Long id, Long userId, String name, Integer sortOrder) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setId(id); + group.setUserId(userId); + group.setName(name); + group.setSortOrder(sortOrder); + group.setIsDelete(0); + return group; + } + + private WishlistDO wishlist(Long id, Long userId, Long productId, Long groupId, String note, Integer sortOrder) { + WishlistDO wishlist = new WishlistDO(); + wishlist.setId(id); + wishlist.setUserId(userId); + wishlist.setProductId(productId); + wishlist.setGroupId(groupId); + wishlist.setNote(note); + wishlist.setSortOrder(sortOrder); + wishlist.setIsDelete(0); + return wishlist; + } + + private ProductVO product(Long id, String title) { + ProductVO product = new ProductVO(); + product.setId(id); + product.setTitle(title); + product.setPrice(new BigDecimal("168.00")); + return product; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/WishlistSqlSchemaTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/WishlistSqlSchemaTest.java new file mode 100644 index 00000000..1d3f0f4d --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/WishlistSqlSchemaTest.java @@ -0,0 +1,47 @@ +package com.xiaowang.yuminailcore.support; + +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; + +class WishlistSqlSchemaTest { + + @Test + void wishlistGroupsAndMetadataAreSeededInRuntimeSql() throws Exception { + String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql")); + + assertWishlistSchema(sql); + } + + @Test + void wishlistGroupsAndMetadataAreSeededInInitSql() throws Exception { + String sql = Files.readString(Path.of("../scripts/sql/init/YumiNail.sql")); + + assertWishlistSchema(sql); + } + + @Test + void wishlistMigrationCanPatchExistingDatabases() throws Exception { + String sql = Files.readString(Path.of("../scripts/sql/migrations/20260523_wishlist_groups.sql")); + + assertWishlistSchema(sql); + } + + private void assertWishlistSchema(String sql) { + assertThat(sql).contains("t_wishlist_group"); + assertThat(sql).contains("group_id"); + assertThat(sql).contains("note"); + assertThat(sql).contains("sort_order"); + assertThat(sql).contains("最近想做"); + assertThat(sql).contains("婚礼款"); + assertThat(sql).contains("夏天款"); + assertThat(sql).contains("idx_t_wishlist_group_user"); + assertThat(sql).contains("idx_t_wishlist_group_sort"); + assertThat(sql).contains("idx_t_wishlist_group_sort"); + assertThat(sql).contains("idx_t_wishlist_user_group_sort"); + assertThat(sql).contains("sp_drop_auto_increment_on_id_if_exists('t_wishlist_group')"); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java index ff440a16..25cdd0d5 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java @@ -44,4 +44,16 @@ class YumiNailSqlSchemaTest { assertThat(sql).contains("idx_business_event_outbox_due"); assertThat(sql).contains("'security:audit:view'"); } + + @Test + void tagSceneFilterColumnsAreSeeded() throws Exception { + String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql")); + + assertThat(sql).contains("scene_group"); + assertThat(sql).contains("display_name"); + assertThat(sql).contains("front_visible"); + assertThat(sql).contains("idx_t_tag_front_filter"); + assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'scene_group'"); + assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_tag', 'front_visible'"); + } } diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java index d0547fde..f47291fc 100644 --- a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java @@ -105,6 +105,7 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { "/api/shop/list/public", "/api/shop/list/simple", "/api/tag/list/all", + "/api/tag/list/filter-options", "/api/file/get-signed-url/**", "/api/admin/auth/login", "/api/admin/auth/login-shops/**", diff --git a/YumiNail-Gateway/src/main/resources/application.yaml b/YumiNail-Gateway/src/main/resources/application.yaml index 14bd4cab..712b9adf 100644 --- a/YumiNail-Gateway/src/main/resources/application.yaml +++ b/YumiNail-Gateway/src/main/resources/application.yaml @@ -127,6 +127,9 @@ yuminail: - /api/user/phone-login - /api/user/wechat-mini/** - /api/user/reset-password-by-phone + - /api/nail-artist/profile/** + - /api/nail-artist/*/availability + - /api/nail-artist/*/reviews - /api/shop/list/simple - /api/legal-agreement/current - /api/legal-agreement/current/** diff --git a/scripts/sql/init/YumiNail.sql b/scripts/sql/init/YumiNail.sql new file mode 100644 index 00000000..e2e823cc --- /dev/null +++ b/scripts/sql/init/YumiNail.sql @@ -0,0 +1,2120 @@ +-- YumiNail 最小运行初始化 SQL +-- 说明: +-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、基础参数、协议、MessageHub、VIP 规则与管理员初始化。 +-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、 +-- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。 +-- 3. 当前 Nacos datasource.yaml 指向 nailart,本文件默认按该库名初始化;如果你的实际数据库名不同,请先统一 datasource 与下方库名。 +-- 4. 本文件只初始化一个平台管理员 xiaowang(默认密码 888888),不写入开发/验收用户、门店、作品、标签、订单、消息公告等业务数据。 +CREATE DATABASE IF NOT EXISTS nailart DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +use nailart; + +-- auto-generated definition +create table 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 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 '用户余额变动明细表'; + +create index idx_change_time + on t_balance_change_detail (change_time) + comment '按时间查询余额变动的索引'; + +create index idx_user_id + on t_balance_change_detail (user_id) + comment '按用户查询余额变动的索引'; + +-- auto-generated definition +create table 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 '购物车表'; + +create index idx_user_id + on t_cart (user_id) + comment '按用户查询购物车的索引'; + +-- auto-generated definition +create table 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表示为根评论)', + 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 '用户评论信息表'; + +create index idx_parent_comment_id + on t_comment (parent_comment_id) + comment '按父级评论查询回复的索引'; + +create index idx_product_id + on t_comment (product_id) + comment '按商品查询评论的索引'; + +create index idx_shop_id + on t_comment (shop_id) + comment '按店铺查询评论的索引'; + +create index idx_user_id + on t_comment (user_id) + comment '按用户查询评论的索引'; + +-- auto-generated definition +create table 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 '优惠券信息表'; + +create index idx_status + on t_coupon (status) + comment '按状态查询优惠券的索引'; + +-- auto-generated definition +create table 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 '优惠券标签关联表'; + +create index idx_coupon_id + on t_coupon_tag (coupon_id) + comment '按优惠券查询标签的索引'; + +create index idx_tag_id + on t_coupon_tag (tag_id) + comment '按标签查询优惠券的索引'; + +-- auto-generated definition +create table 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 '商品效果图信息表'; + +create index idx_product_id + on t_effect_diagram (product_id) + comment '按商品查询效果图的索引'; + +-- auto-generated definition +create table 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 '用户登录标识信息表'; + +create index idx_login_method + on t_login_identity (login_method) + comment '按登录方式查询的索引'; + +create index idx_user_id + on t_login_identity (user_id) + comment '按用户查询登录标识的索引'; + +-- auto-generated definition +create table 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 '微信小程序账号绑定表'; + +create index idx_wechat_mini_unionid + on t_wechat_mini_binding (unionid) + comment '按unionid查询的索引'; + +-- auto-generated definition +create table 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 '美甲师信息表'; + +create index idx_status + on t_nail_artist_info (status) + comment '按状态查询美甲师的索引'; + +create index idx_user_id + on t_nail_artist_info (user_id) + comment '按用户查询美甲师信息的索引'; + +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + +-- auto-generated definition +create table t_object_storage_file +( + id bigint unsigned auto_increment comment '文件记录唯一主键ID(雪花ID)' + primary key comment '对象存储文件主键索引', + file_name varchar(100) not null comment '文件名称', + file_url text 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-不可用,2-回收站', + delete_time datetime null comment '文件删除时间(NULL表示未删除)', + recycle_time datetime null comment '文件移入回收站时间(NULL表示未移入)' +) + comment '对象存储文件信息表'; + +create index idx_status + on t_object_storage_file (status) + comment '按文件状态查询的索引'; + +-- auto-generated definition +create table 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 '订单表'; + +create index idx_status + on t_order (status) + comment '按状态查询订单的索引'; + +create index idx_user_id + on t_order (user_id) + comment '按用户查询订单的索引'; + +-- auto-generated definition +create table 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 '订单商品表'; + +create index idx_order_id + on t_order_item (order_id) + comment '按订单查询商品的索引'; + +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 '订单美甲师评价任务表'; + +create unique index uk_order_artist_review_item + on t_order_artist_review (order_item_id, is_delete); + +create index idx_order_artist_review_customer + on t_order_artist_review (customer_id, status, create_time); + +create index idx_order_artist_review_artist + on t_order_artist_review (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 '订单美甲师改派申请表'; + +create index idx_order_artist_change_customer + on t_order_artist_change_request (customer_id, status, create_time); + +create index idx_order_artist_change_artist + on t_order_artist_change_request (from_artist_id, to_artist_id, status); + +create index idx_order_artist_change_shop + on t_order_artist_change_request (shop_id, status, create_time); + +create unique index uk_order_artist_change_pending_key + on t_order_artist_change_request (pending_key); + +-- auto-generated definition +create table 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 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以逗号分隔', + 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 '商品信息表'; + +create index idx_price + on t_product (price) + comment '按价格筛选商品的索引'; + +create index idx_shop_id + on t_product (shop_id) + comment '按所属店铺查询商品的索引'; + +create index idx_tags + on t_product (tags) + comment '按标签筛选商品的索引'; + +create index idx_title + on t_product (title) + comment '商品标题搜索的索引'; + +-- auto-generated definition +create table 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 '商品点赞记录表'; + +create index idx_product_id_like + on t_product_like (product_id) + comment '按商品查询点赞的索引'; + +create index idx_user_id_like + on t_product_like (user_id) + comment '按用户查询点赞的索引'; + +-- auto-generated definition +create table 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 '店铺信息表'; + +create index idx_shop_name + on t_shop (shop_name) + comment '按店铺名称查询的索引'; + +-- auto-generated definition +create table 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 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 '手机号', + 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 '系统用户信息表'; + +create index idx_email + on t_user (email) + comment '按邮箱查询的索引'; + +create index idx_phone + on t_user (phone) + comment '按手机号查询的索引'; + +create index idx_shop_id + on t_user (shop_id) + comment '按店铺查询用户的索引'; + +create index idx_type + on t_user (type) + comment '按用户类型查询的索引'; + +-- auto-generated definition +create table 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 '用户优惠券关联表'; + +create index idx_status + on t_user_coupon (status) + comment '按状态查询用户优惠券的索引'; + +create index idx_user_id + on t_user_coupon (user_id) + comment '按用户查询优惠券的索引'; + +-- auto-generated definition +create table 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 '用户权限关联表'; + +create index idx_permission_id + on t_user_permission (permission_id) + comment '权限ID索引'; + +create index idx_user_id + on t_user_permission (user_id) + comment '用户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 '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create unique index uk_t_system_message_idempotency + on t_system_message (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 '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (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 '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (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充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + +-- auto-generated definition +create table 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权益信息表'; + +create index idx_required_vip_level + on t_vip_benefit (required_vip_level) + comment '按VIP等级查询权益的索引'; + +-- auto-generated definition +create table 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信息表'; + +create index idx_vip_level + on t_vip_info (vip_level) + comment '按VIP等级查询的索引'; + +-- auto-generated definition +create table 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 '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + +-- auto-generated definition +create table 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 '商品收藏表'; + +create index idx_product_id + on t_wishlist (product_id) + comment '按商品查询收藏的索引'; + +create index idx_user_id + on t_wishlist (user_id) + comment '按用户查询收藏的索引'; + +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + +-- ======================================== +-- 首次部署整合区:用户资产 / 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 ''更新时间'''); + +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 ''创建时间'''); + +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', 'coupon_source_type', 'varchar(32) NULL COMMENT ''优惠来源类型'''); + +UPDATE t_order +SET coupon_id = NULL +WHERE coupon_id = 0; + +UPDATE t_order o +INNER JOIN ( + SELECT oi.order_id, MIN(p.shop_id) AS resolved_shop_id + FROM t_order_item oi + INNER JOIN t_product p ON p.id = oi.product_id + GROUP BY oi.order_id +) detail_shop ON detail_shop.order_id = o.id +SET o.shop_id = detail_shop.resolved_shop_id +WHERE o.shop_id IS NULL; + +UPDATE t_order +SET coupon_source_type = 'USER_COUPON' +WHERE coupon_source_type IS NULL + AND coupon_id IS NOT NULL; + +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_coupon_source_type', '(`coupon_source_type`)'); + +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 ''业务消息幂等键'''); + +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 '订单美甲师评价任务表'; + +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_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 + +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 'yuminail' 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='YumiNail按业务场景投递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 (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + ('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 (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES ('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$I3mV64NhISqMmm7soSki1.Y36ve.TOINGOrVt0U0kxjO7GtxavE16', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT 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 + AND p.permission_code IN ( + 'home:view', + 'dashboard:view', + 'user:view', + 'user:create', + 'user:edit', + 'user:disable', + 'user:unbind', + 'user:reset_password', + 'user:delete', + 'user:balance:view', + 'user:balance:manage', + 'user:vip:manage', + 'product:view', + 'product:create', + 'product:edit', + 'product:delete', + 'product:category:manage', + 'shop:view', + 'shop:create', + 'shop:edit', + 'shop:delete', + 'shop:staff:manage', + 'permission:view', + 'permission:create', + 'permission:edit', + 'permission:delete', + 'permission:assign', + 'tag:view', + 'tag:create', + 'tag:edit', + 'tag:delete', + 'tag:assign', + 'coupon:view', + 'coupon:create', + 'coupon:edit', + 'coupon:delete', + 'coupon:assign', + 'comment:view', + 'comment:delete', + 'order:view', + 'order:process', + 'order:artist-change', + 'order:edit', + 'order:delete', + 'nail_artist:view', + 'nail_artist:edit', + 'message:view', + 'message:create', + 'message:delete', + 'announcement:view', + 'announcement:create', + 'announcement:delete' + ) +WHERE u.is_delete = 0 + AND u.type = 4 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + ); + +INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT 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 + AND p.permission_code IN ( + 'home:view', + 'dashboard:view', + 'user:view', + 'user:create', + 'user:edit', + 'user:unbind', + 'user:reset_password', + 'user:balance:view', + 'user:balance:manage', + 'user:vip:manage', + 'product:view', + 'product:create', + 'product:edit', + 'product:delete', + 'product:category:manage', + 'shop:view', + 'shop:edit', + 'shop:staff:manage', + 'permission:view', + 'permission:assign', + 'tag:view', + 'tag:create', + 'tag:edit', + 'tag:delete', + 'tag:assign', + 'coupon:view', + 'coupon:create', + 'coupon:edit', + 'coupon:delete', + 'coupon:assign', + 'comment:view', + 'comment:delete', + 'order:view', + 'order:process', + 'order:artist-change', + 'order:edit', + 'order:delete', + 'nail_artist:view', + 'nail_artist:edit', + 'message:view', + 'message:create', + 'announcement:view', + 'announcement:create' + ) +WHERE u.is_delete = 0 + AND u.type = 2 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + ); + +INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT 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 + AND p.permission_code IN ( + 'home:view', + 'user:view', + 'user:balance:view', + 'product:view', + 'shop:view', + 'tag:view', + 'coupon:view', + 'comment:view', + 'order:view', + 'order:process', + 'order:artist-change' + ) +WHERE u.is_delete = 0 + AND u.type = 3 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + ); + + +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT 910000000009000 + ((u.id % 1000000) * 10) + CASE p.permission_code + WHEN 'message:view' THEN 1 + WHEN 'message:create' THEN 2 + WHEN 'message:delete' THEN 3 + WHEN 'announcement:view' THEN 4 + WHEN 'announcement:create' THEN 5 + WHEN 'announcement:delete' THEN 6 + ELSE 0 + END, + 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 + AND ( + (u.type = 4 AND p.permission_code IN ('message:view', 'message:create', 'message:delete', 'announcement:view', 'announcement:create', 'announcement:delete')) + OR (u.type = 2 AND p.permission_code IN ('message:view', 'message:create', 'announcement:view', 'announcement:create')) + ) +WHERE u.is_delete = 0 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + ) +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_time = NOW(); + + +-- ======================================== +-- 雪花 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'); + +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='邀请码表'; + +-- Indexes are created by the corresponding migration path in environments that need them. +-- Existing databases already have these indexes, and MySQL 5.7 does not support CREATE INDEX IF NOT EXISTS. + +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', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', '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', '欢迎使用 YumiNail。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'YumiNail 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 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) +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(); diff --git a/scripts/sql/migrations/.gitkeep b/scripts/sql/migrations/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/scripts/sql/migrations/20260523_product_detail_guidance.sql b/scripts/sql/migrations/20260523_product_detail_guidance.sql new file mode 100644 index 00000000..cde28d14 --- /dev/null +++ b/scripts/sql/migrations/20260523_product_detail_guidance.sql @@ -0,0 +1,3 @@ +ALTER TABLE t_product + ADD COLUMN target_audience text null comment '适合人群说明' AFTER description, + ADD COLUMN precautions text null comment '注意事项说明' AFTER target_audience; diff --git a/scripts/sql/migrations/20260523_tag_scene_filters.sql b/scripts/sql/migrations/20260523_tag_scene_filters.sql new file mode 100644 index 00000000..47b28993 --- /dev/null +++ b/scripts/sql/migrations/20260523_tag_scene_filters.sql @@ -0,0 +1,10 @@ +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`)'); diff --git a/scripts/sql/migrations/20260523_wishlist_groups.sql b/scripts/sql/migrations/20260523_wishlist_groups.sql new file mode 100644 index 00000000..112a9b12 --- /dev/null +++ b/scripts/sql/migrations/20260523_wishlist_groups.sql @@ -0,0 +1,111 @@ +-- Lightweight wishlist inspiration groups. +-- Preset group names are created per user by the application: 最近想做、婚礼款、夏天款. + +SET NAMES utf8mb4; + +CREATE TABLE IF NOT EXISTS t_wishlist_group +( + id bigint unsigned NOT NULL 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 '商品收藏分组表'; + +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_drop_auto_increment_on_id_if_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_definition 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_definition); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +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_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_add_column_if_not_exists('t_wishlist', 'group_id', 'bigint unsigned NULL COMMENT ''收藏分组ID'''); +CALL sp_add_column_if_not_exists('t_wishlist', 'note', 'varchar(500) NULL COMMENT ''收藏灵感备注'''); +CALL sp_add_column_if_not_exists('t_wishlist', 'sort_order', 'int NOT NULL DEFAULT 100 COMMENT ''分组内排序'''); +CALL sp_add_index_if_not_exists('t_wishlist_group', 'idx_t_wishlist_group_user', '(`user_id`)'); +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', 'idx_t_wishlist_user_group_sort', '(`user_id`, `group_id`, `sort_order`, `create_time`)'); + +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_drop_auto_increment_on_id_if_exists;