杂务:整理文档并收口 YumiNail 修复

This commit is contained in:
xiaowang
2026-05-21 18:43:59 +08:00
parent 3797938616
commit 9227ec6175
362 changed files with 8358 additions and 19928 deletions
@@ -8,6 +8,7 @@ import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.PermissionMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.PermissionService;
import com.xiaowang.yuminailcore.support.PermissionCatalog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -59,6 +60,21 @@ public class PermissionAspect {
}
String permissionCode = requirePermission.value();
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作");
}
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return joinPoint.proceed();
}
boolean hasPermission = !StringUtils.hasText(permissionCode)
|| permissionService.hasPermission(userId, permissionCode);
if (!hasPermission) {
@@ -80,8 +96,24 @@ public class PermissionAspect {
.last("limit 1")
);
if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) {
return "权限不足:缺少权限【" + permissionDO.getPermissionName() + "】(" + permissionCode + ")";
return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")";
}
return "权限不足:缺少权限代码 " + permissionCode;
}
private Long parseShopId(Object value) {
if (value instanceof Number number) {
long shopId = number.longValue();
return shopId > 0 ? shopId : null;
}
if (value instanceof String text && StringUtils.hasText(text)) {
try {
long shopId = Long.parseLong(text.trim());
return shopId > 0 ? shopId : null;
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
}
@@ -1,19 +1,48 @@
package com.xiaowang.yuminailcore.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
return builder -> {
// 雪花 ID 使用 Long,统一按字符串输出给前端,避免 JavaScript Number 精度丢失。
// Snowflake IDs are serialized as strings so the web and mini program do not lose precision.
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
builder.modules(javaTimeModule);
};
}
private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String value = parser.getValueAsString();
if (value == null || value.trim().isEmpty()) {
return null;
}
String normalized = value.trim();
if (normalized.contains("T")) {
return LocalDateTime.parse(normalized);
}
return LocalDateTime.parse(normalized, SPACE_FORMATTER);
}
}
}
@@ -40,10 +40,11 @@ public class AdminOrderController {
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long shopId,
@RequestParam(required = false) Integer status
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
List<OrderVO> allOrders;
if (Integer.valueOf(3).equals(currentUser.getType())) {
@@ -51,9 +52,9 @@ public class AdminOrderController {
} else {
allOrders = orderService.getAllOrders();
}
if (shopId != null && !Integer.valueOf(3).equals(currentUser.getType())) {
if (scopedShopId != null && !Integer.valueOf(3).equals(currentUser.getType())) {
allOrders = allOrders.stream()
.filter(order -> shopId.equals(order.getShopId()))
.filter(order -> scopedShopId.equals(order.getShopId()))
.toList();
}
@@ -39,11 +39,16 @@ public class AdminProductController {
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Long shopId
@RequestParam(required = false) Long shopId,
@RequestParam(required = false) Long tagId,
@RequestParam(required = false) java.math.BigDecimal minPrice,
@RequestParam(required = false) java.math.BigDecimal maxPrice,
@RequestParam(required = false) String createdFrom,
@RequestParam(required = false) String createdTo
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
shopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
PageResultVO<ProductVO> result = productService.pageProducts(page, size, keyword, shopId);
PageResultVO<ProductVO> result = productService.pageProducts(page, size, keyword, shopId, tagId, minPrice, maxPrice, createdFrom, createdTo);
return Result.success(result);
}
@@ -54,7 +59,7 @@ public class AdminProductController {
* 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.
* @param request parameter `request` supplied by the caller
* @param productDTO parameter `productDTO` supplied by the caller
* @param productDTO parameter `productDTO` supplied by the caller yu
* @return Result<Long> result consumed by the caller or returned to the frontend
*/
public Result<Long> createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) {
@@ -18,7 +18,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/announcement", "/api/announcement"})
@RequestMapping({"/announcement", "/api/announcement", "/admin/announcement"})
/**
* AnnouncementController 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.
@@ -27,12 +27,16 @@ import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@@ -117,6 +121,7 @@ public class DashboardController {
*/
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
if (currentUser != null) {
// 根据用户类型显示不同的数据
@@ -125,6 +130,8 @@ public class DashboardController {
stats.setTotalProducts(productMapper.selectCount(null));
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
stats.setTotalCustomers(countUsers(null, 0, null, null));
stats.setTotalArtists(countUsers(null, 3, null, null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
@@ -134,12 +141,16 @@ public class DashboardController {
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
stats.setTotalArtists(countUsers(shopId, 3, null, null));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
}
} else {
@@ -148,7 +159,20 @@ public class DashboardController {
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime weekStart = todayStart.minusDays(6);
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
stats.setPendingOrders(countOrders(shopIdScope, artistScope, 1, null, null));
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, 3, null, null));
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
@@ -168,6 +192,72 @@ public class DashboardController {
}
return currentUser.getShopId();
}
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
if (type != null) {
wrapper.eq(UserDO::getType, type);
}
if (from != null) {
wrapper.ge(UserDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(UserDO::getCreateTime, to);
}
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return 0L;
}
wrapper.in(UserDO::getId, userIds);
}
return userMapper.selectCount(wrapper);
}
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
}
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
return listScopedOrders(shopId, artistId, null, from, to).stream()
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(OrderDO::getShopId, shopId);
}
if (status != null) {
wrapper.eq(OrderDO::getStatus, status);
}
if (from != null) {
wrapper.ge(OrderDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(OrderDO::getCreateTime, to);
}
if (artistId != null) {
Set<Long> orderIds = listOrderIdsByArtist(artistId);
if (orderIds.isEmpty()) {
return Collections.emptyList();
}
wrapper.in(OrderDO::getId, orderIds);
}
return orderMapper.selectList(wrapper);
}
private Set<Long> listOrderIdsByArtist(Long artistId) {
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.select(OrderItemDO::getOrderId)
.eq(OrderItemDO::getArtistId, artistId));
return items.stream()
.map(OrderItemDO::getOrderId)
.filter(id -> id != null)
.collect(Collectors.toCollection(HashSet::new));
}
/**
* Load data by the supplied parameter.
@@ -18,7 +18,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config"})
@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config", "/admin/messagehub-push-config"})
/**
* MessageHubPushConfigController 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.
@@ -79,7 +79,7 @@ public class ObjectStorageFileController {
@RequestParam("totalChunks") Integer totalChunks,
@RequestParam("chunk") MultipartFile chunkFile) {
Long userId = (Long) request.getAttribute("userId");
uploadSecurityValidator.validate(chunkFile);
uploadSecurityValidator.validateChunk(chunkFile);
chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
return Result.success(true);
}
@@ -49,7 +49,7 @@ public class PermissionController {
@RequirePermission("permission:create")
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
Long id = permissionService.createPermission(permissionDTO);
return Result.success(id);
}
@@ -65,7 +65,7 @@ public class PermissionController {
@RequirePermission("permission:edit")
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
boolean success = permissionService.updatePermission(id, permissionDTO);
return Result.success(success);
}
@@ -80,7 +80,7 @@ public class PermissionController {
@RequirePermission("permission:delete")
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ョ淮鎶ゆ潈闄愬畾涔?");
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
boolean success = permissionService.deletePermission(id);
return Result.success(success);
}
@@ -6,9 +6,13 @@ import com.xiaowang.yuminailcore.dto.ProductDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.service.ProductService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.security.UserSessionService;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import com.xiaowang.yuminailcore.vo.ProductVO;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@@ -22,6 +26,9 @@ import java.util.List;
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class ProductController {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER_PREFIX = "Bearer ";
/**
* Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -30,6 +37,9 @@ public class ProductController {
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
private final JwtUtil jwtUtil;
private final UserSessionService userSessionService;
private final UserShopBindingSupport userShopBindingSupport;
@PostMapping("/create")
@RequirePermission("product:create")
@@ -108,8 +118,11 @@ public class ProductController {
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return Result<List<ProductVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<ProductVO>> listAllProducts() {
List<ProductVO> productVOs = productService.listAllProducts();
public Result<List<ProductVO>> listAllProducts(HttpServletRequest request) {
Long currentShopId = resolveOptionalCurrentShopId(request);
List<ProductVO> productVOs = currentShopId == null
? productService.listAllProducts()
: productService.listProductsByShopId(currentShopId);
return Result.success(productVOs);
}
@@ -132,22 +145,52 @@ public class ProductController {
* @param tag parameter `tag` supplied by the caller
* @return Result<List<ProductVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<ProductVO>> listProductsByTag(@PathVariable String tag) {
List<ProductVO> productVOs = productService.listProductsByTag(tag);
public Result<List<ProductVO>> listProductsByTag(HttpServletRequest request, @PathVariable String tag) {
List<ProductVO> productVOs = productService.listProductsByTag(tag, resolveOptionalCurrentShopId(request));
return Result.success(productVOs);
}
@GetMapping("/list/search")
public Result<List<ProductVO>> searchProducts(@RequestParam("keyword") String keyword) {
List<ProductVO> productVOs = productService.searchProducts(keyword);
public Result<List<ProductVO>> searchProducts(HttpServletRequest request, @RequestParam("keyword") String keyword) {
List<ProductVO> productVOs = productService.searchProducts(keyword, resolveOptionalCurrentShopId(request));
return Result.success(productVOs);
}
@GetMapping("/list/page")
public Result<PageResultVO<ProductVO>> pagePublicProducts(@RequestParam(defaultValue = "1") Integer page,
public Result<PageResultVO<ProductVO>> pagePublicProducts(HttpServletRequest request,
@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));
return Result.success(productService.pagePublicProducts(page, size, keyword, tag, resolveOptionalCurrentShopId(request)));
}
private Long resolveOptionalCurrentShopId(HttpServletRequest request) {
if (request == null) {
return null;
}
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(BEARER_PREFIX)) {
return null;
}
String token = authHeader.substring(BEARER_PREFIX.length());
try {
if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) {
return null;
}
Long shopId = jwtUtil.getShopIdFromToken(token);
if (shopId == null || shopId <= 0) {
return null;
}
Long userId = jwtUtil.getUserIdFromToken(token);
String sessionId = jwtUtil.getSessionIdFromToken(token);
String jti = jwtUtil.getJtiFromToken(token);
if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) {
return null;
}
return userShopBindingSupport.canUserAccessShop(userId, shopId, false, null) ? shopId : null;
} catch (RuntimeException exception) {
return null;
}
}
}
@@ -44,7 +44,7 @@ public class ShopController {
*/
public Result<Long> createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垱寤哄簵閾?");
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺");
Long id = shopService.createShop(shopDTO);
return Result.success(id);
}
@@ -84,7 +84,7 @@ public class ShopController {
*/
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垹闄ゅ簵閾?");
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺");
boolean success = shopService.deleteShop(id);
return Result.success(success);
}
@@ -19,7 +19,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/system-message", "/api/system-message"})
@RequestMapping({"/system-message", "/api/system-message", "/admin/system-message"})
/**
* SystemMessageController 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.
@@ -19,7 +19,7 @@ import java.util.Map;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/system-parameter-config", "/api/system-parameter-config"})
@RequestMapping({"/system-parameter-config", "/api/system-parameter-config", "/admin/system-parameter-config"})
public class SystemParameterConfigController {
private final SystemParameterConfigService configService;
@@ -42,11 +42,22 @@ public class SystemParameterConfigController {
}
@GetMapping("/admin/tencent-map")
@RequirePermission("messagehub:config:manage")
public Result<Map<String, String>> getTencentMapKey(HttpServletRequest request) {
adminScopeHelper.getCurrentUser(request);
Map<String, String> result = new HashMap<>();
result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY"));
return Result.success(result);
}
@GetMapping("/admin/map-config")
public Result<Map<String, String>> getMapConfig(HttpServletRequest request) {
adminScopeHelper.getCurrentUser(request);
Map<String, String> result = new HashMap<>();
String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER");
result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT");
result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY"));
result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY"));
result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY"));
return Result.success(result);
}
}
@@ -17,7 +17,7 @@ import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan"})
@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"})
/**
* VipRechargePlanController 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.
@@ -96,4 +96,10 @@ public class VipRechargePlanController {
Long userId = (Long) request.getAttribute("userId");
return Result.success(vipRechargePlanService.listMyPlans(userId));
}
@GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"})
public Result<List<String>> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId));
}
}
@@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
@@ -51,11 +52,27 @@ public class ShopDTO {
*/
private String imageFileIds;
private String themePrimaryColor;
private String themeSecondaryColor;
private String themeAccentColor;
private String themePageBgColor;
private String themeCardBgColor;
private String themeBackgroundImageFileId;
/**
* 店铺状态:1-启用,0-停用
*/
private Integer status;
private LocalDate authorizationStartDate;
private Integer authorizationDays;
/**
* 店铺授权有效期;为空表示长期有效。
*/
@@ -1,9 +1,11 @@
package com.xiaowang.yuminailcore.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@@ -16,9 +18,14 @@ import java.time.LocalDateTime;
* @date 2026-02-13
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_balance")
public class BalanceDO extends BaseEntity {
public class BalanceDO {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 关联用户表主键
@@ -9,6 +9,7 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
@@ -74,12 +75,36 @@ public class ShopDO extends BaseEntity {
@TableField("image_file_ids")
private String imageFileIds;
@TableField("theme_primary_color")
private String themePrimaryColor;
@TableField("theme_secondary_color")
private String themeSecondaryColor;
@TableField("theme_accent_color")
private String themeAccentColor;
@TableField("theme_page_bg_color")
private String themePageBgColor;
@TableField("theme_card_bg_color")
private String themeCardBgColor;
@TableField("theme_background_image_file_id")
private String themeBackgroundImageFileId;
/**
* 店铺状态:1-启用,0-停用
*/
@TableField("status")
private Integer status;
@TableField("authorization_start_date")
private LocalDate authorizationStartDate;
@TableField("authorization_days")
private Integer authorizationDays;
/**
* 店铺授权有效期;为空表示长期有效。
*/
@@ -89,6 +89,8 @@ public interface ProductService extends IService<ProductDO> {
*/
List<ProductVO> listProductsByTag(String tag);
List<ProductVO> listProductsByTag(String tag, Long shopId);
/**
* 前台按标题、描述、标签名搜索商品
*
@@ -96,6 +98,8 @@ public interface ProductService extends IService<ProductDO> {
* @return 商品列表
*/
List<ProductVO> searchProducts(String keyword);
List<ProductVO> searchProducts(String keyword, Long shopId);
/**
* 分页查询商品
@@ -107,6 +111,8 @@ public interface ProductService extends IService<ProductDO> {
*/
PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId);
PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo);
/**
* Query paged records.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -117,4 +123,6 @@ public interface ProductService extends IService<ProductDO> {
* @return PageResultVO<ProductVO> result consumed by the caller or returned to the frontend
*/
PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag);
PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId);
}
@@ -53,4 +53,6 @@ public interface VipRechargePlanService extends IService<VipRechargePlanDO> {
* @return List<VipRechargePlanVO> result consumed by the caller or returned to the frontend
*/
List<VipRechargePlanVO> listMyPlans(Long userId);
List<String> listVipLevelOptions(UserDO currentUser, Long shopId);
}
@@ -28,6 +28,8 @@ import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -317,15 +319,21 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return List<ProductVO> result consumed by the caller or returned to the frontend
*/
public List<ProductVO> listProductsByTag(String tag) {
return listProductsByTag(tag, null);
}
@Override
public List<ProductVO> listProductsByTag(String tag, Long shopId) {
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList();
String normalizedTag = normalizeOptionalKeyword(tag);
Long scopedShopId = normalizeShopId(shopId);
return multiLevelCacheService.getOrLoad(
PRODUCT_LIST_CACHE_PREFIX + "tag:" + normalizedTag,
PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "tag:" + normalizedTag,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<List<ProductVO>>() {
},
() -> loadProductsByTag(normalizedTag)
() -> loadProductsByTag(normalizedTag, scopedShopId)
);
}
@@ -337,18 +345,24 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return List<ProductVO> result consumed by the caller or returned to the frontend
*/
public List<ProductVO> searchProducts(String keyword) {
return searchProducts(keyword, null);
}
@Override
public List<ProductVO> searchProducts(String keyword, Long shopId) {
if (!StringUtils.hasText(keyword)) {
return new ArrayList<>();
}
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch();
String trimmedKeyword = keyword.trim();
Long scopedShopId = normalizeShopId(shopId);
return multiLevelCacheService.getOrLoad(
PRODUCT_SEARCH_CACHE_PREFIX + trimmedKeyword.toLowerCase(Locale.ROOT),
PRODUCT_SEARCH_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + trimmedKeyword.toLowerCase(Locale.ROOT),
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<List<ProductVO>>() {
},
() -> searchFrontProducts(trimmedKeyword)
() -> searchFrontProducts(trimmedKeyword, scopedShopId)
);
}
@@ -479,6 +493,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return PageResultVO<ProductVO> result consumed by the caller or returned to the frontend
*/
public PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId) {
return pageProducts(page, size, keyword, shopId, null, null, null, null, null);
}
@Override
public PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo) {
Page<ProductDO> pageParam = new Page<>(page, size);
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class);
@@ -490,6 +509,23 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
if (shopId != null && shopId > 0) {
wrapper.eq(ProductDO::getShopId, shopId);
}
if (tagId != null) {
wrapper.like(ProductDO::getTags, String.valueOf(tagId));
}
if (minPrice != null) {
wrapper.ge(ProductDO::getPrice, minPrice);
}
if (maxPrice != null) {
wrapper.le(ProductDO::getPrice, maxPrice);
}
LocalDateTime createdFromTime = parseDateTime(createdFrom);
LocalDateTime createdToTime = parseDateTime(createdTo);
if (createdFromTime != null) {
wrapper.ge(ProductDO::getCreateTime, createdFromTime);
}
if (createdToTime != null) {
wrapper.le(ProductDO::getCreateTime, createdToTime);
}
wrapper.orderByDesc(ProductDO::getCreateTime);
Page<ProductDO> productPage = productMapper.selectPage(pageParam, wrapper);
@@ -503,6 +539,21 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
return result;
}
private LocalDateTime parseDateTime(String value) {
if (!StringUtils.hasText(value)) {
return null;
}
try {
return LocalDateTime.parse(value.replace(" ", "T"));
} catch (Exception ignored) {
try {
return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (Exception secondIgnored) {
return null;
}
}
}
@Override
/**
* Query paged records.
@@ -514,14 +565,20 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return PageResultVO<ProductVO> result consumed by the caller or returned to the frontend
*/
public PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag) {
return pagePublicProducts(page, size, keyword, tag, null);
}
@Override
public PageResultVO<ProductVO> pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId) {
int normalizedPage = normalizePage(page);
int normalizedSize = normalizePageSize(size);
String normalizedKeyword = normalizeOptionalKeyword(keyword);
String normalizedTag = normalizeOptionalKeyword(tag);
Long scopedShopId = normalizeShopId(shopId);
AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword)
? appCacheProperties.getProductSearch()
: appCacheProperties.getProductList();
String cacheKey = PRODUCT_LIST_CACHE_PREFIX + "page:" + normalizedPage
String cacheKey = PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "page:" + normalizedPage
+ ":" + normalizedSize
+ ":" + normalizedKeyword.toLowerCase(Locale.ROOT)
+ ":" + normalizedTag.toLowerCase(Locale.ROOT);
@@ -531,7 +588,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<PageResultVO<ProductVO>>() {
},
() -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag)
() -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, scopedShopId)
);
}
@@ -553,7 +610,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("配置可预约美甲师前必须先选择店铺");
}
for (String artistIdStr : bookableArtists.split(",")) {
@@ -570,7 +627,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("可预约美甲师配置格式不正确");
}
if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) {
@@ -579,7 +636,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("存在无效、已停用或不属于当前店铺的美甲师配置");
}
}
}
@@ -602,7 +659,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("配置可用优惠券前必须先选择店铺");
}
for (String couponIdStr : availableCoupons.split(",")) {
@@ -619,7 +676,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("鍙敤浼樻儬鍒搁厤缃牸寮忎笉姝g‘");
throw new RuntimeException("可用优惠券配置格式不正确");
}
CouponDO couponDO = couponMapper.selectById(couponId);
@@ -629,7 +686,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("存在无效的优惠券配置");
}
if (!Integer.valueOf(1).equals(couponDO.getStatus())) {
/**
@@ -637,7 +694,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("存在已失效的优惠券配置");
}
if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) {
/**
@@ -645,7 +702,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* 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("不可跨店铺配置可用优惠券");
}
}
}
@@ -685,7 +742,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @param tag parameter `tag` supplied by the caller
* @return private List<ProductVO> result consumed by the caller or returned to the frontend
*/
private List<ProductVO> loadProductsByTag(String tag) {
private List<ProductVO> loadProductsByTag(String tag, Long shopId) {
if (!StringUtils.hasText(tag)) {
return new ArrayList<>();
}
@@ -696,6 +753,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0)
.orderByDesc(ProductDO::getCreateTime);
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
/**
* Run business method `applyTagIdConditions`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -713,8 +773,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @param keyword parameter `keyword` supplied by the caller
* @return private List<ProductVO> result consumed by the caller or returned to the frontend
*/
private List<ProductVO> searchFrontProducts(String keyword) {
LambdaQueryWrapper<ProductDO> wrapper = buildFrontQuery(keyword, null, null);
private List<ProductVO> searchFrontProducts(String keyword, Long shopId) {
LambdaQueryWrapper<ProductDO> wrapper = buildFrontQuery(keyword, null, null, shopId);
return toProductVOList(productMapper.selectList(wrapper));
}
@@ -727,7 +787,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @param tag parameter `tag` supplied by the caller
* @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) {
private PageResultVO<ProductVO> buildPublicProductPage(int page, int size, String keyword, String tag, Long shopId) {
Set<String> exactTagIds = null;
if (StringUtils.hasText(tag)) {
exactTagIds = findExactTagIds(tag);
@@ -744,7 +804,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
}
Page<ProductDO> pageParam = new Page<>(page, size);
Page<ProductDO> productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds));
Page<ProductDO> productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, shopId));
PageResultVO<ProductVO> result = new PageResultVO<>();
result.setList(toProductVOList(productPage.getRecords()));
result.setTotal(productPage.getTotal());
@@ -762,8 +822,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @return private LambdaQueryWrapper<ProductDO> result consumed by the caller or returned to the frontend
*/
private LambdaQueryWrapper<ProductDO> buildFrontQuery(String keyword, String tag, Set<String> exactTagIds) {
return buildFrontQuery(keyword, tag, exactTagIds, null);
}
private LambdaQueryWrapper<ProductDO> buildFrontQuery(String keyword, String tag, Set<String> exactTagIds, Long shopId) {
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class)
.eq(ProductDO::getIsDelete, 0);
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
/**
* Run business method `applyKeywordFilter`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -997,6 +1064,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
return StringUtils.hasText(value) ? value.trim() : "";
}
private Long normalizeShopId(Long shopId) {
return shopId != null && shopId > 0 ? shopId : null;
}
private String buildShopCacheSegment(Long shopId) {
return shopId == null ? "all:" : "shop:" + shopId + ":";
}
/**
* Run business method `evictPublicProductCaches`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
import com.xiaowang.yuminailcore.service.CouponService;
import com.xiaowang.yuminailcore.service.MapService;
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.PageResultVO;
@@ -32,6 +33,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@@ -109,7 +111,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopDO.setBusinessHours(shopDTO.getBusinessHours());
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
shopDO.setImageFileIds(shopDTO.getImageFileIds());
shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime());
applyTheme(shopDO, shopDTO);
applyAuthorization(shopDO, shopDTO);
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
shopDO.setIsDelete(0);
shopMapper.insert(shopDO);
@@ -140,7 +143,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopDO.setBusinessHours(shopDTO.getBusinessHours());
shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId());
shopDO.setImageFileIds(shopDTO.getImageFileIds());
shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime());
applyTheme(shopDO, shopDTO);
applyAuthorization(shopDO, shopDTO);
if (shopDTO.getStatus() != null) {
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
}
@@ -403,7 +407,15 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopVO.setCoverImageUrls(new java.util.ArrayList<>());
shopVO.setImageFileIds(shopDO.getImageFileIds());
shopVO.setImageUrls(new java.util.ArrayList<>());
shopVO.setThemePrimaryColor(shopDO.getThemePrimaryColor());
shopVO.setThemeSecondaryColor(shopDO.getThemeSecondaryColor());
shopVO.setThemeAccentColor(shopDO.getThemeAccentColor());
shopVO.setThemePageBgColor(shopDO.getThemePageBgColor());
shopVO.setThemeCardBgColor(shopDO.getThemeCardBgColor());
shopVO.setThemeBackgroundImageFileId(shopDO.getThemeBackgroundImageFileId());
shopVO.setStatus(normalizeStatus(shopDO.getStatus()));
shopVO.setAuthorizationStartDate(shopDO.getAuthorizationStartDate());
shopVO.setAuthorizationDays(shopDO.getAuthorizationDays());
shopVO.setAuthorizationExpireTime(shopDO.getAuthorizationExpireTime());
boolean expired = isAuthorizationExpired(shopDO);
shopVO.setAuthorizationExpired(expired);
@@ -477,6 +489,29 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
return Integer.valueOf(0).equals(status) ? 0 : 1;
}
private void applyAuthorization(ShopDO shopDO, ShopDTO shopDTO) {
LocalDate startDate = shopDTO.getAuthorizationStartDate();
Integer days = shopDTO.getAuthorizationDays();
shopDO.setAuthorizationStartDate(startDate);
shopDO.setAuthorizationDays(days);
if (startDate != null && days != null && days > 0) {
shopDO.setAuthorizationExpireTime(startDate.plusDays(days - 1L).atTime(23, 59, 59));
return;
}
shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime());
}
private void applyTheme(ShopDO shopDO, ShopDTO shopDTO) {
shopDO.setThemePrimaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePrimaryColor(), "themePrimaryColor"));
shopDO.setThemeSecondaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeSecondaryColor(), "themeSecondaryColor"));
shopDO.setThemeAccentColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeAccentColor(), "themeAccentColor"));
shopDO.setThemePageBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePageBgColor(), "themePageBgColor"));
shopDO.setThemeCardBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeCardBgColor(), "themeCardBgColor"));
shopDO.setThemeBackgroundImageFileId(StringUtils.hasText(shopDTO.getThemeBackgroundImageFileId())
? shopDTO.getThemeBackgroundImageFileId().trim()
: null);
}
/**
* Run business method `evictShopCaches`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -9,12 +9,14 @@ import com.xiaowang.yuminailcore.entity.OrderDO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.entity.VipBenefitDO;
import com.xiaowang.yuminailcore.entity.VipInfoDO;
import com.xiaowang.yuminailcore.entity.VipRechargePlanDO;
import com.xiaowang.yuminailcore.mapper.BalanceChangeDetailMapper;
import com.xiaowang.yuminailcore.mapper.BalanceMapper;
import com.xiaowang.yuminailcore.mapper.OrderMapper;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.VipBenefitMapper;
import com.xiaowang.yuminailcore.mapper.VipInfoMapper;
import com.xiaowang.yuminailcore.mapper.VipRechargePlanMapper;
import com.xiaowang.yuminailcore.service.UserAssetService;
import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO;
import com.xiaowang.yuminailcore.vo.UserAssetVO;
@@ -59,6 +61,7 @@ public class UserAssetServiceImpl implements UserAssetService {
* Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final VipBenefitMapper vipBenefitMapper;
private final VipRechargePlanMapper vipRechargePlanMapper;
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -270,7 +273,7 @@ public class UserAssetServiceImpl implements UserAssetService {
.eq(VipBenefitDO::getRequiredVipLevel, targetLevel)
.eq(VipBenefitDO::getStatus, 1)
.last("limit 1"));
if (benefit == null) {
if (benefit == null && !isVipLevelAvailable(targetLevel)) {
/**
* 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.
@@ -278,7 +281,7 @@ public class UserAssetServiceImpl implements UserAssetService {
*/
throw new RuntimeException("目标 VIP 等级未配置有效规则");
}
vipInfo.setBenefitId(benefit.getId());
vipInfo.setBenefitId(benefit != null ? benefit.getId() : null);
} else {
vipInfo.setBenefitId(null);
}
@@ -514,6 +517,21 @@ public class UserAssetServiceImpl implements UserAssetService {
return user;
}
private boolean isVipLevelAvailable(String vipLevel) {
if (!StringUtils.hasText(vipLevel)) {
return false;
}
if (VipRechargePlanServiceImpl.DEFAULT_VIP_LEVELS.contains(vipLevel.trim())) {
return true;
}
Long count = vipRechargePlanMapper.selectCount(
Wrappers.lambdaQuery(VipRechargePlanDO.class)
.eq(VipRechargePlanDO::getVipLevel, vipLevel.trim())
.eq(VipRechargePlanDO::getStatus, 1)
.eq(VipRechargePlanDO::getIsDelete, 0));
return count != null && count > 0;
}
/**
* Run business method `defaultDecimal`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -26,6 +26,7 @@ import com.xiaowang.yuminailcore.service.ShopService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.service.VerificationCodeService;
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.support.PermissionCatalog;
import com.xiaowang.yuminailcore.support.security.UserSessionService;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.support.PermissionPolicy;
@@ -52,7 +53,6 @@ import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -74,13 +74,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private static final String VIP_LEVEL_NORMAL = "普通";
private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5);
private static final String DELETED_PHONE_MARKER = "_deleted_";
private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:";
private static final int MAX_LOGIN_FAILURES = 5;
private static final Duration LOGIN_FAIL_EXPIRE = Duration.ofDays(7);
private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L;
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes();
private static final Map<String, PermissionSeed> DEFAULT_PERMISSION_SEEDS = buildDefaultPermissionSeeds();
private static final Map<String, PermissionCatalog.PermissionDefinition> DEFAULT_PERMISSION_SEEDS = PermissionCatalog.getDefinitionsByCode();
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -147,67 +148,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
private final UserSessionService userSessionService;
/**
* Run business method `buildDefaultPermissionSeeds`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return private static Map<String, PermissionSeed> result consumed by the caller or returned to the frontend
*/
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
Map<String, PermissionSeed> seeds = new HashMap<>();
seeds.put("home:view", new PermissionSeed("查看首页", "首页", "查看系统首页入口与概览"));
seeds.put("dashboard:view", new PermissionSeed("查看仪表盘", "仪表盘", "查看后台仪表盘统计"));
seeds.put("user:view", new PermissionSeed("查看用户", "用户管理", "查看用户列表与详情"));
seeds.put("user:create", new PermissionSeed("新增用户", "用户管理", "创建用户账号"));
seeds.put("user:edit", new PermissionSeed("编辑用户", "用户管理", "修改用户基础信息"));
seeds.put("user:disable", new PermissionSeed("启停用户", "用户管理", "启用或禁用用户账号"));
seeds.put("user:unbind", new PermissionSeed("解绑用户", "用户管理", "解绑用户与当前店铺的关系"));
seeds.put("user:reset_password", new PermissionSeed("重置密码", "用户管理", "重置用户密码"));
seeds.put("user:delete", new PermissionSeed("删除用户", "用户管理", "删除用户账号"));
seeds.put("user:balance:view", new PermissionSeed("查看余额资产", "用户资产", "查看用户余额、累计充值与流水"));
seeds.put("user:balance:manage", new PermissionSeed("调整余额", "用户资产", "充值、手工加减余额与关联订单"));
seeds.put("user:vip:manage", new PermissionSeed("管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级"));
seeds.put("role:view", new PermissionSeed("查看店铺角色", "角色管理", "查看店铺自定义角色"));
seeds.put("role:create", new PermissionSeed("新增店铺角色", "角色管理", "创建店铺自定义角色"));
seeds.put("role:edit", new PermissionSeed("编辑店铺角色", "角色管理", "编辑角色权限和绑定员工"));
seeds.put("role:delete", new PermissionSeed("删除店铺角色", "角色管理", "删除店铺自定义角色"));
seeds.put("user:relation:view", new PermissionSeed("查看用户所属", "用户管理", "查看用户归属关系"));
seeds.put("user:relation:edit", new PermissionSeed("编辑用户所属", "用户管理", "调整用户店铺和直属上级"));
seeds.put("product:view", new PermissionSeed("查看商品", "商品管理", "查看商品列表与详情"));
seeds.put("product:create", new PermissionSeed("新增商品", "商品管理", "创建商品"));
seeds.put("product:edit", new PermissionSeed("编辑商品", "商品管理", "编辑商品信息"));
seeds.put("product:delete", new PermissionSeed("删除商品", "商品管理", "删除商品"));
seeds.put("product:category:manage", new PermissionSeed("管理商品分类", "商品管理", "维护商品分类与归类信息"));
seeds.put("shop:view", new PermissionSeed("查看店铺", "店铺管理", "查看店铺列表与详情"));
seeds.put("shop:create", new PermissionSeed("新增店铺", "店铺管理", "创建店铺"));
seeds.put("shop:edit", new PermissionSeed("编辑店铺", "店铺管理", "编辑店铺信息"));
seeds.put("shop:delete", new PermissionSeed("删除店铺", "店铺管理", "删除店铺"));
seeds.put("shop:staff:manage", new PermissionSeed("管理员工", "店铺管理", "管理店铺员工与归属"));
seeds.put("permission:view", new PermissionSeed("查看权限", "权限管理", "查看权限清单"));
seeds.put("permission:create", new PermissionSeed("新增权限", "权限管理", "新增系统权限定义"));
seeds.put("permission:edit", new PermissionSeed("编辑权限", "权限管理", "编辑系统权限定义"));
seeds.put("permission:delete", new PermissionSeed("删除权限", "权限管理", "删除系统权限定义"));
seeds.put("permission:assign", new PermissionSeed("分配权限", "权限管理", "给用户分配后台权限"));
seeds.put("tag:view", new PermissionSeed("查看标签", "标签管理", "查看标签列表与详情"));
seeds.put("tag:create", new PermissionSeed("新增标签", "标签管理", "创建标签"));
seeds.put("tag:edit", new PermissionSeed("编辑标签", "标签管理", "编辑标签"));
seeds.put("tag:delete", new PermissionSeed("删除标签", "标签管理", "删除标签"));
seeds.put("tag:assign", new PermissionSeed("分配标签", "标签管理", "给商品或优惠券分配标签"));
seeds.put("coupon:view", new PermissionSeed("查看优惠券", "优惠券管理", "查看优惠券与发放情况"));
seeds.put("coupon:create", new PermissionSeed("新增优惠券", "优惠券管理", "创建优惠券模板"));
seeds.put("coupon:edit", new PermissionSeed("编辑优惠券", "优惠券管理", "编辑优惠券模板"));
seeds.put("coupon:delete", new PermissionSeed("删除优惠券", "优惠券管理", "删除优惠券模板"));
seeds.put("coupon:assign", new PermissionSeed("发放优惠券", "优惠券管理", "向用户发放普通优惠券"));
seeds.put("comment:view", new PermissionSeed("查看评论", "评论管理", "查看作品评论与回复"));
seeds.put("comment:delete", new PermissionSeed("删除评论", "评论管理", "删除不合规作品评论"));
seeds.put("order:view", new PermissionSeed("查看订单", "订单管理", "查看订单列表与详情"));
seeds.put("order:process", new PermissionSeed("处理订单", "订单管理", "处理订单状态或由美甲师完结订单"));
seeds.put("order:edit", new PermissionSeed("编辑订单", "订单管理", "编辑订单信息的预留权限"));
seeds.put("order:delete", new PermissionSeed("删除订单", "订单管理", "删除订单的预留权限"));
seeds.put("nail_artist:view", new PermissionSeed("查看美甲师", "美甲师管理", "查看美甲师信息与排班入口"));
seeds.put("nail_artist:edit", new PermissionSeed("编辑美甲师", "美甲师管理", "编辑美甲师信息"));
return Map.copyOf(seeds);
}
/**
* Run business method `synchronizeManagedDefaultPermissions`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -280,30 +220,33 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private void ensurePermissionDefinitions() {
List<PermissionDO> existingPermissions = permissionMapper.selectList(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getIsDelete, 0)
.in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES)
);
Set<String> existingCodes = existingPermissions.stream()
.map(PermissionDO::getPermissionCode)
.collect(Collectors.toSet());
Map<String, PermissionDO> existingByCode = existingPermissions.stream()
.collect(Collectors.toMap(PermissionDO::getPermissionCode, permission -> permission, (left, right) -> left));
for (String permissionCode : MANAGED_DEFAULT_PERMISSION_CODES) {
if (existingCodes.contains(permissionCode)) {
continue;
}
PermissionSeed permissionSeed = DEFAULT_PERMISSION_SEEDS.get(permissionCode);
PermissionCatalog.PermissionDefinition permissionSeed = DEFAULT_PERMISSION_SEEDS.get(permissionCode);
if (permissionSeed == null) {
continue;
}
PermissionDO permissionDO = new PermissionDO();
permissionDO.setPermissionCode(permissionCode);
PermissionDO permissionDO = existingByCode.get(permissionCode);
if (permissionDO == null) {
permissionDO = new PermissionDO();
permissionDO.setPermissionCode(permissionCode);
}
permissionDO.setPermissionName(permissionSeed.permissionName());
permissionDO.setPermissionGroup(permissionSeed.permissionGroup());
permissionDO.setDescription(permissionSeed.description());
permissionDO.setIsDelete(0);
permissionMapper.insert(permissionDO);
permissionDO.setUpdateTime(LocalDateTime.now());
if (permissionDO.getId() == null) {
permissionMapper.insert(permissionDO);
} else {
permissionMapper.updateById(permissionDO);
}
}
}
@@ -426,7 +369,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
nailArtistInfoDTO.setIdentity(""); // 默认身份为空
nailArtistInfoDTO.setExperience(0); // 默认经验为0
nailArtistInfoDTO.setSkills(""); // 默认技能为空
nailArtistInfoDTO.setRating(BigDecimal.ZERO); // 默认评分为0
nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5
nailArtistInfoDTO.setStatus(1); // 默认状态为营业中
nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空
nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO);
@@ -814,6 +757,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
}
if (Integer.valueOf(4).equals(userDO.getType())) {
List<ShopSimpleVO> shops = listSelectableShopOptionsForPlatformAdmin();
String message = shops.isEmpty()
? "当前暂无店铺,可直接登录"
: "平台管理员可选择任意店铺作为本次登录店铺";
return buildLoginShopSelection(shops, true, message);
}
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (!shops.isEmpty()) {
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
@@ -860,6 +811,14 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return buildLoginShopSelection(List.of(), false, "该账号已被禁用");
}
if (Integer.valueOf(4).equals(userDO.getType())) {
List<ShopSimpleVO> shops = listSelectableShopOptionsForPlatformAdmin();
String message = shops.isEmpty()
? "当前暂无店铺,可直接登录"
: "平台管理员可选择任意店铺作为本次登录店铺";
return buildLoginShopSelection(shops, true, message);
}
List<ShopSimpleVO> shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (!shops.isEmpty()) {
return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops));
@@ -907,11 +866,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
if (Integer.valueOf(4).equals(userDO.getType())) {
List<ShopSimpleVO> shops = listEnabledShopOptionsForAdmin();
boolean allowShoplessLogin = shops.isEmpty();
String message = allowShoplessLogin
? "当前暂无启用店铺,可直接登录后台创建店铺"
: buildAdminLoginShopMessage(shops);
List<ShopSimpleVO> shops = listSelectableShopOptionsForPlatformAdmin();
String message = shops.isEmpty()
? "当前暂无可选店铺,可直接进入平台总览模式"
: "平台管理员可直接进入平台总览,也可选择任意店铺作为本次登录店铺";
/**
* Run business method `buildLoginShopSelection`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -920,7 +878,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @param message parameter `message` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return buildLoginShopSelection(shops, allowShoplessLogin, message);
return buildLoginShopSelection(shops, true, message);
}
List<ShopSimpleVO> shops = listEnabledShopOptionsForUser(userDO.getId());
@@ -1214,7 +1172,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return result consumed by the caller or returned to the frontend
*/
assertUserAvailable(userDO);
if (userDO.getType() != null && userDO.getType() >= 2) {
Integer userType = userDO.getType();
if (userType != null && userType >= 2 && !Integer.valueOf(4).equals(userType)) {
/**
* 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.
@@ -1274,27 +1233,16 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) {
if (Integer.valueOf(4).equals(userDO.getType()) && !hasAnyShop()) {
return null;
}
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
if (Integer.valueOf(4).equals(userDO.getType())) {
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
if (normalizedRequestedShopId == 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("请选择登录店铺");
return null;
}
if (!userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedRequestedShopId)) {
/**
* 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("所选店铺不存在或已停用");
boolean canSelectShop = listSelectableShopOptionsForPlatformAdmin().stream()
.map(ShopSimpleVO::getId)
.anyMatch(shopId -> Objects.equals(shopId, normalizedRequestedShopId));
if (!canSelectShop) {
throw new RuntimeException("当前账号无权登录所选店铺");
}
return normalizedRequestedShopId;
}
@@ -1310,7 +1258,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员");
}
Long normalizedRequestedShopId = normalizeShopId(requestedShopId);
if (normalizedRequestedShopId != null) {
if (!activeShopIds.contains(normalizedRequestedShopId)) {
/**
@@ -2489,12 +2436,12 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
private String buildAdminLoginShopMessage(List<ShopSimpleVO> shops) {
if (shops == null || shops.isEmpty()) {
return "当前暂无启用店铺,可直接登录后台创建店铺";
return "当前暂无启用店铺,可直接进入平台总览模式";
}
if (shops.size() == 1) {
return "当前已有 1 家启用店铺,已为您默认选中";
return "平台管理员将进入平台总览模式,店铺业务默认仅可查看";
}
return "当前已有 " + shops.size() + " 家启用店铺,请选择本次登录店铺";
return "当前已有 " + shops.size() + " 家启用店铺;平台管理员将进入平台总览模式";
}
/**
@@ -2505,6 +2452,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) {
if (Integer.valueOf(4).equals(userDO.getType())) {
return resolveAdminLoginShopId(userDO, requestedShopId);
}
Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId);
List<Long> activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId());
if (!activeShopIds.isEmpty()) {
@@ -2672,7 +2622,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
if (Integer.valueOf(4).equals(userDO.getType())) {
shopOptions = new ArrayList<>(onlyActiveShops
? userShopBindingSupport.listAllActiveShopOptions()
: listEnabledShopOptionsForAdmin());
: listSelectableShopOptionsForPlatformAdmin());
} else {
shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId(
userDO.getId(),
@@ -2742,6 +2692,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.collect(Collectors.toList());
}
private List<ShopSimpleVO> listSelectableShopOptionsForPlatformAdmin() {
return shopService.listAllShopsForAdmin().stream()
.filter(shop -> !Boolean.TRUE.equals(shop.getAuthorizationExpired()))
.map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName()))
.collect(Collectors.toList());
}
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -3061,14 +3018,4 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* Run business method `PermissionSeed`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param permissionName parameter `permissionName` supplied by the caller
* @param permissionGroup parameter `permissionGroup` supplied by the caller
* @param description parameter `description` supplied by the caller
* @return private record result consumed by the caller or returned to the frontend
*/
private record PermissionSeed(String permissionName, String permissionGroup, String description) {
}
}
@@ -18,6 +18,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -32,6 +33,7 @@ import java.util.stream.Collectors;
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class VipRechargePlanServiceImpl extends ServiceImpl<VipRechargePlanMapper, VipRechargePlanDO> implements VipRechargePlanService {
public static final List<String> DEFAULT_VIP_LEVELS = List.of("普通", "青铜", "白银", "黄金");
/**
* Variable `planMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -148,6 +150,9 @@ public class VipRechargePlanServiceImpl extends ServiceImpl<VipRechargePlanMappe
*/
public List<VipRechargePlanVO> listAdminPlans(UserDO currentUser, Long shopId) {
Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
if (scopedShopId != null && scopedShopId > 0) {
ensureDefaultPlans(scopedShopId);
}
LambdaQueryWrapper<VipRechargePlanDO> wrapper = new LambdaQueryWrapper<VipRechargePlanDO>()
.eq(VipRechargePlanDO::getIsDelete, 0)
.orderByAsc(VipRechargePlanDO::getSortOrder)
@@ -189,6 +194,7 @@ public class VipRechargePlanServiceImpl extends ServiceImpl<VipRechargePlanMappe
if (shopIds.isEmpty()) {
return List.of();
}
shopIds.forEach(this::ensureDefaultPlans);
return toVOList(planMapper.selectList(new LambdaQueryWrapper<VipRechargePlanDO>()
.eq(VipRechargePlanDO::getIsDelete, 0)
.eq(VipRechargePlanDO::getStatus, 1)
@@ -197,6 +203,30 @@ public class VipRechargePlanServiceImpl extends ServiceImpl<VipRechargePlanMappe
.orderByAsc(VipRechargePlanDO::getRechargeAmount)));
}
@Override
public List<String> listVipLevelOptions(UserDO currentUser, Long shopId) {
Long scopedShopId = currentUser == null ? shopId : adminScopeHelper.resolveShopScope(currentUser, shopId);
if (scopedShopId != null && scopedShopId > 0) {
ensureDefaultPlans(scopedShopId);
}
LambdaQueryWrapper<VipRechargePlanDO> wrapper = new LambdaQueryWrapper<VipRechargePlanDO>()
.eq(VipRechargePlanDO::getIsDelete, 0)
.eq(VipRechargePlanDO::getStatus, 1)
.isNotNull(VipRechargePlanDO::getVipLevel)
.orderByAsc(VipRechargePlanDO::getSortOrder)
.orderByAsc(VipRechargePlanDO::getRechargeAmount);
if (scopedShopId != null && scopedShopId > 0) {
wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId);
}
LinkedHashSet<String> levels = new LinkedHashSet<>(DEFAULT_VIP_LEVELS);
planMapper.selectList(wrapper).stream()
.map(VipRechargePlanDO::getVipLevel)
.filter(level -> level != null && !level.trim().isEmpty())
.map(String::trim)
.forEach(levels::add);
return List.copyOf(levels);
}
/**
* Run business method `apply`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -292,6 +322,36 @@ public class VipRechargePlanServiceImpl extends ServiceImpl<VipRechargePlanMappe
}
}
private void ensureDefaultPlans(Long shopId) {
if (shopId == null || shopId <= 0) {
return;
}
createDefaultPlanIfMissing(shopId, "青铜", new BigDecimal("99.00"), 10);
createDefaultPlanIfMissing(shopId, "白银", new BigDecimal("299.00"), 20);
createDefaultPlanIfMissing(shopId, "黄金", new BigDecimal("599.00"), 30);
}
private void createDefaultPlanIfMissing(Long shopId, String vipLevel, BigDecimal rechargeAmount, int sortOrder) {
Long count = planMapper.selectCount(new LambdaQueryWrapper<VipRechargePlanDO>()
.eq(VipRechargePlanDO::getShopId, shopId)
.eq(VipRechargePlanDO::getVipLevel, vipLevel)
.eq(VipRechargePlanDO::getIsDelete, 0));
if (count != null && count > 0) {
return;
}
VipRechargePlanDO plan = new VipRechargePlanDO();
plan.setShopId(shopId);
plan.setTitle(vipLevel + "会员充值");
plan.setRechargeAmount(rechargeAmount);
plan.setGiftAmount(BigDecimal.ZERO);
plan.setVipLevel(vipLevel);
plan.setDescription("系统默认配置,可按门店实际规则修改");
plan.setSortOrder(sortOrder);
plan.setStatus(1);
plan.setIsDelete(0);
planMapper.insert(plan);
}
/**
* Run business method `toVOList`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -18,6 +18,7 @@ import com.xiaowang.yuminailcore.service.WechatMiniClientService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
import lombok.Data;
@@ -235,6 +236,20 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
WechatMiniClientService.SessionInfo sessionInfo,
boolean newUser
) {
if (Integer.valueOf(4).equals(userDO.getType())) {
List<ShopSimpleVO> platformAdminShops = resolvePlatformAdminLoginShops(userDO);
if (platformAdminShops.isEmpty()) {
LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), null);
ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId());
return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser);
}
return buildSelectShopResult(
"平台管理员可选择任意门店作为本次登录门店。",
platformAdminShops,
new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser)
);
}
List<ShopSimpleVO> activeShops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
if (activeShops.isEmpty()) {
return WechatMiniLoginResultVO.needManualLogin("当前账号没有可登录的门店,请联系管理员处理。");
@@ -254,6 +269,16 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
);
}
private List<ShopSimpleVO> resolvePlatformAdminLoginShops(UserDO userDO) {
LoginShopSelectionVO selection = null;
if (StringUtils.hasText(userDO.getPhone())) {
selection = userService.getLoginShopSelectionByPhone(userDO.getPhone());
} else if (StringUtils.hasText(userDO.getAccount())) {
selection = userService.getLoginShopSelectionByAccount(userDO.getAccount());
}
return selection == null || selection.getShops() == null ? List.of() : selection.getShops();
}
/**
* 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.
@@ -35,6 +35,24 @@ public class AdminScopeHelper {
return currentUser != null && Integer.valueOf(4).equals(currentUser.getType());
}
public boolean isPlatformOverviewMode(UserDO currentUser) {
return isPlatformAdmin(currentUser)
&& (currentUser.getShopId() == null || currentUser.getShopId() <= 0);
}
public void requireShopContext(UserDO currentUser) {
requireShopContext(currentUser, "请先选择店铺后再管理店铺细节");
}
public void requireShopContext(UserDO currentUser, String message) {
if (isPlatformOverviewMode(currentUser)) {
throw new RuntimeException(message);
}
if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) {
throw new RuntimeException(message);
}
}
public Long getManagedShopId(UserDO currentUser) {
if (isPlatformAdmin(currentUser)) {
return null;
@@ -0,0 +1,229 @@
package com.xiaowang.yuminailcore.support;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 权限目录是后台权限编码、中文展示文案和默认角色矩阵的唯一真源。
*/
public final class PermissionCatalog {
private static final Map<String, PermissionDefinition> DEFINITIONS = buildDefinitions();
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit",
"message:view", "message:create", "message:delete",
"announcement:view", "announcement:create", "announcement:delete",
"messagehub:config:manage",
"legal_agreement:manage"
);
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:unbind", "user:reset_password",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:edit", "shop:staff:manage",
"permission:view", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit",
"message:view", "message:create",
"announcement:view", "announcement:create"
);
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"user:view", "user:create",
"user:balance:view",
"product:view", "product:create",
"shop:view",
"tag:view", "tag:create",
"coupon:view",
"comment:view",
"order:view", "order:process"
);
private static final Set<String> PLATFORM_OVERVIEW_PREFIXES = Set.of(
"user:",
"shop:",
"permission:",
"message:",
"announcement:"
);
private static final Set<String> PLATFORM_OVERVIEW_PERMISSIONS = Set.of(
"messagehub:config:manage",
"legal_agreement:manage"
);
private static final Set<String> MANAGED_PERMISSION_CODES = buildManagedPermissionCodes();
private PermissionCatalog() {
}
public static List<String> getDefaultPermissionCodes(Integer userType) {
return switch (userType == null ? -1 : userType) {
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
default -> List.of();
};
}
public static Set<String> getDefaultPermissionCodeSet(Integer userType) {
return Set.copyOf(getDefaultPermissionCodes(userType));
}
public static Set<String> getManagedPermissionCodes() {
return MANAGED_PERMISSION_CODES;
}
public static Collection<PermissionDefinition> getManagedDefinitions() {
return MANAGED_PERMISSION_CODES.stream()
.map(PermissionCatalog::getRequiredDefinition)
.toList();
}
public static Map<String, PermissionDefinition> getDefinitionsByCode() {
return DEFINITIONS;
}
public static PermissionDefinition getRequiredDefinition(String permissionCode) {
PermissionDefinition definition = DEFINITIONS.get(permissionCode);
if (definition == null) {
throw new IllegalArgumentException("Unknown permission code: " + permissionCode);
}
return definition;
}
public static boolean isAllowedForPlatformOverview(String permissionCode) {
if (permissionCode == null || permissionCode.isBlank()) {
return true;
}
if ("dashboard:view".equals(permissionCode) || permissionCode.endsWith(":view")) {
return true;
}
if (PLATFORM_OVERVIEW_PERMISSIONS.contains(permissionCode)) {
return true;
}
return PLATFORM_OVERVIEW_PREFIXES.stream().anyMatch(permissionCode::startsWith);
}
public static boolean canManageUserType(Integer operatorType, Integer targetType) {
if (operatorType == null || targetType == null) {
return false;
}
return switch (operatorType) {
case 4 -> true;
case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType);
case 3 -> Integer.valueOf(0).equals(targetType);
default -> false;
};
}
private static Set<String> buildManagedPermissionCodes() {
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
return Set.copyOf(permissionCodes);
}
private static Map<String, PermissionDefinition> buildDefinitions() {
LinkedHashMap<String, PermissionDefinition> definitions = new LinkedHashMap<>();
put(definitions, "home:view", "查看首页", "首页", "查看系统首页入口与概览");
put(definitions, "dashboard:view", "查看仪表盘", "仪表盘", "查看后台仪表盘统计");
put(definitions, "user:view", "查看用户", "用户管理", "查看用户列表与详情");
put(definitions, "user:create", "新增用户", "用户管理", "创建用户账号");
put(definitions, "user:edit", "编辑用户", "用户管理", "修改用户基础信息");
put(definitions, "user:disable", "启停用户", "用户管理", "启用或禁用用户账号");
put(definitions, "user:unbind", "解绑用户", "用户管理", "解绑用户与当前店铺的关系");
put(definitions, "user:reset_password", "重置密码", "用户管理", "重置用户密码");
put(definitions, "user:delete", "删除用户", "用户管理", "删除用户账号");
put(definitions, "user:balance:view", "查看余额资产", "用户资产", "查看用户余额、累计充值与流水");
put(definitions, "user:balance:manage", "调整余额", "用户资产", "充值、手工加减余额与关联订单");
put(definitions, "user:vip:manage", "管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级");
put(definitions, "role:view", "查看店铺角色", "角色管理", "查看店铺自定义角色");
put(definitions, "role:create", "新增店铺角色", "角色管理", "创建店铺自定义角色");
put(definitions, "role:edit", "编辑店铺角色", "角色管理", "编辑角色权限和绑定员工");
put(definitions, "role:delete", "删除店铺角色", "角色管理", "删除店铺自定义角色");
put(definitions, "user:relation:view", "查看用户所属", "用户管理", "查看用户归属关系");
put(definitions, "user:relation:edit", "编辑用户所属", "用户管理", "调整用户店铺和直属上级");
put(definitions, "product:view", "查看商品", "商品管理", "查看商品列表与详情");
put(definitions, "product:create", "新增商品", "商品管理", "创建商品");
put(definitions, "product:edit", "编辑商品", "商品管理", "编辑商品信息");
put(definitions, "product:delete", "删除商品", "商品管理", "删除商品");
put(definitions, "product:category:manage", "管理商品分类", "商品管理", "维护商品分类与归类信息");
put(definitions, "shop:view", "查看店铺", "店铺管理", "查看店铺列表与详情");
put(definitions, "shop:create", "新增店铺", "店铺管理", "创建店铺");
put(definitions, "shop:edit", "编辑店铺", "店铺管理", "编辑店铺信息");
put(definitions, "shop:delete", "删除店铺", "店铺管理", "删除店铺");
put(definitions, "shop:staff:manage", "管理员工", "店铺管理", "管理店铺员工与归属");
put(definitions, "permission:view", "查看权限", "权限管理", "查看权限清单");
put(definitions, "permission:create", "新增权限", "权限管理", "新增系统权限定义");
put(definitions, "permission:edit", "编辑权限", "权限管理", "编辑系统权限定义");
put(definitions, "permission:delete", "删除权限", "权限管理", "删除系统权限定义");
put(definitions, "permission:assign", "分配权限", "权限管理", "给用户分配后台权限");
put(definitions, "tag:view", "查看标签", "标签管理", "查看标签列表与详情");
put(definitions, "tag:create", "新增标签", "标签管理", "创建标签");
put(definitions, "tag:edit", "编辑标签", "标签管理", "编辑标签");
put(definitions, "tag:delete", "删除标签", "标签管理", "删除标签");
put(definitions, "tag:assign", "分配标签", "标签管理", "给商品或优惠券分配标签");
put(definitions, "coupon:view", "查看优惠券", "优惠券管理", "查看优惠券与发放情况");
put(definitions, "coupon:create", "新增优惠券", "优惠券管理", "创建优惠券模板");
put(definitions, "coupon:edit", "编辑优惠券", "优惠券管理", "编辑优惠券模板");
put(definitions, "coupon:delete", "删除优惠券", "优惠券管理", "删除优惠券模板");
put(definitions, "coupon:assign", "发放优惠券", "优惠券管理", "向用户发放普通优惠券");
put(definitions, "comment:view", "查看评论", "评论管理", "查看作品评论与回复");
put(definitions, "comment:delete", "删除评论", "评论管理", "删除不合规作品评论");
put(definitions, "order:view", "查看订单", "订单管理", "查看订单列表与详情");
put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单");
put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限");
put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限");
put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口");
put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息");
put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知");
put(definitions, "message:create", "发布消息", "消息管理", "发布站内消息");
put(definitions, "message:delete", "撤回消息", "消息管理", "撤回已发布站内消息");
put(definitions, "announcement:view", "查看公告", "公告管理", "查看公告列表与详情");
put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告");
put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数");
put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本");
return Map.copyOf(definitions);
}
private static void put(Map<String, PermissionDefinition> definitions, String code, String name, String group, String description) {
definitions.put(code, new PermissionDefinition(code, name, group, description));
}
public record PermissionDefinition(
String permissionCode,
String permissionName,
String permissionGroup,
String description
) {
}
}
@@ -1,6 +1,5 @@
package com.xiaowang.yuminailcore.support;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -9,95 +8,22 @@ import java.util.Set;
*/
public final class PermissionPolicy {
private static final List<String> ADMIN_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage",
"permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit",
"message:view", "message:create", "message:delete",
"announcement:view", "announcement:create", "announcement:delete",
"messagehub:config:manage"
);
private static final List<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"dashboard:view",
"user:view", "user:create", "user:edit", "user:unbind", "user:reset_password",
"user:balance:view", "user:balance:manage", "user:vip:manage",
"role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit",
"product:view", "product:create", "product:edit", "product:delete", "product:category:manage",
"shop:view", "shop:edit", "shop:staff:manage",
"permission:view", "permission:assign",
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
"comment:view", "comment:delete",
"order:view", "order:process", "order:edit", "order:delete",
"nail_artist:view", "nail_artist:edit",
"message:view", "message:create",
"announcement:view", "announcement:create"
);
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
"home:view",
"user:view", "user:create",
"user:balance:view",
"product:view", "product:create",
"shop:view",
"tag:view", "tag:create",
"coupon:view",
"comment:view",
"order:view", "order:process"
);
private static final Set<String> MANAGED_DEFAULT_PERMISSION_CODES = buildManagedDefaultPermissionCodes();
private PermissionPolicy() {
}
public static List<String> getDefaultPermissionCodes(Integer userType) {
return switch (userType == null ? -1 : userType) {
case 4 -> ADMIN_DEFAULT_PERMISSION_CODES;
case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES;
case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES;
default -> List.of();
};
return PermissionCatalog.getDefaultPermissionCodes(userType);
}
public static Set<String> getDefaultPermissionCodeSet(Integer userType) {
return Set.copyOf(getDefaultPermissionCodes(userType));
return PermissionCatalog.getDefaultPermissionCodeSet(userType);
}
public static Set<String> getManagedDefaultPermissionCodes() {
return MANAGED_DEFAULT_PERMISSION_CODES;
return PermissionCatalog.getManagedPermissionCodes();
}
public static boolean canManageUserType(Integer operatorType, Integer targetType) {
if (operatorType == null || targetType == null) {
return false;
}
return switch (operatorType) {
case 4 -> true;
case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType);
case 3 -> Integer.valueOf(0).equals(targetType);
default -> false;
};
}
private static Set<String> buildManagedDefaultPermissionCodes() {
LinkedHashSet<String> permissionCodes = new LinkedHashSet<>();
permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES);
permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES);
return Set.copyOf(permissionCodes);
return PermissionCatalog.canManageUserType(operatorType, targetType);
}
}
@@ -0,0 +1,24 @@
package com.xiaowang.yuminailcore.support;
import org.springframework.util.StringUtils;
import java.util.Locale;
import java.util.regex.Pattern;
public final class ShopThemeSupport {
private static final Pattern HEX_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$");
private ShopThemeSupport() {
}
public static String normalizeColor(String color, String fieldName) {
if (!StringUtils.hasText(color)) {
return null;
}
String value = color.trim();
if (!HEX_COLOR.matcher(value).matches()) {
throw new IllegalArgumentException(fieldName + " must be a #RRGGBB color");
}
return value.toUpperCase(Locale.ROOT);
}
}
@@ -364,10 +364,14 @@ public class UserShopBindingSupport {
}
public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) {
if (Integer.valueOf(4).equals(userType)) {
if (shopId == null || shopId <= 0) {
return Boolean.TRUE.equals(adminLogin);
}
return isShopSelectableForPlatformAdmin(shopId);
}
if (shopId == null || shopId <= 0) {
return Boolean.TRUE.equals(adminLogin)
&& Integer.valueOf(4).equals(userType)
&& listAllActiveShopOptions().isEmpty();
return false;
}
if (Boolean.TRUE.equals(adminLogin)) {
if (!isShopEnabledIgnoringAuthorization(shopId)) {
@@ -376,12 +380,20 @@ public class UserShopBindingSupport {
} else if (!isShopActive(shopId)) {
return false;
}
if (Boolean.TRUE.equals(adminLogin) && Integer.valueOf(4).equals(userType)) {
return true;
}
return hasActiveBinding(userId, shopId);
}
private boolean isShopSelectableForPlatformAdmin(Long shopId) {
if (shopId == null || shopId <= 0) {
return false;
}
ShopDO shopDO = shopMapper.selectById(shopId);
return shopDO != null
&& !Integer.valueOf(1).equals(shopDO.getIsDelete())
&& (shopDO.getAuthorizationExpireTime() == null
|| !shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()));
}
public boolean isUserAccessibleInShop(Long userId, Long shopId) {
return hasActiveBinding(userId, shopId);
}
@@ -19,6 +19,15 @@ public class UploadSecurityValidator {
private static final Set<String> IMAGE_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp", ".gif");
private static final Set<String> COMPATIBLE_IMAGE_MIME_TYPES = Set.of(
"image/jpeg",
"image/jpg",
"image/pjpeg",
"image/png",
"image/webp",
"image/gif"
);
private final UploadSecurityProperties properties;
public void validate(MultipartFile file) {
@@ -33,11 +42,11 @@ public class UploadSecurityValidator {
if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) {
throw new RuntimeException("不支持的文件类型");
}
String contentType = StringUtils.hasText(file.getContentType()) ? file.getContentType().toLowerCase(Locale.ROOT) : "";
if (!properties.getAllowedMimeTypes().contains(contentType)) {
String contentType = normalizeContentType(file.getContentType());
if (!contentType.isEmpty() && !isAllowedMimeType(contentType)) {
throw new RuntimeException("文件 MIME 类型不允许");
}
if (contentType.startsWith("image/") && !IMAGE_EXTENSIONS.contains(extension)) {
if (isLikelyImage(extension, contentType) && !IMAGE_EXTENSIONS.contains(extension)) {
throw new RuntimeException("图片文件扩展名不匹配");
}
}
@@ -50,16 +59,52 @@ public class UploadSecurityValidator {
if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) {
throw new RuntimeException("不支持的文件类型");
}
String normalizedContentType = StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT) : "";
if (!properties.getAllowedMimeTypes().contains(normalizedContentType)) {
String normalizedContentType = normalizeContentType(contentType);
if (!normalizedContentType.isEmpty() && !isAllowedMimeType(normalizedContentType)) {
throw new RuntimeException("文件 MIME 类型不允许");
}
}
public void validateChunk(MultipartFile chunkFile) {
if (chunkFile == null || chunkFile.isEmpty()) {
throw new RuntimeException("上传分片不能为空");
}
if (chunkFile.getSize() > properties.getMaxSize()) {
throw new RuntimeException("上传文件过大");
}
String filename = chunkFile.getOriginalFilename();
String extension = resolveExtension(filename);
if (StringUtils.hasText(extension) && BLOCKED_EXTENSIONS.contains(extension)) {
throw new RuntimeException("不支持的文件类型");
}
}
private boolean isAllowedMimeType(String contentType) {
return properties.getAllowedMimeTypes().contains(contentType) || COMPATIBLE_IMAGE_MIME_TYPES.contains(contentType);
}
private boolean isLikelyImage(String extension, String contentType) {
return IMAGE_EXTENSIONS.contains(extension) || contentType.startsWith("image/");
}
private String normalizeContentType(String contentType) {
return StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT).trim() : "";
}
private String resolveExtension(String filename) {
if (!StringUtils.hasText(filename) || !filename.contains(".")) {
return "";
}
return filename.substring(filename.lastIndexOf(".")).toLowerCase(Locale.ROOT);
String normalized = filename.trim();
int queryIndex = normalized.indexOf('?');
if (queryIndex >= 0) {
normalized = normalized.substring(0, queryIndex);
}
int fragmentIndex = normalized.indexOf('#');
if (fragmentIndex >= 0) {
normalized = normalized.substring(0, fragmentIndex);
}
int dotIndex = normalized.lastIndexOf(".");
return dotIndex >= 0 ? normalized.substring(dotIndex).toLowerCase(Locale.ROOT) : "";
}
}
@@ -4,8 +4,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.yuminailcore.config.JwtProperties;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@@ -131,6 +133,8 @@ public class UserSessionService {
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class SessionState {
private String sessionId;
private Long userId;
@@ -2,6 +2,7 @@ package com.xiaowang.yuminailcore.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
@@ -26,6 +27,16 @@ public class DashboardStatsVO {
* Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long todayOrders;
private BigDecimal totalOrderAmount;
private BigDecimal todayOrderAmount;
private BigDecimal weekOrderAmount;
private Long totalCustomers;
private Long totalArtists;
private Long newCustomersToday;
private Long newCustomers7Days;
private Long newOrders7Days;
private Long pendingOrders;
private Long completedOrders;
/**
* Field `hotProducts` (List<HotProductVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@@ -73,11 +74,27 @@ public class ShopVO {
*/
private List<String> imageUrls;
private String themePrimaryColor;
private String themeSecondaryColor;
private String themeAccentColor;
private String themePageBgColor;
private String themeCardBgColor;
private String themeBackgroundImageFileId;
/**
* 店铺状态:1-启用,0-停用
*/
private Integer status;
private LocalDate authorizationStartDate;
private Integer authorizationDays;
/**
* 店铺授权有效期;为空表示长期有效。
*/
+1 -4
View File
@@ -5,11 +5,8 @@
| 模块 | 路径 | 说明 |
|------|------|------|
| YumiNail-Frontend | `YumiNail-Frontend/` | YumiNail 主业务 Vue3 前端项目 |
| YumiNail-Calendar-Frontend | `YumiNail-Calendar-Frontend/` | 美甲师日历表独立前端项目 |
| YumiNail-Calendar-Gateway | `YumiNail-Calendar-Gateway/` | 美甲师日历表独立网关 |
| YumiNail-Calendar-Core | `YumiNail-Calendar-Core/` | 美甲师日历表独立后端服务 |
| YumiNail-Gateway | `YumiNail-Gateway/` | Spring Cloud Gateway网关 |
| YumiNail-Core | `YumiNail-Core/` | 核心业务服务 |
| YumiNail-Core | `YumiNail-Core/` | 核心业务服务,内置美甲师预约日历接口 |
| MessageHub | `MessageHub/` | 消息推送服务 |
---
@@ -1,9 +1,10 @@
-- YumiNail 首次部署主 SQL
-- YumiNail 最小运行初始化 SQL
-- 说明:
-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、VIP 规则、admin01 初始化与默认权限分配。
-- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、基础参数、协议、MessageHub、VIP 规则与管理员初始化。
-- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、
-- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。
-- 3. 当前 Nacos datasource.yaml 指向 nailart,本文件默认按该库名初始化;如果你的实际数据库名不同,请先统一 datasource 与下方库名。
-- 4. 本文件只初始化一个平台管理员 xiaowang(默认密码 888888),不写入开发/验收用户、门店、作品、标签、订单、消息公告等业务数据。
CREATE DATABASE IF NOT EXISTS nailart DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
use nailart;
@@ -14,6 +15,8 @@ create table t_balance
primary key comment '余额表主键索引',
user_id bigint unsigned not null comment '关联用户表主键',
amount decimal(10, 2) default 0.00 not null comment '当前余额',
total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额',
last_recharge_time datetime null comment '最近一次充值时间',
create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间',
last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间',
constraint uk_user_id
@@ -31,6 +34,14 @@ create table t_balance_change_detail
amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)',
type varchar(20) not null comment '变动类型(如充值、消费、退款)',
current_balance decimal(10, 2) not null comment '变动后的当前余额',
before_balance decimal(10, 2) null comment '变动前余额',
after_balance decimal(10, 2) null comment '变动后余额',
change_scene varchar(32) null comment '余额变动场景',
related_order_id bigint unsigned null comment '关联系统订单ID',
related_order_no varchar(64) null comment '关联系统订单号',
external_order_no varchar(64) null comment '手工录入的外部订单号',
operator_id bigint unsigned null comment '操作人ID',
remark varchar(255) null comment '备注',
change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间'
)
comment '用户余额变动明细表';
@@ -116,6 +127,9 @@ create table t_coupon
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
shop_id bigint null comment '所属店铺ID',
coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景',
required_vip_level varchar(20) null comment '要求的VIP等级',
auto_match tinyint unsigned default 0 not null comment '是否自动匹配',
constraint uk_coupon_code
unique (coupon_code) comment '优惠券编码唯一索引'
)
@@ -181,6 +195,7 @@ create table t_login_identity
login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)',
input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)',
input_time datetime not null comment '输入时间',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
status tinyint unsigned default 1 null comment '状态:1-有效,0-无效'
)
@@ -226,7 +241,7 @@ create table t_nail_artist_info
identity varchar(50) default '' null comment '身份',
experience int unsigned default 0 null comment '从业年限',
skills text null comment '技能标签ID集合,多个ID以逗号分隔',
rating decimal(3, 1) default 0.0 null comment '评分',
rating decimal(3, 1) default 4.5 null comment '评分',
status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中',
participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与',
work_start_time time null comment '工作开始时间',
@@ -277,9 +292,12 @@ create table t_order
primary key,
order_no varchar(50) not null comment '订单编号',
user_id bigint unsigned not null comment '关联用户表主键',
shop_id bigint unsigned null comment '所属店铺ID',
total_amount decimal(10, 2) not null comment '订单总金额',
actual_amount decimal(10, 2) not null comment '实际支付金额',
coupon_id bigint unsigned default 0 null comment '使用的优惠券ID',
user_coupon_id bigint unsigned null comment '用户券ID',
coupon_source_type varchar(32) null comment '优惠来源类型',
status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
@@ -307,6 +325,7 @@ create table t_order_item
quantity int unsigned not null comment '商品数量',
price decimal(10, 2) not null comment '商品单价',
artist_id bigint unsigned null comment '关联美甲师ID',
appointment_time datetime null comment '预约开始时间',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
@@ -408,6 +427,16 @@ create table t_shop
latitude decimal(12, 8) null comment '店铺纬度',
business_hours varchar(100) default '' null comment '店铺营业时间',
cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID',
theme_primary_color varchar(20) null comment '前台主题主色',
theme_secondary_color varchar(20) null comment '前台主题辅色',
theme_accent_color varchar(20) null comment '前台主题强调色',
theme_page_bg_color varchar(20) null comment '前台主题页面背景色',
theme_card_bg_color varchar(20) null comment '前台主题卡片背景色',
theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID',
status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用',
authorization_start_date date null comment '店铺授权起始日',
authorization_days int null comment '店铺授权有效天数',
authorization_expire_time datetime null comment '店铺授权到期时间',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
@@ -633,6 +662,9 @@ create table t_vip_benefit
primary key comment 'VIP权益主键索引',
benefit_info text not null comment '权益详情(如折扣、专属服务)',
required_vip_level varchar(20) not null comment '所需VIP等级',
level_rank int default 0 not null comment '等级序号',
recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛',
status tinyint unsigned default 1 not null comment '状态',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
@@ -647,11 +679,13 @@ create table t_vip_info
(
id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)'
primary key comment 'VIP信息主键索引',
user_id bigint unsigned null comment '所属用户ID',
vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)',
start_time datetime not null comment 'VIP开通时间',
expire_time datetime not null comment 'VIP到期时间',
expire_time datetime null comment 'VIP到期时间',
activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)',
benefit_id bigint unsigned not null comment '关联VIP权益信息表主键',
benefit_id bigint unsigned null comment '关联VIP权益信息表主键',
manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
)
@@ -783,6 +817,7 @@ CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no',
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID''');
CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注''');
CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间''');
UPDATE t_balance_change_detail
SET before_balance = COALESCE(before_balance, current_balance - amount),
@@ -984,45 +1019,6 @@ WHERE NOT EXISTS (
WHERE required_vip_level = '黄金'
);
INSERT INTO t_coupon (
coupon_code,
coupon_name,
coupon_type,
discount_value,
min_amount,
reduce_amount,
total_count,
used_count,
start_time,
end_time,
status,
create_time,
update_time,
is_delete,
shop_id,
coupon_scene,
required_vip_level,
auto_match
)
VALUES
('VIP_AUTO_BRONZE_95', '青铜VIP自动95折券', 1, 9.50, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '青铜', 1),
('VIP_AUTO_SILVER_92', '白银VIP自动92折券', 1, 9.20, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '白银', 1),
('VIP_AUTO_GOLD_90', '黄金VIP自动90折券', 1, 9.00, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '黄金', 1)
ON DUPLICATE KEY UPDATE
coupon_name = VALUES(coupon_name),
coupon_type = VALUES(coupon_type),
discount_value = VALUES(discount_value),
min_amount = VALUES(min_amount),
reduce_amount = VALUES(reduce_amount),
total_count = VALUES(total_count),
status = VALUES(status),
is_delete = VALUES(is_delete),
shop_id = VALUES(shop_id),
coupon_scene = VALUES(coupon_scene),
required_vip_level = VALUES(required_vip_level),
auto_match = VALUES(auto_match),
update_time = NOW();
DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
@@ -1112,10 +1108,18 @@ END$$
DELIMITER ;
CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用''');
CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日''');
CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数''');
CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效''');
CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP''');
CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度''');
CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色''');
CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID''');
UPDATE t_shop
SET status = 1
@@ -1217,7 +1221,7 @@ DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
-- ========================================
-- 首次部署整合区:权限种子 / admin01 初始化 / 默认权限分配
-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配
-- 来源:2026-03-20_init_admin_permission_template.sql
-- ========================================
@@ -1274,9 +1278,9 @@ VALUES
('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0),
('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0)
,
('announcement:view', 'View Announcements', 'Announcement Management', 'View announcement list and detail', NOW(), NOW(), 0),
('announcement:create', 'Create Announcements', 'Announcement Management', 'Publish announcements', NOW(), NOW(), 0),
('announcement:delete', 'Withdraw Announcements', 'Announcement Management', 'Withdraw published announcements', NOW(), NOW(), 0)
('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0),
('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0),
('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
@@ -1298,9 +1302,9 @@ ON DUPLICATE KEY UPDATE
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
VALUES
(910000000008011, 'announcement:view', 'View Announcements', 'Announcement Management', 'View announcement list and detail', NOW(), NOW(), 0),
(910000000008012, 'announcement:create', 'Create Announcements', 'Announcement Management', 'Publish announcements', NOW(), NOW(), 0),
(910000000008013, 'announcement:delete', 'Withdraw Announcements', 'Announcement Management', 'Withdraw published announcements', NOW(), NOW(), 0)
(910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0),
(910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0),
(910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
@@ -1327,10 +1331,10 @@ INSERT INTO t_user (
SELECT
0,
'系统管理员',
'admin01',
'xiaowang',
0,
0,
'$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W',
'$2a$10$I3mV64NhISqMmm7soSki1.Y36ve.TOINGOrVt0U0kxjO7GtxavE16',
'',
'管理员',
4,
@@ -1342,7 +1346,7 @@ SELECT
WHERE NOT EXISTS (
SELECT 1
FROM t_user
WHERE account = 'admin01'
WHERE account = 'xiaowang'
);
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
@@ -1535,233 +1539,15 @@ ON DUPLICATE KEY UPDATE
is_delete = 0,
update_time = NOW();
-- YumiNail 手工验收种子数据
INSERT INTO t_nail_artist_info (user_id, identity, experience, skills, rating, status, participate_production, work_start_time, work_end_time, portfolio, create_time, update_time, is_delete)
SELECT u.id, '店长', 3, '', 5.0, 1, 0, '09:00:00', '18:00:00', '', NOW(), NOW(), 0
FROM t_user u
WHERE u.type = 2 AND u.is_delete = 0
AND NOT EXISTS (SELECT 1 FROM t_nail_artist_info nai WHERE nai.user_id = u.id AND nai.is_delete = 0);
UPDATE t_nail_artist_info nai
INNER JOIN t_user u ON u.id = nai.user_id AND u.type = 3
SET nai.participate_production = 1
WHERE nai.participate_production IS NULL;
UPDATE t_nail_artist_info nai
INNER JOIN t_user u ON u.id = nai.user_id AND u.type = 2
SET nai.participate_production = COALESCE(nai.participate_production, 0);
-- 小型全覆盖验收数据,便于人工抽检。
-- Password hash matches the existing admin seed password hash; reset in non-local environments if needed.
INSERT INTO t_shop (id, shop_name, description, address, business_hours, cover_image_file_id, create_time, update_time, is_delete, image_file_ids, status)
SELECT 910000000000001, '验收主店', '用于验收的主门店', '验收路 1 号', '09:00-21:00', '', NOW(), NOW(), 0, '', 1
WHERE NOT EXISTS (SELECT 1 FROM t_shop WHERE id = 910000000000001);
INSERT INTO t_shop (id, shop_name, description, address, business_hours, cover_image_file_id, create_time, update_time, is_delete, image_file_ids, status)
SELECT 910000000000002, '验收分店', '用于验收的分门店', '验收路 2 号', '10:00-20:00', '', NOW(), NOW(), 0, '', 1
WHERE NOT EXISTS (SELECT 1 FROM t_shop WHERE id = 910000000000002);
INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time)
SELECT 910000000000101, '青铜会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 1 LIMIT 1), 0), NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000101);
INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time)
SELECT 910000000000102, '白银会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 2 LIMIT 1), 0), NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000102);
INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time)
SELECT 910000000000103, '黄金会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 3 LIMIT 1), 0), NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000103);
INSERT INTO t_user (id, shop_id, nickname, account, phone, email, phone_verified, email_verified, password, signature, level, type, vip_id, create_time, update_time, is_delete, status, avatar)
VALUES
(910000000001001, 910000000000001, '验收普通用户', 'accept_user_normal', '18800001001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '普通用户', 0, 0, NOW(), NOW(), 0, 1, NULL),
(910000000001002, 910000000000001, '验收青铜用户', 'accept_user_bronze', '18800001002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '青铜会员', 0, 910000000000101, NOW(), NOW(), 0, 1, NULL),
(910000000001003, 910000000000001, '验收白银用户', 'accept_user_silver', '18800001003', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '白银会员', 0, 910000000000102, NOW(), NOW(), 0, 1, NULL),
(910000000001004, 910000000000001, '验收黄金用户', 'accept_user_gold', '18800001004', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '黄金会员', 0, 910000000000103, NOW(), NOW(), 0, 1, NULL),
(910000000002001, 910000000000001, '验收店长', 'accept_manager_main', '18800002001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL),
(910000000002002, 910000000000001, '验收参与制作店长', 'accept_manager_artist', '18800002002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL),
(910000000002003, 910000000000002, '验收分店店长', 'accept_manager_branch', '18800002003', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL),
(910000000003001, 910000000000001, '验收美甲师', 'accept_artist_main', '18800003001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '美甲师', 3, 0, NOW(), NOW(), 0, 1, NULL),
(910000000003002, 910000000000002, '验收分店美甲师', 'accept_artist_branch', '18800003002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '美甲师', 3, 0, NOW(), NOW(), 0, 1, NULL)
ON DUPLICATE KEY UPDATE
shop_id = VALUES(shop_id),
nickname = VALUES(nickname),
phone = VALUES(phone),
level = VALUES(level),
type = VALUES(type),
vip_id = VALUES(vip_id),
status = VALUES(status),
is_delete = 0,
update_time = NOW();
INSERT INTO t_user_shop_binding (user_id, shop_id, status, create_time, update_time, is_delete)
SELECT u.id, u.shop_id, 1, NOW(), NOW(), 0
FROM t_user u
WHERE u.id BETWEEN 910000000001001 AND 910000000003002
AND u.shop_id > 0
ON DUPLICATE KEY UPDATE
status = 1,
is_delete = 0,
update_time = NOW();
INSERT INTO t_nail_artist_info (user_id, identity, experience, skills, rating, status, participate_production, work_start_time, work_end_time, portfolio, create_time, update_time, is_delete)
VALUES
(910000000002001, '店长', 5, '门店管理', 5.0, 1, 0, '09:00:00', '18:00:00', '', NOW(), NOW(), 0),
(910000000002002, '参与制作店长', 8, '美甲设计', 5.0, 1, 1, '09:30:00', '20:00:00', '', NOW(), NOW(), 0),
(910000000002003, '分店店长', 4, '分店管理', 4.8, 1, 1, '10:00:00', '19:00:00', '', NOW(), NOW(), 0),
(910000000003001, '美甲师', 3, '凝胶,护理', 4.9, 1, 1, '10:00:00', '21:00:00', '', NOW(), NOW(), 0),
(910000000003002, '分店美甲师', 2, '基础护理,修复', 4.7, 1, 1, '10:00:00', '19:00:00', '', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
identity = VALUES(identity),
experience = VALUES(experience),
skills = VALUES(skills),
rating = VALUES(rating),
status = VALUES(status),
participate_production = VALUES(participate_production),
work_start_time = VALUES(work_start_time),
work_end_time = VALUES(work_end_time),
is_delete = 0,
update_time = NOW();
INSERT INTO t_balance (user_id, amount, create_time, last_update_time, total_recharge_amount, last_recharge_time)
VALUES
(910000000001001, 68.00, NOW(), NOW(), 100.00, DATE_SUB(NOW(), INTERVAL 10 DAY)),
(910000000001002, 288.00, NOW(), NOW(), 600.00, DATE_SUB(NOW(), INTERVAL 8 DAY)),
(910000000001003, 588.00, NOW(), NOW(), 1200.00, DATE_SUB(NOW(), INTERVAL 6 DAY)),
(910000000001004, 988.00, NOW(), NOW(), 2600.00, DATE_SUB(NOW(), INTERVAL 4 DAY))
ON DUPLICATE KEY UPDATE
amount = VALUES(amount),
total_recharge_amount = VALUES(total_recharge_amount),
last_recharge_time = VALUES(last_recharge_time),
last_update_time = NOW();
INSERT INTO t_balance_change_detail (id, user_id, amount, type, current_balance, change_time)
VALUES
(910000000007001, 910000000001001, 100.00, 'RECHARGE', 100.00, DATE_SUB(NOW(), INTERVAL 10 DAY)),
(910000000007002, 910000000001001, -32.00, 'CONSUME', 68.00, DATE_SUB(NOW(), INTERVAL 9 DAY)),
(910000000007003, 910000000001002, 600.00, 'RECHARGE', 600.00, DATE_SUB(NOW(), INTERVAL 8 DAY)),
(910000000007004, 910000000001002, -312.00, 'CONSUME', 288.00, DATE_SUB(NOW(), INTERVAL 7 DAY)),
(910000000007005, 910000000001003, 1200.00, 'RECHARGE', 1200.00, DATE_SUB(NOW(), INTERVAL 6 DAY)),
(910000000007006, 910000000001003, -612.00, 'CONSUME', 588.00, DATE_SUB(NOW(), INTERVAL 5 DAY)),
(910000000007007, 910000000001004, 2600.00, 'RECHARGE', 2600.00, DATE_SUB(NOW(), INTERVAL 4 DAY)),
(910000000007008, 910000000001004, -1612.00, 'CONSUME', 988.00, DATE_SUB(NOW(), INTERVAL 3 DAY))
ON DUPLICATE KEY UPDATE
amount = VALUES(amount),
type = VALUES(type),
current_balance = VALUES(current_balance),
change_time = VALUES(change_time);
INSERT INTO t_product (id, shop_id, title, description, image_file_ids, price, tags, like_count, collect_count, approximate_duration, bookable_artists, available_coupons, create_time, update_time, is_delete)
VALUES
(910000000004001, 910000000000001, '验收凝胶美甲', '可由普通美甲师和参与制作店长预约服务。', '', 168.00, '验收,凝胶', 0, 0, '90 分钟', '910000000003001,910000000002002', '', NOW(), NOW(), 0),
(910000000004002, 910000000000001, '验收店长专属款', '用于验证参与制作店长的预约流程。', '', 268.00, '验收,店长', 0, 0, '120 分钟', '910000000002002', '', NOW(), NOW(), 0),
(910000000004003, 910000000000002, '验收分店护理', '用于验证跨店不可预约的分店商品。', '', 128.00, '验收,分店', 0, 0, '60 分钟', '910000000003002,910000000002003', '', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
shop_id = VALUES(shop_id),
title = VALUES(title),
description = VALUES(description),
price = VALUES(price),
tags = VALUES(tags),
approximate_duration = VALUES(approximate_duration),
bookable_artists = VALUES(bookable_artists),
is_delete = 0,
update_time = NOW();
INSERT INTO t_cart (user_id, product_id, quantity, create_time, update_time, is_delete)
VALUES (910000000001004, 910000000004001, 1, NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
quantity = VALUES(quantity),
is_delete = 0,
update_time = NOW();
INSERT INTO t_order (id, order_no, user_id, total_amount, actual_amount, coupon_id, status, create_time, update_time, is_delete)
SELECT 910000000005001, 'ACCEPTANCE-ORDER-001', 910000000001004, 168.00, 168.00, 0, 1, NOW(), NOW(), 0
WHERE NOT EXISTS (SELECT 1 FROM t_order WHERE order_no = 'ACCEPTANCE-ORDER-001');
INSERT INTO t_order_item (order_id, product_id, quantity, price, artist_id, create_time, update_time, is_delete)
SELECT 910000000005001, 910000000004001, 1, 168.00, 910000000002002, NOW(), NOW(), 0
WHERE EXISTS (SELECT 1 FROM t_order WHERE id = 910000000005001)
AND NOT EXISTS (SELECT 1 FROM t_order_item WHERE order_id = 910000000005001 AND product_id = 910000000004001);
INSERT INTO t_system_message (id, title, content, publisher_id, publisher_name, publisher_type, target_type, target_ids, popup_enabled, status, publish_time, create_time, update_time, is_delete)
VALUES
(910000000006001, '平台验收通知', '这是一条面向当前和后续新增用户的平台通知。', 910000000001001, '验收管理员', 4, 'PLATFORM_ALL', '', 1, 1, NOW(), NOW(), NOW(), 0),
(910000000006002, '本店验收通知', '这是一条面向本店动态用户范围的店铺通知。', 910000000002002, '参与制作店长', 2, 'CURRENT_SHOP_ALL', '910000000000001', 1, 1, NOW(), NOW(), NOW(), 0),
(910000000006003, '指定用户验收通知', '这是一条仅指定用户可见的通知。', 910000000002002, '参与制作店长', 2, 'SELECTED_USERS', '910000000001004', 1, 1, NOW(), NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
title = VALUES(title),
content = VALUES(content),
publisher_id = VALUES(publisher_id),
publisher_name = VALUES(publisher_name),
publisher_type = VALUES(publisher_type),
target_type = VALUES(target_type),
target_ids = VALUES(target_ids),
popup_enabled = VALUES(popup_enabled),
status = VALUES(status),
is_delete = 0,
update_time = NOW();
INSERT INTO t_system_message_user_state (message_id, user_id, popup_shown, read_status, popup_time, read_time, create_time, update_time, is_delete)
VALUES
(910000000006001, 910000000001001, 1, 1, DATE_SUB(NOW(), INTERVAL 1 DAY), DATE_SUB(NOW(), INTERVAL 1 DAY), NOW(), NOW(), 0),
(910000000006002, 910000000001002, 1, 0, DATE_SUB(NOW(), INTERVAL 2 HOUR), NULL, NOW(), NOW(), 0),
(910000000006003, 910000000001004, 0, 0, NULL, NULL, NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
popup_shown = VALUES(popup_shown),
read_status = VALUES(read_status),
popup_time = VALUES(popup_time),
read_time = VALUES(read_time),
is_delete = 0,
update_time = NOW();
-- 小型全覆盖抽检数据可在空库初始化后按需扩展:管理员、店长、美甲师、普通用户、VIP 等级、商品、余额流水均由本初始化文件统一承载。
-- ========================================
-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT
-- 说明:
-- 1. 前面的建表与种子数据继续沿用旧链路,保证空库初始化过程不受影响
-- 2. 本段在所有初始化数据完成后执行,将运行时已切到应用层雪花 ID 的表统一收口
-- 3. 与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径
-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响
-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口
-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径
-- ========================================
INSERT INTO t_announcement (id, title, content, publisher_id, publisher_name, publisher_type, target_type, target_ids, status, sort_order, publish_time, create_time, update_time, is_delete)
VALUES
(910000000010001, '平台公告', '平台公告:欢迎体验首页滚动公告功能。', 910000000001001, '验收管理员', 4, 'PLATFORM_ALL', '', 1, 10, NOW(), NOW(), NOW(), 0),
(910000000010002, '本店公告', '本店公告:今日可预约店长参与制作服务。', 910000000002002, '参与制作店长', 2, 'CURRENT_SHOP_ALL', '910000000000001', 1, 20, NOW(), NOW(), NOW(), 0),
(910000000010003, '专属公告', '专属公告:这是指定用户可见的验收公告。', 910000000002002, '参与制作店长', 2, 'SELECTED_USERS', '910000000001004', 1, 30, NOW(), NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
title = VALUES(title),
content = VALUES(content),
publisher_id = VALUES(publisher_id),
publisher_name = VALUES(publisher_name),
publisher_type = VALUES(publisher_type),
target_type = VALUES(target_type),
target_ids = VALUES(target_ids),
status = VALUES(status),
sort_order = VALUES(sort_order),
is_delete = 0,
update_time = NOW();
INSERT INTO t_vip_recharge_plan (id, shop_id, title, recharge_amount, gift_amount, vip_level, description, sort_order, status, create_time, update_time, is_delete)
VALUES
(910000000011001, 910000000000001, '充100送10', 100.00, 10.00, '青铜VIP', '适合轻量体验用户,仅展示不发起支付。', 10, 1, NOW(), NOW(), 0),
(910000000011002, 910000000000001, '充500送80', 500.00, 80.00, '白银VIP', '适合常规护理用户,仅展示不发起支付。', 20, 1, NOW(), NOW(), 0),
(910000000011003, 910000000000001, '充1000送200', 1000.00, 200.00, '黄金VIP', '适合高频预约用户,仅展示不发起支付。', 30, 1, NOW(), NOW(), 0),
(910000000011004, 910000000000002, '分店充100送10', 100.00, 10.00, '青铜VIP', '分店验收充值档位。', 10, 1, NOW(), NOW(), 0),
(910000000011005, 910000000000002, '分店充500送80', 500.00, 80.00, '白银VIP', '分店验收充值档位。', 20, 1, NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
shop_id = VALUES(shop_id),
title = VALUES(title),
recharge_amount = VALUES(recharge_amount),
gift_amount = VALUES(gift_amount),
vip_level = VALUES(vip_level),
description = VALUES(description),
sort_order = VALUES(sort_order),
status = VALUES(status),
is_delete = 0,
update_time = NOW();
DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists;
DELIMITER $$
@@ -1896,7 +1682,7 @@ CREATE TABLE IF NOT EXISTS t_user_invite_code (
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
VALUES
(313931273555136490, 'messagehub:config:manage', '管理MessageHub配置', '消息配置', '管理YumiNail投递MessageHub的场景级对接参数', NOW(), NOW(), 0)
(313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
@@ -1904,22 +1690,6 @@ ON DUPLICATE KEY UPDATE
is_delete = 0,
update_time = NOW();
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
AND p.permission_code = 'messagehub:config:manage'
WHERE u.is_delete = 0
AND u.type = 4
AND NOT EXISTS (
SELECT 1
FROM t_user_permission up
WHERE up.user_id = u.id
AND up.permission_id = p.id
AND up.is_delete = 0
);
INSERT INTO t_messagehub_push_config (
id,
scene_code,
@@ -2040,6 +1810,22 @@ CREATE TABLE IF NOT EXISTS t_system_parameter_config (
UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置';
SET @system_parameter_enabled_missing := (
SELECT COUNT(1) = 0
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 't_system_parameter_config'
AND COLUMN_NAME = 'enabled'
);
SET @system_parameter_enabled_sql := IF(
@system_parameter_enabled_missing,
'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value',
'SELECT 1'
);
PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql;
EXECUTE stmt_system_parameter_enabled;
DEALLOCATE PREPARE stmt_system_parameter_enabled;
INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
VALUES
(313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 YumiNail。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0),
@@ -2054,7 +1840,7 @@ ON DUPLICATE KEY UPDATE
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
VALUES
(313931273555136601, 'legal_agreement:manage', '协议管理', '安全管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0)
(313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
permission_name = VALUES(permission_name),
permission_group = VALUES(permission_group),
@@ -2062,29 +1848,39 @@ ON DUPLICATE KEY UPDATE
is_delete = 0,
update_time = NOW();
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
AND p.permission_code = 'legal_agreement:manage'
WHERE u.is_delete = 0
AND u.type = 4
AND NOT EXISTS (
SELECT 1
FROM t_user_permission up
WHERE up.user_id = u.id
AND up.permission_id = p.id
AND up.is_delete = 0
);
INSERT INTO t_system_parameter_config (
id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete
)
VALUES
(313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯位置服务 Key', '', 0, '用于后台店铺选点和腾讯地图展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0)
(313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0),
(313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0),
(313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0),
(313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
config_name = VALUES(config_name),
remark = VALUES(remark),
config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value),
is_delete = 0,
update_time = NOW();
-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。
INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete)
SELECT
313931273556000000 + p.id,
u.id,
p.id,
NOW(),
NOW(),
u.id,
u.id,
0
FROM t_user u
INNER JOIN t_permission p
ON p.is_delete = 0
WHERE u.account = 'xiaowang'
AND u.is_delete = 0
AND u.type = 4
ON DUPLICATE KEY UPDATE
is_delete = 0,
update_by = VALUES(update_by),
update_time = NOW();
@@ -0,0 +1,18 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class TestBCrypt {
public static void main(String[] args) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = "123456";
String hashedPassword = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW";
System.out.println("Password: " + password);
System.out.println("Hashed Password: " + hashedPassword);
System.out.println("Matches: " + passwordEncoder.matches(password, hashedPassword));
String newHash = passwordEncoder.encode(password);
System.out.println("New Hash: " + newHash);
System.out.println("New Hash Matches: " + passwordEncoder.matches(password, newHash));
}
}
@@ -0,0 +1,20 @@
package com.xiaowang.yuminailcore;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class PasswordTest {
public static void main(String[] args) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String plainPassword = "123456";
String hashedPassword = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW";
System.out.println("Plain Password: " + plainPassword);
System.out.println("Hashed Password: " + hashedPassword);
System.out.println("Password Matches: " + passwordEncoder.matches(plainPassword, hashedPassword));
String newHash = passwordEncoder.encode(plainPassword);
System.out.println("New Hash: " + newHash);
System.out.println("New Hash Matches: " + passwordEncoder.matches(plainPassword, newHash));
}
}
@@ -0,0 +1,77 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.service.OrderService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.OrderVO;
import com.xiaowang.yuminailcore.vo.PageResultVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AdminOrderControllerTest {
@Mock
private OrderService orderService;
@Mock
private AdminScopeHelper adminScopeHelper;
private AdminOrderController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new AdminOrderController(orderService, adminScopeHelper);
}
@Test
void listOrdersShouldAcceptShopFilterAndResolveScopeOnServer() throws Exception {
Method method = Arrays.stream(AdminOrderController.class.getDeclaredMethods())
.filter(candidate -> "listOrders".equals(candidate.getName()))
.filter(candidate -> Arrays.stream(candidate.getParameters()).anyMatch(this::isShopIdRequestParam))
.findFirst()
.orElseThrow(() -> new AssertionError("listOrders must expose optional shopId request parameter"));
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO platformAdmin = new UserDO();
platformAdmin.setType(4);
when(adminScopeHelper.getCurrentUser(request)).thenReturn(platformAdmin);
when(adminScopeHelper.resolveShopScope(platformAdmin, 8L)).thenReturn(8L);
OrderVO visibleOrder = order(8L);
OrderVO hiddenOrder = order(9L);
when(orderService.getAllOrders()).thenReturn(List.of(visibleOrder, hiddenOrder));
@SuppressWarnings("unchecked")
Result<PageResultVO<OrderVO>> result = (Result<PageResultVO<OrderVO>>) method.invoke(controller, request, 1, 10, null, 8L, null);
verify(adminScopeHelper).resolveShopScope(platformAdmin, 8L);
assertThat(result.getData().getList()).containsExactly(visibleOrder);
}
private boolean isShopIdRequestParam(Parameter parameter) {
RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
return requestParam != null && Long.class.equals(parameter.getType());
}
private OrderVO order(Long shopId) {
OrderVO order = new OrderVO();
order.setId(shopId);
order.setShopId(shopId);
return order;
}
}
@@ -0,0 +1,93 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.service.ProductService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.security.UserSessionService;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import com.xiaowang.yuminailcore.vo.ProductVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.List;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ProductControllerTest {
@Mock
private ProductService productService;
@Mock
private AdminScopeHelper adminScopeHelper;
@Mock
private JwtUtil jwtUtil;
@Mock
private UserSessionService userSessionService;
@Mock
private UserShopBindingSupport userShopBindingSupport;
private ProductController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
controller = new ProductController(productService, adminScopeHelper, jwtUtil, userSessionService, userShopBindingSupport);
}
@Test
void listAllProductsShouldUseCurrentShopFromValidToken() {
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
when(productService.listProductsByShopId(3L)).thenReturn(List.of(new ProductVO()));
controller.listAllProducts(request);
verify(productService).listProductsByShopId(3L);
verify(productService, never()).listAllProducts();
}
@Test
void searchProductsShouldUseCurrentShopFromValidToken() {
MockHttpServletRequest request = authenticatedShopRequest(7L, 3L);
when(productService.searchProducts("猫眼", 3L)).thenReturn(List.of(new ProductVO()));
controller.searchProducts(request, "猫眼");
verify(productService).searchProducts("猫眼", 3L);
verify(productService, never()).searchProducts("猫眼");
}
@Test
void listAllProductsShouldRemainPublicWithoutToken() {
MockHttpServletRequest request = new MockHttpServletRequest();
when(productService.listAllProducts()).thenReturn(List.of(new ProductVO()));
controller.listAllProducts(request);
verify(productService).listAllProducts();
verify(productService, never()).listProductsByShopId(3L);
}
private MockHttpServletRequest authenticatedShopRequest(Long userId, Long shopId) {
String token = "access-token";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + token);
when(jwtUtil.validateToken(token)).thenReturn(true);
when(jwtUtil.isAccessToken(token)).thenReturn(true);
when(jwtUtil.getShopIdFromToken(token)).thenReturn(shopId);
when(jwtUtil.getUserIdFromToken(token)).thenReturn(userId);
when(jwtUtil.getSessionIdFromToken(token)).thenReturn("session-id");
when(jwtUtil.getJtiFromToken(token)).thenReturn("jti");
when(userSessionService.isAccessSessionActive(userId, "session-id", "jti")).thenReturn(true);
when(userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)).thenReturn(true);
return request;
}
}
@@ -0,0 +1,183 @@
package com.xiaowang.yuminailcore.service.impl;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.yuminailcore.common.BusinessException;
import com.xiaowang.yuminailcore.dto.WechatMiniAutoLoginRequestDTO;
import com.xiaowang.yuminailcore.dto.WechatMiniPhoneLoginRequestDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.entity.WechatMiniBindingDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.WechatMiniBindingMapper;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.service.WechatMiniClientService;
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class WechatMiniAuthServiceImplTest {
@Mock
private WechatMiniClientService wechatMiniClientService;
@Mock
private WechatMiniBindingMapper wechatMiniBindingMapper;
@Mock
private UserMapper userMapper;
@Mock
private UserService userService;
@Mock
private UserShopBindingSupport userShopBindingSupport;
@Mock
private StringRedisTemplate redisTemplate;
@Mock
private ValueOperations<String, String> valueOperations;
private WechatMiniAuthServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
initTableInfo(WechatMiniBindingDO.class);
initTableInfo(UserDO.class);
service = new WechatMiniAuthServiceImpl(
wechatMiniClientService,
wechatMiniBindingMapper,
userMapper,
userService,
userShopBindingSupport,
redisTemplate,
new ObjectMapper(),
new TimeOrderedSnowflakeIdGenerator(1704067200000L, 1L, 1L, "test-app")
);
}
private void initTableInfo(Class<?> entityClass) {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
assistant.setCurrentNamespace(entityClass.getName());
TableInfoHelper.initTableInfo(assistant, entityClass);
}
@Test
void autoLoginShouldDeactivateInvalidBindingAndFallbackToManualLogin() {
WechatMiniAutoLoginRequestDTO requestDTO = new WechatMiniAutoLoginRequestDTO();
requestDTO.setWxCode("wx-code");
when(wechatMiniClientService.code2Session("wx-code"))
.thenReturn(new WechatMiniClientService.SessionInfo("openid-1", "union-1", "session-1"));
WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
bindingDO.setId(100L);
bindingDO.setUserId(200L);
bindingDO.setStatus(1);
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(bindingDO);
UserDO deletedUser = new UserDO();
deletedUser.setId(200L);
deletedUser.setIsDelete(1);
when(userMapper.selectById(200L)).thenReturn(deletedUser);
WechatMiniLoginResultVO result = service.autoLogin(requestDTO);
assertEquals(WechatMiniLoginResultVO.STATUS_NEED_MANUAL_LOGIN, result.getStatus());
assertFalse(Boolean.TRUE.equals(result.getNewUser()));
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
}
@Test
void phoneLoginShouldReturnSelectShopWhenNewWechatPhoneNeedsShopSelection() {
WechatMiniPhoneLoginRequestDTO requestDTO = new WechatMiniPhoneLoginRequestDTO();
requestDTO.setWxCode("wx-code");
requestDTO.setPhoneCode("phone-code");
when(wechatMiniClientService.code2Session("wx-code"))
.thenReturn(new WechatMiniClientService.SessionInfo("openid-2", "union-2", "session-2"));
when(wechatMiniClientService.getPhoneNumber("phone-code")).thenReturn("13800138000");
when(wechatMiniBindingMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
when(userMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
when(userShopBindingSupport.listAllActiveShopOptions()).thenReturn(List.of(
new ShopSimpleVO(1L, "A 店"),
new ShopSimpleVO(2L, "B 店")
));
WechatMiniLoginResultVO result = service.phoneLogin(requestDTO);
assertEquals(WechatMiniLoginResultVO.STATUS_SELECT_SHOP, result.getStatus());
assertTrue(Boolean.TRUE.equals(result.getNewUser()));
assertEquals(2, result.getShops().size());
}
@Test
void ensureBindingShouldDeactivateHistoricalDuplicatesAndKeepSingleActiveRecord() {
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
WechatMiniBindingDO currentBinding = new WechatMiniBindingDO();
currentBinding.setId(1L);
currentBinding.setUserId(8L);
currentBinding.setOpenId("openid-3");
currentBinding.setAppId("mini-app");
currentBinding.setStatus(1);
WechatMiniBindingDO duplicateBinding = new WechatMiniBindingDO();
duplicateBinding.setId(2L);
duplicateBinding.setUserId(8L);
duplicateBinding.setOpenId("openid-legacy");
duplicateBinding.setAppId("mini-app");
duplicateBinding.setStatus(0);
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
.thenReturn(List.of(currentBinding), List.of(currentBinding, duplicateBinding));
service.ensureBinding(8L, "openid-3", "union-3");
verify(wechatMiniBindingMapper).updateById(currentBinding);
verify(wechatMiniBindingMapper).update(eq(null), any(LambdaUpdateWrapper.class));
verify(wechatMiniBindingMapper, never()).insert(any(WechatMiniBindingDO.class));
}
@Test
void ensureBindingShouldRejectOtherUsersActiveBinding() {
when(wechatMiniClientService.getConfiguredAppId()).thenReturn("mini-app");
WechatMiniBindingDO activeBinding = new WechatMiniBindingDO();
activeBinding.setId(11L);
activeBinding.setUserId(9L);
activeBinding.setOpenId("openid-4");
activeBinding.setAppId("mini-app");
activeBinding.setStatus(1);
when(wechatMiniBindingMapper.selectList(any(LambdaQueryWrapper.class)))
.thenReturn(List.of(activeBinding), List.of());
BusinessException exception = assertThrows(BusinessException.class, () -> service.ensureBinding(8L, "openid-4", "union-4"));
assertEquals("当前微信已绑定其他账号,无法完成登录", exception.getMessage());
}
}
@@ -0,0 +1,61 @@
package com.xiaowang.yuminailcore.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.yuminailcore.common.BusinessException;
import com.xiaowang.yuminailcore.config.WechatMiniProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
class WechatMiniClientServiceImplTest {
@Mock
private RestTemplate restTemplate;
@Mock
private StringRedisTemplate redisTemplate;
@Mock
private ValueOperations<String, String> valueOperations;
private WechatMiniClientServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
WechatMiniProperties properties = new WechatMiniProperties();
properties.setAppId("app-id");
properties.setAppSecret("app-secret");
service = new WechatMiniClientServiceImpl(restTemplate, redisTemplate, new ObjectMapper(), properties);
}
@Test
void getPhoneNumberShouldFailWhenWechatResponseMissesPhoneInfo() {
when(valueOperations.get(anyString())).thenReturn(null);
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"access_token\":\"access-token\",\"expires_in\":7200}");
when(restTemplate.postForObject(anyString(), any(HttpEntity.class), any())).thenReturn("{\"errcode\":0}");
BusinessException exception = assertThrows(BusinessException.class, () -> service.getPhoneNumber("phone-code"));
assertEquals("获取微信手机号失败:未返回手机号信息", exception.getMessage());
}
@Test
void code2SessionShouldFailWhenWechatResponseMissesOpenId() {
when(restTemplate.getForObject(anyString(), any())).thenReturn("{\"errcode\":0,\"session_key\":\"abc\"}");
BusinessException exception = assertThrows(BusinessException.class, () -> service.code2Session("wx-code"));
assertEquals("获取微信登录身份失败:缺少 openid", exception.getMessage());
}
}
@@ -0,0 +1,64 @@
package com.xiaowang.yuminailcore.support;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
class PermissionCatalogTest {
@Test
void announcementPermissionsUseChineseDisplayText() {
assertChinesePermission("announcement:view", "查看公告", "公告管理", "查看公告列表与详情");
assertChinesePermission("announcement:create", "发布公告", "公告管理", "发布公告");
assertChinesePermission("announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
}
@Test
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
.contains("messagehub:config:manage", "legal_agreement:manage");
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("permission:assign")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:create")).isFalse();
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:process")).isFalse();
}
@Test
void everyManagedDefaultPermissionHasDefinition() {
Set<String> definedCodes = PermissionCatalog.getManagedPermissionCodes();
assertThat(definedCodes)
.containsAll(PermissionCatalog.getDefaultPermissionCodes(4))
.containsAll(PermissionCatalog.getDefaultPermissionCodes(2))
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
}
@Test
void everyManagedDefaultPermissionUsesChineseDisplayText() {
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
assertThat(definition.permissionName()).matches(PermissionCatalogTest::containsChinese);
assertThat(definition.permissionGroup()).matches(PermissionCatalogTest::containsChinese);
assertThat(definition.description()).matches(PermissionCatalogTest::containsChinese);
});
}
private void assertChinesePermission(String code, String name, String group, String description) {
PermissionCatalog.PermissionDefinition definition = PermissionCatalog.getRequiredDefinition(code);
assertThat(definition.permissionName()).isEqualTo(name);
assertThat(definition.permissionGroup()).isEqualTo(group);
assertThat(definition.description()).isEqualTo(description);
}
private static boolean containsChinese(String value) {
return value != null && value.chars().anyMatch(codePoint -> codePoint >= 0x4E00 && codePoint <= 0x9FFF);
}
}
@@ -0,0 +1,30 @@
package com.xiaowang.yuminailcore.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class ShopThemeSupportTest {
@Test
void normalizeColorAcceptsOnlySixDigitHexAndUppercasesIt() {
assertThat(ShopThemeSupport.normalizeColor("#c6597d", "themePrimaryColor")).isEqualTo("#C6597D");
assertThat(ShopThemeSupport.normalizeColor(" #ffffff ", "themeCardBgColor")).isEqualTo("#FFFFFF");
}
@Test
void normalizeColorTreatsBlankAsUnset() {
assertThat(ShopThemeSupport.normalizeColor(null, "themePrimaryColor")).isNull();
assertThat(ShopThemeSupport.normalizeColor(" ", "themePrimaryColor")).isNull();
}
@Test
void normalizeColorRejectsUnsafeValues() {
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("#fff", "themePrimaryColor"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("themePrimaryColor");
assertThatThrownBy(() -> ShopThemeSupport.normalizeColor("url(javascript:alert(1))", "themePrimaryColor"))
.isInstanceOf(IllegalArgumentException.class);
}
}