功能:更新消息中心和 YumiNail 模块
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.yuminailcore.common;
|
||||
|
||||
/**
|
||||
* 业务异常。
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final Integer code;
|
||||
|
||||
public BusinessException(String message) {
|
||||
this(500, message);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(String message, Throwable cause) {
|
||||
this(500, message, cause);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
+12
-15
@@ -2,20 +2,17 @@ package com.xiaowang.yuminailcore.common;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-12
|
||||
* 全局异常处理器。
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
@@ -68,25 +65,25 @@ public class GlobalExceptionHandler {
|
||||
log.warn("上传文件超过限制: {}", e.getMessage());
|
||||
return Result.error(buildUploadLimitMessage());
|
||||
}
|
||||
log.error("非法状态异常: ", e);
|
||||
log.error("非法状态异常", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理运行时异常
|
||||
*/
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public Result<Void> handleBusinessException(BusinessException e) {
|
||||
log.warn("业务异常: {}", e.getMessage());
|
||||
return Result.error(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public Result<Void> handleRuntimeException(RuntimeException e) {
|
||||
log.error("运行时异常: ", e);
|
||||
log.error("运行时异常", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理系统异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result<Void> handleException(Exception e) {
|
||||
log.error("系统异常: ", e);
|
||||
log.error("系统异常", e);
|
||||
return Result.error("系统繁忙,请稍后再试");
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ public class AppCacheProperties {
|
||||
|
||||
private CacheSpec tag = new CacheSpec(300, 1200);
|
||||
|
||||
private CacheSpec objectStorageFile = new CacheSpec(300, 1800);
|
||||
|
||||
@Data
|
||||
public static class CacheSpec {
|
||||
private long localTtlSeconds;
|
||||
|
||||
@@ -1,17 +1,46 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* HTTP 客户端配置。
|
||||
*/
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
public class HttpClientConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
return new RestTemplate();
|
||||
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) {
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
|
||||
connectionManager.setMaxTotal(properties.getMaxTotalConnections());
|
||||
connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute());
|
||||
return connectionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate(HttpClientProperties properties,
|
||||
PoolingHttpClientConnectionManager connectionManager) {
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(properties.getConnectTimeoutMs())
|
||||
.setSocketTimeout(properties.getReadTimeoutMs())
|
||||
.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs())
|
||||
.build();
|
||||
CloseableHttpClient httpClient = HttpClients.custom()
|
||||
.setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.disableCookieManagement()
|
||||
.evictIdleConnections(30, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
|
||||
requestFactory.setConnectTimeout(properties.getConnectTimeoutMs());
|
||||
requestFactory.setReadTimeout(properties.getReadTimeoutMs());
|
||||
requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs());
|
||||
return new RestTemplate(requestFactory);
|
||||
}
|
||||
}
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.http-client")
|
||||
public class HttpClientProperties {
|
||||
|
||||
private int connectTimeoutMs = 3000;
|
||||
|
||||
private int readTimeoutMs = 5000;
|
||||
|
||||
private int connectionRequestTimeoutMs = 1000;
|
||||
|
||||
private int maxTotalConnections = 200;
|
||||
|
||||
private int maxConnectionsPerRoute = 50;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "yuminail.slow-request")
|
||||
public class SlowRequestLogProperties {
|
||||
|
||||
private boolean enabled = true;
|
||||
|
||||
private long thresholdMs = 300;
|
||||
|
||||
private boolean logResponseHeaderRequestId = true;
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.xiaowang.yuminailcore.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class SlowRequestLoggingInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime";
|
||||
private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow");
|
||||
|
||||
private final SlowRequestLogProperties properties;
|
||||
|
||||
public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
String requestId = resolveRequestId(request);
|
||||
request.setAttribute(REQUEST_ID_HEADER, requestId);
|
||||
if (properties.isLogResponseHeaderRequestId()) {
|
||||
response.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
}
|
||||
if (properties.isEnabled()) {
|
||||
request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
|
||||
if (!properties.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE);
|
||||
if (!(startTimeValue instanceof Long)) {
|
||||
return;
|
||||
}
|
||||
|
||||
long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L);
|
||||
if (durationMs < properties.getThresholdMs()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String requestId = (String) request.getAttribute(REQUEST_ID_HEADER);
|
||||
String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
|
||||
String controllerMethod = resolveControllerMethod(handler);
|
||||
String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName();
|
||||
|
||||
SLOW_REQUEST_LOGGER.warn(
|
||||
"requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}",
|
||||
sanitize(requestId),
|
||||
request.getMethod(),
|
||||
request.getRequestURI(),
|
||||
sanitize(request.getQueryString()),
|
||||
sanitize(bestMatchingPattern),
|
||||
sanitize(controllerMethod),
|
||||
response.getStatus(),
|
||||
durationMs,
|
||||
castLong(request.getAttribute("userId")),
|
||||
castInteger(request.getAttribute("userType")),
|
||||
castLong(request.getAttribute("currentShopId")),
|
||||
resolveClientIp(request),
|
||||
request.getContentLengthLong(),
|
||||
sanitize(exceptionClass)
|
||||
);
|
||||
}
|
||||
|
||||
private String resolveRequestId(HttpServletRequest request) {
|
||||
String requestId = request.getHeader(REQUEST_ID_HEADER);
|
||||
return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
private String resolveControllerMethod(Object handler) {
|
||||
if (handler instanceof HandlerMethod handlerMethod) {
|
||||
return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String resolveClientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.hasText(forwarded)) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.hasText(realIp)) {
|
||||
return realIp.trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
private String sanitize(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
return value.replace('\n', '_').replace('\r', '_');
|
||||
}
|
||||
|
||||
private String toStringValue(Object value) {
|
||||
return value == null ? "" : value.toString();
|
||||
}
|
||||
|
||||
private Long castLong(Object value) {
|
||||
return value instanceof Long ? (Long) value : null;
|
||||
}
|
||||
|
||||
private Integer castInteger(Object value) {
|
||||
return value instanceof Integer ? (Integer) value : null;
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,17 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final AuthInterceptor authInterceptor;
|
||||
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(slowRequestLoggingInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(-100);
|
||||
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(0)
|
||||
.excludePathPatterns(
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
|
||||
+10
@@ -5,7 +5,9 @@ import com.xiaowang.yuminailcore.entity.ObjectStorageFileDO;
|
||||
import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 对象存储文件信息表 Service
|
||||
@@ -49,6 +51,14 @@ public interface ObjectStorageFileService extends IService<ObjectStorageFileDO>
|
||||
*/
|
||||
ObjectStorageFileVO getObjectStorageFileById(Long id);
|
||||
|
||||
/**
|
||||
* 鎵归噺鏌ヨ鏂囦欢锛岃繑鍥瀒D -> 鏂囦欢淇℃伅鏄犲皠
|
||||
*
|
||||
* @param ids 鏂囦欢ID闆嗗悎
|
||||
* @return 鏂囦欢鏄犲皠
|
||||
*/
|
||||
Map<Long, ObjectStorageFileVO> getObjectStorageFileMapByIds(Collection<Long> ids);
|
||||
|
||||
/**
|
||||
* 查询所有文件
|
||||
*
|
||||
|
||||
+82
-6
@@ -1,16 +1,27 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
|
||||
import com.xiaowang.yuminailcore.entity.ObjectStorageFileDO;
|
||||
import com.xiaowang.yuminailcore.mapper.ObjectStorageFileMapper;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -24,7 +35,11 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileMapper, ObjectStorageFileDO> implements ObjectStorageFileService {
|
||||
|
||||
private static final String FILE_DETAIL_CACHE_PREFIX = "cache:file:detail:";
|
||||
|
||||
private final ObjectStorageFileMapper objectStorageFileMapper;
|
||||
private final MultiLevelCacheService multiLevelCacheService;
|
||||
private final AppCacheProperties appCacheProperties;
|
||||
|
||||
@Override
|
||||
public Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO) {
|
||||
@@ -35,6 +50,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
|
||||
objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime());
|
||||
objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime());
|
||||
objectStorageFileMapper.insert(objectStorageFileDO);
|
||||
evictFileCache(objectStorageFileDO.getId());
|
||||
return objectStorageFileDO.getId();
|
||||
}
|
||||
|
||||
@@ -49,21 +65,71 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
|
||||
objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus());
|
||||
objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime());
|
||||
objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime());
|
||||
return objectStorageFileMapper.updateById(objectStorageFileDO) > 0;
|
||||
boolean updated = objectStorageFileMapper.updateById(objectStorageFileDO) > 0;
|
||||
if (updated) {
|
||||
evictFileCache(id);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteObjectStorageFile(Long id) {
|
||||
return objectStorageFileMapper.deleteById(id) > 0;
|
||||
boolean deleted = objectStorageFileMapper.deleteById(id) > 0;
|
||||
if (deleted) {
|
||||
evictFileCache(id);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectStorageFileVO getObjectStorageFileById(Long id) {
|
||||
ObjectStorageFileDO objectStorageFileDO = objectStorageFileMapper.selectById(id);
|
||||
if (objectStorageFileDO == null) {
|
||||
return null;
|
||||
return getObjectStorageFileMapByIds(Collections.singleton(id)).get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, ObjectStorageFileVO> getObjectStorageFileMapByIds(Collection<Long> ids) {
|
||||
if (CollectionUtils.isEmpty(ids)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return convertToVO(objectStorageFileDO);
|
||||
|
||||
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getObjectStorageFile();
|
||||
Duration localTtl = Duration.ofSeconds(cacheSpec.getLocalTtlSeconds());
|
||||
Duration redisTtl = Duration.ofSeconds(cacheSpec.getRedisTtlSeconds());
|
||||
Map<Long, ObjectStorageFileVO> result = new LinkedHashMap<>();
|
||||
Set<Long> missingIds = new LinkedHashSet<>();
|
||||
|
||||
for (Long id : ids) {
|
||||
if (id == null || id <= 0) {
|
||||
continue;
|
||||
}
|
||||
MultiLevelCacheService.CacheLookup<ObjectStorageFileVO> lookup = multiLevelCacheService.get(
|
||||
buildDetailCacheKey(id),
|
||||
localTtl,
|
||||
new TypeReference<ObjectStorageFileVO>() {
|
||||
}
|
||||
);
|
||||
if (lookup.isHit()) {
|
||||
if (lookup.getValue() != null) {
|
||||
result.put(id, lookup.getValue());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
missingIds.add(id);
|
||||
}
|
||||
|
||||
if (!missingIds.isEmpty()) {
|
||||
Map<Long, ObjectStorageFileVO> loadedMap = objectStorageFileMapper.selectBatchIds(missingIds).stream()
|
||||
.collect(Collectors.toMap(ObjectStorageFileDO::getId, this::convertToVO, (left, right) -> left, LinkedHashMap::new));
|
||||
for (Long missingId : missingIds) {
|
||||
ObjectStorageFileVO fileVO = loadedMap.get(missingId);
|
||||
multiLevelCacheService.put(buildDetailCacheKey(missingId), fileVO, localTtl, redisTtl);
|
||||
if (fileVO != null) {
|
||||
result.put(missingId, fileVO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -102,4 +168,14 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
|
||||
objectStorageFileVO.setRecycleTime(objectStorageFileDO.getRecycleTime());
|
||||
return objectStorageFileVO;
|
||||
}
|
||||
|
||||
private void evictFileCache(Long id) {
|
||||
if (id != null && id > 0) {
|
||||
multiLevelCacheService.evict(buildDetailCacheKey(id));
|
||||
}
|
||||
}
|
||||
|
||||
private String buildDetailCacheKey(Long id) {
|
||||
return FILE_DETAIL_CACHE_PREFIX + id;
|
||||
}
|
||||
}
|
||||
|
||||
+210
-161
@@ -17,33 +17,28 @@ import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||
import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||
import com.xiaowang.yuminailcore.service.ProductService;
|
||||
import com.xiaowang.yuminailcore.service.TagService;
|
||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||
import com.xiaowang.yuminailcore.vo.ProductVO;
|
||||
import com.xiaowang.yuminailcore.vo.TagInfo;
|
||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品信息表 Service 实现
|
||||
* 对应数据库表 t_product
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-02-13
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> implements ProductService {
|
||||
@@ -54,7 +49,6 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
private static final int MAX_PUBLIC_PAGE_SIZE = 30;
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
private final TagService tagService;
|
||||
private final ObjectStorageFileService objectStorageFileService;
|
||||
private final CouponMapper couponMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
@@ -175,13 +169,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
|
||||
new TypeReference<List<ProductVO>>() {
|
||||
},
|
||||
() -> productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
).stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList())
|
||||
() -> toProductVOList(productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -191,10 +183,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.eq(ProductDO::getShopId, shopId)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
);
|
||||
return productDOs.stream()
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
return toProductVOList(productDOs);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -228,17 +219,30 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 DO 转换为 VO
|
||||
*
|
||||
* @param productDO 商品DO
|
||||
* @return 商品VO
|
||||
*/
|
||||
private ProductVO convertToVO(ProductDO productDO) {
|
||||
if (productDO == null) {
|
||||
return null;
|
||||
}
|
||||
return toProductVOList(Collections.singletonList(productDO)).stream()
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private List<ProductVO> toProductVOList(List<ProductDO> productDOs) {
|
||||
if (productDOs == null || productDOs.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
ProductEnrichmentContext context = buildEnrichmentContext(productDOs);
|
||||
return productDOs.stream()
|
||||
.map(productDO -> convertToVO(productDO, context))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private ProductVO convertToVO(ProductDO productDO, ProductEnrichmentContext context) {
|
||||
ProductVO productVO = new ProductVO();
|
||||
productVO.setId(productDO.getId());
|
||||
productVO.setShopId(productDO.getShopId());
|
||||
productVO.setShopName(resolveShopName(productDO.getShopId()));
|
||||
productVO.setShopName(context.shopNames().get(productDO.getShopId()));
|
||||
productVO.setTitle(productDO.getTitle());
|
||||
productVO.setDescription(productDO.getDescription());
|
||||
productVO.setImageFileIds(productDO.getImageFileIds());
|
||||
@@ -254,60 +258,62 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
productVO.setAvailableCoupons(productDO.getAvailableCoupons());
|
||||
productVO.setCreateTime(productDO.getCreateTime());
|
||||
productVO.setUpdateTime(productDO.getUpdateTime());
|
||||
|
||||
// 转换标签ID为标签名称列表
|
||||
java.util.List<String> tagNames = new java.util.ArrayList<>();
|
||||
java.util.List<TagInfo> tagInfos = new java.util.ArrayList<>();
|
||||
if (productDO.getTags() != null && !productDO.getTags().isEmpty()) {
|
||||
String[] tagIds = productDO.getTags().split(";");
|
||||
for (String tagIdStr : tagIds) {
|
||||
try {
|
||||
Long tagId = Long.parseLong(tagIdStr.trim());
|
||||
TagVO tagVO = tagService.getTagById(tagId);
|
||||
if (tagVO != null) {
|
||||
tagNames.add(tagVO.getTagName());
|
||||
// 添加标签详情(包含样式信息)
|
||||
TagInfo tagInfo = new TagInfo();
|
||||
tagInfo.setId(tagId);
|
||||
tagInfo.setTagName(tagVO.getTagName());
|
||||
tagInfo.setTextColor(tagVO.getTextColor());
|
||||
tagInfo.setBgColor(tagVO.getBgColor());
|
||||
tagInfo.setBorderColor(tagVO.getBorderColor());
|
||||
tagInfos.add(tagInfo);
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// 忽略无效的标签ID
|
||||
}
|
||||
|
||||
List<String> tagNames = new ArrayList<>();
|
||||
List<TagInfo> tagInfos = new ArrayList<>();
|
||||
for (Long tagId : parseDelimitedLongIds(productDO.getTags(), ";")) {
|
||||
TagDO tagDO = context.tags().get(tagId);
|
||||
if (tagDO == null) {
|
||||
continue;
|
||||
}
|
||||
tagNames.add(tagDO.getTagName());
|
||||
TagInfo tagInfo = new TagInfo();
|
||||
tagInfo.setId(tagId);
|
||||
tagInfo.setTagName(tagDO.getTagName());
|
||||
tagInfo.setTextColor(tagDO.getTextColor());
|
||||
tagInfo.setBgColor(tagDO.getBgColor());
|
||||
tagInfo.setBorderColor(tagDO.getBorderColor());
|
||||
tagInfos.add(tagInfo);
|
||||
}
|
||||
productVO.setTagList(tagNames);
|
||||
productVO.setTagInfos(tagInfos);
|
||||
|
||||
// 转换图片ID为图片URL列表
|
||||
|
||||
List<String> imageUrls = new ArrayList<>();
|
||||
if (productDO.getImageFileIds() != null && !productDO.getImageFileIds().isEmpty()) {
|
||||
String[] fileIds = productDO.getImageFileIds().split(",");
|
||||
for (String fileIdStr : fileIds) {
|
||||
try {
|
||||
Long fileId = Long.parseLong(fileIdStr.trim());
|
||||
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
|
||||
if (fileVO != null && fileVO.getFileUrl() != null) {
|
||||
imageUrls.add(fileVO.getFileUrl());
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// 忽略无效的文件ID
|
||||
}
|
||||
for (Long fileId : parseDelimitedLongIds(productDO.getImageFileIds(), ",")) {
|
||||
ObjectStorageFileVO fileVO = context.files().get(fileId);
|
||||
if (fileVO != null && StringUtils.hasText(fileVO.getFileUrl())) {
|
||||
imageUrls.add(fileVO.getFileUrl());
|
||||
}
|
||||
}
|
||||
productVO.setImageUrls(imageUrls);
|
||||
|
||||
return productVO;
|
||||
}
|
||||
|
||||
|
||||
private ProductEnrichmentContext buildEnrichmentContext(List<ProductDO> productDOs) {
|
||||
Set<Long> shopIds = new LinkedHashSet<>();
|
||||
Set<Long> tagIds = new LinkedHashSet<>();
|
||||
Set<Long> fileIds = new LinkedHashSet<>();
|
||||
for (ProductDO productDO : productDOs) {
|
||||
if (productDO == null) {
|
||||
continue;
|
||||
}
|
||||
if (productDO.getShopId() != null && productDO.getShopId() > 0) {
|
||||
shopIds.add(productDO.getShopId());
|
||||
}
|
||||
tagIds.addAll(parseDelimitedLongIds(productDO.getTags(), ";"));
|
||||
fileIds.addAll(parseDelimitedLongIds(productDO.getImageFileIds(), ","));
|
||||
}
|
||||
return new ProductEnrichmentContext(
|
||||
loadShopNameMap(shopIds),
|
||||
loadTagMap(tagIds),
|
||||
objectStorageFileService.getObjectStorageFileMapByIds(fileIds)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResultVO<ProductVO> pageProducts(Integer page, Integer size, String keyword, Long shopId) {
|
||||
Page<ProductDO> pageParam = new Page<>(page, size);
|
||||
|
||||
|
||||
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class);
|
||||
wrapper.eq(ProductDO::getIsDelete, 0);
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
@@ -318,15 +324,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
wrapper.eq(ProductDO::getShopId, shopId);
|
||||
}
|
||||
wrapper.orderByDesc(ProductDO::getCreateTime);
|
||||
|
||||
|
||||
Page<ProductDO> productPage = productMapper.selectPage(pageParam, wrapper);
|
||||
|
||||
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(productPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList()));
|
||||
result.setList(toProductVOList(productPage.getRecords()));
|
||||
result.setTotal(productPage.getTotal());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -359,7 +365,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
}
|
||||
|
||||
if (shopId == null || shopId <= 0) {
|
||||
throw new RuntimeException("配置可预约美甲师前必须先选择店铺");
|
||||
throw new RuntimeException("閰嶇疆鍙绾︾編鐢插笀鍓嶅繀椤诲厛閫夋嫨搴楅摵");
|
||||
}
|
||||
|
||||
for (String artistIdStr : bookableArtists.split(",")) {
|
||||
@@ -371,11 +377,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
try {
|
||||
artistId = Long.parseLong(artistIdStr.trim());
|
||||
} catch (NumberFormatException ex) {
|
||||
throw new RuntimeException("可预约美甲师配置格式不正确");
|
||||
throw new RuntimeException("鍙绾︾編鐢插笀閰嶇疆鏍煎紡涓嶆纭?");
|
||||
}
|
||||
|
||||
if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) {
|
||||
throw new RuntimeException("存在无效、已停用或不属于当前店铺的美甲师配置");
|
||||
throw new RuntimeException("瀛樺湪鏃犳晥銆佸凡鍋滅敤鎴栦笉灞炰簬褰撳墠搴楅摵鐨勭編鐢插笀閰嶇疆");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -386,7 +392,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
}
|
||||
|
||||
if (shopId == null || shopId <= 0) {
|
||||
throw new RuntimeException("配置可用优惠券前必须先选择店铺");
|
||||
throw new RuntimeException("閰嶇疆鍙敤浼樻儬鍒稿墠蹇呴』鍏堥€夋嫨搴楅摵");
|
||||
}
|
||||
|
||||
for (String couponIdStr : availableCoupons.split(",")) {
|
||||
@@ -398,30 +404,22 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
try {
|
||||
couponId = Long.parseLong(couponIdStr.trim());
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new RuntimeException("可用优惠券配置格式不正确");
|
||||
throw new RuntimeException("鍙敤浼樻儬鍒搁厤缃牸寮忎笉姝g‘");
|
||||
}
|
||||
|
||||
CouponDO couponDO = couponMapper.selectById(couponId);
|
||||
if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) {
|
||||
throw new RuntimeException("存在无效的优惠券配置");
|
||||
throw new RuntimeException("瀛樺湪鏃犳晥鐨勪紭鎯犲埜閰嶇疆");
|
||||
}
|
||||
if (!Integer.valueOf(1).equals(couponDO.getStatus())) {
|
||||
throw new RuntimeException("存在已失效的优惠券配置");
|
||||
throw new RuntimeException("瀛樺湪宸插け鏁堢殑浼樻儬鍒搁厤缃?");
|
||||
}
|
||||
if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) {
|
||||
throw new RuntimeException("不可跨店铺配置可用优惠券");
|
||||
throw new RuntimeException("涓嶅彲璺ㄥ簵閾洪厤缃彲鐢ㄤ紭鎯犲埜");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveShopName(Long shopId) {
|
||||
if (shopId == null || shopId <= 0) {
|
||||
return null;
|
||||
}
|
||||
ShopDO shopDO = shopMapper.selectById(shopId);
|
||||
return shopDO == null ? null : shopDO.getShopName();
|
||||
}
|
||||
|
||||
private int countBookableArtists(String bookableArtists) {
|
||||
if (!StringUtils.hasText(bookableArtists)) {
|
||||
return 0;
|
||||
@@ -439,37 +437,6 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
return count;
|
||||
}
|
||||
|
||||
private boolean matchesFrontSearch(ProductDO productDO, String normalizedKeyword, Set<String> matchedTagIds) {
|
||||
if (containsKeyword(productDO.getTitle(), normalizedKeyword)
|
||||
|| containsKeyword(productDO.getDescription(), normalizedKeyword)) {
|
||||
return true;
|
||||
}
|
||||
return containsAnyTagId(productDO.getTags(), matchedTagIds);
|
||||
}
|
||||
|
||||
private String normalizeSearchKeyword(String keyword) {
|
||||
return keyword.trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private boolean containsKeyword(String source, String normalizedKeyword) {
|
||||
if (!StringUtils.hasText(source) || !StringUtils.hasText(normalizedKeyword)) {
|
||||
return false;
|
||||
}
|
||||
return source.toLowerCase(Locale.ROOT).contains(normalizedKeyword);
|
||||
}
|
||||
|
||||
private boolean containsAnyTagId(String tags, Set<String> targetTagIds) {
|
||||
if (!StringUtils.hasText(tags) || targetTagIds == null || targetTagIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (String tagId : tags.split(";")) {
|
||||
if (targetTagIds.contains(tagId.trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<ProductVO> loadProductsByTag(String tag) {
|
||||
if (!StringUtils.hasText(tag)) {
|
||||
return new ArrayList<>();
|
||||
@@ -478,62 +445,128 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
if (matchedTagIds.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return listFrontProductDOs().stream()
|
||||
.filter(productDO -> containsAnyTagId(productDO.getTags(), matchedTagIds))
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime);
|
||||
applyTagIdConditions(wrapper, matchedTagIds);
|
||||
return toProductVOList(productMapper.selectList(wrapper));
|
||||
}
|
||||
|
||||
private List<ProductVO> searchFrontProducts(String keyword) {
|
||||
String normalizedKeyword = normalizeSearchKeyword(keyword);
|
||||
Set<String> matchedTagIds = findLikeTagIds(keyword);
|
||||
return listFrontProductDOs().stream()
|
||||
.filter(productDO -> matchesFrontSearch(productDO, normalizedKeyword, matchedTagIds))
|
||||
.map(this::convertToVO)
|
||||
.collect(Collectors.toList());
|
||||
LambdaQueryWrapper<ProductDO> wrapper = buildFrontQuery(keyword, null, null);
|
||||
return toProductVOList(productMapper.selectList(wrapper));
|
||||
}
|
||||
|
||||
private PageResultVO<ProductVO> buildPublicProductPage(int page, int size, String keyword, String tag) {
|
||||
if (!StringUtils.hasText(keyword) && !StringUtils.hasText(tag)) {
|
||||
Page<ProductDO> pageParam = new Page<>(page, size);
|
||||
Page<ProductDO> productPage = productMapper.selectPage(pageParam,
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime));
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(productPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList()));
|
||||
result.setTotal(productPage.getTotal());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
return result;
|
||||
Set<String> exactTagIds = null;
|
||||
if (StringUtils.hasText(tag)) {
|
||||
exactTagIds = findExactTagIds(tag);
|
||||
if (exactTagIds.isEmpty()) {
|
||||
return buildEmptyPageResult(page, size);
|
||||
}
|
||||
}
|
||||
|
||||
List<ProductVO> source = StringUtils.hasText(keyword)
|
||||
? searchFrontProducts(keyword)
|
||||
: loadProductsByTag(tag);
|
||||
if (StringUtils.hasText(keyword) && StringUtils.hasText(tag)) {
|
||||
Set<String> exactTagIds = findExactTagIds(tag);
|
||||
source = source.stream()
|
||||
.filter(productVO -> containsAnyTagId(productVO.getTags(), exactTagIds))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
int fromIndex = Math.max((page - 1) * size, 0);
|
||||
int toIndex = Math.min(fromIndex + size, source.size());
|
||||
Page<ProductDO> pageParam = new Page<>(page, size);
|
||||
Page<ProductDO> productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds));
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(fromIndex >= source.size() ? List.of() : new ArrayList<>(source.subList(fromIndex, toIndex)));
|
||||
result.setTotal((long) source.size());
|
||||
result.setList(toProductVOList(productPage.getRecords()));
|
||||
result.setTotal(productPage.getTotal());
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<ProductDO> listFrontProductDOs() {
|
||||
return productMapper.selectList(
|
||||
Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0)
|
||||
.orderByDesc(ProductDO::getCreateTime)
|
||||
);
|
||||
private LambdaQueryWrapper<ProductDO> buildFrontQuery(String keyword, String tag, Set<String> exactTagIds) {
|
||||
LambdaQueryWrapper<ProductDO> wrapper = Wrappers.lambdaQuery(ProductDO.class)
|
||||
.eq(ProductDO::getIsDelete, 0);
|
||||
applyKeywordFilter(wrapper, keyword);
|
||||
if (StringUtils.hasText(tag)) {
|
||||
applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds);
|
||||
}
|
||||
wrapper.orderByDesc(ProductDO::getCreateTime);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
private void applyKeywordFilter(LambdaQueryWrapper<ProductDO> wrapper, String keyword) {
|
||||
if (!StringUtils.hasText(keyword)) {
|
||||
return;
|
||||
}
|
||||
Set<String> matchedTagIds = findLikeTagIds(keyword);
|
||||
wrapper.and(w -> {
|
||||
w.like(ProductDO::getTitle, keyword)
|
||||
.or()
|
||||
.like(ProductDO::getDescription, keyword);
|
||||
appendOrTagIdConditions(w, matchedTagIds);
|
||||
});
|
||||
}
|
||||
|
||||
private void applyTagIdConditions(LambdaQueryWrapper<ProductDO> wrapper, Set<String> tagIds) {
|
||||
wrapper.and(w -> {
|
||||
boolean appended = false;
|
||||
if (tagIds != null) {
|
||||
for (String tagId : tagIds) {
|
||||
if (!StringUtils.hasText(tagId)) {
|
||||
continue;
|
||||
}
|
||||
if (appended) {
|
||||
w.or();
|
||||
}
|
||||
w.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId);
|
||||
appended = true;
|
||||
}
|
||||
}
|
||||
if (!appended) {
|
||||
w.apply("1 = 0");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void appendOrTagIdConditions(LambdaQueryWrapper<ProductDO> wrapper, Set<String> tagIds) {
|
||||
if (tagIds == null || tagIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (String tagId : tagIds) {
|
||||
if (!StringUtils.hasText(tagId)) {
|
||||
continue;
|
||||
}
|
||||
wrapper.or().apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagId);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Long, String> loadShopNameMap(Set<Long> shopIds) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return shopMapper.selectBatchIds(shopIds).stream()
|
||||
.filter(shopDO -> !Integer.valueOf(1).equals(shopDO.getIsDelete()))
|
||||
.collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (left, right) -> left, LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private Map<Long, TagDO> loadTagMap(Set<Long> tagIds) {
|
||||
if (tagIds == null || tagIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return tagMapper.selectBatchIds(tagIds).stream()
|
||||
.filter(tagDO -> !Integer.valueOf(1).equals(tagDO.getIsDelete()))
|
||||
.collect(Collectors.toMap(TagDO::getId, tagDO -> tagDO, (left, right) -> left, LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private List<Long> parseDelimitedLongIds(String rawValue, String delimiter) {
|
||||
if (!StringUtils.hasText(rawValue)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<Long> ids = new ArrayList<>();
|
||||
for (String value : rawValue.split(java.util.regex.Pattern.quote(delimiter))) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ids.add(Long.parseLong(value.trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// Ignore malformed ids in historical data and keep the rest of the product visible.
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private Set<String> findExactTagIds(String tag) {
|
||||
@@ -564,6 +597,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
}
|
||||
|
||||
private PageResultVO<ProductVO> buildEmptyPageResult(int page, int size) {
|
||||
PageResultVO<ProductVO> result = new PageResultVO<>();
|
||||
result.setList(List.of());
|
||||
result.setTotal(0L);
|
||||
result.setPage(page);
|
||||
result.setSize(size);
|
||||
return result;
|
||||
}
|
||||
|
||||
private int normalizePage(Integer page) {
|
||||
return page == null || page < 1 ? 1 : page;
|
||||
}
|
||||
@@ -586,4 +628,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
|
||||
multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX);
|
||||
multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX);
|
||||
}
|
||||
|
||||
private record ProductEnrichmentContext(
|
||||
Map<Long, String> shopNames,
|
||||
Map<Long, TagDO> tags,
|
||||
Map<Long, ObjectStorageFileVO> files
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
+135
-58
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.common.BusinessException;
|
||||
import com.xiaowang.yuminailcore.dto.WechatMiniAutoLoginRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.WechatMiniConfirmLoginRequestDTO;
|
||||
import com.xiaowang.yuminailcore.dto.WechatMiniPhoneLoginRequestDTO;
|
||||
@@ -21,6 +22,7 @@ import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
|
||||
import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -28,6 +30,8 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -35,6 +39,7 @@ import java.util.Objects;
|
||||
* 微信小程序登录编排服务实现。
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
|
||||
@@ -53,7 +58,14 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
|
||||
@Override
|
||||
public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode());
|
||||
WechatMiniClientService.SessionInfo sessionInfo;
|
||||
try {
|
||||
sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode());
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("微信小程序自动登录识别失败,回退手动登录: {}", exception.getMessage());
|
||||
return WechatMiniLoginResultVO.needManualLogin("微信自动识别失败,请手动登录");
|
||||
}
|
||||
|
||||
WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId());
|
||||
if (bindingDO == null) {
|
||||
return WechatMiniLoginResultVO.needManualLogin("当前微信尚未绑定账号,请使用微信手机号一键登录。");
|
||||
@@ -72,7 +84,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode());
|
||||
String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode()));
|
||||
if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) {
|
||||
throw new RuntimeException("获取到的微信手机号格式不正确");
|
||||
throw new BusinessException("获取到的微信手机号格式不正确");
|
||||
}
|
||||
|
||||
WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId());
|
||||
@@ -81,7 +93,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
if (boundUser != null) {
|
||||
UserDO phoneUser = findActiveUserByPhone(phone);
|
||||
if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) {
|
||||
throw new RuntimeException("当前微信已绑定其他账号,无法关联该手机号");
|
||||
throw new BusinessException("当前微信已绑定其他账号,无法关联该手机号");
|
||||
}
|
||||
return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false);
|
||||
}
|
||||
@@ -109,7 +121,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) {
|
||||
Long shopId = normalizeShopId(requestDTO.getShopId());
|
||||
if (shopId == null) {
|
||||
throw new RuntimeException("请选择登录门店");
|
||||
throw new BusinessException("请选择登录门店");
|
||||
}
|
||||
|
||||
TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket());
|
||||
@@ -119,7 +131,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
} else if (StringUtils.hasText(ticketPayload.getPhone())) {
|
||||
loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId);
|
||||
} else {
|
||||
throw new RuntimeException("登录票据数据不完整,请重新发起微信一键登录");
|
||||
throw new BusinessException("登录票据数据不完整,请重新发起微信一键登录");
|
||||
}
|
||||
|
||||
ensureBinding(loginResponse.getUserInfo().getId(), ticketPayload.getOpenId(), ticketPayload.getUnionId());
|
||||
@@ -182,10 +194,10 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
|
||||
private void assertUserAvailable(UserDO userDO) {
|
||||
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||
throw new RuntimeException("账号不存在");
|
||||
throw new BusinessException("账号不存在");
|
||||
}
|
||||
if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
|
||||
throw new RuntimeException("账号已停用");
|
||||
throw new BusinessException("账号已停用");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,75 +223,69 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
);
|
||||
}
|
||||
|
||||
private WechatMiniBindingDO findAnyBindingByOpenId(String openId) {
|
||||
return wechatMiniBindingMapper.selectOne(
|
||||
private List<WechatMiniBindingDO> listBindingsByOpenId(String appId, String openId) {
|
||||
if (!StringUtils.hasText(openId)) {
|
||||
return List.of();
|
||||
}
|
||||
return wechatMiniBindingMapper.selectList(
|
||||
new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
|
||||
.eq(WechatMiniBindingDO::getAppId, appId)
|
||||
.eq(WechatMiniBindingDO::getOpenId, openId)
|
||||
.last("limit 1")
|
||||
.orderByDesc(WechatMiniBindingDO::getStatus)
|
||||
.orderByDesc(WechatMiniBindingDO::getUpdateTime)
|
||||
.orderByDesc(WechatMiniBindingDO::getCreateTime)
|
||||
.orderByDesc(WechatMiniBindingDO::getId)
|
||||
);
|
||||
}
|
||||
|
||||
private WechatMiniBindingDO findAnyBindingByUserId(Long userId) {
|
||||
return wechatMiniBindingMapper.selectOne(
|
||||
private List<WechatMiniBindingDO> listBindingsByUserId(String appId, Long userId) {
|
||||
if (userId == null) {
|
||||
return List.of();
|
||||
}
|
||||
return wechatMiniBindingMapper.selectList(
|
||||
new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
|
||||
.eq(WechatMiniBindingDO::getAppId, appId)
|
||||
.eq(WechatMiniBindingDO::getUserId, userId)
|
||||
.last("limit 1")
|
||||
.orderByDesc(WechatMiniBindingDO::getStatus)
|
||||
.orderByDesc(WechatMiniBindingDO::getUpdateTime)
|
||||
.orderByDesc(WechatMiniBindingDO::getCreateTime)
|
||||
.orderByDesc(WechatMiniBindingDO::getId)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
protected void ensureBinding(Long userId, String openId, String unionId) {
|
||||
if (userId == null || !StringUtils.hasText(openId)) {
|
||||
throw new RuntimeException("微信绑定信息不完整");
|
||||
throw new BusinessException("微信绑定信息不完整");
|
||||
}
|
||||
|
||||
WechatMiniBindingDO openIdBinding = findAnyBindingByOpenId(openId);
|
||||
WechatMiniBindingDO userBinding = findAnyBindingByUserId(userId);
|
||||
String appId = wechatMiniClientService.getConfiguredAppId();
|
||||
List<WechatMiniBindingDO> openIdBindings = listBindingsByOpenId(appId, openId);
|
||||
List<WechatMiniBindingDO> userBindings = listBindingsByUserId(appId, userId);
|
||||
|
||||
if (openIdBinding != null && userBinding != null && !Objects.equals(openIdBinding.getId(), userBinding.getId())) {
|
||||
if (Integer.valueOf(1).equals(openIdBinding.getStatus()) && !Objects.equals(openIdBinding.getUserId(), userId)) {
|
||||
throw new RuntimeException("当前微信已绑定其他账号,无法完成登录");
|
||||
}
|
||||
if (Integer.valueOf(1).equals(userBinding.getStatus()) && !Objects.equals(userBinding.getOpenId(), openId)) {
|
||||
throw new RuntimeException("当前账号已绑定其他微信,请联系管理员处理");
|
||||
}
|
||||
wechatMiniBindingMapper.deleteById(userBinding.getId());
|
||||
userBinding = null;
|
||||
}
|
||||
validateExclusiveActiveBinding(userId, openId, openIdBindings, userBindings);
|
||||
|
||||
if (openIdBinding != null) {
|
||||
if (Integer.valueOf(1).equals(openIdBinding.getStatus()) && !Objects.equals(openIdBinding.getUserId(), userId)) {
|
||||
throw new RuntimeException("当前微信已绑定其他账号,无法完成登录");
|
||||
}
|
||||
openIdBinding.setUserId(userId);
|
||||
openIdBinding.setUnionId(unionId);
|
||||
openIdBinding.setStatus(1);
|
||||
openIdBinding.setUpdateTime(LocalDateTime.now());
|
||||
wechatMiniBindingMapper.updateById(openIdBinding);
|
||||
WechatMiniBindingDO targetBinding = pickTargetBinding(userId, openId, openIdBindings, userBindings);
|
||||
if (targetBinding == null) {
|
||||
WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
|
||||
bindingDO.setUserId(userId);
|
||||
bindingDO.setAppId(appId);
|
||||
bindingDO.setOpenId(openId);
|
||||
bindingDO.setUnionId(unionId);
|
||||
bindingDO.setStatus(1);
|
||||
wechatMiniBindingMapper.insert(bindingDO);
|
||||
return;
|
||||
}
|
||||
|
||||
if (userBinding != null) {
|
||||
if (Integer.valueOf(1).equals(userBinding.getStatus()) && !Objects.equals(userBinding.getOpenId(), openId)) {
|
||||
throw new RuntimeException("当前账号已绑定其他微信,请联系管理员处理");
|
||||
}
|
||||
userBinding.setOpenId(openId);
|
||||
userBinding.setUnionId(unionId);
|
||||
userBinding.setStatus(1);
|
||||
userBinding.setUpdateTime(LocalDateTime.now());
|
||||
wechatMiniBindingMapper.updateById(userBinding);
|
||||
return;
|
||||
}
|
||||
targetBinding.setUserId(userId);
|
||||
targetBinding.setAppId(appId);
|
||||
targetBinding.setOpenId(openId);
|
||||
targetBinding.setUnionId(unionId);
|
||||
targetBinding.setStatus(1);
|
||||
targetBinding.setUpdateTime(LocalDateTime.now());
|
||||
wechatMiniBindingMapper.updateById(targetBinding);
|
||||
|
||||
WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
|
||||
bindingDO.setUserId(userId);
|
||||
bindingDO.setAppId(wechatMiniClientService.getConfiguredAppId());
|
||||
bindingDO.setOpenId(openId);
|
||||
bindingDO.setUnionId(unionId);
|
||||
bindingDO.setStatus(1);
|
||||
wechatMiniBindingMapper.insert(bindingDO);
|
||||
deactivateDuplicateBindings(targetBinding.getId(), mergeBindings(openIdBindings, userBindings));
|
||||
}
|
||||
|
||||
private void deactivateBinding(Long bindingId) {
|
||||
@@ -295,6 +301,77 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
);
|
||||
}
|
||||
|
||||
private void validateExclusiveActiveBinding(
|
||||
Long userId,
|
||||
String openId,
|
||||
List<WechatMiniBindingDO> openIdBindings,
|
||||
List<WechatMiniBindingDO> userBindings
|
||||
) {
|
||||
boolean openIdBoundToOtherUser = openIdBindings.stream()
|
||||
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
|
||||
.anyMatch(binding -> !Objects.equals(binding.getUserId(), userId));
|
||||
if (openIdBoundToOtherUser) {
|
||||
throw new BusinessException("当前微信已绑定其他账号,无法完成登录");
|
||||
}
|
||||
|
||||
boolean userBoundToOtherWechat = userBindings.stream()
|
||||
.filter(binding -> Integer.valueOf(1).equals(binding.getStatus()))
|
||||
.anyMatch(binding -> !Objects.equals(binding.getOpenId(), openId));
|
||||
if (userBoundToOtherWechat) {
|
||||
throw new BusinessException("当前账号已绑定其他微信,请联系管理员处理");
|
||||
}
|
||||
}
|
||||
|
||||
private WechatMiniBindingDO pickTargetBinding(
|
||||
Long userId,
|
||||
String openId,
|
||||
List<WechatMiniBindingDO> openIdBindings,
|
||||
List<WechatMiniBindingDO> userBindings
|
||||
) {
|
||||
List<WechatMiniBindingDO> mergedBindings = mergeBindings(openIdBindings, userBindings);
|
||||
return mergedBindings.stream()
|
||||
.filter(binding -> Objects.equals(binding.getUserId(), userId) && Objects.equals(binding.getOpenId(), openId))
|
||||
.findFirst()
|
||||
.orElseGet(() -> mergedBindings.stream()
|
||||
.filter(binding -> Objects.equals(binding.getOpenId(), openId))
|
||||
.findFirst()
|
||||
.orElseGet(() -> mergedBindings.stream()
|
||||
.filter(binding -> Objects.equals(binding.getUserId(), userId))
|
||||
.findFirst()
|
||||
.orElse(null)));
|
||||
}
|
||||
|
||||
private List<WechatMiniBindingDO> mergeBindings(
|
||||
List<WechatMiniBindingDO> openIdBindings,
|
||||
List<WechatMiniBindingDO> userBindings
|
||||
) {
|
||||
List<WechatMiniBindingDO> merged = new ArrayList<>();
|
||||
openIdBindings.forEach(binding -> appendUniqueBinding(merged, binding));
|
||||
userBindings.forEach(binding -> appendUniqueBinding(merged, binding));
|
||||
merged.sort(Comparator
|
||||
.comparing((WechatMiniBindingDO binding) -> Integer.valueOf(1).equals(binding.getStatus()) ? 0 : 1)
|
||||
.thenComparing(WechatMiniBindingDO::getUpdateTime, Comparator.nullsLast(Comparator.reverseOrder()))
|
||||
.thenComparing(WechatMiniBindingDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))
|
||||
.thenComparing(WechatMiniBindingDO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
return merged;
|
||||
}
|
||||
|
||||
private void appendUniqueBinding(List<WechatMiniBindingDO> merged, WechatMiniBindingDO candidate) {
|
||||
if (candidate == null) {
|
||||
return;
|
||||
}
|
||||
boolean exists = merged.stream().anyMatch(item -> Objects.equals(item.getId(), candidate.getId()));
|
||||
if (!exists) {
|
||||
merged.add(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
private void deactivateDuplicateBindings(Long keepBindingId, List<WechatMiniBindingDO> bindings) {
|
||||
bindings.stream()
|
||||
.filter(binding -> binding.getId() != null && !Objects.equals(binding.getId(), keepBindingId))
|
||||
.forEach(binding -> deactivateBinding(binding.getId()));
|
||||
}
|
||||
|
||||
private Long resolvePreferredOrOnlyShop(List<ShopSimpleVO> shops, Long preferredShopId) {
|
||||
Long normalizedPreferredShopId = normalizeShopId(preferredShopId);
|
||||
if (normalizedPreferredShopId != null) {
|
||||
@@ -328,19 +405,19 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
|
||||
);
|
||||
return ticket;
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new RuntimeException("生成微信登录票据失败", exception);
|
||||
throw new BusinessException("生成微信登录票据失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private TicketPayload readTicketPayload(String ticket) {
|
||||
String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket);
|
||||
if (!StringUtils.hasText(payloadJson)) {
|
||||
throw new RuntimeException("登录票据已失效,请重新发起微信一键登录");
|
||||
throw new BusinessException("登录票据已失效,请重新发起微信一键登录");
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(payloadJson, TicketPayload.class);
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new RuntimeException("解析微信登录票据失败", exception);
|
||||
throw new BusinessException("解析微信登录票据失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+67
-28
@@ -1,7 +1,9 @@
|
||||
package com.xiaowang.yuminailcore.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.yuminailcore.common.BusinessException;
|
||||
import com.xiaowang.yuminailcore.config.WechatMiniProperties;
|
||||
import com.xiaowang.yuminailcore.service.WechatMiniClientService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -11,6 +13,7 @@ import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
@@ -19,7 +22,7 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 微信小程序开放接口客户端实现。
|
||||
* WeChat mini program API client.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -35,55 +38,70 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
|
||||
@Override
|
||||
public SessionInfo code2Session(String wxCode) {
|
||||
if (!StringUtils.hasText(wxCode)) {
|
||||
throw new BusinessException("微信登录凭证不能为空");
|
||||
}
|
||||
requireConfiguredCredentials();
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
restTemplate.getForObject(
|
||||
doGetForString(
|
||||
UriComponentsBuilder.fromHttpUrl(properties.getCode2sessionUrl())
|
||||
.queryParam("appid", properties.getAppId())
|
||||
.queryParam("secret", properties.getAppSecret())
|
||||
.queryParam("js_code", wxCode)
|
||||
.queryParam("grant_type", "authorization_code")
|
||||
.build(true)
|
||||
.toUri(),
|
||||
Map.class
|
||||
)
|
||||
.toUriString(),
|
||||
"获取微信登录身份失败"
|
||||
),
|
||||
"获取微信登录身份失败"
|
||||
);
|
||||
assertWechatResponseOk(response, "获取微信登录身份失败");
|
||||
String openId = asText(response.get("openid"));
|
||||
if (!StringUtils.hasText(openId)) {
|
||||
throw new RuntimeException("获取微信登录身份失败:缺少 openid");
|
||||
throw new BusinessException("获取微信登录身份失败:缺少 openid");
|
||||
}
|
||||
return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPhoneNumber(String phoneCode) {
|
||||
if (!StringUtils.hasText(phoneCode)) {
|
||||
throw new BusinessException("微信手机号凭证不能为空");
|
||||
}
|
||||
|
||||
String accessToken = getAccessToken();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
restTemplate.postForObject(
|
||||
doPostForString(
|
||||
UriComponentsBuilder.fromHttpUrl(properties.getPhoneNumberUrl())
|
||||
.queryParam("access_token", accessToken)
|
||||
.build(true)
|
||||
.toUri(),
|
||||
.toUriString(),
|
||||
new HttpEntity<>(Map.of("code", phoneCode), headers),
|
||||
Map.class
|
||||
)
|
||||
"获取微信手机号失败"
|
||||
),
|
||||
"获取微信手机号失败"
|
||||
);
|
||||
assertWechatResponseOk(response, "获取微信手机号失败");
|
||||
Map<String, Object> phoneInfo = objectMapper.convertValue(
|
||||
response.get("phone_info"),
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
}
|
||||
);
|
||||
|
||||
Object phoneInfoRaw = response.get("phone_info");
|
||||
if (phoneInfoRaw == null) {
|
||||
throw new BusinessException("获取微信手机号失败:未返回手机号信息");
|
||||
}
|
||||
Map<String, Object> phoneInfo = objectMapper.convertValue(phoneInfoRaw, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
if (phoneInfo == null || phoneInfo.isEmpty()) {
|
||||
throw new BusinessException("获取微信手机号失败:未返回手机号信息");
|
||||
}
|
||||
|
||||
String phoneNumber = asText(phoneInfo.get("phoneNumber"));
|
||||
if (!StringUtils.hasText(phoneNumber)) {
|
||||
phoneNumber = asText(phoneInfo.get("purePhoneNumber"));
|
||||
}
|
||||
if (!StringUtils.hasText(phoneNumber)) {
|
||||
throw new RuntimeException("获取微信手机号失败:未返回手机号");
|
||||
throw new BusinessException("获取微信手机号失败:未返回手机号信息");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
@@ -103,21 +121,22 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
}
|
||||
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
restTemplate.getForObject(
|
||||
doGetForString(
|
||||
UriComponentsBuilder.fromHttpUrl(ACCESS_TOKEN_URL)
|
||||
.queryParam("grant_type", "client_credential")
|
||||
.queryParam("appid", properties.getAppId())
|
||||
.queryParam("secret", properties.getAppSecret())
|
||||
.build(true)
|
||||
.toUri(),
|
||||
Map.class
|
||||
)
|
||||
.toUriString(),
|
||||
"获取微信 access_token 失败"
|
||||
),
|
||||
"获取微信 access_token 失败"
|
||||
);
|
||||
assertWechatResponseOk(response, "获取微信 access_token 失败");
|
||||
|
||||
String accessToken = asText(response.get("access_token"));
|
||||
if (!StringUtils.hasText(accessToken)) {
|
||||
throw new RuntimeException("获取微信 access_token 失败:未返回 access_token");
|
||||
throw new BusinessException("获取微信 access_token 失败:未返回 access_token");
|
||||
}
|
||||
|
||||
long expiresIn = parseLong(response.get("expires_in"), 7200L);
|
||||
@@ -129,16 +148,36 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
|
||||
private void requireConfiguredCredentials() {
|
||||
if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) {
|
||||
throw new RuntimeException("微信小程序登录未配置 appId/appSecret");
|
||||
throw new BusinessException("微信小程序登录未配置 appId/appSecret");
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> readJsonResponse(Object response) {
|
||||
if (response == null) {
|
||||
throw new RuntimeException("微信服务未返回数据");
|
||||
private String doGetForString(String url, String defaultMessage) {
|
||||
try {
|
||||
return restTemplate.getForObject(url, String.class);
|
||||
} catch (RestClientException exception) {
|
||||
throw new BusinessException(defaultMessage + ":微信服务调用失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String doPostForString(String url, HttpEntity<?> requestEntity, String defaultMessage) {
|
||||
try {
|
||||
return restTemplate.postForObject(url, requestEntity, String.class);
|
||||
} catch (RestClientException exception) {
|
||||
throw new BusinessException(defaultMessage + ":微信服务调用失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> readJsonResponse(String responseBody, String defaultMessage) {
|
||||
if (!StringUtils.hasText(responseBody)) {
|
||||
throw new BusinessException(defaultMessage + ":微信服务未返回数据");
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(responseBody, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
} catch (JsonProcessingException exception) {
|
||||
throw new BusinessException(defaultMessage + ":微信服务返回了无法解析的响应", exception);
|
||||
}
|
||||
return objectMapper.convertValue(response, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
}
|
||||
|
||||
private void assertWechatResponseOk(Map<String, Object> response, String defaultMessage) {
|
||||
@@ -147,7 +186,7 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
return;
|
||||
}
|
||||
String errMsg = asText(response.get("errmsg"));
|
||||
throw new RuntimeException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode)));
|
||||
throw new BusinessException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode)));
|
||||
}
|
||||
|
||||
private long parseLong(Object value, long defaultValue) {
|
||||
|
||||
@@ -69,3 +69,16 @@ yuminail:
|
||||
tag:
|
||||
local-ttl-seconds: 300
|
||||
redis-ttl-seconds: 1200
|
||||
object-storage-file:
|
||||
local-ttl-seconds: 300
|
||||
redis-ttl-seconds: 1800
|
||||
slow-request:
|
||||
enabled: true
|
||||
threshold-ms: 300
|
||||
log-response-header-request-id: true
|
||||
http-client:
|
||||
connect-timeout-ms: 3000
|
||||
read-timeout-ms: 5000
|
||||
connection-request-timeout-ms: 1000
|
||||
max-total-connections: 200
|
||||
max-connections-per-route: 50
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
-- 用户余额信息表
|
||||
create table t_balance
|
||||
(
|
||||
id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)'
|
||||
primary key comment '余额表主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
amount decimal(10, 2) default 0.00 not null comment '当前余额',
|
||||
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
|
||||
unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)'
|
||||
)
|
||||
comment '用户余额信息表';
|
||||
-- 用户余额变动明细表
|
||||
create table t_balance_change_detail
|
||||
(
|
||||
id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)'
|
||||
primary key comment '余额变动明细主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)',
|
||||
type varchar(20) not null comment '变动类型(如充值、消费、退款)',
|
||||
current_balance decimal(10, 2) not null comment '变动后的当前余额',
|
||||
change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间'
|
||||
)
|
||||
comment '用户余额变动明细表';
|
||||
|
||||
create index idx_change_time
|
||||
on t_balance_change_detail (change_time)
|
||||
comment '按时间查询余额变动的索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_balance_change_detail (user_id)
|
||||
comment '按用户查询余额变动的索引';
|
||||
|
||||
-- 用户评论信息表
|
||||
create table t_comment
|
||||
(
|
||||
id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)'
|
||||
primary key comment '评论主键索引',
|
||||
user_id bigint unsigned not null comment '评论用户ID,关联用户表主键',
|
||||
shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)',
|
||||
product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)',
|
||||
comment_content text not null comment '评论内容',
|
||||
parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)',
|
||||
like_count int unsigned default 0 null comment '评论点赞数',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除'
|
||||
)
|
||||
comment '用户评论信息表';
|
||||
|
||||
create index idx_parent_comment_id
|
||||
on t_comment (parent_comment_id)
|
||||
comment '按父级评论查询回复的索引';
|
||||
|
||||
create index idx_product_id
|
||||
on t_comment (product_id)
|
||||
comment '按商品查询评论的索引';
|
||||
|
||||
create index idx_shop_id
|
||||
on t_comment (shop_id)
|
||||
comment '按店铺查询评论的索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_comment (user_id)
|
||||
comment '按用户查询评论的索引';
|
||||
|
||||
|
||||
|
||||
-- 商品效果图信息表
|
||||
create table t_effect_diagram
|
||||
(
|
||||
id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)'
|
||||
primary key comment '效果图主键索引',
|
||||
product_id bigint unsigned not null comment '所属商品ID,关联商品表主键',
|
||||
category varchar(50) default '' null comment '效果图类别',
|
||||
image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔',
|
||||
description text null comment '效果图描述',
|
||||
price decimal(10, 2) default 0.00 null comment '效果图对应服务价格',
|
||||
duration varchar(50) default '' null comment '效果图对应服务耗时',
|
||||
tag varchar(50) default '' null comment '效果图标签',
|
||||
like_count int unsigned default 0 null comment '效果图点赞数',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
)
|
||||
comment '商品效果图信息表';
|
||||
|
||||
create index idx_product_id
|
||||
on t_effect_diagram (product_id)
|
||||
comment '按商品查询效果图的索引';
|
||||
|
||||
-- 用户登录标识信息表
|
||||
create table t_login_identity
|
||||
(
|
||||
id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)'
|
||||
primary key comment '登录标识主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)',
|
||||
input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)',
|
||||
input_time datetime not null comment '输入时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
status tinyint unsigned default 1 null comment '状态:1-有效,0-无效'
|
||||
)
|
||||
comment '用户登录标识信息表';
|
||||
|
||||
create index idx_login_method
|
||||
on t_login_identity (login_method)
|
||||
comment '按登录方式查询的索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_login_identity (user_id)
|
||||
comment '按用户查询登录标识的索引';
|
||||
|
||||
-- 对象存储文件信息表
|
||||
create table t_object_storage_file
|
||||
(
|
||||
id bigint unsigned auto_increment comment '文件记录唯一主键ID(雪花ID)'
|
||||
primary key comment '对象存储文件主键索引',
|
||||
file_name varchar(100) not null comment '文件名称',
|
||||
file_url text not null comment '文件访问链接',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '文件上传时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '文件更新时间',
|
||||
status tinyint unsigned default 1 null comment '文件状态:1-可用,0-不可用,2-回收站',
|
||||
delete_time datetime null comment '文件删除时间(NULL表示未删除)',
|
||||
recycle_time datetime null comment '文件移入回收站时间(NULL表示未移入)'
|
||||
)
|
||||
comment '对象存储文件信息表';
|
||||
|
||||
create index idx_status
|
||||
on t_object_storage_file (status)
|
||||
comment '按文件状态查询的索引';
|
||||
|
||||
|
||||
-- 系统权限表
|
||||
create table t_permission
|
||||
(
|
||||
id bigint unsigned auto_increment comment '权限唯一主键ID'
|
||||
primary key,
|
||||
permission_code varchar(100) not null comment '权限编码(唯一标识)',
|
||||
permission_name varchar(100) not null comment '权限名称',
|
||||
permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)',
|
||||
description varchar(255) null comment '权限描述',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_permission_code
|
||||
unique (permission_code) comment '权限编码唯一索引'
|
||||
)
|
||||
comment '系统权限表';
|
||||
|
||||
-- 商品信息表
|
||||
create table t_product
|
||||
(
|
||||
id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)'
|
||||
primary key comment '商品主键索引',
|
||||
shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键',
|
||||
title varchar(100) not null comment '商品标题',
|
||||
description text null comment '商品描述',
|
||||
image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔',
|
||||
price decimal(10, 2) not null comment '商品价格,保留2位小数',
|
||||
tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个',
|
||||
like_count int unsigned default 0 null comment '商品点赞数',
|
||||
collect_count int unsigned default 0 null comment '商品收藏数',
|
||||
approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)',
|
||||
bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔',
|
||||
available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除'
|
||||
)
|
||||
comment '商品信息表';
|
||||
|
||||
create index idx_price
|
||||
on t_product (price)
|
||||
comment '按价格筛选商品的索引';
|
||||
|
||||
create index idx_shop_id
|
||||
on t_product (shop_id)
|
||||
comment '按所属店铺查询商品的索引';
|
||||
|
||||
create index idx_tags
|
||||
on t_product (tags)
|
||||
comment '按标签筛选商品的索引';
|
||||
|
||||
create index idx_title
|
||||
on t_product (title)
|
||||
comment '商品标题搜索的索引';
|
||||
|
||||
-- 店铺信息表
|
||||
create table t_shop
|
||||
(
|
||||
id bigint unsigned comment '店铺唯一主键ID(雪花ID)'
|
||||
primary key comment '店铺主键索引',
|
||||
shop_name varchar(100) not null comment '店铺名称',
|
||||
description text null comment '店铺描述',
|
||||
address varchar(200) not null comment '店铺地址',
|
||||
business_hours varchar(100) default '' null comment '店铺营业时间',
|
||||
cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔'
|
||||
)
|
||||
comment '店铺信息表';
|
||||
|
||||
create index idx_shop_name
|
||||
on t_shop (shop_name)
|
||||
comment '按店铺名称查询的索引';
|
||||
|
||||
|
||||
-- 系统标签信息表
|
||||
create table t_tag
|
||||
(
|
||||
id bigint unsigned auto_increment comment '标签唯一主键ID'
|
||||
primary key comment '标签主键索引',
|
||||
tag_name varchar(50) not null comment '标签名称',
|
||||
text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)',
|
||||
bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)',
|
||||
border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
shop_id bigint null comment '店铺ID',
|
||||
constraint uk_tag_name
|
||||
unique (tag_name) comment '标签名称唯一索引'
|
||||
)
|
||||
comment '系统标签信息表';
|
||||
|
||||
-- 系统用户信息表
|
||||
create table t_user
|
||||
(
|
||||
id bigint unsigned comment '用户唯一主键ID(雪花ID)'
|
||||
primary key comment '用户主键索引',
|
||||
shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)',
|
||||
nickname varchar(50) not null comment '用户昵称',
|
||||
account varchar(50) not null comment '用户账号(登录用)',
|
||||
phone varchar(50) null comment '手机号',
|
||||
email varchar(100) null comment '邮箱',
|
||||
phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证',
|
||||
email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证',
|
||||
password varchar(100) not null comment '用户密码(加密存储)',
|
||||
signature varchar(200) default '' null comment '用户签名',
|
||||
level varchar(20) default '普通' null comment '用户等级',
|
||||
type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)',
|
||||
vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用',
|
||||
avatar varchar(512) null comment '头像链接',
|
||||
constraint uk_account
|
||||
unique (account) comment '用户账号唯一索引'
|
||||
)
|
||||
comment '系统用户信息表';
|
||||
|
||||
create index idx_email
|
||||
on t_user (email)
|
||||
comment '按邮箱查询的索引';
|
||||
|
||||
create index idx_phone
|
||||
on t_user (phone)
|
||||
comment '按手机号查询的索引';
|
||||
|
||||
create index idx_shop_id
|
||||
on t_user (shop_id)
|
||||
comment '按店铺查询用户的索引';
|
||||
|
||||
create index idx_type
|
||||
on t_user (type)
|
||||
comment '按用户类型查询的索引';
|
||||
|
||||
-- 用户权限关联表
|
||||
create table t_user_permission
|
||||
(
|
||||
id bigint unsigned auto_increment comment '关联ID'
|
||||
primary key,
|
||||
user_id bigint unsigned not null comment '用户ID',
|
||||
permission_id bigint unsigned not null comment '权限ID',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
create_by bigint unsigned null comment '创建人ID',
|
||||
update_by bigint unsigned null comment '更新人ID',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_user_permission
|
||||
unique (user_id, permission_id) comment '用户-权限唯一索引'
|
||||
)
|
||||
comment '用户权限关联表';
|
||||
|
||||
create index idx_permission_id
|
||||
on t_user_permission (permission_id)
|
||||
comment '权限ID索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_user_permission (user_id)
|
||||
comment '用户ID索引';
|
||||
|
||||
|
||||
-- VIP权益信息表
|
||||
create table t_vip_benefit
|
||||
(
|
||||
id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)'
|
||||
primary key comment 'VIP权益主键索引',
|
||||
benefit_info text not null comment '权益详情(如折扣、专属服务)',
|
||||
required_vip_level varchar(20) not null comment '所需VIP等级',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
|
||||
)
|
||||
comment 'VIP权益信息表';
|
||||
|
||||
create index idx_required_vip_level
|
||||
on t_vip_benefit (required_vip_level)
|
||||
comment '按VIP等级查询权益的索引';
|
||||
|
||||
-- 用户VIP信息表
|
||||
create table t_vip_info
|
||||
(
|
||||
id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)'
|
||||
primary key comment 'VIP信息主键索引',
|
||||
vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)',
|
||||
start_time datetime not null comment 'VIP开通时间',
|
||||
expire_time datetime not null comment 'VIP到期时间',
|
||||
activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)',
|
||||
benefit_id bigint unsigned not null comment '关联VIP权益信息表主键',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间'
|
||||
)
|
||||
comment '用户VIP信息表';
|
||||
|
||||
create index idx_vip_level
|
||||
on t_vip_info (vip_level)
|
||||
comment '按VIP等级查询的索引';
|
||||
|
||||
|
||||
|
||||
-- 清空现有数据
|
||||
DELETE FROM t_user_permission WHERE 1=1;
|
||||
DELETE FROM t_permission WHERE 1=1;
|
||||
DELETE FROM t_user WHERE 1=1;
|
||||
|
||||
-- 插入完整的系统权限
|
||||
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) VALUES
|
||||
-- 首页权限
|
||||
('home:view', '查看首页', '首页', '查看系统首页', NOW(), NOW(), 0),
|
||||
|
||||
-- 仪表盘权限
|
||||
('dashboard:view', '查看仪表盘', '仪表盘', '查看系统仪表盘', NOW(), NOW(), 0),
|
||||
|
||||
-- 用户管理权限
|
||||
('user:view', '查看用户', '用户管理', '查看用户列表和详情', NOW(), NOW(), 0),
|
||||
('user:create', '新增用户', '用户管理', '新增用户', NOW(), NOW(), 0),
|
||||
('user:edit', '编辑用户', '用户管理', '编辑用户信息', NOW(), NOW(), 0),
|
||||
('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0),
|
||||
('user:delete', '删除用户', '用户管理', '删除用户', NOW(), NOW(), 0),
|
||||
|
||||
-- 商品管理权限
|
||||
('product:view', '查看商品', '商品管理', '查看商品列表和详情', NOW(), NOW(), 0),
|
||||
('product:create', '新增商品', '商品管理', '新增商品', NOW(), NOW(), 0),
|
||||
('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0),
|
||||
('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0),
|
||||
('product:category:manage', '管理商品分类', '商品管理', '管理商品分类', NOW(), NOW(), 0),
|
||||
|
||||
-- 店铺管理权限
|
||||
('shop:view', '查看店铺', '店铺管理', '查看店铺列表和详情', NOW(), NOW(), 0),
|
||||
('shop:create', '新增店铺', '店铺管理', '新增店铺', NOW(), NOW(), 0),
|
||||
('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0),
|
||||
('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0),
|
||||
('shop:staff:manage', '管理店铺员工', '店铺管理', '管理店铺员工', NOW(), NOW(), 0),
|
||||
|
||||
-- 权限管理权限
|
||||
('permission:view', '查看权限', '权限管理', '查看权限列表', NOW(), NOW(), 0),
|
||||
('permission:create', '新增权限', '权限管理', '新增系统权限', NOW(), NOW(), 0),
|
||||
('permission:edit', '编辑权限', '权限管理', '编辑系统权限', NOW(), NOW(), 0),
|
||||
('permission:delete', '删除权限', '权限管理', '删除系统权限', NOW(), NOW(), 0),
|
||||
('permission:assign', '分配权限', '权限管理', '为用户分配权限', NOW(), NOW(), 0),
|
||||
|
||||
-- 标签管理权限
|
||||
('tag:view', '查看标签', '标签管理', '查看标签列表和详情', NOW(), NOW(), 0),
|
||||
('tag:create', '新增标签', '标签管理', '新增标签', NOW(), NOW(), 0),
|
||||
('tag:edit', '编辑标签', '标签管理', '编辑标签信息', NOW(), NOW(), 0),
|
||||
('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0),
|
||||
('tag:assign', '分配标签', '标签管理', '为商品分配标签', NOW(), NOW(), 0),
|
||||
|
||||
-- 优惠券管理权限
|
||||
('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券列表和详情', NOW(), NOW(), 0),
|
||||
('coupon:create', '新增优惠券', '优惠券管理', '新增优惠券', NOW(), NOW(), 0),
|
||||
('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券信息', NOW(), NOW(), 0),
|
||||
('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券', NOW(), NOW(), 0),
|
||||
('coupon:assign', '分配优惠券', '优惠券管理', '为用户分配优惠券', NOW(), NOW(), 0),
|
||||
|
||||
-- 订单管理权限
|
||||
('order:view', '查看订单', '订单管理', '查看订单列表和详情', NOW(), NOW(), 0),
|
||||
('order:edit', '编辑订单', '订单管理', '编辑订单信息', NOW(), NOW(), 0),
|
||||
('order:delete', '删除订单', '订单管理', '删除订单', NOW(), NOW(), 0),
|
||||
('order:process', '处理订单', '订单管理', '处理订单状态', NOW(), NOW(), 0);
|
||||
|
||||
-- 初始化admin用户,密码为123456
|
||||
-- 密码使用BCrypt加密,123456的加密值为:$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW
|
||||
INSERT INTO t_user (id, shop_id, nickname, account, password, type, status, create_time, update_time, is_delete) VALUES
|
||||
(1, 0, '管理员', 'admin', '$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW', 4, 1, NOW(), NOW(), 0);
|
||||
|
||||
-- 为管理员分配权限
|
||||
-- 首页的全部权限
|
||||
-- 仪表盘的全部权限
|
||||
-- 所有店铺的用户管理的全部权限
|
||||
-- 所有店铺的商品管理的查看权限,无新增编辑删除管理商品分类权限
|
||||
-- 所有店铺的店铺管理的全部权限
|
||||
-- 所有店铺的权限管理的全部权限
|
||||
-- 所有店铺的标签管理的查看权限无新增编辑删除权限
|
||||
-- 所有店铺的优惠券管理的查看权限
|
||||
-- 所有店铺的订单管理的查看权限
|
||||
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by)
|
||||
SELECT
|
||||
1 as user_id,
|
||||
p.id as permission_id,
|
||||
NOW() as create_time,
|
||||
NOW() as update_time,
|
||||
1 as create_by
|
||||
FROM t_permission p
|
||||
WHERE p.is_delete = 0
|
||||
AND p.permission_code IN (
|
||||
'home:view',
|
||||
'dashboard:view',
|
||||
'user:view',
|
||||
'user:create',
|
||||
'user:edit',
|
||||
'user:reset_password',
|
||||
'user:delete',
|
||||
'product:view',
|
||||
'shop:view',
|
||||
'shop:create',
|
||||
'shop:edit',
|
||||
'shop:delete',
|
||||
'shop:staff:manage',
|
||||
'permission:view',
|
||||
'permission:create',
|
||||
'permission:edit',
|
||||
'permission:delete',
|
||||
'permission:assign',
|
||||
'tag:view',
|
||||
'coupon:view',
|
||||
'order:view'
|
||||
);
|
||||
|
||||
-- 注意:店长和美甲师的权限需要在系统中手动分配,因为需要关联具体的店铺
|
||||
-- 这里只初始化管理员的权限
|
||||
|
||||
-- 优惠券信息表
|
||||
create table t_coupon
|
||||
(
|
||||
id bigint unsigned auto_increment comment '优惠券唯一主键ID'
|
||||
primary key comment '优惠券主键索引',
|
||||
coupon_code varchar(50) not null comment '优惠券编码',
|
||||
coupon_name varchar(100) not null comment '优惠券名称',
|
||||
coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券',
|
||||
discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)',
|
||||
min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额',
|
||||
reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额',
|
||||
total_count int unsigned default 100 not null comment '优惠券总数量',
|
||||
used_count int unsigned default 0 not null comment '已使用数量',
|
||||
start_time datetime not null comment '开始时间',
|
||||
end_time datetime not null comment '结束时间',
|
||||
status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完',
|
||||
shop_id bigint unsigned not null comment '所属店铺ID',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_coupon_code
|
||||
unique (coupon_code) comment '优惠券编码唯一索引'
|
||||
) comment '优惠券信息表';
|
||||
|
||||
create index idx_status
|
||||
on t_coupon (status) comment '按状态查询优惠券的索引';
|
||||
|
||||
create index idx_shop_id
|
||||
on t_coupon (shop_id) comment '按店铺查询优惠券的索引';
|
||||
|
||||
-- 用户优惠券关联表
|
||||
create table t_user_coupon
|
||||
(
|
||||
id bigint unsigned auto_increment comment '用户优惠券关联唯一主键ID'
|
||||
primary key comment '用户优惠券关联主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
coupon_id bigint unsigned not null comment '关联优惠券表主键',
|
||||
status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期',
|
||||
obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间',
|
||||
use_time datetime null comment '使用时间',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_user_coupon
|
||||
unique (user_id, coupon_id) comment '用户-优惠券唯一索引'
|
||||
) comment '用户优惠券关联表';
|
||||
|
||||
create index idx_status
|
||||
on t_user_coupon (status) comment '按状态查询用户优惠券的索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_user_coupon (user_id) comment '按用户查询优惠券的索引';
|
||||
|
||||
-- 优惠券标签关联表
|
||||
create table t_coupon_tag
|
||||
(
|
||||
id bigint unsigned auto_increment comment '优惠券标签关联唯一主键ID'
|
||||
primary key comment '优惠券标签关联主键索引',
|
||||
coupon_id bigint unsigned not null comment '关联优惠券表主键',
|
||||
tag_id bigint unsigned not null comment '关联标签表主键',
|
||||
is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_coupon_tag
|
||||
unique (coupon_id, tag_id) comment '优惠券-标签唯一索引'
|
||||
) comment '优惠券标签关联表';
|
||||
|
||||
create index idx_coupon_id
|
||||
on t_coupon_tag (coupon_id) comment '按优惠券查询标签的索引';
|
||||
|
||||
create index idx_tag_id
|
||||
on t_coupon_tag (tag_id) comment '按标签查询优惠券的索引';
|
||||
|
||||
-- 购物车表
|
||||
create table t_cart
|
||||
(
|
||||
id bigint unsigned auto_increment comment '购物车唯一主键ID'
|
||||
primary key comment '购物车主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
product_id bigint unsigned not null comment '关联商品表主键',
|
||||
quantity int unsigned default 1 not null comment '商品数量',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_user_product
|
||||
unique (user_id, product_id) comment '用户-商品唯一索引'
|
||||
) comment '购物车表';
|
||||
|
||||
create index idx_user_id
|
||||
on t_cart (user_id) comment '按用户查询购物车的索引';
|
||||
|
||||
-- 订单表
|
||||
create table t_order
|
||||
(
|
||||
id bigint unsigned auto_increment comment '订单唯一主键ID'
|
||||
primary key comment '订单主键索引',
|
||||
order_no varchar(50) not null comment '订单编号',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
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',
|
||||
status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
|
||||
constraint uk_order_no
|
||||
unique (order_no) comment '订单编号唯一索引'
|
||||
) comment '订单表';
|
||||
|
||||
create index idx_status
|
||||
on t_order (status) comment '按状态查询订单的索引';
|
||||
|
||||
create index idx_user_id
|
||||
on t_order (user_id) comment '按用户查询订单的索引';
|
||||
|
||||
-- 订单商品表
|
||||
create table t_order_item
|
||||
(
|
||||
id bigint unsigned auto_increment comment '订单商品唯一主键ID'
|
||||
primary key comment '订单商品主键索引',
|
||||
order_id bigint unsigned not null comment '关联订单表主键',
|
||||
product_id bigint unsigned not null comment '关联商品表主键',
|
||||
quantity int unsigned not null comment '商品数量',
|
||||
price decimal(10, 2) not null comment '商品单价',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||
) comment '订单商品表';
|
||||
|
||||
create index idx_order_id
|
||||
on t_order_item (order_id) comment '按订单查询商品的索引';
|
||||
|
||||
|
||||
-- 商品收藏表
|
||||
create table t_wishlist
|
||||
(
|
||||
id bigint unsigned auto_increment comment '收藏记录唯一主键ID'
|
||||
primary key comment '商品收藏主键索引',
|
||||
user_id bigint unsigned not null comment '关联用户表主键',
|
||||
product_id bigint unsigned not null comment '关联商品表主键',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除',
|
||||
constraint uk_user_product
|
||||
unique (user_id, product_id) comment '用户-商品唯一索引'
|
||||
) comment '商品收藏表';
|
||||
|
||||
create index idx_user_id
|
||||
on t_wishlist (user_id) comment '按用户查询收藏的索引';
|
||||
|
||||
create index idx_product_id
|
||||
on t_wishlist (product_id) comment '按商品查询收藏的索引';
|
||||
|
||||
|
||||
-- 美甲师信息表
|
||||
CREATE TABLE t_nail_artist_info (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT COMMENT '美甲师信息唯一主键ID'
|
||||
PRIMARY KEY COMMENT '美甲师信息主键索引',
|
||||
user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户表主键(美甲师用户)',
|
||||
identity VARCHAR(50) DEFAULT '' NULL COMMENT '身份',
|
||||
experience INT UNSIGNED DEFAULT 0 NULL COMMENT '从业年限',
|
||||
skills TEXT NULL COMMENT '技能标签ID集合,多个ID以逗号分隔',
|
||||
rating DECIMAL(3, 1) DEFAULT 0.0 NULL COMMENT '评分',
|
||||
status TINYINT UNSIGNED DEFAULT 1 NULL COMMENT '状态:1-营业中,0-休息中',
|
||||
portfolio TEXT NULL COMMENT '作品集商品ID集合,多个ID以逗号分隔',
|
||||
create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
|
||||
update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
is_delete TINYINT UNSIGNED DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删',
|
||||
CONSTRAINT uk_user_id
|
||||
UNIQUE (user_id) COMMENT '用户ID唯一索引(一个美甲师对应一条信息记录)'
|
||||
) COMMENT '美甲师信息表';
|
||||
|
||||
-- 为美甲师信息表添加索引
|
||||
CREATE INDEX idx_user_id ON t_nail_artist_info (user_id) COMMENT '按用户查询美甲师信息的索引';
|
||||
CREATE INDEX idx_status ON t_nail_artist_info (status) COMMENT '按状态查询美甲师的索引';
|
||||
|
||||
-- 添加美甲师管理相关权限
|
||||
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) VALUES
|
||||
('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师列表和详情', NOW(), NOW(), 0),
|
||||
('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0);
|
||||
|
||||
-- 为管理员分配美甲师管理权限
|
||||
INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by)
|
||||
SELECT
|
||||
1 as user_id,
|
||||
p.id as permission_id,
|
||||
NOW() as create_time,
|
||||
NOW() as update_time,
|
||||
1 as create_by
|
||||
FROM t_permission p
|
||||
WHERE p.is_delete = 0
|
||||
AND p.permission_code IN (
|
||||
'nail_artist:view',
|
||||
'nail_artist:edit'
|
||||
);
|
||||
-- 商品点赞记录表
|
||||
CREATE TABLE t_product_like (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT COMMENT '点赞记录唯一主键ID'
|
||||
PRIMARY KEY COMMENT '商品点赞主键索引',
|
||||
user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户表主键',
|
||||
product_id BIGINT UNSIGNED NOT NULL COMMENT '关联商品表主键',
|
||||
create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
|
||||
update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
is_delete TINYINT UNSIGNED DEFAULT 0 NULL COMMENT '逻辑删除:0-未删除,1-已删除',
|
||||
CONSTRAINT uk_user_product_like
|
||||
UNIQUE (user_id, product_id) COMMENT '用户-商品唯一索引'
|
||||
) COMMENT '商品点赞记录表';
|
||||
|
||||
CREATE INDEX idx_user_id_like ON t_product_like (user_id) COMMENT '按用户查询点赞的索引';
|
||||
CREATE INDEX idx_product_id_like ON t_product_like (product_id) COMMENT '按商品查询点赞的索引';
|
||||
|
||||
|
||||
ALTER TABLE t_order_item ADD COLUMN artist_id BIGINT UNSIGNED DEFAULT NULL COMMENT '关联美甲师ID' AFTER price;
|
||||
@@ -41,6 +41,21 @@
|
||||
</Delete>
|
||||
</DefaultRolloverStrategy>
|
||||
</RollingFile>
|
||||
|
||||
<RollingFile name="SlowRollingFile" fileName="${LOG_HOME}/yuminail-core-slow.log"
|
||||
filePattern="${LOG_HOME}/yuminail-core-slow-%d{yyyy-MM-dd}-%i.log.gz">
|
||||
<PatternLayout pattern="${LOG_PATTERN}"/>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
|
||||
<SizeBasedTriggeringPolicy size="100 MB"/>
|
||||
</Policies>
|
||||
<DefaultRolloverStrategy max="30">
|
||||
<Delete basePath="${LOG_HOME}" maxDepth="1">
|
||||
<IfFileName glob="yuminail-core-slow-*.log.gz"/>
|
||||
<IfLastModified age="30d"/>
|
||||
</Delete>
|
||||
</DefaultRolloverStrategy>
|
||||
</RollingFile>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
@@ -50,14 +65,18 @@
|
||||
<AppenderRef ref="ErrorRollingFile"/>
|
||||
</Root>
|
||||
|
||||
<Logger name="com.xiaowang.yuminailcore" level="DEBUG" additivity="false">
|
||||
<Logger name="com.xiaowang.yuminailcore" level="INFO" additivity="false">
|
||||
<AppenderRef ref="Console"/>
|
||||
<AppenderRef ref="RollingFile"/>
|
||||
<AppenderRef ref="ErrorRollingFile"/>
|
||||
</Logger>
|
||||
|
||||
<Logger name="core-slow" level="WARN" additivity="false">
|
||||
<AppenderRef ref="SlowRollingFile"/>
|
||||
</Logger>
|
||||
|
||||
<Logger name="org.springframework" level="INFO"/>
|
||||
<Logger name="com.alibaba.nacos" level="INFO"/>
|
||||
<Logger name="org.mybatis" level="DEBUG"/>
|
||||
<Logger name="org.mybatis" level="INFO"/>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
|
||||
Reference in New Issue
Block a user