功能(核心):新增用户体验支撑接口和表结构

This commit is contained in:
xiaowang
2026-05-23 21:55:41 +08:00
parent 1adc586c37
commit c2c985b2f8
63 changed files with 5880 additions and 134 deletions
@@ -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/**",
@@ -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<NailArtistProfileVO> getPublicProfile(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getPublicProfile(artistId));
}
@GetMapping("/{artistId}/availability")
public Result<List<NailArtistAvailabilityVO>> getAvailability(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getAvailability(artistId));
}
@GetMapping("/{artistId}/reviews")
public Result<List<NailArtistReviewVO>> listPublicReviews(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.listPublicReviews(artistId));
}
}
@@ -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<CheckoutPreviewVO> 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<List<OrderArtistChangeRequestVO>> 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<OrderArtistChangeRequestVO> approveArtistChange(@PathVariable Long requestId,
@@ -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)));
}
/**
@@ -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<ShopTrustProfileVO> result consumed by the caller or returned to the frontend
*/
public Result<ShopTrustProfileVO> getShopTrustProfile(@PathVariable Long id) {
return Result.success(shopService.getShopTrustProfile(id));
}
@GetMapping("/list/all")
@RequirePermission("shop:view")
/**
@@ -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<List<TagFilterGroupVO>> listFilterOptions(@RequestParam(required = false) Long shopId) {
return Result.success(tagService.listFilterOptions(shopId));
}
/**
* 根据店铺ID查询标签
*
@@ -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<String, Long> 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<String, Long> 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<Boolean> 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<List<WishlistDTO>> getWishlist(@RequestAttribute("userId") Long userId) {
List<WishlistDTO> wishlist = wishlistService.getWishlistByUserId(userId);
return Result.success(wishlist);
return Result.success(wishlistService.getWishlistByUserId(userId));
}
@GetMapping("/groups")
public Result<List<WishlistGroupVO>> listGroups(@RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.listGroups(userId));
}
@PostMapping("/groups")
public Result<Long> createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.createGroup(userId, request));
}
@PutMapping("/groups/{id}")
public Result<Boolean> updateGroup(
@PathVariable Long id,
@RequestBody WishlistGroupDTO request,
@RequestAttribute("userId") Long userId
) {
return Result.success(wishlistService.updateGroup(userId, id, request));
}
@DeleteMapping("/groups/{id}")
public Result<Boolean> 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<Boolean> moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.moveWishlist(userId, request));
}
@GetMapping("/inspiration")
public Result<WishlistInspirationVO> getInspiration(@RequestAttribute("userId") Long userId) {
return Result.success(wishlistService.getInspiration(userId));
}
}
@@ -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<OrderItemDTO> items;
}
@@ -29,6 +29,16 @@ public class ProductDTO {
*/
private String description;
/**
* 适合人群说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。
*/
private String targetAudience;
/**
* 注意事项说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。
*/
private String precautions;
/**
* 图片文件ID集合,多个ID以逗号分隔
*/
@@ -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
*/
@@ -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;
}
@@ -28,6 +28,14 @@ public class WishlistDTO {
*/
private Long productId;
private Long groupId;
private String groupName;
private String note;
private Integer sortOrder;
/**
* 商品详细信息
*/
@@ -0,0 +1,9 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
@Data
public class WishlistGroupDTO {
private String name;
private Integer sortOrder;
}
@@ -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;
}
@@ -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以逗号分隔
*/
@@ -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-已删
*/
@@ -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")
/**
@@ -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;
}
@@ -30,6 +30,9 @@ public interface OrderArtistChangeRequestMapper extends BaseMapper<OrderArtistCh
@Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
List<OrderArtistChangeRequestDO> 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<OrderArtistChangeRequestDO> 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);
@@ -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<WishlistGroupDO> {
}
@@ -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<NailArtistInfoDO> {
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getAllAvailableNailArtists();
NailArtistProfileVO getPublicProfile(Long artistId);
List<NailArtistAvailabilityVO> getAvailability(Long artistId);
List<NailArtistReviewVO> listPublicReviews(Long artistId);
}
@@ -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<OrderArtistChangeRequestVO> listMyPendingArtistChangeRequests(Long userId, Integer userType);
List<OrderArtistChangeRequestVO> 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);
@@ -125,4 +125,10 @@ public interface ProductService extends IService<ProductDO> {
PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag);
PageResultVO<ProductVO> 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<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId);
}
@@ -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<ShopDO> {
*/
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);
/**
* 查询所有店铺
*
@@ -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<TagDO> {
* @return 标签VO列表
*/
List<TagVO> 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<TagFilterGroupVO> listFilterOptions(Long shopId);
}
@@ -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<WishlistDO> {
* @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<WishlistDO> {
* @return List<WishlistDTO> result consumed by the caller or returned to the frontend
*/
List<WishlistDTO> getWishlistByUserId(Long userId);
List<WishlistGroupVO> 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);
}
@@ -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<NailArtistInfoMapper, NailArtistInfoDO> 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<NailArtistInfoMapper,
*/
private UserShopBindingSupport userShopBindingSupport;
@Autowired
private ProductMapper productMapper;
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderItemMapper orderItemMapper;
@Autowired
private OrderArtistReviewMapper orderArtistReviewMapper;
@Autowired
private ObjectStorageFileService objectStorageFileService;
@Override
/**
* Load data by the supplied parameter.
@@ -173,6 +224,108 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
return result;
}
@Override
public NailArtistProfileVO getPublicProfile(Long artistId) {
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
UserDO artist = userMapper.selectById(artistId);
if (artist == null || isDeleted(artist.getIsDelete())) {
throw new RuntimeException("美甲师信息不存在");
}
List<OrderItemDO> servedItems = loadArtistOrderItems(artistId, true);
List<NailArtistReviewVO> 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<NailArtistAvailabilityVO> 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<LocalDateTime> bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd);
LocalDateTime now = LocalDateTime.now();
List<NailArtistAvailabilityVO> 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<NailArtistReviewVO> listPublicReviews(Long artistId) {
if (artistId == null) {
return new ArrayList<>();
}
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
.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<OrderArtistReviewDO> limitedReviews = reviews.stream().limit(20).collect(Collectors.toList());
Map<Long, UserDO> customerMap = loadUsers(limitedReviews.stream()
.map(OrderArtistReviewDO::getCustomerId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Map<Long, ProductDO> productMap = loadProducts(limitedReviews.stream()
.map(OrderArtistReviewDO::getProductId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Set<Long> imageIds = new LinkedHashSet<>();
for (OrderArtistReviewDO review : limitedReviews) {
imageIds.addAll(parseLongTokens(review.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(imageIds);
List<NailArtistReviewVO> 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<NailArtistInfoMapper,
}
return "用户";
}
private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) {
if (artistId == null) {
throw new RuntimeException("美甲师信息不存在");
}
NailArtistInfoDTO artistInfo = getByUserId(artistId);
if (artistInfo == null || !isVisibleServiceUser(artistInfo)) {
throw new RuntimeException("美甲师信息不存在");
}
return artistInfo;
}
private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) {
BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating;
if (rating == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
return rating.setScale(1, RoundingMode.HALF_UP);
}
private List<OrderItemDO> loadArtistOrderItems(Long artistId, boolean completedOnly) {
List<OrderDO> orders = orderMapper.selectByArtistId(artistId);
if (orders == null || orders.isEmpty()) {
return new ArrayList<>();
}
Set<Long> 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<OrderItemDO> items = new ArrayList<>();
for (Long orderId : allowedOrderIds) {
List<OrderItemDO> 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<OrderItemDO> 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<NailArtistWorkVO> buildWorks(String portfolio, List<OrderItemDO> servedItems, int limit) {
LinkedHashSet<Long> 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<Long> limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList());
Map<Long, ProductDO> productMap = loadProducts(new LinkedHashSet<>(limitedIds));
Set<Long> fileIds = new LinkedHashSet<>();
for (ProductDO product : productMap.values()) {
fileIds.addAll(parseLongTokens(product.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(fileIds);
List<NailArtistWorkVO> 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<Long, ObjectStorageFileVO> 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<String> 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<Long, UserDO> customerMap,
Map<Long, ProductDO> productMap,
Map<Long, ObjectStorageFileVO> 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<Long> imageFileIds = parseLongTokens(review.getImageFileIds());
vo.setImageFileIds(imageFileIds);
vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap));
vo.setSubmittedAt(review.getSubmittedAt());
return vo;
}
private Set<LocalDateTime> loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) {
List<OrderItemDO> 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<Long, ProductDO> loadProducts(Set<Long> productIds) {
if (productIds == null || productIds.isEmpty()) {
return new HashMap<>();
}
List<ProductDO> 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<Long, UserDO> loadUsers(Set<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return new HashMap<>();
}
List<UserDO> 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<Long, ObjectStorageFileVO> loadFiles(Set<Long> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {
return new HashMap<>();
}
Map<Long, ObjectStorageFileVO> files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds);
return files == null ? new HashMap<>() : files;
}
private List<String> resolveImageUrls(List<Long> fileIds, Map<Long, ObjectStorageFileVO> fileMap) {
if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) {
return new ArrayList<>();
}
List<String> 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<Long> parseLongTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<Long> 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<String> parseTextTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<String> 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);
}
}
@@ -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<UserCouponVO> availableCouponOptions = couponService.getAvailableCoupons(
userId,
pricingContext.getProductTagNames(),
pricingContext.getTotalAmount().doubleValue(),
pricingContext.getShopId()
);
if (availableCouponOptions == null) {
availableCouponOptions = List.of();
}
List<CheckoutCouponPreviewVO> 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<OrderItemDTO> orderItemDTOs = orderDTO.getItems();
Map<Long, Integer> requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs);
BigDecimal totalAmount = BigDecimal.ZERO;
Set<String> 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<String> 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<CheckoutCouponPreviewVO> 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<CheckoutCouponPreviewVO> 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<CheckoutCouponPreviewVO> buildUnavailableCouponPreviews(List<CheckoutCouponPreviewVO> availableCoupons,
CheckoutPricingContext pricingContext) {
Set<Long> availableCouponIds = availableCoupons == null ? Collections.emptySet() : availableCoupons.stream()
.map(CheckoutCouponPreviewVO::getCouponId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
List<CouponDO> coupons = couponMapper.selectList(new LambdaQueryWrapper<CouponDO>()
.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<CheckoutCouponPreviewVO> 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<OrderArtistChangeRequestVO> 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.
@@ -120,6 +120,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> 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<ProductMapper, ProductDO> 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<ProductMapper, ProductDO> 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<ProductMapper, ProductDO> im
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public PageResultVO<ProductVO> 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<ProductVO> 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<ProductMapper, ProductDO> 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<PageResultVO<ProductVO>>() {
},
() -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, scopedShopId)
() -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, normalizedTagIds, scopedShopId)
);
}
@@ -828,6 +845,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return private PageResultVO<ProductVO> result consumed by the caller or returned to the frontend
*/
private PageResultVO<ProductVO> 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<ProductVO> buildPublicProductPage(int page, int size, String keyword, String tag, String tagIds, Long shopId) {
Set<String> exactTagIds = null;
if (StringUtils.hasText(tag)) {
exactTagIds = findExactTagIds(tag);
@@ -842,9 +867,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
return buildEmptyPageResult(page, size);
}
}
Set<String> selectedTagIds = parseTagIdFilter(tagIds);
Page<ProductDO> pageParam = new Page<>(page, size);
Page<ProductDO> productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, shopId));
Page<ProductDO> productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, selectedTagIds, shopId));
PageResultVO<ProductVO> result = new PageResultVO<>();
result.setList(toProductVOList(productPage.getRecords()));
result.setTotal(productPage.getTotal());
@@ -870,6 +896,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private LambdaQueryWrapper<ProductDO> buildFrontQuery(String keyword, String tag, Set<String> 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<ProductDO> buildFrontQuery(String keyword, String tag, Set<String> exactTagIds, Set<String> selectedTagIds, Long shopId) {
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0);
if (shopId != null) {
@@ -886,6 +920,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> 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<ProductMapper, ProductDO> 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<String> 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.
@@ -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<ShopMapper, ShopDO> 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<ShopMapper, ShopDO> 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<ProductDO> featuredProducts = listFeaturedProducts(id);
List<OrderArtistReviewDO> recentReviews = listSubmittedReviews(id, 3);
BigDecimal averageRating = calculateAverageRating(id);
long reviewCount = countSubmittedReviews(id);
Set<Long> 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<Long, ObjectStorageFileVO> 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<ShopMapper, ShopDO> 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<ProductDO> 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<OrderArtistReviewDO> 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<OrderArtistReviewDO> 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<Long, ObjectStorageFileVO> 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<ProductDO> featuredProducts,
Map<Long, ObjectStorageFileVO> 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<String> buildCoarseSlotHints(String businessHours) {
String hours = StringUtils.hasText(businessHours) ? businessHours.trim() : "营业时间内";
List<String> 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<Long> fileIdsForShop(ShopDO shopDO) {
List<Long> 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<Long, ObjectStorageFileVO> 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<String> resolveImageUrls(List<Long> fileIds, Map<Long, ObjectStorageFileVO> fileMap) {
if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) {
return Collections.emptyList();
}
List<String> 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<ProductDO> 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<Long> parseLongIds(String value, String delimiter) {
if (!StringUtils.hasText(value)) {
return Collections.emptyList();
}
List<Long> 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
*
@@ -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<TagMapper, TagDO> 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<TagMapper, TagDO> 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<TagMapper, TagDO> 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<TagMapper, TagDO> 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<TagFilterGroupVO> 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<List<TagFilterGroupVO>>() {
},
() -> buildFilterOptions(scopedShopId)
);
}
@Override
/**
* Load data by the supplied parameter.
@@ -297,6 +333,10 @@ public class TagServiceImpl extends ServiceImpl<TagMapper, TagDO> 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<TagMapper, TagDO> 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<TagFilterGroupVO> buildFilterOptions(Long shopId) {
List<TagDO> tags = tagMapper.selectList(
Wrappers.lambdaQuery(TagDO.class)
.eq(TagDO::getIsDelete, 0)
.eq(shopId != null, TagDO::getShopId, shopId)
);
Map<String, List<TagVO>> 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<TagMapper, TagDO> 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");
}
}
@@ -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<WishlistMapper, WishlistDO> 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<String> 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<WishlistDO> 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<WishlistDO> 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<WishlistDO> 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<WishlistDTO> result consumed by the caller or returned to the frontend
*/
public List<WishlistDTO> getWishlistByUserId(Long userId) {
List<WishlistGroupVO> groups = listGroups(userId);
Map<Long, String> 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<WishlistGroupVO> 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<WishlistDO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(WishlistDO::getUserId, userId);
List<WishlistDO> 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<WishlistGroupVO> groups = listGroups(userId);
Map<Long, WishlistGroupVO> groupMap = new LinkedHashMap<>();
groups.forEach(group -> groupMap.put(group.getId(), group));
WishlistGroupDO defaultGroup = resolveDefaultGroup(userId);
Map<Long, String> groupNames = groups.stream()
.filter(group -> group.getId() != null)
.collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left));
List<WishlistDTO> 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<Long, String> 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<WishlistDO> 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<WishlistDO> 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<WishlistDO> loadActiveWishlist(Long userId) {
LambdaQueryWrapper<WishlistDO> 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<WishlistGroupDO> ensurePresetGroups(Long userId) {
List<WishlistGroupDO> groups = loadActiveGroups(userId);
Map<String, WishlistGroupDO> 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<WishlistGroupDO> loadActiveGroups(Long userId) {
LambdaQueryWrapper<WishlistGroupDO> 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<WishlistMapper, WishlistDO>
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;
}
}
@@ -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;
}
@@ -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<CheckoutCouponPreviewVO> availableCoupons = new ArrayList<>();
private List<CheckoutCouponPreviewVO> unavailableCoupons = new ArrayList<>();
private String vipTip;
private String summaryText;
}
@@ -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;
}
@@ -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<String> styleTags = new ArrayList<>();
private List<NailArtistWorkVO> works = new ArrayList<>();
private List<NailArtistReviewVO> reviews = new ArrayList<>();
private List<NailArtistAvailabilityVO> availability = new ArrayList<>();
}
@@ -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<Long> imageFileIds = new ArrayList<>();
private List<String> imageUrls = new ArrayList<>();
private LocalDateTime submittedAt;
}
@@ -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<String> imageUrls = new ArrayList<>();
private List<String> tags = new ArrayList<>();
private Integer likeCount;
private Integer collectCount;
}
@@ -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.
@@ -42,6 +42,16 @@ public class ProductVO {
*/
private String description;
/**
* 适合人群说明;作品详情接口返回后由 Web/小程序在有值时展示。
*/
private String targetAudience;
/**
* 注意事项说明;作品详情接口返回后由 Web/小程序在有值时展示。
*/
private String precautions;
/**
* 图片文件ID集合,多个ID以逗号分隔
*/
@@ -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<String> environmentImages = new ArrayList<>();
/**
* Purpose: featuredProducts lists representative products from this shop.
* Usage: render as quick inspection or booking entry cards.
*/
private List<FeaturedProduct> featuredProducts = new ArrayList<>();
/**
* Purpose: recentReviews lists recent submitted reviews only.
* Usage: show social proof while keeping customer identity private.
*/
private List<RecentReview> 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<String> 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<String> 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;
}
}
@@ -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<TagVO> tags = new ArrayList<>();
}
@@ -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;
/**
* 创建时间
*/
@@ -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<WishlistDTO> items = new ArrayList<>();
}
@@ -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<WishlistGroupVO> groups = new ArrayList<>();
}
@@ -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');
@@ -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();
@@ -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<NailArtistReviewVO> 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<NailArtistAvailabilityVO> 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)));
}
}
@@ -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;
}
}
@@ -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();
@@ -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<ProductDO> 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());
}
}
@@ -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();
}
}
@@ -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<TagFilterGroupVO> 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;
}
}
@@ -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<WishlistGroupVO> groups = service.listGroups(88L);
ArgumentCaptor<WishlistGroupDO> 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<WishlistDO> 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<WishlistGroupDO> 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;
}
}
@@ -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')");
}
}
@@ -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'");
}
}
@@ -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/**",
@@ -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/**
File diff suppressed because it is too large Load Diff
View File
@@ -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;
@@ -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`)');
@@ -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;