diff --git a/.gitea/scripts/publish-nacos.mjs b/.gitea/scripts/publish-nacos.mjs new file mode 100644 index 00000000..91edc15b --- /dev/null +++ b/.gitea/scripts/publish-nacos.mjs @@ -0,0 +1,88 @@ +import { createHash } from 'node:crypto'; +import { readFile, readdir } from 'node:fs/promises'; +import { join, relative, sep } from 'node:path'; + +const repositoryRoot = process.cwd(); +const configRoot = join(repositoryRoot, 'nacos', 'namespaces', 'prod'); +const nacosUrls = requiredEnvironment('NACOS_URLS').split(',').map((value) => value.trim()).filter(Boolean); +const username = requiredEnvironment('NACOS_USERNAME'); +const password = requiredEnvironment('NACOS_PASSWORD'); +const group = 'DEFAULT_GROUP'; + +const configFiles = await collectYamlFiles(configRoot); +if (configFiles.length === 0) { + throw new Error('nacos/namespaces/prod 下没有可发布的 YAML 配置'); +} + +const token = await login(nacosUrls[0], username, password); +for (const filePath of configFiles) { + const relativePath = relative(configRoot, filePath).split(sep); + if (relativePath.length !== 3 || relativePath[1] !== group) { + throw new Error(`配置路径必须是 /${group}/.yaml:${relativePath.join('/')}`); + } + const [namespace, , dataId] = relativePath; + const content = await readFile(filePath, 'utf8'); + await publish(nacosUrls[0], token, namespace, group, dataId, content); + await verify(nacosUrls.slice(0, 2), token, namespace, group, dataId, content); + console.log(`已发布并校验 ${namespace}/${group}/${dataId}`); +} + +function requiredEnvironment(name) { + const value = process.env[name]; + if (!value) { + throw new Error(`缺少环境变量 ${name}`); + } + return value; +} + +async function collectYamlFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const files = []; + for (const entry of entries) { + const entryPath = join(directory, entry.name); + if (entry.isDirectory()) { + files.push(...await collectYamlFiles(entryPath)); + } else if (entry.isFile() && entry.name.endsWith('.yaml')) { + files.push(entryPath); + } + } + return files.sort(); +} + +async function login(baseUrl, user, secret) { + const body = new URLSearchParams({ username: user, password: secret }); + const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body }); + if (!response.ok) { + throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`); + } + const payload = await response.json(); + if (!payload.accessToken) { + throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`); + } + return payload.accessToken; +} + +async function publish(baseUrl, token, namespace, configGroup, dataId, content) { + const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content }); + const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body }); + const result = await response.text(); + if (!response.ok || result.trim() !== 'true') { + throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`); + } +} + +async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) { + const expectedHash = sha256(expectedContent); + for (const baseUrl of baseUrls) { + const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace }); + const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`); + const content = await response.text(); + if (!response.ok || sha256(content) !== expectedHash) { + throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status}`); + } + } +} + +function sha256(value) { + return createHash('sha256').update(value, 'utf8').digest('hex'); +} diff --git a/.gitea/workflows/publish-nacos.yml b/.gitea/workflows/publish-nacos.yml new file mode 100644 index 00000000..45a4d3e9 --- /dev/null +++ b/.gitea/workflows/publish-nacos.yml @@ -0,0 +1,17 @@ +name: 发布生产 Nacos 配置 + +on: + workflow_dispatch: + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - name: 检出配置源 + uses: actions/checkout@v4 + - name: 发布并校验配置 + env: + NACOS_URLS: ${{ secrets.NACOS_URLS }} + NACOS_USERNAME: ${{ secrets.NACOS_USERNAME }} + NACOS_PASSWORD: ${{ secrets.NACOS_PASSWORD }} + run: node .gitea/scripts/publish-nacos.mjs diff --git a/FD-Core/src/main/resources/application.yaml b/FD-Core/src/main/resources/application.yaml index 29e6a6bf..a5f6cc9a 100644 --- a/FD-Core/src/main/resources/application.yaml +++ b/FD-Core/src/main/resources/application.yaml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:mysql://localhost:3306/FingertipDesigner?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + url: jdbc:mysql://localhost:3306/jayucloud_artlist?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai servlet: multipart: max-file-size: 5MB diff --git a/FD-Core/src/main/resources/bootstrap.yaml b/FD-Core/src/main/resources/bootstrap.yaml index 7bdc6e47..4f4ad7ff 100644 --- a/FD-Core/src/main/resources/bootstrap.yaml +++ b/FD-Core/src/main/resources/bootstrap.yaml @@ -1,14 +1,14 @@ spring: application: - name: fingertip-designer-core + name: jayucloud-artlist-core cloud: nacos: discovery: # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 - server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} # Nacos 命名空间,默认指向开发环境。 - namespace: FingertipDesigner-Dev + namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 服务注册分组。 group: DEFAULT_GROUP # 注册到 Nacos 的服务名。 @@ -18,14 +18,14 @@ spring: # 是否将当前服务注册到 Nacos。 register-enabled: true # Nacos 认证用户名。 - username: xiaowang + username: ${NACOS_USERNAME} # Nacos 认证密码。 - password: 122503wcy.... + password: ${NACOS_PASSWORD} config: # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 - server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} # Nacos 配置中心命名空间,默认指向开发环境。 - namespace: FingertipDesigner-Dev + namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} # Core 服务独有配置文件。 @@ -35,9 +35,9 @@ spring: # 是否启用配置中心。 enabled: true # Nacos 认证用户名。 - username: ${NACOS_USERNAME:xiaowang} + username: ${NACOS_USERNAME} # Nacos 认证密码。 - password: ${NACOS_PASSWORD:122503wcy....} + password: ${NACOS_PASSWORD} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml diff --git a/FD-Gateway/src/main/resources/application.yaml b/FD-Gateway/src/main/resources/application.yaml index a3cc94b6..841c26d1 100644 --- a/FD-Gateway/src/main/resources/application.yaml +++ b/FD-Gateway/src/main/resources/application.yaml @@ -4,91 +4,91 @@ spring: routes: # 前台API路由 - id: product-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/product/** filters: - RewritePath=/api/(?.*), /${remaining} - id: product-like-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/product-like/** filters: - RewritePath=/api/(?.*), /${remaining} - id: shop-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/shop/** filters: - RewritePath=/api/(?.*), /${remaining} - id: user-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/user/** filters: - RewritePath=/api/(?.*), /${remaining} - id: comment-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/comment/** filters: - RewritePath=/api/(?.*), /${remaining} - id: balance-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/balance/** filters: - RewritePath=/api/(?.*), /${remaining} - id: tag-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/tag/** filters: - RewritePath=/api/(?.*), /${remaining} - id: file-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/file/** filters: - RewritePath=/api/(?.*), /${remaining} - id: permission-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/permission/** filters: - RewritePath=/api/(?.*), /${remaining} - id: coupon-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/coupon/** filters: - RewritePath=/api/(?.*), /${remaining} - id: cart-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/cart/** filters: - RewritePath=/api/(?.*), /${remaining} - id: order-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/order/** filters: - RewritePath=/api/(?.*), /${remaining} - id: wishlist-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/wishlist/** filters: - RewritePath=/api/(?.*), /${remaining} - id: nail-artist-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/nail-artist/** filters: - RewritePath=/api/(?.*), /${remaining} - id: legal-agreement-route - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/legal-agreement/** filters: @@ -96,7 +96,7 @@ spring: # 后台管理API路由(/api/admin/** 格式) - id: admin-api-route order: -10 - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/admin/** filters: @@ -104,20 +104,20 @@ spring: # 后台管理API路由(/admin/api/** 格式) - id: admin-route order: -9 - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/admin/api/** filters: - RewritePath=/admin/api/(?.*), /admin/${remaining} - id: admin-auth-compat-route order: -8 - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/admin/auth/** # 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404 - id: frontend-fallback-route order: 100 - uri: lb://fingertip-designer-core + uri: lb://jayucloud-artlist-core predicates: - Path=/api/** filters: diff --git a/FD-Gateway/src/main/resources/bootstrap.yaml b/FD-Gateway/src/main/resources/bootstrap.yaml index 2f7c8d5e..30e0ddf3 100644 --- a/FD-Gateway/src/main/resources/bootstrap.yaml +++ b/FD-Gateway/src/main/resources/bootstrap.yaml @@ -1,27 +1,27 @@ spring: application: - name: fingertip-designer-gateway + name: jayucloud-artlist-gateway cloud: nacos: discovery: # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 - server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} # Nacos 命名空间,默认指向开发环境 - namespace: FingertipDesigner-Dev + namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 服务注册分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} # 注册到 Nacos 的服务名。 service: ${spring.application.name} # Nacos 认证用户名。 - username: ${NACOS_USERNAME:xiaowang} + username: ${NACOS_USERNAME} # Nacos 认证密码。 - password: ${NACOS_PASSWORD:122503wcy....} + password: ${NACOS_PASSWORD} config: # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 - server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} # Nacos 配置中心命名空间,默认指向开发环境。 - namespace: FingertipDesigner-Dev + namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} # Gateway 服务独有配置文件。 @@ -29,9 +29,9 @@ spring: # 所有 Nacos 配置均使用 YAML。 file-extension: yaml # Nacos 认证用户名。 - username: ${NACOS_USERNAME:xiaowang} + username: ${NACOS_USERNAME} # Nacos 认证密码。 - password: ${NACOS_PASSWORD:122503wcy....} + password: ${NACOS_PASSWORD} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml diff --git a/FM-Core/.mvn/wrapper/maven-wrapper.properties b/FM-Core/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..8dea6c22 --- /dev/null +++ b/FM-Core/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/FM-Core/pom.xml b/FM-Core/pom.xml new file mode 100644 index 00000000..c0e3ef42 --- /dev/null +++ b/FM-Core/pom.xml @@ -0,0 +1,313 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + + com.xiaowang + JayuCloud-Salon-Core + 0.0.1 + JayuCloud-Salon-Core + JayuCloud-Salon-Core-店务核心业务微服务 + + + 17 + 2021.0.8 + 2021.0.5.0 + 3.5.3.1 + 1.2.23 + 0.11.5 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + com.mysql + mysql-connector-j + runtime + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + org.springframework.boot + spring-boot-starter-logging + + + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-aop + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + io.jsonwebtoken + jjwt-api + ${jwt.version} + + + io.jsonwebtoken + jjwt-impl + ${jwt.version} + runtime + + + io.jsonwebtoken + jjwt-jackson + ${jwt.version} + runtime + + + + + org.springframework.security + spring-security-crypto + + + + + com.github.ben-manes.caffeine + caffeine + + + + org.apache.httpcomponents + httpclient + + + + + com.qiniu + qiniu-java-sdk + [7.19.0, 7.19.99] + + + + + io.minio + minio + 8.5.17 + + + + + com.aliyun.oss + aliyun-sdk-oss + 3.18.5 + + + + + org.projectlombok + lombok + 1.18.32 + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + + + JayuCloud-Salon-Core + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy-release-jar + package + + run + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + ${java.version} + ${java.version} + + + org.projectlombok + lombok + 1.18.32 + + + + + + + + diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/FingertipDesignerCoreApplication.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/FingertipDesignerCoreApplication.java new file mode 100644 index 00000000..4ce87a16 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/FingertipDesignerCoreApplication.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.scheduling.annotation.EnableScheduling; + +@EnableDiscoveryClient +@EnableScheduling +@SpringBootApplication +/** + * Purpose: FingertipDesignerCoreApplication supports FingertipDesignerCoreApplication.java by holding or executing the fingertip designer core application business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class FingertipDesignerCoreApplication { + + /** + * Purpose: main supports FingertipDesignerCoreApplication.java by holding or executing the main business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void main(String[] args) { + SpringApplication.run(FingertipDesignerCoreApplication.class, args); + } + +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/OperationGuard.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/OperationGuard.java new file mode 100644 index 00000000..aa5cd95b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/OperationGuard.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.annotation; + +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +/** + * Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public @interface OperationGuard { + + String action(); + + OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING; + + int ttlSeconds() default 10; + + String message() default "操作进行中,请勿重复点击"; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/RequirePermission.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/RequirePermission.java new file mode 100644 index 00000000..5f07e0f0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/annotation/RequirePermission.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +/** + * Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public @interface RequirePermission { + + String value() default ""; + + int requireUserType() default -1; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/OperationGuardAspect.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/OperationGuardAspect.java new file mode 100644 index 00000000..dd20ef97 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/OperationGuardAspect.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.aspect; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardService; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.time.Duration; + +@Aspect +@Component +@Order(100) +@RequiredArgsConstructor +/** + * Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OperationGuardAspect { + + /** + * Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OperationGuardService operationGuardService; + + @Around("@annotation(operationGuard)") + /** + * Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Result.error(500, "无法获取请求信息"); + } + + HttpServletRequest request = attributes.getRequest(); + OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire( + request, + operationGuard.action(), + Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds())) + ); + if (!handle.acquired()) { + if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) { + return Result.success(); + } + return Result.error(409, operationGuard.message()); + } + + try { + return joinPoint.proceed(); + } finally { + operationGuardService.release(handle); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/PermissionAspect.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/PermissionAspect.java new file mode 100644 index 00000000..46310d6f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/aspect/PermissionAspect.java @@ -0,0 +1,147 @@ +package com.xiaowang.fingertipdesigner.core.aspect; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; + +@Aspect +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +@RequiredArgsConstructor +/** + * Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class PermissionAspect { + + /** + * Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final PermissionService permissionService; + /** + * Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final PermissionMapper permissionMapper; + /** + * Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + + @Around("@annotation(com.xiaowang.fingertipdesigner.core.annotation.RequirePermission)") + /** + * Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Result.error(403, "无法获取请求信息"); + } + + HttpServletRequest request = attributes.getRequest(); + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error(401, "未登录"); + } + + MethodSignature signature = (MethodSignature) joinPoint.getSignature(); + Method method = signature.getMethod(); + RequirePermission requirePermission = method.getAnnotation(RequirePermission.class); + if (requirePermission == null) { + return joinPoint.proceed(); + } + + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + return Result.error(404, "用户不存在"); + } + + String permissionCode = requirePermission.value(); + Long currentShopId = parseShopId(request.getAttribute("currentShopId")); + if (Integer.valueOf(4).equals(userDO.getType()) + && currentShopId == null + && StringUtils.hasText(permissionCode) + && !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { + return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作"); + } + + if (Integer.valueOf(4).equals(userDO.getType()) + && currentShopId == null + && StringUtils.hasText(permissionCode) + && PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) { + return joinPoint.proceed(); + } + + boolean hasPermission = !StringUtils.hasText(permissionCode) + || permissionService.hasPermission(userId, permissionCode); + if (!hasPermission) { + return Result.error(403, buildPermissionDeniedMessage(permissionCode)); + } + + return joinPoint.proceed(); + } + + /** + * Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildPermissionDeniedMessage(String permissionCode) { + if (!StringUtils.hasText(permissionCode)) { + return "权限不足"; + } + + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + .last("limit 1") + ); + if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) { + return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")"; + } + return "权限不足:缺少权限代码 " + permissionCode; + } + + /** + * Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long parseShopId(Object value) { + if (value instanceof Number number) { + long shopId = number.longValue(); + return shopId > 0 ? shopId : null; + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + long shopId = Long.parseLong(text.trim()); + return shopId > 0 ? shopId : null; + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/BusinessException.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/BusinessException.java new file mode 100644 index 00000000..07a527ff --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/BusinessException.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.common; + +/** + * 业务异常。 + */ +public class BusinessException extends RuntimeException { + + /** + * Purpose: code supports BusinessException.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + 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; + } + + /** + * Purpose: getCode supports BusinessException.java by holding or executing the get code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Integer getCode() { + return code; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/GlobalExceptionHandler.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/GlobalExceptionHandler.java new file mode 100644 index 00000000..3dcd6f3c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/GlobalExceptionHandler.java @@ -0,0 +1,155 @@ +package com.xiaowang.fingertipdesigner.core.common; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.support.DefaultMessageSourceResolvable; +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; + +/** + * 全局异常处理器。 + */ +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024; + + @ExceptionHandler(MethodArgumentNotValidException.class) + /** + * Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + String message = e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(BindException.class) + /** + * Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleBindException(BindException e) { + String message = e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(ConstraintViolationException.class) + /** + * Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleConstraintViolationException(ConstraintViolationException e) { + String message = e.getConstraintViolations().stream() + .map(violation -> violation.getMessage()) + .findFirst() + .orElse("请求参数不合法"); + return Result.error(message); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + /** + * Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) { + log.warn("上传文件超过限制: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + + @ExceptionHandler(MultipartException.class) + /** + * Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleMultipartException(MultipartException e) { + log.warn("文件上传请求异常: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + + @ExceptionHandler(IllegalStateException.class) + /** + * Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleIllegalStateException(IllegalStateException e) { + if (isUploadLimitException(e)) { + log.warn("上传文件超过限制: {}", e.getMessage()); + return Result.error(buildUploadLimitMessage()); + } + log.error("非法状态异常", e); + return Result.error(e.getMessage()); + } + + @ExceptionHandler(BusinessException.class) + /** + * Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleBusinessException(BusinessException e) { + log.warn("业务异常: {}", e.getMessage()); + return Result.error(e.getCode(), e.getMessage()); + } + + @ExceptionHandler(RuntimeException.class) + /** + * Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleRuntimeException(RuntimeException e) { + log.error("运行时异常", e); + return Result.error(e.getMessage()); + } + + @ExceptionHandler(Exception.class) + /** + * Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result handleException(Exception e) { + log.error("系统异常", e); + return Result.error("系统繁忙,请稍后再试"); + } + + /** + * Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUploadLimitMessage() { + return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB"; + } + + /** + * Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isUploadLimitException(Throwable throwable) { + Throwable current = throwable; + while (current != null) { + String message = current.getMessage(); + if (message != null && (message.contains("maximum permitted size") + || message.contains("FileSizeLimitExceededException") + || message.contains("exceeds its maximum permitted size"))) { + return true; + } + current = current.getCause(); + } + return false; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/Result.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/Result.java new file mode 100644 index 00000000..32a7116b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/Result.java @@ -0,0 +1,68 @@ +package com.xiaowang.fingertipdesigner.core.common; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * 统一响应结果类 + * + * @param 数据类型 + * @author xiaowang + * @date 2026-02-12 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Result implements Serializable { + + /** + * Purpose: code supports Result.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer code; + /** + * Purpose: message supports Result.java by holding or executing the message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String message; + /** + * Purpose: data supports Result.java by holding or executing the data business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private T data; + + /** + * Purpose: success supports Result.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result success() { + return new Result<>(200, "操作成功", null); + } + + /** + * Purpose: success supports Result.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result success(T data) { + return new Result<>(200, "操作成功", data); + } + + /** + * Purpose: error supports Result.java by holding or executing the error business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result error(String message) { + return new Result<>(500, message, null); + } + + /** + * Purpose: error supports Result.java by holding or executing the error business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Result error(Integer code, String message) { + return new Result<>(code, message, null); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/dto/AgreementAwareRequest.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/dto/AgreementAwareRequest.java new file mode 100644 index 00000000..f060848d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/dto/AgreementAwareRequest.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.common.dto; + +import java.util.Map; + +/** + * Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface AgreementAwareRequest { + + Boolean getAgreementAccepted(); + + Map getAgreementVersions(); + + String getClientType(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/entity/BaseEntity.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/entity/BaseEntity.java new file mode 100644 index 00000000..34a82b57 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/entity/BaseEntity.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.common.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 实体类基类 + * 提取公共字段,方便后续实体类扩展 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Data +public abstract class BaseEntity { + + /** + * 主键ID + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/vo/PageResultVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/vo/PageResultVO.java new file mode 100644 index 00000000..b5f8adb1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/common/vo/PageResultVO.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.common.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * PageResultVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class PageResultVO { + /** + * Field `list` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List list; + /** + * Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long total; + /** + * Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer page; + /** + * Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer size; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AppCacheProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AppCacheProperties.java new file mode 100644 index 00000000..0ba115f8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AppCacheProperties.java @@ -0,0 +1,60 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 多级缓存配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.cache") +public class AppCacheProperties { + + /** + * Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long localMaxSize = 2048; + + private CacheSpec productDetail = new CacheSpec(120, 900); + + private CacheSpec productList = new CacheSpec(60, 300); + + private CacheSpec productSearch = new CacheSpec(60, 300); + + private CacheSpec shop = new CacheSpec(180, 900); + + private CacheSpec tag = new CacheSpec(300, 1200); + + private CacheSpec objectStorageFile = new CacheSpec(300, 1800); + + private CacheSpec dashboard = new CacheSpec(30, 90); + + @Data + /** + * Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class CacheSpec { + /** + * Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long localTtlSeconds; + /** + * Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long redisTtlSeconds; + + public CacheSpec() { + } + + public CacheSpec(long localTtlSeconds, long redisTtlSeconds) { + this.localTtlSeconds = localTtlSeconds; + this.redisTtlSeconds = redisTtlSeconds; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AuthInterceptor.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AuthInterceptor.java new file mode 100644 index 00000000..de5795c7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/AuthInterceptor.java @@ -0,0 +1,230 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.support.RequestShopContext; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.security.RequestSignatureService; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService; +import com.xiaowang.fingertipdesigner.core.utils.JwtUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Component +@RequiredArgsConstructor +/** + * Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AuthInterceptor implements HandlerInterceptor { + + /** + * Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtUtil jwtUtil; + /** + * Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + /** + * Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserSessionService userSessionService; + /** + * Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestSignatureService requestSignatureService; + /** + * Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestThrottleService requestThrottleService; + + /** + * Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String AUTHORIZATION_HEADER = "Authorization"; + /** + * Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BEARER_PREFIX = "Bearer "; + + @Override + /** + * Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String path = request.getRequestURI(); + + String authHeader = request.getHeader(AUTHORIZATION_HEADER); + + if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + response.setContentType("application/json;charset=UTF-8"); + response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}"); + return false; + } + + String token = authHeader.substring(BEARER_PREFIX.length()); + + if (!jwtUtil.validateToken(token)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期"); + return false; + } + + if (!jwtUtil.isAccessToken(token)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误"); + return false; + } + + Long userId = jwtUtil.getUserIdFromToken(token); + String account = jwtUtil.getAccountFromToken(token); + Long currentShopId = jwtUtil.getShopIdFromToken(token); + String sessionId = jwtUtil.getSessionIdFromToken(token); + String jti = jwtUtil.getJtiFromToken(token); + if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录"); + return false; + } + + UserDO currentUser = userMapper.selectById(userId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效"); + return false; + } + + if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用"); + return false; + } + + boolean adminPath = isAdminPath(path); + if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限"); + return false; + } + + boolean canAccessShop = userShopBindingSupport.canUserAccessShop( + userId, + currentShopId, + adminPath, + currentUser.getType() + ); + if (!canAccessShop) { + String message = currentShopId == null || currentShopId <= 0 + ? "当前登录未选择可用店铺,请重新登录" + : (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + ? "店铺已被冻结" + : "当前登录店铺已停用或账号已失去该店铺访问权限"); + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message); + return false; + } + + if (adminPath + && !Integer.valueOf(4).equals(currentUser.getType()) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + && !isExpiredAdminAllowedPath(path)) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); + return false; + } + + if (requiresSignature(request)) { + try { + requestSignatureService.validateRequest(request, token, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); + return false; + } + } + + if (requiresWriteRateLimit(request)) { + try { + requestThrottleService.checkAuthenticatedWrite(request, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, 429, exception.getMessage()); + return false; + } + } + + request.setAttribute("userId", userId); + request.setAttribute("account", account); + request.setAttribute("userType", currentUser.getType()); + request.setAttribute("accessToken", token); + request.setAttribute("sessionId", sessionId); + request.setAttribute("tokenJti", jti); + request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId); + + return true; + } + + /** + * Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean requiresSignature(HttpServletRequest request) { + return requiresWriteRateLimit(request); + } + + /** + * Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean requiresWriteRateLimit(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalized = method.toUpperCase(); + return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized)); + } + + /** + * Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAdminPath(String path) { + return path.startsWith("/admin/") || path.startsWith("/order/admin/"); + } + + /** + * Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isExpiredAdminAllowedPath(String path) { + return path.startsWith("/admin/auth/") + || path.equals("/admin/user/info") + || path.equals("/permission/list/user/current") + || path.equals("/api/permission/list/user/current") + || path.startsWith("/admin/planning/") + || path.startsWith("/admin/shops/"); + } + + /** + * Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception { + response.setStatus(status); + response.setContentType("application/json;charset=UTF-8"); + response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}"); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/BrandProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/BrandProperties.java new file mode 100644 index 00000000..d9ce1166 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/BrandProperties.java @@ -0,0 +1,24 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 平台品牌文案配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.brand") +public class BrandProperties { + + /** + * 短信模板中的平台名称。 + */ + private String messageTemplateName = "FingertipDesigner"; + + /** + * 管理师注册店铺的默认描述。 + */ + private String managerRegisterShopDescription = "甲屿店务注册店铺"; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientConfig.java new file mode 100644 index 00000000..ab8463b5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientConfig.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.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; + +import java.util.concurrent.TimeUnit; + +@Configuration +/** + * Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class HttpClientConfig { + + @Bean + /** + * Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + 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); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientProperties.java new file mode 100644 index 00000000..89bd6dc3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/HttpClientProperties.java @@ -0,0 +1,45 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.http-client") +/** + * Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class HttpClientProperties { + + /** + * Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int connectTimeoutMs = 3000; + + /** + * Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int readTimeoutMs = 5000; + + /** + * Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int connectionRequestTimeoutMs = 1000; + + /** + * Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxTotalConnections = 200; + + /** + * Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxConnectionsPerRoute = 50; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JacksonConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JacksonConfig.java new file mode 100644 index 00000000..3f15775b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JacksonConfig.java @@ -0,0 +1,64 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.time.LocalDateTime; +import java.io.IOException; +import java.time.format.DateTimeFormatter; + +@Configuration +/** + * Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class JacksonConfig { + + @Bean + /** + * Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() { + return builder -> { + // Snowflake IDs are serialized as strings so the web and mini program do not lose precision. + builder.serializerByType(Long.class, ToStringSerializer.instance); + builder.serializerByType(Long.TYPE, ToStringSerializer.instance); + + JavaTimeModule javaTimeModule = new JavaTimeModule(); + javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer()); + builder.modules(javaTimeModule); + }; + } + + /** + * Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer { + private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + @Override + /** + * Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + String value = parser.getValueAsString(); + if (value == null || value.trim().isEmpty()) { + return null; + } + String normalized = value.trim(); + if (normalized.contains("T")) { + return LocalDateTime.parse(normalized); + } + return LocalDateTime.parse(normalized, SPACE_FORMATTER); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JwtProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JwtProperties.java new file mode 100644 index 00000000..80b977be --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/JwtProperties.java @@ -0,0 +1,44 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * JWT 配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.jwt") +public class JwtProperties { + + /** + * HS512 密钥,生产环境请通过 Nacos 覆盖。 + */ + private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + + /** + * Token 发行者。 + */ + private String issuer = "fingertip-designer"; + + /** + * AccessToken 有效期,单位秒。 + */ + private long accessTokenExpirationSeconds = 2 * 60 * 60; + + /** + * 记住登录 AccessToken 有效期,单位秒。 + */ + private long rememberMeAccessTokenExpirationSeconds = 7 * 24 * 60 * 60; + + /** + * RefreshToken 有效期,单位秒。 + */ + private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; + + /** + * 时钟偏移容忍,单位秒。 + */ + private long clockSkewSeconds = 30; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/LoginLockProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/LoginLockProperties.java new file mode 100644 index 00000000..26c9ec27 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/LoginLockProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.login-lock") +/** + * Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LoginLockProperties { + + /** + * Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int maxFailures = 5; + + /** + * Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long windowSeconds = 600; + + /** + * Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long lockSeconds = 900; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyBatisPlusConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyBatisPlusConfig.java new file mode 100644 index 00000000..87c0feb3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyBatisPlusConfig.java @@ -0,0 +1,87 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * MyBatis-Plus配置类 + * 配置分页、乐观锁和防止全表更新等插件 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Configuration +@MapperScan({ + "com.xiaowang.fingertipdesigner.core.modules.artist.mapper", + "com.xiaowang.fingertipdesigner.core.modules.auth.mapper", + "com.xiaowang.fingertipdesigner.core.modules.content.mapper", + "com.xiaowang.fingertipdesigner.core.modules.file.mapper", + "com.xiaowang.fingertipdesigner.core.modules.integration.mapper", + "com.xiaowang.fingertipdesigner.core.modules.inventory.mapper", + "com.xiaowang.fingertipdesigner.core.modules.marketing.mapper", + "com.xiaowang.fingertipdesigner.core.modules.message.mapper", + "com.xiaowang.fingertipdesigner.core.modules.order.mapper", + "com.xiaowang.fingertipdesigner.core.modules.payment.mapper", + "com.xiaowang.fingertipdesigner.core.modules.planning.mapper", + "com.xiaowang.fingertipdesigner.core.modules.product.mapper", + "com.xiaowang.fingertipdesigner.core.modules.security.mapper", + "com.xiaowang.fingertipdesigner.core.modules.shop.mapper", + "com.xiaowang.fingertipdesigner.core.modules.system.mapper", + "com.xiaowang.fingertipdesigner.core.modules.user.mapper" +}) +public class MyBatisPlusConfig { + + /** + * 配置MyBatis-Plus插件 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + + // 1. 分页插件 + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + + // 2. 乐观锁插件 + interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + + // 3. 防止全表更新与删除插件 + interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); + + return interceptor; + } + + @Bean + /** + * Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) { + return new IdentifierGenerator() { + @Override + /** + * Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Number nextId(Object entity) { + return snowflakeIdGenerator.nextId(); + } + + @Override + /** + * Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextUUID(Object entity) { + return snowflakeIdGenerator.nextIdString(); + } + }; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyMetaObjectHandler.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyMetaObjectHandler.java new file mode 100644 index 00000000..c7de16ad --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/MyMetaObjectHandler.java @@ -0,0 +1,41 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +/** + * MyBatis-Plus 自动填充配置 + * 用于自动填充实体类中的创建时间、更新时间等字段 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Slf4j +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + + @Override + /** + * Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void insertFill(MetaObject metaObject) { + log.info("start insert fill ...."); + this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); + this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + } + + @Override + /** + * Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void updateFill(MetaObject metaObject) { + log.info("start update fill ...."); + this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/ObjectStorageProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/ObjectStorageProperties.java new file mode 100644 index 00000000..2e36f118 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/ObjectStorageProperties.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.util.Arrays; +import java.util.List; + +@Data +@Component +@Validated +@ConfigurationProperties(prefix = "object-storage") +public class ObjectStorageProperties { + + @NotEmpty + private List providerOrder = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); + + @NotEmpty + private List replicaRequiredProviders = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS"); + + private String primaryProvider; + + private String backupProvider; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @NotBlank + private String backupQueueName; + + @NotBlank + private String backupExchangeName; + + @NotBlank + private String backupRoutingKey; + + @NotNull + @Min(1) + private Integer backupRetryBatchLimit; + + @NotBlank + private String backupRetryCron; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RabbitMQConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RabbitMQConfig.java new file mode 100644 index 00000000..bb79e110 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RabbitMQConfig.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.DirectExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; +import org.springframework.amqp.support.converter.MessageConverter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class RabbitMQConfig { + + public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue"; + public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange"; + public static final String EXAMPLE_ROUTING_KEY = "fingertip-designer.example.routing.key"; + + private final ObjectStorageProperties objectStorageProperties; + + @Bean + public MessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } + + @Bean + public Queue exampleQueue() { + return new Queue(EXAMPLE_QUEUE, true); + } + + @Bean + public DirectExchange exampleExchange() { + return new DirectExchange(EXAMPLE_EXCHANGE); + } + + @Bean + public Binding exampleBinding() { + return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY); + } + + @Bean + public Queue objectStorageBackupQueue() { + return new Queue(objectStorageProperties.getBackupQueueName(), true); + } + + @Bean + public DirectExchange objectStorageBackupExchange() { + return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false); + } + + @Bean + public Binding objectStorageBackupBinding() { + return BindingBuilder.bind(objectStorageBackupQueue()) + .to(objectStorageBackupExchange()) + .with(objectStorageProperties.getBackupRoutingKey()); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RateLimitProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RateLimitProperties.java new file mode 100644 index 00000000..f86e58d3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RateLimitProperties.java @@ -0,0 +1,56 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 限流配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit") +public class RateLimitProperties { + + private LimitRule login = new LimitRule(10, 60); + + private LimitRule register = new LimitRule(5, 300); + + private LimitRule sendCode = new LimitRule(5, 60); + + private LimitRule resetPassword = new LimitRule(5, 600); + + private LimitRule wechatMiniLogin = new LimitRule(10, 60); + + private LimitRule agreementRead = new LimitRule(60, 60); + + private LimitRule authenticatedWrite = new LimitRule(80, 60); + + private LimitRule orderCreate = new LimitRule(10, 60); + + @Data + /** + * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class LimitRule { + /** + * Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private int limit; + /** + * Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long windowSeconds; + + public LimitRule() { + } + + public LimitRule(int limit, long windowSeconds) { + this.limit = limit; + this.windowSeconds = windowSeconds; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RedisConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RedisConfig.java new file mode 100644 index 00000000..4a92bee4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RedisConfig.java @@ -0,0 +1,56 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * Redis配置类 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport { + + @Bean + /** + * Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + + // key采用String的序列化方式 + template.setKeySerializer(stringRedisSerializer); + // hash的key也采用String的序列化方式 + template.setHashKeySerializer(stringRedisSerializer); + // value序列化方式采用jackson + template.setValueSerializer(jackson2JsonRedisSerializer); + // hash的value序列化方式采用jackson + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + + return template; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RequestSignatureProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RequestSignatureProperties.java new file mode 100644 index 00000000..ac6c0c96 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/RequestSignatureProperties.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 请求签名配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.signature") +public class RequestSignatureProperties { + + /** + * 是否启用签名校验。 + */ + private boolean enabled = true; + + /** + * 时间窗口,单位秒。 + */ + private long windowSeconds = 300; + + /** + * nonce 额外保留时间,单位秒。 + */ + private long nonceRetentionSeconds = 600; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SecurityHeadersFilter.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SecurityHeadersFilter.java new file mode 100644 index 00000000..4264ac66 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SecurityHeadersFilter.java @@ -0,0 +1,34 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import org.springframework.stereotype.Component; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +/** + * Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityHeadersFilter implements Filter { + + @Override + /** + * Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (response instanceof HttpServletResponse httpResponse) { + httpResponse.setHeader("X-Content-Type-Options", "nosniff"); + httpResponse.setHeader("X-Frame-Options", "DENY"); + httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin"); + httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:"); + } + chain.doFilter(request, response); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLogProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLogProperties.java new file mode 100644 index 00000000..fa1446e8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLogProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.slow-request") +/** + * Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SlowRequestLogProperties { + + /** + * Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean enabled = true; + + /** + * Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long thresholdMs = 300; + + /** + * Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean logResponseHeaderRequestId = true; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLoggingInterceptor.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLoggingInterceptor.java new file mode 100644 index 00000000..a30e118a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/SlowRequestLoggingInterceptor.java @@ -0,0 +1,172 @@ +package com.xiaowang.fingertipdesigner.core.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 +/** + * Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SlowRequestLoggingInterceptor implements HandlerInterceptor { + + /** + * Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + 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"); + + /** + * Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SlowRequestLogProperties properties; + + public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) { + this.properties = properties; + } + + @Override + /** + * Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + 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 + /** + * Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + 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) + ); + } + + /** + * Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveRequestId(HttpServletRequest request) { + String requestId = request.getHeader(REQUEST_ID_HEADER); + return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", ""); + } + + /** + * Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveControllerMethod(Object handler) { + if (handler instanceof HandlerMethod handlerMethod) { + return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName(); + } + return ""; + } + + /** + * Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + 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(); + } + + /** + * Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(String value) { + if (!StringUtils.hasText(value)) { + return ""; + } + return value.replace('\n', '_').replace('\r', '_'); + } + + /** + * Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toStringValue(Object value) { + return value == null ? "" : value.toString(); + } + + /** + * Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long castLong(Object value) { + return value instanceof Long ? (Long) value : null; + } + + /** + * Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer castInteger(Object value) { + return value instanceof Integer ? (Integer) value : null; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/UploadSecurityProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/UploadSecurityProperties.java new file mode 100644 index 00000000..49fb0f7a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/UploadSecurityProperties.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.upload") +/** + * Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UploadSecurityProperties { + + /** + * Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long maxSize = 10 * 1024 * 1024; + + private long maxTotalSize = 500L * 1024 * 1024; + + private List allowedMimeTypes = new ArrayList<>(List.of( + "image/jpeg", + "image/png", + "image/webp", + "image/gif" + )); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WebMvcConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WebMvcConfig.java new file mode 100644 index 00000000..9c8ea74f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WebMvcConfig.java @@ -0,0 +1,75 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@RequiredArgsConstructor +/** + * Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class WebMvcConfig implements WebMvcConfigurer { + + /** + * Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AuthInterceptor authInterceptor; + /** + * Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor; + + @Override + /** + * Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(slowRequestLoggingInterceptor) + .addPathPatterns("/**") + .order(-100); + + registry.addInterceptor(authInterceptor) + .addPathPatterns("/**") + .order(0) + .excludePathPatterns( + "/user/login", + "/user/register", + "/user/check/**", + "/user/refresh-token", + "/user/send-verification-code", + "/user/phone-login", + "/user/wechat-mini/**", + "/user/reset-password-by-phone", + "/legal-agreement/current", + "/legal-agreement/current/**", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", + "/product/get/**", + "/product/list/**", + "/comment/list/product/**", + "/api/comment/list/product/**", + "/nail-artist/profile/**", + "/nail-artist/*/availability", + "/nail-artist/*/reviews", + "/shop/get/**", + "/shop/trust-profile/**", + "/shop/list", + "/shop/list/public", + "/shop/list/simple", + "/tag/list/all", + "/tag/list/filter-options", + "/file/get-signed-url/**", + "/admin/auth/login", + "/admin/auth/login-shops/**", + "/admin/auth/refresh", + "/error", + "/health/**" + ); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WechatMiniProperties.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WechatMiniProperties.java new file mode 100644 index 00000000..fa5d20bd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/config/WechatMiniProperties.java @@ -0,0 +1,40 @@ +package com.xiaowang.fingertipdesigner.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 微信小程序登录配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.wechat.mini") +public class WechatMiniProperties { + + /** + * Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String appId; + /** + * Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String appSecret; + /** + * Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session"; + /** + * Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"; + /** + * Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer accessTokenBufferSeconds = 60; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/filter/RequestBodyCacheFilter.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/filter/RequestBodyCacheFilter.java new file mode 100644 index 00000000..2599b7c3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/filter/RequestBodyCacheFilter.java @@ -0,0 +1,60 @@ +package com.xiaowang.fingertipdesigner.core.filter; + +import com.xiaowang.fingertipdesigner.core.support.security.CachedBodyHttpServletRequest; +import com.xiaowang.fingertipdesigner.core.support.security.RequestSignatureService; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 缓存 JSON 请求体,供签名校验复用。 + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestBodyCacheFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + if (!shouldWrap(request)) { + filterChain.doFilter(request, response); + return; + } + + byte[] body = StreamUtils.copyToByteArray(request.getInputStream()); + CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body); + wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body); + filterChain.doFilter(wrappedRequest, response); + } + + /** + * Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean shouldWrap(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalizedMethod = method.toUpperCase(); + if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) { + return false; + } + String contentType = request.getContentType(); + if (!StringUtils.hasText(contentType)) { + return false; + } + String normalizedType = contentType.toLowerCase(); + return normalizedType.contains("application/json"); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/admin/AdminWorkbenchController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/admin/AdminWorkbenchController.java new file mode 100644 index 00000000..431e40a4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/admin/AdminWorkbenchController.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.analytics.service.WorkbenchService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/workbench") +@RequiredArgsConstructor +public class AdminWorkbenchController { + + private final AdminScopeHelper adminScopeHelper; + private final WorkbenchService workbenchService; + + @GetMapping("/summary") + @RequirePermission("workbench:view") + public Result summary(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + Long artistId = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; + return Result.success(workbenchService.getWorkbench(shopId, artistId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/front/DashboardController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/front/DashboardController.java new file mode 100644 index 00000000..447f10a4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/controller/front/DashboardController.java @@ -0,0 +1,451 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.controller.front; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.analytics.service.OperationsAnalyticsService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.DashboardStatsVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.HotProductVO; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.RecentActivityVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/admin/dashboard") +@RequiredArgsConstructor +/** + * DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class DashboardController { + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderItemMapper orderItemMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + private final OperationsAnalyticsService operationsAnalyticsService; + + @GetMapping("/stats") + @RequirePermission("dashboard:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getDashboardStats(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopIdScope = resolveShopScope(currentUser); + String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); + DashboardStatsVO stats = multiLevelCacheService.getOrLoad( + "cache:dashboard:stats:" + cacheScope, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> buildDashboardStats(currentUser, shopIdScope) + ); + return Result.success(stats); + } + + @GetMapping("/analytics") + @RequirePermission("analytics:view") + public Result getAnalytics(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopIdScope = resolveShopScope(currentUser); + Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; + return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope)); + } + + /** + * Run business method `buildDashboardStats`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopIdScope parameter `shopIdScope` supplied by the caller + * @return private DashboardStatsVO result consumed by the caller or returned to the frontend + */ + private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) { + DashboardStatsVO stats = new DashboardStatsVO(); + Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null; + + if (currentUser != null) { + // 根据用户类型显示不同的数据 + if (currentUser.getType() == 4) { // 管理员 + stats.setTotalUsers(userMapper.selectCount(null)); + stats.setTotalProducts(productMapper.selectCount(null)); + stats.setTotalShops(shopMapper.selectCount(null)); + stats.setTodayOrders(getTodayOrders(null)); + stats.setTotalCustomers(countUsers(null, 0, null, null)); + stats.setTotalArtists(countUsers(null, 3, null, null)); + } else { // 店长或美甲师 + Long shopId = currentUser.getShopId(); + if (shopId != null) { + shopIdScope = shopId; + // 只显示当前店铺的数据 + stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false)); + stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper().eq(ProductDO::getShopId, shopId))); + stats.setTotalShops(0L); // 非管理员不显示店铺数量 + stats.setTodayOrders(getTodayOrders(shopId)); + stats.setTotalCustomers(countUsers(shopId, 0, null, null)); + stats.setTotalArtists(countUsers(shopId, 3, null, null)); + } else { + // 没有店铺ID的情况 + stats.setTotalUsers(0L); + stats.setTotalProducts(0L); + stats.setTotalShops(0L); + stats.setTodayOrders(0L); + stats.setTotalCustomers(0L); + stats.setTotalArtists(0L); + } + } + } else { + // 无法获取用户信息的情况 + stats.setTotalUsers(0L); + stats.setTotalProducts(0L); + stats.setTotalShops(0L); + stats.setTodayOrders(0L); + stats.setTotalCustomers(0L); + stats.setTotalArtists(0L); + } + + LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); + LocalDateTime weekStart = todayStart.minusDays(6); + stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null)); + stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null)); + stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null)); + stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null)); + stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null)); + stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null)); + long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null); + long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null); + stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders); + stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null)); + + stats.setHotProducts(getHotProducts(shopIdScope)); + stats.setRecentActivities(getRecentActivities(shopIdScope)); + + return stats; + } + + /** + * Run business method `resolveShopScope`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveShopScope(UserDO currentUser) { + if (currentUser == null || currentUser.getType() == 4) { + return null; + } + return currentUser.getShopId(); + } + + /** + * Purpose: countUsers supports DashboardController.java by holding or executing the count users business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (type != null) { + wrapper.eq(UserDO::getType, type); + } + if (from != null) { + wrapper.ge(UserDO::getCreateTime, from); + } + if (to != null) { + wrapper.le(UserDO::getCreateTime, to); + } + if (shopId != null) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); + if (userIds.isEmpty()) { + return 0L; + } + wrapper.in(UserDO::getId, userIds); + } + return userMapper.selectCount(wrapper); + } + + /** + * Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { + return (long) listScopedOrders(shopId, artistId, status, from, to).size(); + } + + /** + * Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) { + return listScopedOrders(shopId, artistId, null, from, to).stream() + .map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount()) + .filter(amount -> amount != null) + .reduce(BigDecimal.ZERO, BigDecimal::add); + } + + /** + * Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + wrapper.eq(OrderDO::getShopId, shopId); + } + if (status != null) { + wrapper.eq(OrderDO::getStatus, status); + } + if (from != null) { + wrapper.ge(OrderDO::getCreateTime, from); + } + if (to != null) { + wrapper.le(OrderDO::getCreateTime, to); + } + if (artistId != null) { + Set orderIds = listOrderIdsByArtist(artistId); + if (orderIds.isEmpty()) { + return Collections.emptyList(); + } + wrapper.in(OrderDO::getId, orderIds); + } + return orderMapper.selectList(wrapper); + } + + /** + * Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set listOrderIdsByArtist(Long artistId) { + List items = orderItemMapper.selectList(new LambdaQueryWrapper() + .select(OrderItemDO::getOrderId) + .eq(OrderItemDO::getArtistId, artistId)); + return items.stream() + .map(OrderItemDO::getOrderId) + .filter(id -> id != null) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getTodayOrders(Long shopId) { + // 获取今天的开始时间 + LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); + String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + + if (shopId != null) { + // 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺 + java.util.Map result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; + } else { + // 管理员查询所有订单 + java.util.Map result = orderItemMapper.countTodayOrders(todayStartStr); + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getHotProducts(Long shopId) { + // 通过订单商品表统计每个商品的订单数量,按订单数量排序 + // 使用SQL查询获取商品及其订单数量 + List> productOrderCounts = orderItemMapper.selectMaps( + new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper() + .select("product_id, COUNT(*) as order_count") + .groupBy("product_id") + .orderByDesc("order_count") + .last("LIMIT 5") + ); + + List hotProducts = new ArrayList<>(); + + // 遍历查询结果,获取商品详情 + for (Map map : productOrderCounts) { + Long productId = Long.valueOf(map.get("product_id").toString()); + ProductDO product = productMapper.selectById(productId); + + if (product != null && (shopId == null || shopId.equals(product.getShopId()))) { + HotProductVO vo = new HotProductVO(); + BeanUtils.copyProperties(product, vo); + vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); + hotProducts.add(vo); + } + } + + // 如果按订单数量查询没有结果,使用点赞数作为备选 + if (hotProducts.isEmpty()) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + wrapper.orderByDesc(ProductDO::getLikeCount) + .last("LIMIT 5"); + List products = productMapper.selectList(wrapper); + + hotProducts = products.stream().map(product -> { + HotProductVO vo = new HotProductVO(); + BeanUtils.copyProperties(product, vo); + vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0); + return vo; + }).collect(Collectors.toList()); + } + + return hotProducts; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getRecentActivities(Long shopId) { + List activities = new ArrayList<>(); + + LambdaQueryWrapper userWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false); + if (userIds.isEmpty()) { + userWrapper.eq(UserDO::getId, -1L); + } else { + userWrapper.in(UserDO::getId, userIds); + } + } + userWrapper.orderByDesc(UserDO::getCreateTime) + .last("LIMIT 3"); + List recentUsers = userMapper.selectList(userWrapper); + + for (UserDO user : recentUsers) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(user.getId()); + vo.setType("user"); + vo.setTitle("新用户注册"); + vo.setDescription("用户\"" + user.getNickname() + "\"注册成功"); + vo.setTime(user.getCreateTime()); + vo.setColor(""); + activities.add(vo); + } + + LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + productWrapper.eq(ProductDO::getShopId, shopId); + } + productWrapper.orderByDesc(ProductDO::getCreateTime) + .last("LIMIT 2"); + List recentProducts = productMapper.selectList(productWrapper); + + for (ProductDO product : recentProducts) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(product.getId()); + vo.setType("product"); + vo.setTitle("新品上架"); + vo.setDescription("新品\"" + product.getTitle() + "\"已上架"); + vo.setTime(product.getCreateTime()); + vo.setColor("blue"); + activities.add(vo); + } + + LambdaQueryWrapper commentWrapper = new LambdaQueryWrapper<>(); + if (shopId != null) { + commentWrapper.eq(CommentDO::getShopId, shopId); + } + commentWrapper.orderByDesc(CommentDO::getCreateTime) + .last("LIMIT 2"); + List recentComments = commentMapper.selectList(commentWrapper); + + for (CommentDO comment : recentComments) { + RecentActivityVO vo = new RecentActivityVO(); + vo.setId(comment.getId()); + vo.setType("comment"); + vo.setTitle("用户评论"); + String content = comment.getCommentContent(); + if (content != null && content.length() > 20) { + content = content.substring(0, 20) + "..."; + } + vo.setDescription(content != null ? content : "用户发表了评论"); + vo.setTime(comment.getCreateTime()); + vo.setColor("green"); + activities.add(vo); + } + + activities.sort((a, b) -> b.getTime().compareTo(a.getTime())); + + return activities.stream().limit(5).collect(Collectors.toList()); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/OperationsAnalyticsService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/OperationsAnalyticsService.java new file mode 100644 index 00000000..beafef99 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/OperationsAnalyticsService.java @@ -0,0 +1,7 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.service; + +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO; + +public interface OperationsAnalyticsService { + OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/WorkbenchService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/WorkbenchService.java new file mode 100644 index 00000000..8ce74030 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/WorkbenchService.java @@ -0,0 +1,7 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.service; + +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO; + +public interface WorkbenchService { + StoreWorkbenchVO getWorkbench(Long shopId, Long artistId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java new file mode 100644 index 00000000..113b2b73 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserGrowthRecordDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserGrowthRecordMapper; +import com.xiaowang.fingertipdesigner.core.modules.analytics.service.OperationsAnalyticsService; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.OperationsAnalyticsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService { + + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final ProductMapper productMapper; + private final UserGrowthRecordMapper userGrowthRecordMapper; + + @Override + public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) { + List orders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, OrderDO::getShopId, shopId) + .eq(OrderDO::getIsDelete, 0)); + if (artistId != null) { + Set orderIds = new HashSet<>(); + orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .eq(OrderItemDO::getIsDelete, 0)) + .forEach(item -> orderIds.add(item.getOrderId())); + orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); + } + OperationsAnalyticsVO vo = new OperationsAnalyticsVO(); + vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)) + .stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); + vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)) + .stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum()); + vo.setCartCount(0L); + vo.setOrderCount((long) orders.size()); + vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count()); + vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); + vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getSourceType, "REBOOK"))); + vo.setTotalAmount(orders.stream() + .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/WorkbenchServiceImpl.java new file mode 100644 index 00000000..9fcec68b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/service/impl/WorkbenchServiceImpl.java @@ -0,0 +1,146 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.fingertipdesigner.core.modules.inventory.mapper.InventoryItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.analytics.service.WorkbenchService; +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus; +import com.xiaowang.fingertipdesigner.core.modules.analytics.vo.StoreWorkbenchVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Service +@RequiredArgsConstructor +public class WorkbenchServiceImpl implements WorkbenchService { + + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final AfterSaleMapper afterSaleMapper; + private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + private final InventoryItemMapper inventoryItemMapper; + private final ArtistScheduleMapper artistScheduleMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + + @Override + public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) { + LocalDateTime todayStart = LocalDate.now().atStartOfDay(); + LocalDateTime tomorrowStart = todayStart.plusDays(1); + List orders = scopedOrders(shopId, artistId); + StoreWorkbenchVO vo = new StoreWorkbenchVO(); + vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count()); + vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count()); + vo.setPendingAfterSaleCount(countAfterSales(shopId)); + vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId)); + vo.setLowStockItemCount(countLowStock(shopId)); + vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate())); + vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart)); + vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setServiceAmount(orders.stream() + .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) + .reduce(BigDecimal.ZERO, BigDecimal::add)); + vo.setAverageRating(resolveRating(artistId)); + return vo; + } + + private boolean isActionableOrder(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private List scopedOrders(Long shopId, Long artistId) { + List orders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, OrderDO::getShopId, shopId) + .eq(OrderDO::getIsDelete, 0)); + if (artistId == null) { + return orders; + } + Set orderIds = new HashSet<>(); + orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .eq(OrderItemDO::getIsDelete, 0)) + .forEach(item -> orderIds.add(item.getOrderId())); + return orders.stream().filter(order -> orderIds.contains(order.getId())).toList(); + } + + private long countAfterSales(Long shopId) { + return afterSaleMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, AfterSaleDO::getShopId, shopId) + .eq(AfterSaleDO::getStatus, "PENDING") + .eq(AfterSaleDO::getIsDelete, 0)); + } + + private long countArtistChanges(Long shopId, Long artistId) { + return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId) + .eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId) + .eq(OrderArtistChangeRequestDO::getStatus, "PENDING") + .eq(OrderArtistChangeRequestDO::getIsDelete, 0)); + } + + private long countLowStock(Long shopId) { + return inventoryItemMapper.selectList(new LambdaQueryWrapper() + .eq(shopId != null, InventoryItemDO::getShopId, shopId) + .eq(InventoryItemDO::getIsDelete, 0)) + .stream() + .filter(item -> item.getStockQuantity() != null + && item.getWarningThreshold() != null + && item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0) + .count(); + } + + private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) { + return artistScheduleMapper.selectCount(new LambdaQueryWrapper() + .eq(shopId != null, ArtistScheduleDO::getShopId, shopId) + .eq(artistId != null, ArtistScheduleDO::getArtistId, artistId) + .ge(ArtistScheduleDO::getWorkDate, today) + .lt(ArtistScheduleDO::getWorkDate, today.plusDays(3)) + .eq(ArtistScheduleDO::getIsDelete, 0)); + } + + private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) { + if (artistId == null) { + return 0L; + } + return orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getArtistId, artistId) + .ge(OrderItemDO::getAppointmentTime, todayStart) + .lt(OrderItemDO::getAppointmentTime, tomorrowStart) + .eq(OrderItemDO::getIsDelete, 0)) + .size(); + } + + private BigDecimal resolveRating(Long artistId) { + if (artistId == null) { + return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); + } + BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP); + } + + private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) { + return value != null && !value.isBefore(start) && value.isBefore(end); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/DashboardStatsVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/DashboardStatsVO.java new file mode 100644 index 00000000..a5f01edf --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/DashboardStatsVO.java @@ -0,0 +1,89 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.modules.product.vo.HotProductVO; +@Data +/** + * DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class DashboardStatsVO { + /** + * Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalUsers; + /** + * Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalProducts; + /** + * Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long totalShops; + /** + * Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long todayOrders; + /** + * Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal totalOrderAmount; + /** + * Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal todayOrderAmount; + /** + * Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal weekOrderAmount; + /** + * Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long totalCustomers; + /** + * Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long totalArtists; + /** + * Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newCustomersToday; + /** + * Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newCustomers7Days; + /** + * Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long newOrders7Days; + /** + * Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long pendingOrders; + /** + * Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long completedOrders; + /** + * Field `hotProducts` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List hotProducts; + /** + * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List recentActivities; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/OperationsAnalyticsVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/OperationsAnalyticsVO.java new file mode 100644 index 00000000..1fcf8ec4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/OperationsAnalyticsVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OperationsAnalyticsVO { + private Long viewCount; + private Long favoriteCount; + private Long cartCount; + private Long orderCount; + private Long paidOrderCount; + private Long completedOrderCount; + private Long reviewCount; + private Long rebookCount; + private BigDecimal totalAmount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/RecentActivityVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/RecentActivityVO.java new file mode 100644 index 00000000..bb6b23fd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/RecentActivityVO.java @@ -0,0 +1,37 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * RecentActivityVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class RecentActivityVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String type; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + /** + * Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime time; + /** + * Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String color; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/StoreWorkbenchVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/StoreWorkbenchVO.java new file mode 100644 index 00000000..fd4032dc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/analytics/vo/StoreWorkbenchVO.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.analytics.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class StoreWorkbenchVO { + private Long todayOrderCount; + private Long pendingOrderCount; + private Long pendingAfterSaleCount; + private Long pendingArtistChangeCount; + private Long lowStockItemCount; + private Long scheduleReminderCount; + private Long todayServiceCount; + private Long completedServiceCount; + private BigDecimal serviceAmount; + private BigDecimal averageRating; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminArtistScheduleController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminArtistScheduleController.java new file mode 100644 index 00000000..0b0f1877 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminArtistScheduleController.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDate; +import java.util.List; + +@RestController +@RequestMapping("/admin/artist-schedule") +@RequiredArgsConstructor +public class AdminArtistScheduleController { + + private final ArtistScheduleService artistScheduleService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @PostMapping("/save") + @RequirePermission("schedule:edit") + public Result save(HttpServletRequest request, @RequestBody ArtistScheduleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + try { + ArtistScheduleVO result = artistScheduleService.saveSchedule(dto); + securityAuditSupport.success(request, SecurityAuditActions.SCHEDULE_UPDATE, "artistId=" + dto.getArtistId() + ",date=" + dto.getWorkDate()); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SCHEDULE_UPDATE, "artistId=" + dto.getArtistId() + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/list") + @RequirePermission("schedule:view") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) Long artistId, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(artistScheduleService.listSchedules(shopId, artistId, startDate, endDate)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminNailArtistController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminNailArtistController.java new file mode 100644 index 00000000..85baa110 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/admin/AdminNailArtistController.java @@ -0,0 +1,142 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/admin/nail-artist") +@RequiredArgsConstructor +/** + * AdminNailArtistController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminNailArtistController { + + /** + * Purpose: USER_NOT_FOUND_MESSAGE supports AdminNailArtistController.java by holding or executing the user not found message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String USER_NOT_FOUND_MESSAGE = "用户信息不存在"; + /** + * Purpose: VIEW_SCOPE_MESSAGE supports AdminNailArtistController.java by holding or executing the view scope message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIEW_SCOPE_MESSAGE = "当前登录店铺无权查看该美甲师,请切换到所属店铺后重试"; + /** + * Purpose: EDIT_SCOPE_MESSAGE supports AdminNailArtistController.java by holding or executing the edit scope message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String EDIT_SCOPE_MESSAGE = "当前登录店铺无权编辑该美甲师,请切换到所属店铺后重试"; + /** + * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final NailArtistInfoService nailArtistInfoService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @RequirePermission("nail_artist:view") + @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getAllNailArtists(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (currentUser == null) { + return Result.error(USER_NOT_FOUND_MESSAGE); + } + + List nailArtistInfoDTOList; + if (Integer.valueOf(4).equals(currentUser.getType())) { + nailArtistInfoDTOList = nailArtistInfoService.getAllNailArtists(); + } else if (Integer.valueOf(2).equals(currentUser.getType())) { + nailArtistInfoDTOList = nailArtistInfoService.getByShopId(currentUser.getShopId()); + } else { + return Result.error("权限不足:缺少权限【查看美甲师】(nail_artist:view)"); + } + + return Result.success(nailArtistInfoDTOList); + } + + @RequirePermission("nail_artist:view") + @GetMapping("/get/{userId}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getNailArtistInfo(@PathVariable Long userId, HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (currentUser == null) { + return Result.error(USER_NOT_FOUND_MESSAGE); + } + + if (!Integer.valueOf(4).equals(currentUser.getType())) { + if (Integer.valueOf(2).equals(currentUser.getType())) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, VIEW_SCOPE_MESSAGE); + } else if (Integer.valueOf(3).equals(currentUser.getType())) { + if (!currentUser.getId().equals(userId)) { + return Result.error(VIEW_SCOPE_MESSAGE); + } + } else { + return Result.error("权限不足:缺少权限【查看美甲师】(nail_artist:view)"); + } + } + + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + return Result.success(nailArtistInfoDTO); + } + + @RequirePermission("nail_artist:edit") + @PostMapping("/save") + @OperationGuard(action = "admin-nail-artist-save", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param nailArtistInfoDTO parameter `nailArtistInfoDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (currentUser == null) { + return Result.error(USER_NOT_FOUND_MESSAGE); + } + + if (!Integer.valueOf(4).equals(currentUser.getType())) { + if (Integer.valueOf(2).equals(currentUser.getType())) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, nailArtistInfoDTO.getUserId(), EDIT_SCOPE_MESSAGE); + } else if (Integer.valueOf(3).equals(currentUser.getType())) { + if (!currentUser.getId().equals(nailArtistInfoDTO.getUserId())) { + return Result.error(EDIT_SCOPE_MESSAGE); + } + } else { + return Result.error("权限不足:缺少权限【编辑美甲师】(nail_artist:edit)"); + } + } + + NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + return Result.success(saved); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/front/NailArtistController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/front/NailArtistController.java new file mode 100644 index 00000000..eea2389f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/controller/front/NailArtistController.java @@ -0,0 +1,68 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 美甲师信息Controller(前台) + */ +@RestController +@RequestMapping("/nail-artist") +public class NailArtistController { + + @Autowired + /** + * Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoService nailArtistInfoService; + + /** + * 获取所有可用的美甲师信息(前台使用) + */ + @GetMapping("/list") + public Result> getAllAvailableNailArtists() { + List nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists(); + return Result.success(nailArtistInfoDTOList); + } + + @GetMapping("/list/shop/{shopId}") + public Result> listByShopId(@PathVariable Long shopId) { + return Result.success(nailArtistInfoService.getByShopId(shopId)); + } + + /** + * 根据用户ID获取美甲师信息(前台使用) + */ + @GetMapping("/get/{userId}") + public Result getNailArtistInfo(@PathVariable Long userId) { + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + return Result.success(nailArtistInfoDTO); + } + + @GetMapping("/profile/{artistId}") + public Result getPublicProfile(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getPublicProfile(artistId)); + } + + @GetMapping("/{artistId}/availability") + public Result> getAvailability(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.getAvailability(artistId)); + } + + @GetMapping("/{artistId}/reviews") + public Result> listPublicReviews(@PathVariable Long artistId) { + return Result.success(nailArtistInfoService.listPublicReviews(artistId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleDTO.java new file mode 100644 index 00000000..8c630c1b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +public class ArtistScheduleDTO { + private Long shopId; + private Long artistId; + private LocalDate workDate; + private LocalTime startTime; + private LocalTime endTime; + private Integer slotMinutes; + private Integer capacity; + private Integer status; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleExceptionDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleExceptionDTO.java new file mode 100644 index 00000000..f065a35c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleExceptionDTO.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +public class ArtistScheduleExceptionDTO { + private Long shopId; + private Long artistId; + private LocalDate workDate; + private String exceptionType; + private LocalTime startTime; + private LocalTime endTime; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleRuleDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleRuleDTO.java new file mode 100644 index 00000000..0c938da6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/ArtistScheduleRuleDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.dto; + +import lombok.Data; + +import java.time.LocalTime; +import java.util.List; + +@Data +public class ArtistScheduleRuleDTO { + private Long shopId; + private Long artistId; + private String presetType; + private List workDays; + private LocalTime startTime; + private LocalTime endTime; + private Integer status; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/NailArtistInfoDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/NailArtistInfoDTO.java new file mode 100644 index 00000000..40e3dcad --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/dto/NailArtistInfoDTO.java @@ -0,0 +1,117 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.dto; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalTime; + +/** + * 美甲师信息DTO + */ +@Data +public class NailArtistInfoDTO { + /** + * 主键ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 关联用户表主键(美甲师用户) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long userId; + + /** + * 身份 + */ + private String identity; + + /** + * 从业年限 + */ + private Integer experience; + + /** + * 技能标签ID集合,多个ID以逗号分隔 + */ + private String skills; + + /** + * 评分 + */ + private BigDecimal rating; + + /** + * 状态:1-营业中,0-休息中 + */ + private Integer status; + + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; + + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + + /** + * Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String userTypeName; + + /** + * 作品集商品ID集合,多个ID以逗号分隔 + */ + private String portfolio; + + /** + * 美甲师姓名(从用户表获取) + */ + private String nickname; + + /** + * 所属店铺ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 用户签名 + */ + private String signature; + + /** + * 头像访问地址 + */ + private String avatar; + + /** + * 排班模式摘要 + */ + private String scheduleModeSummary; + + /** + * 排班时间摘要 + */ + private String scheduleTimeSummary; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleDO.java new file mode 100644 index 00000000..a5b0bf44 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; +import java.time.LocalTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule") +public class ArtistScheduleDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("work_date") + private LocalDate workDate; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("status") + private Integer status; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleExceptionDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleExceptionDO.java new file mode 100644 index 00000000..52a54dc6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleExceptionDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule_exception") +public class ArtistScheduleExceptionDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("work_date") + private LocalDate workDate; + @TableField("exception_type") + private String exceptionType; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleRuleDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleRuleDO.java new file mode 100644 index 00000000..6b6360d5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/ArtistScheduleRuleDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_artist_schedule_rule") +public class ArtistScheduleRuleDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("preset_type") + private String presetType; + @TableField("work_days") + private String workDays; + @TableField("start_time") + private LocalTime startTime; + @TableField("end_time") + private LocalTime endTime; + @TableField("slot_minutes") + private Integer slotMinutes; + @TableField("capacity") + private Integer capacity; + @TableField("status") + private Integer status; + @TableField("remark") + private String remark; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/NailArtistInfoDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/NailArtistInfoDO.java new file mode 100644 index 00000000..12b75509 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/entity/NailArtistInfoDO.java @@ -0,0 +1,79 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 美甲师信息实体类 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_nail_artist_info") +public class NailArtistInfoDO extends BaseEntity { + /** + * 关联用户表主键(美甲师用户) + */ + private Long userId; + + /** + * 身份 + */ + private String identity; + + /** + * 从业年限 + */ + private Integer experience; + + /** + * 技能标签ID集合,多个ID以逗号分隔 + */ + private String skills; + + /** + * 评分 + */ + private BigDecimal rating; + + /** + * 状态:1-营业中,0-休息中 + */ + private Integer status; + + @TableField("participate_production") + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + @TableField("work_start_time") + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + @TableField("work_end_time") + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; + + /** + * 作品集商品ID集合,多个ID以逗号分隔 + */ + private String portfolio; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java new file mode 100644 index 00000000..a2096acb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleExceptionMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ArtistScheduleExceptionMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleMapper.java new file mode 100644 index 00000000..fdfdbf58 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleMapper.java @@ -0,0 +1,47 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDate; +import java.time.LocalTime; + +@Mapper +public interface ArtistScheduleMapper extends BaseMapper { + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " + + "AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") LocalTime startTime, + @Param("endTime") LocalTime endTime); + + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate); + + @Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE") + ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") LocalTime startTime); + + @Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " + + "slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " + + "update_time = NOW() WHERE id = #{id} AND is_delete = 0") + int updateGeneratedSchedule(@Param("id") Long id, + @Param("startTime") LocalTime startTime, + @Param("endTime") LocalTime endTime, + @Param("slotMinutes") Integer slotMinutes, + @Param("capacity") Integer capacity, + @Param("status") Integer status, + @Param("remark") String remark); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleRuleMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleRuleMapper.java new file mode 100644 index 00000000..9523ad08 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/ArtistScheduleRuleMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ArtistScheduleRuleMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/NailArtistInfoMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/NailArtistInfoMapper.java new file mode 100644 index 00000000..c45d713e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/mapper/NailArtistInfoMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 美甲师信息Mapper + */ +@Mapper +public interface NailArtistInfoMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/ArtistScheduleService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/ArtistScheduleService.java new file mode 100644 index 00000000..51584445 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/ArtistScheduleService.java @@ -0,0 +1,24 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.service; + +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO; + +import java.time.LocalDate; +import java.util.List; + +public interface ArtistScheduleService { + ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto); + + List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate); + + ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId); + + ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto); + + ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/NailArtistInfoService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/NailArtistInfoService.java new file mode 100644 index 00000000..b297b82c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/NailArtistInfoService.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO; + +import java.util.List; + +/** + * 美甲师信息服务 + */ +public interface NailArtistInfoService extends IService { + /** + * 根据用户ID获取美甲师信息 + * @param userId 用户ID + * @return 美甲师信息 + */ + NailArtistInfoDTO getByUserId(Long userId); + + /** + * 获取所有美甲师信息 + * @return 美甲师信息列表 + */ + List getAllNailArtists(); + + /** + * 根据店铺ID获取美甲师信息 + * @param shopId 店铺ID + * @return 美甲师信息列表 + */ + List getByShopId(Long shopId); + + /** + * 保存或更新美甲师信息 + * @param nailArtistInfoDTO 美甲师信息DTO + * @return 保存后的美甲师信息 + */ + NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); + + /** + * 获取所有可用的美甲师信息(前台使用) + * @return 美甲师信息列表 + */ + List getAllAvailableNailArtists(); + + NailArtistProfileVO getPublicProfile(Long artistId); + + List getAvailability(Long artistId); + + List listPublicReviews(Long artistId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java new file mode 100644 index 00000000..2d674937 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/ArtistScheduleServiceImpl.java @@ -0,0 +1,423 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class ArtistScheduleServiceImpl implements ArtistScheduleService { + + private static final int GENERATED_DAYS = 60; + private static final int DEFAULT_SLOT_MINUTES = 60; + private static final int DEFAULT_CAPACITY = 1; + private static final String PRESET_SINGLE_REST = "SINGLE_REST"; + private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; + private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE"; + private static final String PRESET_LATE_SHIFT = "LATE_SHIFT"; + private static final String PRESET_CUSTOM = "CUSTOM"; + private static final String EXCEPTION_REST = "REST"; + private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK"; + private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT"; + + private final ArtistScheduleMapper artistScheduleMapper; + private final ArtistScheduleRuleMapper ruleMapper; + private final ArtistScheduleExceptionMapper exceptionMapper; + private final AppointmentReservationMapper reservationMapper; + + @Override + @Transactional + public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null + || dto.getStartTime() == null || dto.getEndTime() == null) { + throw new RuntimeException("排班信息不完整"); + } + ArtistScheduleDO schedule = new ArtistScheduleDO(); + BeanUtils.copyProperties(dto, schedule); + schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes()); + schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity()); + schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + schedule.setIsDelete(0); + ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime()); + if (existing == null) { + artistScheduleMapper.insert(schedule); + } else { + schedule.setId(existing.getId()); + artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(), + schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark()); + } + return toVO(schedule); + } + + @Override + public List listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(ArtistScheduleDO::getIsDelete, 0) + .orderByAsc(ArtistScheduleDO::getWorkDate) + .orderByAsc(ArtistScheduleDO::getStartTime); + if (shopId != null) { + wrapper.eq(ArtistScheduleDO::getShopId, shopId); + } + if (artistId != null) { + wrapper.eq(ArtistScheduleDO::getArtistId, artistId); + } + if (startDate != null) { + wrapper.ge(ArtistScheduleDO::getWorkDate, startDate); + } + if (endDate != null) { + wrapper.le(ArtistScheduleDO::getWorkDate, endDate); + } + return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList(); + } + + private ArtistScheduleVO toVO(ArtistScheduleDO schedule) { + ArtistScheduleVO vo = new ArtistScheduleVO(); + BeanUtils.copyProperties(schedule, vo); + return vo; + } + + @Override + public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) { + if (shopId == null || artistId == null) { + throw new RuntimeException("排班规则查询参数不完整"); + } + ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO(); + ArtistScheduleRuleDO rule = selectRule(shopId, artistId); + setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule)); + setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L)) + .stream() + .map(this::toExceptionVO) + .toList()); + return setting; + } + + @Override + @Transactional + public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) { + ArtistScheduleRuleDO normalized = normalizeRule(dto); + ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId()); + if (existing == null) { + ruleMapper.insert(normalized); + } else { + normalized.setId(existing.getId()); + ruleMapper.updateById(normalized); + } + refreshGeneratedSchedules(normalized); + return toRuleVO(normalized); + } + + @Override + @Transactional + public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) { + ArtistScheduleExceptionDO normalized = normalizeException(dto); + ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId()); + if (rule == null) { + rule = defaultRule(normalized.getShopId(), normalized.getArtistId()); + } + ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate()); + if (existing == null) { + exceptionMapper.insert(normalized); + } else { + normalized.setId(existing.getId()); + exceptionMapper.updateById(normalized); + } + refreshScheduleForDate(rule, normalized, normalized.getWorkDate()); + return toExceptionVO(normalized); + } + + private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) { + throw new RuntimeException("排班规则信息不完整"); + } + String presetType = normalizePresetType(dto.getPresetType()); + LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime(); + LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime(); + validateTimeRange(startTime, endTime); + ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); + rule.setShopId(dto.getShopId()); + rule.setArtistId(dto.getArtistId()); + rule.setPresetType(presetType); + rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType))); + rule.setStartTime(startTime); + rule.setEndTime(endTime); + rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); + rule.setCapacity(DEFAULT_CAPACITY); + rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + rule.setRemark(trimText(dto.getRemark())); + rule.setIsDelete(0); + return rule; + } + + private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) { + throw new RuntimeException("排班例外信息不完整"); + } + String exceptionType = normalizeExceptionType(dto.getExceptionType()); + LocalTime startTime = dto.getStartTime(); + LocalTime endTime = dto.getEndTime(); + if (!EXCEPTION_REST.equals(exceptionType)) { + if (startTime == null || endTime == null) { + throw new RuntimeException("临时上班或改班必须填写开始和结束时间"); + } + validateTimeRange(startTime, endTime); + } + ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO(); + exception.setShopId(dto.getShopId()); + exception.setArtistId(dto.getArtistId()); + exception.setWorkDate(dto.getWorkDate()); + exception.setExceptionType(exceptionType); + exception.setStartTime(startTime); + exception.setEndTime(endTime); + exception.setSlotMinutes(DEFAULT_SLOT_MINUTES); + exception.setCapacity(DEFAULT_CAPACITY); + exception.setRemark(trimText(dto.getRemark())); + exception.setIsDelete(0); + return exception; + } + + private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) { + return ruleMapper.selectOne(new LambdaQueryWrapper() + .eq(ArtistScheduleRuleDO::getShopId, shopId) + .eq(ArtistScheduleRuleDO::getArtistId, artistId) + .eq(ArtistScheduleRuleDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) { + return exceptionMapper.selectOne(new LambdaQueryWrapper() + .eq(ArtistScheduleExceptionDO::getShopId, shopId) + .eq(ArtistScheduleExceptionDO::getArtistId, artistId) + .eq(ArtistScheduleExceptionDO::getWorkDate, workDate) + .eq(ArtistScheduleExceptionDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + private List listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) { + return exceptionMapper.selectList(new LambdaQueryWrapper() + .eq(ArtistScheduleExceptionDO::getShopId, shopId) + .eq(ArtistScheduleExceptionDO::getArtistId, artistId) + .eq(ArtistScheduleExceptionDO::getIsDelete, 0) + .between(ArtistScheduleExceptionDO::getWorkDate, start, end) + .orderByAsc(ArtistScheduleExceptionDO::getWorkDate)); + } + + private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) { + LocalDate start = LocalDate.now(); + LocalDate end = start.plusDays(GENERATED_DAYS - 1L); + Map exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end) + .stream() + .collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a)); + LocalDate cursor = start; + while (!cursor.isAfter(end)) { + refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor); + cursor = cursor.plusDays(1L); + } + } + + private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { + GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate); + if (!generated.working()) { + assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate); + upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark()); + return; + } + assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime()); + upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark()); + } + + private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) { + if (exception != null) { + if (EXCEPTION_REST.equals(exception.getExceptionType())) { + return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception)); + } + if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) { + return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception)); + } + } + boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue()); + return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班"); + } + + private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime, + Integer slotMinutes, Integer capacity, Integer status, String remark) { + ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate); + if (schedule == null) { + schedule = new ArtistScheduleDO(); + schedule.setShopId(rule.getShopId()); + schedule.setArtistId(rule.getArtistId()); + schedule.setWorkDate(workDate); + schedule.setStartTime(startTime); + schedule.setEndTime(endTime); + schedule.setSlotMinutes(slotMinutes); + schedule.setCapacity(capacity); + schedule.setStatus(status); + schedule.setRemark(remark); + schedule.setIsDelete(0); + artistScheduleMapper.insert(schedule); + return; + } + artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark); + } + + private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) { + int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate); + if (count > 0) { + throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count); + } + } + + private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) { + int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime); + if (count > 0) { + throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count); + } + } + + private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) { + return toRuleVO(defaultRule(shopId, artistId)); + } + + private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) { + ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO(); + rule.setShopId(shopId); + rule.setArtistId(artistId); + rule.setPresetType(PRESET_DOUBLE_REST); + rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5))); + rule.setStartTime(LocalTime.of(9, 0)); + rule.setEndTime(LocalTime.of(17, 0)); + rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); + rule.setCapacity(DEFAULT_CAPACITY); + rule.setStatus(1); + rule.setIsDelete(0); + return rule; + } + + private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) { + ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO(); + BeanUtils.copyProperties(rule, vo); + vo.setWorkDays(decodeWorkDays(rule.getWorkDays())); + return vo; + } + + private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) { + ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO(); + BeanUtils.copyProperties(exception, vo); + return vo; + } + + private String normalizePresetType(String presetType) { + String value = trimText(presetType); + if (value == null || value.isBlank()) { + return PRESET_CUSTOM; + } + return value; + } + + private String normalizeExceptionType(String exceptionType) { + String value = trimText(exceptionType); + if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) { + return value; + } + throw new RuntimeException("不支持的排班例外类型:" + value); + } + + private List resolveWorkDays(List inputWorkDays, String presetType) { + List presetDays = switch (presetType) { + case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5); + case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6); + default -> inputWorkDays; + }; + Set normalized = new LinkedHashSet<>(); + for (Integer day : presetDays == null ? List.of() : presetDays) { + if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) { + normalized.add(day); + } + } + if (normalized.isEmpty()) { + throw new RuntimeException("请至少选择一个工作日"); + } + return normalized.stream().sorted().toList(); + } + + private String encodeWorkDays(List workDays) { + return workDays.stream() + .sorted() + .map(String::valueOf) + .collect(Collectors.joining(",")); + } + + private List decodeWorkDays(String workDays) { + if (workDays == null || workDays.isBlank()) { + return new ArrayList<>(); + } + return List.of(workDays.split(",")).stream() + .map(String::trim) + .filter(value -> !value.isBlank()) + .map(Integer::valueOf) + .sorted() + .toList(); + } + + private LocalTime presetStartTime(String presetType) { + if (PRESET_NINE_TO_FIVE.equals(presetType)) { + return LocalTime.of(9, 0); + } + return LocalTime.of(10, 0); + } + + private LocalTime presetEndTime(String presetType) { + if (PRESET_NINE_TO_FIVE.equals(presetType)) { + return LocalTime.of(17, 0); + } + return LocalTime.of(22, 0); + } + + private void validateTimeRange(LocalTime startTime, LocalTime endTime) { + if (startTime == null || endTime == null || !startTime.isBefore(endTime)) { + throw new RuntimeException("排班开始时间必须早于结束时间"); + } + } + + private String trimText(String value) { + return value == null ? null : value.trim(); + } + + private String exceptionRemark(ArtistScheduleExceptionDO exception) { + if (exception.getRemark() != null && !exception.getRemark().isBlank()) { + return exception.getRemark(); + } + return "例外排班:" + exception.getExceptionType(); + } + + private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes, + Integer capacity, String remark) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java new file mode 100644 index 00000000..353bbf23 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -0,0 +1,832 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistAvailabilityVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistReviewVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.NailArtistWorkVO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +/** + * NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class NailArtistInfoServiceImpl extends ServiceImpl implements NailArtistInfoService { + + private static final int REVIEW_STATUS_SUBMITTED = 1; + private static final int ORDER_STATUS_COMPLETED = 2; + private static final int AVAILABILITY_DAYS = 7; + private static final int SLOT_MINUTES = 60; + private static final int MAX_AVAILABILITY_SLOTS = 16; + private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE; + private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm"); + private static final String PRESET_DOUBLE_REST = "DOUBLE_REST"; + private static final String PRESET_SINGLE_REST = "SINGLE_REST"; + + @Autowired + /** + * Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Autowired + /** + * Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ShopMapper shopMapper; + + @Autowired + /** + * Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Autowired + private ProductMapper productMapper; + + @Autowired + private OrderMapper orderMapper; + + @Autowired + private OrderItemMapper orderItemMapper; + + @Autowired + private OrderArtistReviewMapper orderArtistReviewMapper; + + @Autowired + private ObjectStorageFileService objectStorageFileService; + + @Autowired + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Autowired(required = false) + private ArtistScheduleMapper artistScheduleMapper; + + @Autowired(required = false) + private ArtistScheduleRuleMapper artistScheduleRuleMapper; + + @Autowired(required = false) + private AppointmentReservationMapper appointmentReservationMapper; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + public NailArtistInfoDTO getByUserId(Long userId) { + NailArtistInfoDO info = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + return info == null ? null : convertToDTO(info); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllNailArtists() { + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isVisibleServiceUser(dto)) { + result.add(dto); + } + } + enrichScheduleSummaries(result, null); + return result; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getByShopId(Long shopId) { + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { + return new ArrayList<>(); + } + + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .eq(UserDO::getType, 3) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .orderByAsc(UserDO::getCreateTime) + .orderByAsc(UserDO::getId)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto == null) { + dto = buildFallbackArtistInfo(user); + } + dto.setShopId(shopId); + dto.setShopName(shop == null ? null : shop.getShopName()); + result.add(dto); + } + enrichScheduleSummaries(result, shopId); + return result; + } + + @Override + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) { + NailArtistInfoDO entity = new NailArtistInfoDO(); + BeanUtils.copyProperties(dto, entity); + + NailArtistInfoDO existing = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, dto.getUserId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + entity.setId(existing.getId()); + } + if (entity.getStatus() == null) { + entity.setStatus(1); + } + if (entity.getParticipateProduction() == null) { + UserDO user = userMapper.selectById(dto.getUserId()); + entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + saveOrUpdate(entity); + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToDTO(entity); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllAvailableNailArtists() { + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getStatus, 1) + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isBookableServiceUser(dto)) { + result.add(dto); + } + } + return result; + } + + @Override + public NailArtistProfileVO getPublicProfile(Long artistId) { + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + UserDO artist = userMapper.selectById(artistId); + if (artist == null || isDeleted(artist.getIsDelete())) { + throw new RuntimeException("美甲师信息不存在"); + } + + List servedItems = loadArtistOrderItems(artistId, true); + List reviews = listPublicReviews(artistId); + NailArtistProfileVO profile = new NailArtistProfileVO(); + profile.setArtistId(artistId); + profile.setArtistName(resolveArtistName(artistInfo, artist)); + profile.setAvatar(artist.getAvatar()); + profile.setIdentity(artistInfo.getIdentity()); + profile.setSignature(artistInfo.getSignature()); + profile.setExperience(artistInfo.getExperience()); + profile.setStatus(artistInfo.getStatus()); + profile.setShopId(artistInfo.getShopId()); + profile.setShopName(artistInfo.getShopName()); + profile.setRating(resolvePublicRating(artistId, artistInfo)); + profile.setServiceCount(countServiceQuantity(servedItems)); + profile.setWorkStartTime(artistInfo.getWorkStartTime()); + profile.setWorkEndTime(artistInfo.getWorkEndTime()); + profile.setStyleTags(parseTextTokens(artistInfo.getSkills())); + profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24)); + profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList())); + profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList())); + return profile; + } + + @Override + public List getAvailability(Long artistId) { + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (!Integer.valueOf(1).equals(artistInfo.getStatus())) { + return new ArrayList<>(); + } + + List scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo); + if (!scheduleSlots.isEmpty()) { + return scheduleSlots; + } + + LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime(); + LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime(); + if (!workEnd.isAfter(workStart)) { + workStart = LocalTime.of(10, 0); + workEnd = LocalTime.of(20, 0); + } + + LocalDate today = LocalDate.now(); + LocalDateTime rangeStart = today.atStartOfDay(); + LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay(); + Set bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd); + LocalDateTime now = LocalDateTime.now(); + List slots = new ArrayList<>(); + + for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) { + LocalDate date = today.plusDays(dayOffset); + LocalTime cursor = workStart; + while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) { + LocalDateTime slotStart = date.atTime(cursor); + LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES); + if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) { + slots.add(buildAvailabilitySlot(slotStart, slotEnd)); + } + cursor = cursor.plusMinutes(SLOT_MINUTES); + } + } + return slots; + } + + private List buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) { + if (artistScheduleMapper == null || artistInfo.getShopId() == null) { + return new ArrayList<>(); + } + LocalDate today = LocalDate.now(); + List schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper() + .eq(ArtistScheduleDO::getShopId, artistInfo.getShopId()) + .eq(ArtistScheduleDO::getArtistId, artistId) + .eq(ArtistScheduleDO::getStatus, 1) + .eq(ArtistScheduleDO::getIsDelete, 0) + .ge(ArtistScheduleDO::getWorkDate, today) + .lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS)) + .orderByAsc(ArtistScheduleDO::getWorkDate) + .orderByAsc(ArtistScheduleDO::getStartTime)); + if (schedules == null || schedules.isEmpty()) { + return new ArrayList<>(); + } + LocalDateTime minStart = LocalDateTime.now().plusMinutes(30); + List slots = new ArrayList<>(); + for (ArtistScheduleDO schedule : schedules) { + int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes(); + int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity(); + LocalTime cursor = schedule.getStartTime(); + while (cursor != null && schedule.getEndTime() != null + && !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime()) + && slots.size() < MAX_AVAILABILITY_SLOTS) { + LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor); + LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes); + int used = appointmentReservationMapper == null ? 0 + : appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd); + if (slotStart.isAfter(minStart) && used < capacity) { + slots.add(buildAvailabilitySlot(slotStart, slotEnd)); + } + cursor = cursor.plusMinutes(slotMinutes); + } + if (slots.size() >= MAX_AVAILABILITY_SLOTS) { + break; + } + } + return slots; + } + + @Override + public List listPublicReviews(Long artistId) { + if (artistId == null) { + return new ArrayList<>(); + } + List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getId)); + if (reviews == null || reviews.isEmpty()) { + return new ArrayList<>(); + } + + List limitedReviews = reviews.stream().limit(20).collect(Collectors.toList()); + Map customerMap = loadUsers(limitedReviews.stream() + .map(OrderArtistReviewDO::getCustomerId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Map productMap = loadProducts(limitedReviews.stream() + .map(OrderArtistReviewDO::getProductId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + Set imageIds = new LinkedHashSet<>(); + for (OrderArtistReviewDO review : limitedReviews) { + imageIds.addAll(parseLongTokens(review.getImageFileIds())); + } + Map fileMap = loadFiles(imageIds); + + List result = new ArrayList<>(); + for (OrderArtistReviewDO review : limitedReviews) { + result.add(buildReviewVO(review, customerMap, productMap, fileMap)); + } + return result; + } + + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) { + NailArtistInfoDTO dto = new NailArtistInfoDTO(); + BeanUtils.copyProperties(entity, dto); + + UserDO user = userMapper.selectById(entity.getUserId()); + if (user != null) { + dto.setNickname(user.getNickname()); + dto.setSignature(user.getSignature()); + dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + dto.setUserType(user.getType()); + dto.setUserTypeName(resolveUserTypeName(user.getType())); + if (dto.getParticipateProduction() == null) { + dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); + if (!shopOptions.isEmpty()) { + ShopSimpleVO primaryShop = shopOptions.get(0); + dto.setShopId(primaryShop.getId()); + dto.setShopName(primaryShop.getShopName()); + } else if (user.getShopId() != null && user.getShopId() > 0) { + ShopDO shop = shopMapper.selectById(user.getShopId()); + if (shop != null) { + dto.setShopId(shop.getId()); + dto.setShopName(shop.getShopName()); + } + } + } + return dto; + } + + private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) { + NailArtistInfoDTO dto = new NailArtistInfoDTO(); + dto.setUserId(user.getId()); + dto.setNickname(user.getNickname()); + dto.setSignature(user.getSignature()); + dto.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + dto.setUserType(user.getType()); + dto.setUserTypeName(resolveUserTypeName(user.getType())); + dto.setIdentity("美甲师"); + dto.setStatus(1); + dto.setParticipateProduction(1); + dto.setShopId(user.getShopId()); + List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); + if (!shopOptions.isEmpty()) { + ShopSimpleVO primaryShop = shopOptions.get(0); + dto.setShopId(primaryShop.getId()); + dto.setShopName(primaryShop.getShopName()); + } else if (user.getShopId() != null && user.getShopId() > 0) { + ShopDO shop = shopMapper.selectById(user.getShopId()); + if (shop != null) { + dto.setShopId(shop.getId()); + dto.setShopName(shop.getShopName()); + } + } + return dto; + } + + private void enrichScheduleSummaries(List artists, Long shopId) { + if (artistScheduleRuleMapper == null || artists == null || artists.isEmpty()) { + return; + } + Set artistIds = artists.stream() + .map(NailArtistInfoDTO::getUserId) + .filter(userId -> userId != null && userId > 0) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (artistIds.isEmpty()) { + return; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .in(ArtistScheduleRuleDO::getArtistId, artistIds) + .eq(ArtistScheduleRuleDO::getIsDelete, 0); + if (shopId != null && shopId > 0) { + wrapper.eq(ArtistScheduleRuleDO::getShopId, shopId); + } + Map ruleByArtistId = artistScheduleRuleMapper.selectList(wrapper).stream() + .collect(Collectors.toMap(ArtistScheduleRuleDO::getArtistId, rule -> rule, (left, right) -> left)); + artists.forEach(artist -> applyScheduleSummary(artist, ruleByArtistId.get(artist.getUserId()))); + } + + private void applyScheduleSummary(NailArtistInfoDTO artist, ArtistScheduleRuleDO rule) { + if (artist == null) { + return; + } + if (rule == null || !Integer.valueOf(1).equals(rule.getStatus())) { + artist.setScheduleModeSummary("未设置"); + artist.setScheduleTimeSummary(""); + return; + } + artist.setScheduleModeSummary(resolveScheduleModeSummary(rule.getPresetType())); + artist.setScheduleTimeSummary(formatScheduleTimeSummary(rule.getStartTime(), rule.getEndTime())); + } + + private String resolveScheduleModeSummary(String presetType) { + if (PRESET_DOUBLE_REST.equals(presetType)) { + return "双休"; + } + if (PRESET_SINGLE_REST.equals(presetType)) { + return "单休"; + } + return "自定义"; + } + + private String formatScheduleTimeSummary(LocalTime startTime, LocalTime endTime) { + if (startTime == null || endTime == null) { + return ""; + } + return TIME_TEXT_FORMATTER.format(startTime) + "-" + TIME_TEXT_FORMATTER.format(endTime); + } + + private String resolveAccessibleAvatar(String avatar) { + if (!StringUtils.hasText(avatar)) { + return null; + } + String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar); + return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar; + } + + /** + * Run business method `isVisibleServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleServiceUser(NailArtistInfoDTO dto) { + if (dto == null || dto.getUserType() == null) { + return false; + } + return Integer.valueOf(3).equals(dto.getUserType()) + || Integer.valueOf(2).equals(dto.getUserType()); + } + + /** + * Run business method `isBookableServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isBookableServiceUser(NailArtistInfoDTO dto) { + return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus()); + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + if (Integer.valueOf(2).equals(type)) { + return "店长"; + } + if (Integer.valueOf(3).equals(type)) { + return "美甲师"; + } + return "用户"; + } + + private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) { + if (artistId == null) { + throw new RuntimeException("美甲师信息不存在"); + } + NailArtistInfoDTO artistInfo = getByUserId(artistId); + if (artistInfo != null && isVisibleServiceUser(artistInfo)) { + return artistInfo; + } + UserDO artist = userMapper.selectById(artistId); + if (artist == null + || isDeleted(artist.getIsDelete()) + || !Integer.valueOf(3).equals(artist.getType()) + || !Integer.valueOf(1).equals(artist.getStatus())) { + throw new RuntimeException("美甲师信息不存在"); + } + return buildFallbackArtistInfo(artist); + } + + private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) { + BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating; + if (rating == null) { + return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); + } + return rating.setScale(1, RoundingMode.HALF_UP); + } + + private List loadArtistOrderItems(Long artistId, boolean completedOnly) { + List orders = orderMapper.selectByArtistId(artistId); + if (orders == null || orders.isEmpty()) { + return new ArrayList<>(); + } + + Set allowedOrderIds = orders.stream() + .filter(order -> !isDeleted(order.getIsDelete())) + .filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus())) + .map(OrderDO::getId) + .collect(Collectors.toCollection(LinkedHashSet::new)); + if (allowedOrderIds.isEmpty()) { + return new ArrayList<>(); + } + + List items = new ArrayList<>(); + for (Long orderId : allowedOrderIds) { + List orderItems = orderItemMapper.selectByOrderId(orderId); + if (orderItems == null) { + continue; + } + for (OrderItemDO item : orderItems) { + if (item != null + && artistId.equals(item.getArtistId()) + && !isDeleted(item.getIsDelete())) { + items.add(item); + } + } + } + return items; + } + + private long countServiceQuantity(List items) { + if (items == null || items.isEmpty()) { + return 0L; + } + long count = 0L; + for (OrderItemDO item : items) { + if (item == null) { + continue; + } + count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity(); + } + return count; + } + + private List buildWorks(String portfolio, List servedItems, int limit) { + LinkedHashSet productIds = new LinkedHashSet<>(parseLongTokens(portfolio)); + if (servedItems != null) { + servedItems.stream() + .sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .map(OrderItemDO::getProductId) + .filter(productId -> productId != null && productId > 0) + .forEach(productIds::add); + } + if (productIds.isEmpty()) { + return new ArrayList<>(); + } + + List limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList()); + Map productMap = loadProducts(new LinkedHashSet<>(limitedIds)); + Set fileIds = new LinkedHashSet<>(); + for (ProductDO product : productMap.values()) { + fileIds.addAll(parseLongTokens(product.getImageFileIds())); + } + Map fileMap = loadFiles(fileIds); + + List works = new ArrayList<>(); + for (Long productId : limitedIds) { + ProductDO product = productMap.get(productId); + if (product == null || isDeleted(product.getIsDelete()) || !isFrontVisible(product)) { + continue; + } + works.add(buildWorkVO(product, fileMap)); + } + return works; + } + + private NailArtistWorkVO buildWorkVO(ProductDO product, Map fileMap) { + NailArtistWorkVO work = new NailArtistWorkVO(); + work.setId(product.getId()); + work.setTitle(product.getTitle()); + work.setDescription(product.getDescription()); + work.setPrice(product.getPrice()); + work.setTags(parseTextTokens(product.getTags())); + work.setLikeCount(product.getLikeCount()); + work.setCollectCount(product.getCollectCount()); + List imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap); + work.setImageUrls(imageUrls); + work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0)); + return work; + } + + private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review, + Map customerMap, + Map productMap, + Map fileMap) { + NailArtistReviewVO vo = new NailArtistReviewVO(); + vo.setId(review.getId()); + vo.setArtistId(review.getArtistId()); + vo.setCustomerId(review.getCustomerId()); + UserDO customer = customerMap.get(review.getCustomerId()); + vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname()); + vo.setCustomerAvatar(customer == null ? null : customer.getAvatar()); + vo.setProductId(review.getProductId()); + ProductDO product = productMap.get(review.getProductId()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setRating(review.getRatingScore()); + vo.setContent(review.getContent()); + List imageFileIds = parseLongTokens(review.getImageFileIds()); + vo.setImageFileIds(imageFileIds); + vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap)); + vo.setSubmittedAt(review.getSubmittedAt()); + return vo; + } + + private Set loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) { + List bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd); + if (bookedItems == null || bookedItems.isEmpty()) { + return new HashSet<>(); + } + return bookedItems.stream() + .map(OrderItemDO::getAppointmentTime) + .filter(appointmentTime -> appointmentTime != null) + .map(this::truncateToMinute) + .collect(Collectors.toSet()); + } + + private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) { + NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO(); + slot.setStartTime(startTime); + slot.setEndTime(endTime); + slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate())); + slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime())); + slot.setAvailable(true); + return slot; + } + + private Map loadProducts(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return new HashMap<>(); + } + List products = productMapper.selectBatchIds(productIds); + if (products == null || products.isEmpty()) { + return new HashMap<>(); + } + return products.stream() + .filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()) && isFrontVisible(product)) + .collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new)); + } + + private Map loadUsers(Set userIds) { + if (userIds == null || userIds.isEmpty()) { + return new HashMap<>(); + } + List users = userMapper.selectBatchIds(new ArrayList<>(userIds)); + if (users == null || users.isEmpty()) { + return new HashMap<>(); + } + return users.stream() + .filter(user -> user != null && user.getId() != null) + .collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new)); + } + + private Map loadFiles(Set fileIds) { + if (fileIds == null || fileIds.isEmpty()) { + return new HashMap<>(); + } + Map files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + return files == null ? new HashMap<>() : files; + } + + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return new ArrayList<>(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); + } + } + return urls; + } + + private List parseLongTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet ids = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;\\s]+")) { + if (!StringUtils.hasText(token)) { + continue; + } + try { + ids.add(Long.parseLong(token.trim())); + } catch (NumberFormatException ignored) { + // Some legacy fields store tag names instead of ids. + } + } + return new ArrayList<>(ids); + } + + private List parseTextTokens(String raw) { + if (!StringUtils.hasText(raw)) { + return new ArrayList<>(); + } + LinkedHashSet tokens = new LinkedHashSet<>(); + for (String token : raw.split("[,;,;、\\s]+")) { + if (StringUtils.hasText(token)) { + tokens.add(token.trim()); + } + } + return new ArrayList<>(tokens); + } + + private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) { + if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) { + return artistInfo.getNickname(); + } + if (artist != null && StringUtils.hasText(artist.getNickname())) { + return artist.getNickname(); + } + return "美甲师"; + } + + private boolean isDeleted(Integer isDelete) { + return Integer.valueOf(1).equals(isDelete); + } + + private boolean isFrontVisible(ProductDO product) { + return product != null && Integer.valueOf(1).equals(product.getFrontVisible()); + } + + private LocalDateTime truncateToMinute(LocalDateTime value) { + return value == null ? null : value.withSecond(0).withNano(0); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/support/BookableArtistSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/support/BookableArtistSupport.java new file mode 100644 index 00000000..7e9fdc44 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/support/BookableArtistSupport.java @@ -0,0 +1,116 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.support; + +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; + +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +@Component +@RequiredArgsConstructor +/** + * Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BookableArtistSupport { + + /** + * Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + /** + * Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final NailArtistInfoMapper nailArtistInfoMapper; + /** + * Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + /** + * Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isValidBookableArtist(Long shopId, Long artistId) { + if (artistId == null || artistId <= 0) { + return false; + } + + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { + return false; + } + if (!isBookableServiceUser(artist)) { + return false; + } + if (!Integer.valueOf(1).equals(artist.getStatus())) { + return false; + } + return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId); + } + + /** + * Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isBookableServiceUser(UserDO user) { + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { + return false; + } + if (Integer.valueOf(3).equals(user.getType())) { + return true; + } + if (!Integer.valueOf(2).equals(user.getType())) { + return false; + } + NailArtistInfoDO info = nailArtistInfoMapper.selectOne( + new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, user.getId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1") + ); + return info != null + && Integer.valueOf(1).equals(info.getStatus()) + && Integer.valueOf(1).equals(info.getParticipateProduction()); + } + + /** + * Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String filterValidBookableArtists(Long shopId, String rawBookableArtists) { + if (!StringUtils.hasText(rawBookableArtists)) { + return ""; + } + + Set validArtistIds = new LinkedHashSet<>(); + for (String artistIdText : rawBookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdText)) { + continue; + } + try { + Long artistId = Long.parseLong(artistIdText.trim()); + if (isValidBookableArtist(shopId, artistId)) { + validArtistIds.add(artistId); + } + } catch (NumberFormatException ignored) { + // Ignore invalid configured IDs and only expose currently valid artists. + } + } + + return validArtistIds.stream() + .map(String::valueOf) + .collect(Collectors.joining(",")); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistCalendarAppointmentVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistCalendarAppointmentVO.java new file mode 100644 index 00000000..6033f373 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistCalendarAppointmentVO.java @@ -0,0 +1,91 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus; +@Data +/** + * ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ArtistCalendarAppointmentVO { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderId; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer orderStatus; + /** + * Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderStatusText; + /** + * Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderItemId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistName; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerPhoneMasked; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentStartTime; + /** + * Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentEndTime; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long durationMinutes; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleExceptionVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleExceptionVO.java new file mode 100644 index 00000000..47c7797f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleExceptionVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +@Data +public class ArtistScheduleExceptionVO { + private Long id; + private Long shopId; + private Long artistId; + private LocalDate workDate; + private String exceptionType; + private LocalTime startTime; + private LocalTime endTime; + private String remark; + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java new file mode 100644 index 00000000..cbd2fb46 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleSettingVO.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class ArtistScheduleRuleSettingVO { + private ArtistScheduleRuleVO rule; + private List exceptions; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleVO.java new file mode 100644 index 00000000..52ec1127 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleRuleVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.List; + +@Data +public class ArtistScheduleRuleVO { + private Long id; + private Long shopId; + private Long artistId; + private String presetType; + private List workDays; + private LocalTime startTime; + private LocalTime endTime; + private Integer status; + private String remark; + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleVO.java new file mode 100644 index 00000000..9c0f315c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/ArtistScheduleVO.java @@ -0,0 +1,22 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; + +@Data +public class ArtistScheduleVO { + private Long id; + private Long shopId; + private Long artistId; + private LocalDate workDate; + private LocalTime startTime; + private LocalTime endTime; + private Integer slotMinutes; + private Integer capacity; + private Integer status; + private String remark; + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistAvailabilityVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistAvailabilityVO.java new file mode 100644 index 00000000..1901046e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistAvailabilityVO.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class NailArtistAvailabilityVO { + private LocalDateTime startTime; + private LocalDateTime endTime; + private String dateText; + private String timeText; + private Boolean available; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistProfileVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistProfileVO.java new file mode 100644 index 00000000..cce90226 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistProfileVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistProfileVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + private String artistName; + private String avatar; + private String identity; + private String signature; + private Integer experience; + private Integer status; + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + private String shopName; + private BigDecimal rating; + private Long serviceCount; + private LocalTime workStartTime; + private LocalTime workEndTime; + private List styleTags = new ArrayList<>(); + private List works = new ArrayList<>(); + private List reviews = new ArrayList<>(); + private List availability = new ArrayList<>(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistReviewVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistReviewVO.java new file mode 100644 index 00000000..e4010a0b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistReviewVO.java @@ -0,0 +1,30 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistReviewVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + private Long artistId; + @JsonSerialize(using = ToStringSerializer.class) + private Long customerId; + private String customerName; + private String customerAvatar; + @JsonSerialize(using = ToStringSerializer.class) + private Long productId; + private String productTitle; + private BigDecimal rating; + private String content; + private List imageFileIds = new ArrayList<>(); + private List imageUrls = new ArrayList<>(); + private LocalDateTime submittedAt; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistWorkVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistWorkVO.java new file mode 100644 index 00000000..ae33c23e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/artist/vo/NailArtistWorkVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.artist.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@Data +public class NailArtistWorkVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + private String title; + private String description; + private BigDecimal price; + private String coverImageUrl; + private List imageUrls = new ArrayList<>(); + private List tags = new ArrayList<>(); + private Integer likeCount; + private Integer collectCount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/admin/AdminAuthController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/admin/AdminAuthController.java new file mode 100644 index 00000000..4ea79ab3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/admin/AdminAuthController.java @@ -0,0 +1,131 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningManagerRegisterDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RefreshTokenRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.SwitchShopRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/auth") +@RequiredArgsConstructor +/** + * AdminAuthController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminAuthController { + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RequestThrottleService requestThrottleService; + /** + * Purpose: securityAuditLogService supports AdminAuthController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + @PostMapping("/login") + @OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { + requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); + try { + LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO); + requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "ADMIN_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(null, loginRequestDTO.getAccount(), "ADMIN_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @PostMapping("/register") + @OperationGuard(action = "admin-planning-register", ttlSeconds = 10, message = "注册处理中,请勿重复提交") + public Result register(@RequestBody PlanningManagerRegisterDTO registerDTO) { + return Result.success(userService.registerPlanningManager(registerDTO)); + } + + @GetMapping("/login-shops/{account}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getLoginShops(@PathVariable String account) { + return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account))); + } + + @PostMapping("/switch-shop") + @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); + } + + @PostMapping("/logout") + @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result logout(HttpServletRequest request) { + return Result.success(userService.logout((String) request.getAttribute("sessionId"))); + } + + @PostMapping("/refresh") + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshTokenRequestDTO parameter `refreshTokenRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { + LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); + if (loginResponseVO.getUserInfo() == null + || loginResponseVO.getUserInfo().getType() == null + || loginResponseVO.getUserInfo().getType() < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("您没有后台管理权限"); + } + return Result.success(loginResponseVO); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/front/LoginIdentityController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/front/LoginIdentityController.java new file mode 100644 index 00000000..fcdd8444 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/controller/front/LoginIdentityController.java @@ -0,0 +1,111 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginIdentityVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.service.LoginIdentityService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户登录标识信息表 Controller + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/login-identity", "/api/login-identity"}) +@RequiredArgsConstructor +public class LoginIdentityController { + /** + * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LoginIdentityService loginIdentityService; + + /** + * 创建登录标识 + * + * @param loginIdentityDTO 登录标识DTO + * @return 登录标识ID + */ + @PostMapping("/create") + public Result createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) { + Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO); + return Result.success(id); + } + + /** + * 更新登录标识 + * + * @param id 登录标识ID + * @param loginIdentityDTO 登录标识DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { + boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO); + return Result.success(success); + } + + /** + * 删除登录标识 + * + * @param id 登录标识ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteLoginIdentity(@PathVariable Long id) { + boolean success = loginIdentityService.deleteLoginIdentity(id); + return Result.success(success); + } + + /** + * 根据ID查询登录标识 + * + * @param id 登录标识ID + * @return 登录标识VO + */ + @GetMapping("/get/{id}") + public Result getLoginIdentityById(@PathVariable Long id) { + LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id); + return Result.success(loginIdentityVO); + } + + /** + * 查询所有登录标识 + * + * @return 登录标识VO列表 + */ + @GetMapping("/list/all") + public Result> listAllLoginIdentities() { + List loginIdentityVOs = loginIdentityService.listAllLoginIdentities(); + return Result.success(loginIdentityVOs); + } + + /** + * 根据用户ID查询登录标识 + * + * @param userId 用户ID + * @return 登录标识VO列表 + */ + @GetMapping("/list/user/{userId}") + public Result> listLoginIdentitiesByUserId(@PathVariable Long userId) { + List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId); + return Result.success(loginIdentityVOs); + } + + /** + * 根据登录方式查询登录标识 + * + * @param loginMethod 登录方式 + * @return 登录标识VO列表 + */ + @GetMapping("/list/loginMethod/{loginMethod}") + public Result> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) { + List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod); + return Result.success(loginIdentityVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindEmailRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindEmailRequestDTO.java new file mode 100644 index 00000000..19751aaa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindEmailRequestDTO.java @@ -0,0 +1,24 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +/** + * 绑定邮箱请求 DTO + * 用于用户绑定邮箱账号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class BindEmailRequestDTO { + + /** + * 邮箱地址 + */ + private String email; + + /** + * 验证码 + */ + private String code; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindPhoneRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindPhoneRequestDTO.java new file mode 100644 index 00000000..4cdf63d2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/BindPhoneRequestDTO.java @@ -0,0 +1,26 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import com.fasterxml.jackson.annotation.JsonAlias; +import lombok.Data; + +/** + * 绑定手机号请求 DTO + * 用于用户绑定手机号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class BindPhoneRequestDTO { + + /** + * 手机号 + */ + private String phone; + + /** + * 验证码 + */ + @JsonAlias("code") + private String verificationCode; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginIdentityDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginIdentityDTO.java new file mode 100644 index 00000000..7dd0629c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginIdentityDTO.java @@ -0,0 +1,41 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户登录标识信息表 DTO + * 用于登录标识信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class LoginIdentityDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + private String loginMethod; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + private String inputValue; + + /** + * 输入时间 + */ + private LocalDateTime inputTime; + + /** + * 状态:1-有效,0-无效 + */ + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginRequestDTO.java new file mode 100644 index 00000000..c54ef16c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/LoginRequestDTO.java @@ -0,0 +1,62 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +/** + * 登录请求 DTO + * 用于用户账号密码登录 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Getter +@Setter +public class LoginRequestDTO implements AgreementAwareRequest { + + /** + * 账号 + */ + @NotBlank(message = "账号不能为空") + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + private String account; + + /** + * 密码 + */ + private String password; + + /** + * 记住我标志 + */ + private Boolean rememberMe; + + /** + * 店铺ID + */ + private Long shopId; + + /** + * Purpose: agreementAccepted supports LoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports LoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports LoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/PhoneLoginRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/PhoneLoginRequestDTO.java new file mode 100644 index 00000000..db6a5fe6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/PhoneLoginRequestDTO.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +/** + * 手机号验证码登录请求 DTO + * + * @author xiaowang + * @date 2026-03-03 + */ +@Data +public class PhoneLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + @NotBlank(message = "验证码不能为空") + @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String verificationCode; + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * 记住登录标志 + */ + private Boolean rememberMe; + + /** + * Purpose: agreementAccepted supports PhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports PhoneLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports PhoneLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RefreshTokenRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RefreshTokenRequestDTO.java new file mode 100644 index 00000000..d09c2c53 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RefreshTokenRequestDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +/** + * 刷新Token请求 DTO + * 用于刷新访问令牌 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class RefreshTokenRequestDTO { + + /** + * 刷新令牌 + */ + private String refreshToken; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RegisterRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RegisterRequestDTO.java new file mode 100644 index 00000000..6db71735 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/RegisterRequestDTO.java @@ -0,0 +1,78 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import lombok.Data; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +/** + * 注册请求 DTO + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class RegisterRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "账号不能为空") + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + + @NotBlank(message = "密码不能为空") + /** + * Field `password` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String password; + + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + @NotBlank(message = "验证码不能为空") + @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String verificationCode; + + /** + * Purpose: agreementAccepted supports RegisterRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports RegisterRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports RegisterRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/ResetPasswordRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/ResetPasswordRequestDTO.java new file mode 100644 index 00000000..966e748b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/ResetPasswordRequestDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +/** + * 重置密码请求 DTO + * 用于用户重置密码 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class ResetPasswordRequestDTO { + + /** + * 手机号 + */ + private String phone; + + /** + * 验证码 + */ + private String verificationCode; + + /** + * 新密码 + */ + private String newPassword; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SendVerificationCodeRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SendVerificationCodeRequestDTO.java new file mode 100644 index 00000000..a965f656 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SendVerificationCodeRequestDTO.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * 发送验证码请求 DTO。 + */ +@Data +public class SendVerificationCodeRequestDTO { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + + /** + * 业务场景编码,用来选择 FingertipDesigner 投递 MessageHub 时的配置。 + */ + private String sceneCode; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SwitchShopRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SwitchShopRequestDTO.java new file mode 100644 index 00000000..32aea2ce --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/SwitchShopRequestDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +@Data +/** + * SwitchShopRequestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SwitchShopRequestDTO { + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/UpdatePhoneRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/UpdatePhoneRequestDTO.java new file mode 100644 index 00000000..5ae525e8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/dto/UpdatePhoneRequestDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.dto; + +import lombok.Data; + +/** + * 更换手机号请求 DTO + * 用于用户更换绑定的手机号 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class UpdatePhoneRequestDTO { + + /** + * 原手机号 + */ + private String oldPhone; + + /** + * 新手机号 + */ + private String newPhone; + + /** + * 验证码 + */ + private String verificationCode; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/entity/LoginIdentityDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/entity/LoginIdentityDO.java new file mode 100644 index 00000000..fcf09a2e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/entity/LoginIdentityDO.java @@ -0,0 +1,52 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户登录标识信息表 DO + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_login_identity") +public class LoginIdentityDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + @TableField("login_method") + private String loginMethod; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + @TableField("input_value") + private String inputValue; + + /** + * 输入时间 + */ + @TableField("input_time") + private LocalDateTime inputTime; + + /** + * 状态:1-有效,0-无效 + */ + @TableField("status") + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/mapper/LoginIdentityMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/mapper/LoginIdentityMapper.java new file mode 100644 index 00000000..e89d7d07 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/mapper/LoginIdentityMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.auth.entity.LoginIdentityDO; + +/** + * 用户登录标识信息表 Mapper + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface LoginIdentityMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/LoginIdentityService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/LoginIdentityService.java new file mode 100644 index 00000000..22544cdd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/LoginIdentityService.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.auth.entity.LoginIdentityDO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginIdentityVO; + +import java.util.List; + +/** + * 用户登录标识信息表 Service + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface LoginIdentityService extends IService { + + /** + * 创建登录标识 + * + * @param loginIdentityDTO 登录标识DTO + * @return 登录标识ID + */ + Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO); + + /** + * 更新登录标识 + * + * @param id 登录标识ID + * @param loginIdentityDTO 登录标识DTO + * @return 是否更新成功 + */ + boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO); + + /** + * 删除登录标识 + * + * @param id 登录标识ID + * @return 是否删除成功 + */ + boolean deleteLoginIdentity(Long id); + + /** + * 根据ID查询登录标识 + * + * @param id 登录标识ID + * @return 登录标识VO + */ + LoginIdentityVO getLoginIdentityById(Long id); + + /** + * 查询所有登录标识 + * + * @return 登录标识VO列表 + */ + List listAllLoginIdentities(); + + /** + * 根据用户ID查询登录标识 + * + * @param userId 用户ID + * @return 登录标识VO列表 + */ + List listLoginIdentitiesByUserId(Long userId); + + /** + * 根据登录方式查询登录标识 + * + * @param loginMethod 登录方式 + * @return 登录标识VO列表 + */ + List listLoginIdentitiesByLoginMethod(String loginMethod); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/VerificationCodeService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/VerificationCodeService.java new file mode 100644 index 00000000..71073072 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/VerificationCodeService.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.service; + + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 验证码服务接口 + * + * @author xiaowang + * @date 2026-03-03 + */ +public interface VerificationCodeService { + + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String generateVerificationCode(); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ + void sendVerificationCode(String phone); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + void sendVerificationCode(String phone, String sceneCode); + + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean verifyCode(String phone, String code); + + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean canResend(String phone); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/LoginIdentityServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/LoginIdentityServiceImpl.java new file mode 100644 index 00000000..6b3343fc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/LoginIdentityServiceImpl.java @@ -0,0 +1,167 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginIdentityDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.entity.LoginIdentityDO; +import com.xiaowang.fingertipdesigner.core.modules.auth.mapper.LoginIdentityMapper; +import com.xiaowang.fingertipdesigner.core.modules.auth.service.LoginIdentityService; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginIdentityVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户登录标识信息表 Service 实现 + * 对应数据库表 t_login_identity + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class LoginIdentityServiceImpl extends ServiceImpl implements LoginIdentityService { + /** + * Variable `loginIdentityMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LoginIdentityMapper loginIdentityMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO) { + LoginIdentityDO loginIdentityDO = new LoginIdentityDO(); + loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); + loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); + loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); + loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); + loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); + loginIdentityMapper.insert(loginIdentityDO); + return loginIdentityDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO) { + LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); + if (loginIdentityDO == null) { + return false; + } + loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); + loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod()); + loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue()); + loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime()); + loginIdentityDO.setStatus(loginIdentityDTO.getStatus()); + return loginIdentityMapper.updateById(loginIdentityDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteLoginIdentity(Long id) { + return loginIdentityMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return LoginIdentityVO result consumed by the caller or returned to the frontend + */ + public LoginIdentityVO getLoginIdentityById(Long id) { + LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); + if (loginIdentityDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDO parameter `loginIdentityDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(loginIdentityDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllLoginIdentities() { + List loginIdentityDOs = loginIdentityMapper.selectList(null); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listLoginIdentitiesByUserId(Long userId) { + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .eq(LoginIdentityDO::getUserId, userId) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginMethod parameter `loginMethod` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listLoginIdentitiesByLoginMethod(String loginMethod) { + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .eq(LoginIdentityDO::getLoginMethod, loginMethod) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param loginIdentityDO 登录标识DO + * @return 登录标识VO + */ + private LoginIdentityVO convertToVO(LoginIdentityDO loginIdentityDO) { + LoginIdentityVO loginIdentityVO = new LoginIdentityVO(); + loginIdentityVO.setId(loginIdentityDO.getId()); + loginIdentityVO.setUserId(loginIdentityDO.getUserId()); + loginIdentityVO.setLoginMethod(loginIdentityDO.getLoginMethod()); + loginIdentityVO.setInputValue(loginIdentityDO.getInputValue()); + loginIdentityVO.setInputTime(loginIdentityDO.getInputTime()); + loginIdentityVO.setUpdateTime(loginIdentityDO.getUpdateTime()); + loginIdentityVO.setStatus(loginIdentityDO.getStatus()); + return loginIdentityVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/VerificationCodeServiceImpl.java new file mode 100644 index 00000000..96ce5f2f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -0,0 +1,148 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.fingertipdesigner.core.modules.auth.service.VerificationCodeService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.security.SecureRandom; +import java.time.Duration; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 验证码服务实现。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class VerificationCodeServiceImpl implements VerificationCodeService { + + /** + * Purpose: CODE_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the code prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CODE_PREFIX = "verification:code:"; + /** + * Purpose: SEND_TIME_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the send time prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SEND_TIME_PREFIX = "verification:send_time:"; + /** + * Purpose: CODE_LENGTH supports VerificationCodeServiceImpl.java by holding or executing the code length business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int CODE_LENGTH = 6; + /** + * Purpose: CODE_EXPIRE_MINUTES supports VerificationCodeServiceImpl.java by holding or executing the code expire minutes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int CODE_EXPIRE_MINUTES = 5; + /** + * Purpose: RESEND_INTERVAL_SECONDS supports VerificationCodeServiceImpl.java by holding or executing the resend interval seconds business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int RESEND_INTERVAL_SECONDS = 60; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubClientService messageHubClientService; + + @Override + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String generateVerificationCode() { + SecureRandom random = new SecureRandom(); + StringBuilder code = new StringBuilder(); + for (int i = 0; i < CODE_LENGTH; i++) { + code.append(random.nextInt(10)); + } + return code.toString(); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ + public void sendVerificationCode(String phone) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendVerificationCode(phone, "USER_LOGIN_SMS_CODE"); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + public void sendVerificationCode(String phone, String sceneCode) { + String code = generateVerificationCode(); + + String codeKey = CODE_PREFIX + phone; + String sendTimeKey = SEND_TIME_PREFIX + phone; + + redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); + redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), + Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); + + messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); + log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + } + + @Override + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean verifyCode(String phone, String code) { + String codeKey = CODE_PREFIX + phone; + String storedCode = redisTemplate.opsForValue().get(codeKey); + + if (storedCode == null) { + log.warn("验证码不存在或已过期,手机号: {}", phone); + return false; + } + + if (!storedCode.equals(code)) { + log.warn("验证码错误,手机号: {}", phone); + return false; + } + + redisTemplate.delete(codeKey); + log.info("验证码验证成功,手机号: {}", phone); + return true; + } + + @Override + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean canResend(String phone) { + String sendTimeKey = SEND_TIME_PREFIX + phone; + String sendTime = redisTemplate.opsForValue().get(sendTimeKey); + return sendTime == null; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginIdentityVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginIdentityVO.java new file mode 100644 index 00000000..6dee9e5f1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginIdentityVO.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户登录标识信息表 VO + * 用于前端展示登录标识信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class LoginIdentityVO { + + /** + * 登录标识唯一主键ID(雪花id) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 登录方式(0-手机号、1-账号、2-邮箱) + */ + private String loginMethod; + + /** + * 登录方式名称 + */ + private String loginMethodName; + + /** + * 前端输入的具体值(如手机号、账号、邮箱) + */ + private String inputValue; + + /** + * 输入时间 + */ + private LocalDateTime inputTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 状态:1-有效,0-无效 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginResponseVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginResponseVO.java new file mode 100644 index 00000000..a78e5d66 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginResponseVO.java @@ -0,0 +1,97 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 登录响应 VO + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class LoginResponseVO { + + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String accessToken; + + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String refreshToken; + + /** + * Field `userInfo` (UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private UserInfo userInfo; + + /** + * Field `needSetPassword` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private boolean needSetPassword; // 是否需要设置密码 + + @Data + /** + * Purpose: UserInfo supports LoginResponseVO.java by holding or executing the user info business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class UserInfo { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String avatar; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer type; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `shopAuthorizationExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime shopAuthorizationExpireTime; + /** + * Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean shopAuthorizationExpired; + @JsonSerialize(contentUsing = ToStringSerializer.class) + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + /** + * Field `shopNames` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopNames; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginShopSelectionVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginShopSelectionVO.java new file mode 100644 index 00000000..96eea3f4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/auth/vo/LoginShopSelectionVO.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.modules.auth.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +/** + * 登录页可选店铺结果。 + */ +@Data +public class LoginShopSelectionVO { + + /** + * Field `allowShoplessLogin` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private boolean allowShoplessLogin; + + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String message; + + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops = new ArrayList<>(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/admin/AdminCommentController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/admin/AdminCommentController.java new file mode 100644 index 00000000..d04d54c6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/admin/AdminCommentController.java @@ -0,0 +1,65 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.content.service.CommentService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.content.vo.CommentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/admin/comment") +@RequiredArgsConstructor +/** + * AdminCommentController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminCommentController { + /** + * Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentService commentService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/list") + @RequirePermission("comment:view") + public Result> listComments( + HttpServletRequest request, + @RequestParam(required = false) Long productId, + @RequestParam(required = false) Long userId, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) String keyword + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return Result.success(commentService.listAdminComments(productId, userId, scopedShopId, keyword)); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("comment:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long managedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(commentService.adminDeleteComment(id, managedShopId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/front/CommentController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/front/CommentController.java new file mode 100644 index 00000000..1c03a0a8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/controller/front/CommentController.java @@ -0,0 +1,215 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.content.dto.CommentDTO; +import com.xiaowang.fingertipdesigner.core.modules.content.service.CommentService; +import com.xiaowang.fingertipdesigner.core.modules.content.vo.CommentVO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ChunkUploadService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.support.security.UploadSecurityValidator; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.io.FileInputStream; +import java.util.List; + +@RestController +@RequestMapping({"/comment", "/api/comment"}) +@RequiredArgsConstructor +public class CommentController { + + private final CommentService commentService; + private final ObjectStorageFileService objectStorageFileService; + private final PrimaryObjectStorageService primaryObjectStorageService; + private final ChunkUploadService chunkUploadService; + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; + + @PostMapping("/create") + public Result createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) { + Long userId = (Long) request.getAttribute("userId"); + Long id = commentService.createComment(userId, commentDTO); + return Result.success(id); + } + + @PostMapping("/upload-image") + @OperationGuard(action = "comment-image-upload", ttlSeconds = 15, message = "图片正在上传中,请勿重复操作") + public Result uploadCommentImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + try { + uploadSecurityValidator.validate(file); + String originalFilename = normalizeOriginalFilename(file.getOriginalFilename()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadFile(file, objectName); + return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize())); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("评价图片上传失败: " + e.getMessage()); + } + } + + @PostMapping("/upload-image/init") + @OperationGuard(action = "comment-image-upload-init", ttlSeconds = 10, message = "图片正在上传中,请勿重复操作") + public Result initCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); + return Result.success(chunkUploadService.initCommentImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-image/chunk") + @OperationGuard(action = "comment-image-upload-chunk", ttlSeconds = 20) + public Result uploadCommentImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateChunk(chunkFile); + chunkUploadService.uploadCommentImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-image/complete") + @OperationGuard(action = "comment-image-upload-complete", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result completeCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareCommentImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = normalizeOriginalFilename(preparedUploadFile.getFileName()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + ObjectStorageFileVO fileVO = createCommentImageRecord(originalFilename, fileUrl, objectName, preparedUploadFile.getContentType(), preparedUploadFile.getFileSize()); + chunkUploadService.clearCommentImageUpload(userId, requestDTO.getUploadId()); + return Result.success(fileVO); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("评价图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-image/{uploadId}") + @OperationGuard(action = "comment-image-upload-cancel", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result cancelCommentImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再取消上传"); + } + chunkUploadService.clearCommentImageUpload(userId, uploadId); + return Result.success(true); + } + + @PutMapping("/update/{id}") + public Result updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = commentService.updateComment(id, userId, commentDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = commentService.deleteComment(id, userId); + return Result.success(success); + } + + @GetMapping("/get/{id}") + public Result getCommentById(@PathVariable Long id) { + CommentVO commentVO = commentService.getCommentById(id); + return Result.success(commentVO); + } + + @GetMapping("/list/all") + public Result> listAllComments() { + List commentVOs = commentService.listAllComments(); + return Result.success(commentVOs); + } + + @GetMapping("/list/user/{userId}") + public Result> listCommentsByUserId(@PathVariable Long userId) { + List commentVOs = commentService.listCommentsByUserId(userId); + return Result.success(commentVOs); + } + + @GetMapping("/list/shop/{shopId}") + public Result> listCommentsByShopId(@PathVariable Long shopId) { + List commentVOs = commentService.listCommentsByShopId(shopId); + return Result.success(commentVOs); + } + + @GetMapping("/list/product/{productId}") + public Result> listCommentsByProductId(@PathVariable Long productId) { + List commentVOs = commentService.listCommentsByProductId(productId); + return Result.success(commentVOs); + } + + @GetMapping("/list/parent/{parentCommentId}") + public Result> listCommentsByParentCommentId(@PathVariable Long parentCommentId) { + List commentVOs = commentService.listCommentsByParentCommentId(parentCommentId); + return Result.success(commentVOs); + } + + private ObjectStorageFileVO createCommentImageRecord(String originalFilename, String fileUrl, String objectName, String contentType, Long fileSize) { + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(fileUrl); + dto.setObjectName(objectName); + dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); + dto.setPrimaryUrl(fileUrl); + dto.setBackupProvider(objectStorageProperties.getBackupProvider()); + dto.setContentType(contentType); + dto.setFileSize(fileSize); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setStatus(1); + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return objectStorageFileService.getObjectStorageFileById(fileId); + } + + private String normalizeOriginalFilename(String originalFilename) { + if (originalFilename == null || originalFilename.isBlank()) { + return "comment-image"; + } + return originalFilename; + } + + private String resolveFileExtension(String originalFilename) { + if (originalFilename == null || !originalFilename.contains(".")) { + return ""; + } + return originalFilename.substring(originalFilename.lastIndexOf(".")); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/dto/CommentDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/dto/CommentDTO.java new file mode 100644 index 00000000..63411b8f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/dto/CommentDTO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 用户评论信息表 DTO + * 用于评论信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class CommentDTO { + + /** + * 评论用户ID,关联用户表主键 + */ + private Long userId; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + private Long shopId; + + /** + * 关联商品表主键(0表示非商品评论) + */ + private Long productId; + + /** + * 评论内容 + */ + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + private Long parentCommentId; + + /** + * 评论评分:1-5星,根评论使用 + */ + private Integer ratingScore; + + /** + * 评论图片文件ID集合,根评论使用 + */ + private List imageFileIds; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/entity/CommentDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/entity/CommentDO.java new file mode 100644 index 00000000..845dd471 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/entity/CommentDO.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户评论信息表 DO + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_comment") +public class CommentDO extends BaseEntity { + + /** + * 评论用户ID,关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + @TableField("shop_id") + private Long shopId; + + /** + * 关联商品表主键(0表示非商品评论) + */ + @TableField("product_id") + private Long productId; + + /** + * 评论内容 + */ + @TableField("comment_content") + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + @TableField("parent_comment_id") + private Long parentCommentId; + + /** + * 评论评分:1-5星 + */ + @TableField("rating_score") + private Integer ratingScore; + + /** + * 评论图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 评论点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/mapper/CommentMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/mapper/CommentMapper.java new file mode 100644 index 00000000..32e081a5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/mapper/CommentMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO; + +/** + * 用户评论信息表 Mapper + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface CommentMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/CommentService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/CommentService.java new file mode 100644 index 00000000..289f6da5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/CommentService.java @@ -0,0 +1,139 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO; +import com.xiaowang.fingertipdesigner.core.modules.content.dto.CommentDTO; +import com.xiaowang.fingertipdesigner.core.modules.content.vo.CommentVO; + +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户评论信息表 Service + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface CommentService extends IService { + + /** + * 创建评论 + * + * @param commentDTO 评论DTO + * @return 评论ID + */ + Long createComment(CommentDTO commentDTO); + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createComment(Long currentUserId, CommentDTO commentDTO); + + /** + * 更新评论 + * + * @param id 评论ID + * @param commentDTO 评论DTO + * @return 是否更新成功 + */ + boolean updateComment(Long id, CommentDTO commentDTO); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO); + + /** + * 删除评论 + * + * @param id 评论ID + * @return 是否删除成功 + */ + boolean deleteComment(Long id); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteComment(Long id, Long currentUserId); + + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean adminDeleteComment(Long id, Long managedShopId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminComments(Long productId, Long userId, Long shopId, String keyword); + + /** + * 根据ID查询评论 + * + * @param id 评论ID + * @return 评论VO + */ + CommentVO getCommentById(Long id); + + /** + * 查询所有评论 + * + * @return 评论VO列表 + */ + List listAllComments(); + + /** + * 根据用户ID查询评论 + * + * @param userId 用户ID + * @return 评论VO列表 + */ + List listCommentsByUserId(Long userId); + + /** + * 根据店铺ID查询评论 + * + * @param shopId 店铺ID + * @return 评论VO列表 + */ + List listCommentsByShopId(Long shopId); + + /** + * 根据商品ID查询评论 + * + * @param productId 商品ID + * @return 评论VO列表 + */ + List listCommentsByProductId(Long productId); + + /** + * 根据父级评论ID查询回复 + * + * @param parentCommentId 父级评论ID + * @return 评论VO列表 + */ + List listCommentsByParentCommentId(Long parentCommentId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/impl/CommentServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/impl/CommentServiceImpl.java new file mode 100644 index 00000000..18e43070 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/service/impl/CommentServiceImpl.java @@ -0,0 +1,621 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.content.dto.CommentDTO; +import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.content.service.CommentService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.content.vo.CommentVO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户评论信息表 Service 实现 + * 对应数据库表 t_comment + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class CommentServiceImpl extends ServiceImpl implements CommentService { + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createComment(CommentDTO commentDTO) { + if (commentDTO == null || commentDTO.getUserId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录后再评论"); + } + return createComment(commentDTO.getUserId(), commentDTO); + } + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createComment(Long currentUserId, CommentDTO commentDTO) { + if (currentUserId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录后再评论"); + } + if (commentDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + String content = sanitizeContent(commentDTO.getCommentContent()); + Long productId = normalizeId(commentDTO.getProductId()); + Long parentCommentId = normalizeId(commentDTO.getParentCommentId()); + if (productId == null && parentCommentId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择要评论的作品"); + } + CommentDO parentComment = null; + if (parentCommentId != null) { + parentComment = commentMapper.selectById(parentCommentId); + if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("回复的评论不存在"); + } + if (productId == null) { + productId = parentComment.getProductId(); + } else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("回复内容与作品不匹配"); + } + } + Long shopId = normalizeId(commentDTO.getShopId()); + if (shopId == null && productId != null) { + ProductDO product = productMapper.selectById(productId); + if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) { + shopId = product.getShopId(); + } + } + CommentDO commentDO = new CommentDO(); + boolean rootComment = parentCommentId == null; + commentDO.setUserId(currentUserId); + commentDO.setShopId(shopId); + commentDO.setProductId(productId); + commentDO.setCommentContent(content); + commentDO.setParentCommentId(parentCommentId); + if (rootComment) { + commentDO.setRatingScore(normalizeRatingScore(commentDTO.getRatingScore())); + commentDO.setImageFileIds(joinImageFileIds(commentDTO.getImageFileIds())); + } + commentDO.setLikeCount(0); + commentDO.setIsDelete(0); + commentMapper.insert(commentDO); + return commentDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateComment(Long id, CommentDTO commentDTO) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null) { + return false; + } + commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteComment(Long id) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null) { + return false; + } + commentDO.setIsDelete(1); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能修改自己的评论"); + } + commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteComment(Long id, Long currentUserId) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能删除自己的评论"); + } + commentDO.setIsDelete(1); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean adminDeleteComment(Long id, Long managedShopId) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return false; + } + if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权删除其他门店评论"); + } + commentDO.setIsDelete(1); + commentDO.setUpdateTime(LocalDateTime.now()); + return commentMapper.updateById(commentDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CommentVO result consumed by the caller or returned to the frontend + */ + public CommentVO getCommentById(Long id) { + CommentDO commentDO = commentMapper.selectById(id); + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDO parameter `commentDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(commentDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllComments() { + return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime)); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByUserId(Long userId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getUserId, userId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByShopId(Long shopId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getShopId, shopId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByProductId(Long productId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getProductId, productId) + .eq(CommentDO::getIsDelete, 0) + .orderByDesc(CommentDO::getCreateTime) + ); + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildTree(commentDOs); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param parentCommentId parameter `parentCommentId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listCommentsByParentCommentId(Long parentCommentId) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getParentCommentId, parentCommentId) + .eq(CommentDO::getIsDelete, 0) + .orderByAsc(CommentDO::getCreateTime) + ); + return commentDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminComments(Long productId, Long userId, Long shopId, String keyword) { + List commentDOs = commentMapper.selectList( + Wrappers.lambdaQuery(CommentDO.class) + .eq(CommentDO::getIsDelete, 0) + .eq(productId != null && productId > 0, CommentDO::getProductId, productId) + .eq(userId != null && userId > 0, CommentDO::getUserId, userId) + .eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId) + .like(StringUtils.hasText(keyword), CommentDO::getCommentContent, keyword) + .orderByDesc(CommentDO::getCreateTime) + ); + return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param commentDO 评论DO + * @return 评论VO + */ + private CommentVO convertToVO(CommentDO commentDO) { + CommentVO commentVO = new CommentVO(); + commentVO.setId(commentDO.getId()); + commentVO.setUserId(commentDO.getUserId()); + commentVO.setShopId(commentDO.getShopId()); + commentVO.setProductId(commentDO.getProductId()); + commentVO.setCommentContent(commentDO.getCommentContent()); + commentVO.setParentCommentId(commentDO.getParentCommentId()); + commentVO.setLikeCount(commentDO.getLikeCount()); + commentVO.setRatingScore(commentDO.getRatingScore()); + List imageFileIds = parseImageFileIds(commentDO.getImageFileIds()); + commentVO.setImageFileIds(imageFileIds); + commentVO.setImageUrls(resolveImageUrls(imageFileIds)); + commentVO.setCreateTime(commentDO.getCreateTime()); + commentVO.setUpdateTime(commentDO.getUpdateTime()); + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + fillDisplayFields(commentVO, commentDO); + return commentVO; + } + + /** + * Run business method `toCommentVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper) { + return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList()); + } + + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List buildTree(List commentDOs) { + Map rootMap = new HashMap<>(); + List roots = new ArrayList<>(); + List replies = new ArrayList<>(); + for (CommentDO commentDO : commentDOs) { + CommentVO vo = convertToVO(commentDO); + if (commentDO.getParentCommentId() == null || commentDO.getParentCommentId() <= 0) { + vo.setReplies(new ArrayList<>()); + rootMap.put(commentDO.getId(), vo); + roots.add(vo); + } else { + replies.add(vo); + } + } + replies.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder()))); + for (CommentVO reply : replies) { + CommentVO root = rootMap.get(reply.getParentCommentId()); + if (root != null) { + root.getReplies().add(reply); + } + } + roots.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed()); + return roots; + } + + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { + UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); + if (user != null) { + commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + } + ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId()); + if (shop != null) { + commentVO.setShopName(shop.getShopName()); + } + ProductDO product = commentDO.getProductId() == null ? null : productMapper.selectById(commentDO.getProductId()); + if (product != null) { + commentVO.setProductTitle(product.getTitle()); + } + if (commentDO.getParentCommentId() != null && commentDO.getParentCommentId() > 0) { + CommentDO parent = commentMapper.selectById(commentDO.getParentCommentId()); + if (parent != null && !Integer.valueOf(1).equals(parent.getIsDelete())) { + commentVO.setParentCommentContent(parent.getCommentContent()); + } + } + } + + private Integer normalizeRatingScore(Integer ratingScore) { + if (ratingScore == null) { + return 5; + } + return Math.max(1, Math.min(5, ratingScore)); + } + + private String joinImageFileIds(List imageFileIds) { + if (imageFileIds == null || imageFileIds.isEmpty()) { + return null; + } + return imageFileIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .limit(6) + .map(String::valueOf) + .collect(Collectors.joining(",")); + } + + private List parseImageFileIds(String imageFileIds) { + List result = new ArrayList<>(); + if (!StringUtils.hasText(imageFileIds)) { + return result; + } + for (String token : imageFileIds.split(",")) { + if (!StringUtils.hasText(token)) { + continue; + } + try { + Long id = Long.valueOf(token.trim()); + if (id > 0) { + result.add(id); + } + } catch (NumberFormatException ignored) { + // Ignore malformed legacy tokens. + } + } + return new ArrayList<>(new LinkedHashSet<>(result)); + } + + private List resolveImageUrls(List imageFileIds) { + if (imageFileIds == null || imageFileIds.isEmpty()) { + return new ArrayList<>(); + } + Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(new LinkedHashSet<>(imageFileIds)); + List urls = new ArrayList<>(); + for (Long imageFileId : imageFileIds) { + ObjectStorageFileVO fileVO = fileMap.get(imageFileId); + if (fileVO == null || !StringUtils.hasText(fileVO.getFileUrl())) { + continue; + } + urls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); + } + return urls; + } + + /** + * Run business method `activeQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { + return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); + } + + /** + * Run business method `normalizeId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeId(Long id) { + return id == null || id <= 0 ? null : id; + } + + /** + * Run business method `sanitizeContent`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param content parameter `content` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String sanitizeContent(String content) { + if (!StringUtils.hasText(content)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim(); + sanitized = sanitized.replaceAll("<[^>]*>", ""); + if (!StringUtils.hasText(sanitized)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论内容不能为空"); + } + if (sanitized.length() > 300) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("评论最多输入 300 个字"); + } + return sanitized; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/vo/CommentVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/vo/CommentVO.java new file mode 100644 index 00000000..e9742717 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/content/vo/CommentVO.java @@ -0,0 +1,102 @@ +package com.xiaowang.fingertipdesigner.core.modules.content.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 用户评论信息表 VO + * 用于前端展示评论信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class CommentVO { + + /** + * 评论唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 评论用户ID,关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 关联店铺表主键(0表示非店铺评论) + */ + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 关联商品表主键(0表示非商品评论) + */ + private Long productId; + + /** + * 商品标题 + */ + private String productTitle; + + /** + * 评论内容 + */ + private String commentContent; + + /** + * 父级评论ID(0表示为根评论) + */ + private Long parentCommentId; + + /** + * 父级评论内容 + */ + private String parentCommentContent; + + /** + * 评论点赞数 + */ + private Integer likeCount; + + /** + * 评论评分:1-5星 + */ + private Integer ratingScore; + + /** + * 评论图片文件ID集合 + */ + private List imageFileIds; + + /** + * 评论图片展示链接 + */ + private List imageUrls; + + /** + * 评论创建时间 + */ + private LocalDateTime createTime; + + /** + * 评论更新时间 + */ + private LocalDateTime updateTime; + + /** + * 回复列表 + */ + private List replies; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/AliyunOssConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/AliyunOssConfig.java new file mode 100644 index 00000000..30ef6f2a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/AliyunOssConfig.java @@ -0,0 +1,49 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.config; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "aliyun.oss") +public class AliyunOssConfig { + + @NotNull + private Boolean enabled; + @NotBlank + private String endpoint; + @NotBlank + private String region; + @NotBlank + private String bucketName; + @NotBlank + private String accessKeyId; + @NotBlank + private String accessKeySecret; + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean(destroyMethod = "shutdown") + @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") + public OSS aliyunOssClient() { + if (!StringUtils.hasText(endpoint) + || !StringUtils.hasText(accessKeyId) + || !StringUtils.hasText(accessKeySecret)) { + throw new IllegalStateException("Aliyun OSS is enabled but endpoint/accessKeyId/accessKeySecret is incomplete"); + } + return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/MinioStorageConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/MinioStorageConfig.java new file mode 100644 index 00000000..74727616 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/MinioStorageConfig.java @@ -0,0 +1,52 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.config; + +import io.minio.MinioClient; +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "minio") +public class MinioStorageConfig { + + @NotNull + private Boolean enabled; + + private String endpoint; + + private String bucketName; + + private String accessKey; + + private String secretKey; + + @NotNull + private Boolean privateBucket; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean + @ConditionalOnProperty(prefix = "minio", name = "enabled", havingValue = "true") + public MinioClient minioClient() { + if (!StringUtils.hasText(endpoint) + || !StringUtils.hasText(accessKey) + || !StringUtils.hasText(secretKey)) { + throw new IllegalStateException("MinIO is enabled but endpoint/accessKey/secretKey is incomplete"); + } + return MinioClient.builder() + .endpoint(endpoint) + .credentials(accessKey, secretKey) + .build(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/QiniuKodoConfig.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/QiniuKodoConfig.java new file mode 100644 index 00000000..15c515f8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/config/QiniuKodoConfig.java @@ -0,0 +1,82 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.config; + +import com.qiniu.common.Zone; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.UploadManager; +import com.qiniu.util.Auth; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "qiniu.kodo") +public class QiniuKodoConfig { + + @NotBlank + private String accessKey; + + @NotBlank + private String secretKey; + + @NotBlank + private String bucketName; + + @NotBlank + private String domain; + + @NotBlank + private String zone; + + @NotNull + private Boolean privateBucket; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean + public Auth qiniuAuth() { + return Auth.create(accessKey, secretKey); + } + + @Bean + public com.qiniu.storage.Configuration qiniuConfiguration() { + return new com.qiniu.storage.Configuration(resolveZone()); + } + + @Bean + public UploadManager qiniuUploadManager(com.qiniu.storage.Configuration qiniuConfiguration) { + return new UploadManager(qiniuConfiguration); + } + + @Bean + public BucketManager qiniuBucketManager(com.qiniu.storage.Configuration qiniuConfiguration, Auth qiniuAuth) { + return new BucketManager(qiniuAuth, qiniuConfiguration); + } + + private Zone resolveZone() { + String normalizedZone = zone.trim().toLowerCase(); + switch (normalizedZone) { + case "z0": + return Zone.zone0(); + case "z1": + return Zone.zone1(); + case "z2": + return Zone.zone2(); + case "na0": + return Zone.zoneNa0(); + case "as0": + return Zone.zoneAs0(); + default: + throw new IllegalStateException("Unsupported Qiniu zone: " + zone); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/FrontendFileController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/FrontendFileController.java new file mode 100644 index 00000000..a26a0ce3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/FrontendFileController.java @@ -0,0 +1,84 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * Purpose: FrontendFileController exposes signed-file access only for public frontend references. + * Usage: anonymous clients call /file/get-signed-url/{fileId}; the controller verifies the file is referenced by public content before returning a URL. + */ +@RestController +@RequestMapping("/file") +@RequiredArgsConstructor +public class FrontendFileController { + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ProductMapper productMapper; + private final ShopMapper shopMapper; + private final EffectDiagramMapper effectDiagramMapper; + + /** + * Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public. + * Usage: pass a public file id and optional expiry minutes; private or unreferenced files are rejected. + */ + @GetMapping("/get-signed-url/{fileId}") + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + try { + ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); + if (fileVO == null) { + return Result.error("文件不存在"); + } + if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) { + return Result.error("文件不可公开访问"); + } + + String signedUrl = hasObjectStorageReference(fileVO) + ? objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes) + : fileVO.getFileUrl(); + return Result.success(signedUrl); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("获取签名链接失败: " + e.getMessage()); + } + } + + private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { + return StringUtils.hasText(fileVO.getObjectName()) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getPrimaryUrl())) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); + } + + /** + * Purpose: isPublicFileReference prevents arbitrary uploaded files from being exposed through the public signing endpoint. + * Usage: call with a file id and keep mapper checks in sync with public content tables. + */ + private boolean isPublicFileReference(Long fileId) { + if (fileId == null) { + return false; + } + return positive(productMapper.countPublicImageReference(fileId)) + || positive(shopMapper.countPublicImageReference(fileId)) + || positive(effectDiagramMapper.countPublicImageReference(fileId)); + } + + /** + * Purpose: positive normalizes nullable mapper counts. + * Usage: use for COUNT(*) results where null should behave like zero. + */ + private boolean positive(Long count) { + return count != null && count > 0; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/ObjectStorageFileController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/ObjectStorageFileController.java new file mode 100644 index 00000000..1653f94c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/controller/front/ObjectStorageFileController.java @@ -0,0 +1,282 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ChunkUploadService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import com.xiaowang.fingertipdesigner.core.support.security.UploadSecurityValidator; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ChunkUploadSessionVO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.io.FileInputStream; +import java.util.List; + +/** + * 对象存储文件控制器,对应表 t_object_storage_file。 + */ +@RestController +@RequestMapping("/admin/object-storage-file") +@RequiredArgsConstructor +@Validated +public class ObjectStorageFileController { + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ChunkUploadService chunkUploadService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Purpose: uploadSecurityValidator supports ObjectStorageFileController.java by holding or executing the upload security validator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; + + @PostMapping("/upload/init") + @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); + return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO)); + } + + @PostMapping("/upload/chunk") + @OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validateChunk(chunkFile); + chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload/complete") + @OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; + + ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( + inputStream, + preparedUploadFile.getFileSize(), + preparedUploadFile.getContentType(), + objectName + ); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(uploadOutcome.getPrimaryUrl()); + dto.setObjectName(objectName); + dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); + dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); + dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); + dto.setContentType(preparedUploadFile.getContentType()); + dto.setFileSize(preparedUploadFile.getFileSize()); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setUploadAttempts(uploadOutcome.getAttempts()); + dto.setStatus(1); + + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("文件上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload/{uploadId}") + @OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelChunkUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId); + return Result.success(true); + } + + /** + * 上传文件。 + */ + @PostMapping("/upload") + @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result uploadFile(@RequestParam("file") MultipartFile file) { + try { + uploadSecurityValidator.validate(file); + String originalFilename = file.getOriginalFilename(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; + + ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary( + file.getInputStream(), + file.getSize(), + file.getContentType(), + objectName + ); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(uploadOutcome.getPrimaryUrl()); + dto.setObjectName(objectName); + dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider()); + dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl()); + dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders())); + dto.setContentType(file.getContentType()); + dto.setFileSize(file.getSize()); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setUploadAttempts(uploadOutcome.getAttempts()); + dto.setStatus(1); + + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("文件上传失败: " + e.getMessage()); + } + } + + /** + * 获取带签名的图片链接。 + */ + @GetMapping("/get-signed-url/{fileId}") + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + try { + ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); + if (fileVO == null) { + return Result.error("文件不存在"); + } + + String signedUrl = objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes); + return Result.success(signedUrl); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("获取签名链接失败: " + e.getMessage()); + } + } + + @PostMapping("/create") + @OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) { + Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateObjectStorageFile(@PathVariable Long id, + @RequestBody ObjectStorageFileDTO objectStorageFileDTO) { + boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteObjectStorageFile(@PathVariable Long id) { + boolean success = objectStorageFileService.deleteObjectStorageFile(id); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getObjectStorageFileById(@PathVariable Long id) { + ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id); + return Result.success(objectStorageFileVO); + } + + @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllObjectStorageFiles() { + List objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles(); + return Result.success(objectStorageFileVOs); + } + + @GetMapping("/list/status/{status}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listObjectStorageFilesByStatus(@PathVariable Integer status) { + List objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status); + return Result.success(objectStorageFileVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java new file mode 100644 index 00000000..c8fa0499 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadCompleteRequestDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 分片上传完成请求 + */ +@Data +public class ChunkUploadCompleteRequestDTO { + + @NotBlank(message = "上传标识不能为空") + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String uploadId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadInitRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadInitRequestDTO.java new file mode 100644 index 00000000..576508ca --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ChunkUploadInitRequestDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.Data; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +/** + * 分片上传初始化请求 + */ +@Data +public class ChunkUploadInitRequestDTO { + + @NotBlank(message = "文件名不能为空") + /** + * Field `fileName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String fileName; + + @NotNull(message = "文件大小不能为空") + @Min(value = 1, message = "文件大小不合法") + /** + * Field `fileSize` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long fileSize; + + @NotBlank(message = "文件类型不能为空") + /** + * Field `contentType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String contentType; + + @NotBlank(message = "文件指纹不能为空") + /** + * Field `fileFingerprint` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String fileFingerprint; + + @NotBlank(message = "上传场景不能为空") + /** + * Field `scene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String scene; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageBackupMessage.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageBackupMessage.java new file mode 100644 index 00000000..02d3e4cd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageBackupMessage.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ObjectStorageBackupMessage { + + private Long fileId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageFileDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageFileDTO.java new file mode 100644 index 00000000..39ff6619 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageFileDTO.java @@ -0,0 +1,70 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 对象存储文件信息表 DTO + * 用于文件信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ObjectStorageFileDTO { + + /** + * 文件名称 + */ + private String fileName; + + /** + * 文件访问链接 + */ + private String fileUrl; + + private String objectName; + + private String primaryProvider; + + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; + + private String contentType; + + private Long fileSize; + + private Integer primaryUploadStatus; + + private Integer backupUploadStatus; + + private Integer backupRetryCount; + + private String backupLastError; + + private LocalDateTime backupUploadedAt; + + private LocalDateTime backupLastRetryTime; + + private List uploadAttempts; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + private Integer status; + + /** + * 文件删除时间(NULL表示未删除) + */ + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + private LocalDateTime recycleTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageReplicaDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageReplicaDTO.java new file mode 100644 index 00000000..b01746c5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageReplicaDTO.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ObjectStorageReplicaDTO { + + private String provider; + + private String objectName; + + private String objectUrl; + + private Integer uploadStatus; + + private Integer retryCount; + + private String lastError; + + private LocalDateTime uploadedAt; + + private LocalDateTime lastRetryTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadAttempt.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadAttempt.java new file mode 100644 index 00000000..1aaae092 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadAttempt.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ObjectStorageUploadAttempt { + + private String provider; + + private String objectName; + + private String objectUrl; + + private Integer uploadStatus; + + private Integer retryCount; + + private String lastError; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadOutcome.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadOutcome.java new file mode 100644 index 00000000..3fc3043b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/dto/ObjectStorageUploadOutcome.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +@Data +@AllArgsConstructor +public class ObjectStorageUploadOutcome { + + private String primaryProvider; + + private String primaryUrl; + + private List attempts; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageFileDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageFileDO.java new file mode 100644 index 00000000..d9dd20f9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageFileDO.java @@ -0,0 +1,91 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 对象存储文件信息表 DO + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_object_storage_file") +public class ObjectStorageFileDO extends BaseEntity { + + /** + * 文件名称 + */ + @TableField("file_name") + private String fileName; + + /** + * 文件访问链接 + */ + @TableField("file_url") + private String fileUrl; + + @TableField("object_name") + private String objectName; + + @TableField("primary_provider") + private String primaryProvider; + + @TableField("primary_url") + private String primaryUrl; + + @TableField("backup_provider") + private String backupProvider; + + @TableField("backup_url") + private String backupUrl; + + @TableField("content_type") + private String contentType; + + @TableField("file_size") + private Long fileSize; + + @TableField("primary_upload_status") + private Integer primaryUploadStatus; + + @TableField("backup_upload_status") + private Integer backupUploadStatus; + + @TableField("backup_retry_count") + private Integer backupRetryCount; + + @TableField("backup_last_error") + private String backupLastError; + + @TableField("backup_uploaded_at") + private LocalDateTime backupUploadedAt; + + @TableField("backup_last_retry_time") + private LocalDateTime backupLastRetryTime; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + @TableField("status") + private Integer status; + + /** + * 文件删除时间(NULL表示未删除) + */ + @TableField("delete_time") + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + @TableField("recycle_time") + private LocalDateTime recycleTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageReplicaDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageReplicaDO.java new file mode 100644 index 00000000..4db307dd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/entity/ObjectStorageReplicaDO.java @@ -0,0 +1,42 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_object_storage_file_replica") +public class ObjectStorageReplicaDO extends BaseEntity { + + @TableField("file_id") + private Long fileId; + + @TableField("provider") + private String provider; + + @TableField("object_name") + private String objectName; + + @TableField("object_url") + private String objectUrl; + + @TableField("upload_status") + private Integer uploadStatus; + + @TableField("retry_count") + private Integer retryCount; + + @TableField("last_error") + private String lastError; + + @TableField("uploaded_at") + private LocalDateTime uploadedAt; + + @TableField("last_retry_time") + private LocalDateTime lastRetryTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageFileMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageFileMapper.java new file mode 100644 index 00000000..eaff86cf --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageFileMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; + +/** + * 对象存储文件信息表 Mapper + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ObjectStorageFileMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageReplicaMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageReplicaMapper.java new file mode 100644 index 00000000..2198bd3d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mapper/ObjectStorageReplicaMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO; + +public interface ObjectStorageReplicaMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessageListener.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessageListener.java new file mode 100644 index 00000000..b42c2fe5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessageListener.java @@ -0,0 +1,28 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.mq; + +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageBackupMessage; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageBackupService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupMessageListener { + + private final ObjectStorageBackupService objectStorageBackupService; + + @RabbitListener(queues = "#{objectStorageProperties.backupQueueName}") + public void handle(ObjectStorageBackupMessage message) { + if (message == null || message.getFileId() == null) { + return; + } + try { + objectStorageBackupService.backupFile(message.getFileId()); + } catch (Exception e) { + log.warn("Handle object storage backup message failed, fileId={}", message.getFileId(), e); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java new file mode 100644 index 00000000..f93fe2d5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/mq/ObjectStorageBackupMessagePublisher.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.mq; + +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageBackupMessage; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupMessagePublisher { + + private final RabbitTemplate rabbitTemplate; + private final ObjectStorageProperties objectStorageProperties; + + public void publish(Long fileId) { + if (fileId == null || fileId <= 0) { + return; + } + try { + rabbitTemplate.convertAndSend( + objectStorageProperties.getBackupExchangeName(), + objectStorageProperties.getBackupRoutingKey(), + new ObjectStorageBackupMessage(fileId) + ); + } catch (Exception e) { + log.warn("Publish object storage backup message failed, fileId={}", fileId, e); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java new file mode 100644 index 00000000..a479f170 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java @@ -0,0 +1,43 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.scheduler; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageReplicaMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageBackupService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.impl.ObjectStorageBackupServiceImpl; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupRetryScheduler { + + private final ObjectStorageReplicaMapper objectStorageReplicaMapper; + private final ObjectStorageBackupService objectStorageBackupService; + private final ObjectStorageProperties objectStorageProperties; + + @Scheduled(cron = "${object-storage.backup-retry-cron}", zone = "Asia/Shanghai") + public void retryPendingOrFailedBackups() { + List replicas = objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .in(ObjectStorageReplicaDO::getProvider, objectStorageProperties.getReplicaRequiredProviders()) + .in(ObjectStorageReplicaDO::getUploadStatus, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_PENDING, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED) + .last("LIMIT " + objectStorageProperties.getBackupRetryBatchLimit()) + ); + for (ObjectStorageReplicaDO replica : replicas) { + try { + objectStorageBackupService.backupFile(replica.getFileId()); + } catch (Exception e) { + log.warn("Retry object storage replica failed, fileId={}, provider={}", replica.getFileId(), replica.getProvider(), e); + } + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/AliyunOssService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/AliyunOssService.java new file mode 100644 index 00000000..e1141ee8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/AliyunOssService.java @@ -0,0 +1,10 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import java.io.InputStream; + +public interface AliyunOssService { + + String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType); + + String getPresignedUrl(String objectName); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ChunkUploadService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ChunkUploadService.java new file mode 100644 index 00000000..bf76da8d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ChunkUploadService.java @@ -0,0 +1,145 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ChunkUploadSessionVO; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * ChunkUploadService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ChunkUploadService { + + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId); + + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId); + + PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId); + + PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId); + + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + void clearAdminObjectStorageUpload(Long ownerId, String uploadId); + + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + void clearUserAvatarUpload(Long ownerId, String uploadId); + + void clearUserProfileImageUpload(Long ownerId, String uploadId); + + void clearCommentImageUpload(Long ownerId, String uploadId); +/** + * PreparedUploadFile declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ + interface PreparedUploadFile extends AutoCloseable { + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ + File getFile(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getFileName(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getContentType(); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ + long getFileSize(); + + @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + void close(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageBackupService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageBackupService.java new file mode 100644 index 00000000..db29042a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageBackupService.java @@ -0,0 +1,6 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +public interface ObjectStorageBackupService { + + void backupFile(Long fileId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageFileService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageFileService.java new file mode 100644 index 00000000..4601f2aa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageFileService.java @@ -0,0 +1,78 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * 对象存储文件信息表 Service + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ObjectStorageFileService extends IService { + + /** + * 创建文件 + * + * @param objectStorageFileDTO 文件DTO + * @return 文件ID + */ + Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO); + + /** + * 更新文件 + * + * @param id 文件ID + * @param objectStorageFileDTO 文件DTO + * @return 是否更新成功 + */ + boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO); + + /** + * 删除文件 + * + * @param id 文件ID + * @return 是否删除成功 + */ + boolean deleteObjectStorageFile(Long id); + + /** + * 根据ID查询文件 + * + * @param id 文件ID + * @return 文件VO + */ + ObjectStorageFileVO getObjectStorageFileById(Long id); + + /** + * 鎵归噺鏌ヨ鏂囦欢锛岃繑鍥瀒D -> 鏂囦欢淇℃伅鏄犲皠 + * + * @param ids 鏂囦欢ID闆嗗悎 + * @return 鏂囦欢鏄犲皠 + */ + Map getObjectStorageFileMapByIds(Collection ids); + + /** + * 查询所有文件 + * + * @return 文件VO列表 + */ + List listAllObjectStorageFiles(); + + /** + * 根据状态查询文件 + * + * @param status 文件状态 + * @return 文件VO列表 + */ + List listObjectStorageFilesByStatus(Integer status); + + void evictObjectStorageFileCache(Long id); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageOrchestrationService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageOrchestrationService.java new file mode 100644 index 00000000..272548c6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageOrchestrationService.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; + +import java.io.InputStream; + +public interface ObjectStorageOrchestrationService { + + ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + void completeReplicas(ObjectStorageFileDO file); + + String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageProvider.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageProvider.java new file mode 100644 index 00000000..aa55e49c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageProvider.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import java.io.InputStream; + +public interface ObjectStorageProvider { + + String providerCode(); + + boolean isEnabled(); + + String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + InputStream downloadFile(String objectName) throws Exception; + + void deleteFile(String objectName) throws Exception; + + String getFileUrl(String objectName); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageReplicaService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageReplicaService.java new file mode 100644 index 00000000..e024872d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/ObjectStorageReplicaService.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public interface ObjectStorageReplicaService { + + List listByFileId(Long fileId); + + Map> listMapByFileIds(Collection fileIds); + + void saveInitialReplicas(Long fileId, List attempts); + + void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/PrimaryObjectStorageService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/PrimaryObjectStorageService.java new file mode 100644 index 00000000..297f9fb3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/PrimaryObjectStorageService.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service; + +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; + +public interface PrimaryObjectStorageService { + + String uploadFile(MultipartFile file, String objectName) throws Exception; + + String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + InputStream downloadFile(String objectName) throws Exception; + + void deleteFile(String objectName) throws Exception; + + String getFileUrl(String objectName); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/AliyunOssServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/AliyunOssServiceImpl.java new file mode 100644 index 00000000..cfc40098 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/AliyunOssServiceImpl.java @@ -0,0 +1,112 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.aliyun.oss.HttpMethod; +import com.aliyun.oss.OSS; +import com.aliyun.oss.model.GeneratePresignedUrlRequest; +import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.PutObjectRequest; +import com.xiaowang.fingertipdesigner.core.modules.file.config.AliyunOssConfig; +import com.xiaowang.fingertipdesigner.core.modules.file.service.AliyunOssService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageProvider; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.io.InputStream; +import java.net.URL; +import java.util.Date; + +@Slf4j +@Service +@RequiredArgsConstructor +public class AliyunOssServiceImpl implements AliyunOssService, ObjectStorageProvider { + + private final ObjectProvider ossClientProvider; + private final AliyunOssConfig aliyunOssConfig; + + @Override + public String providerCode() { + return "ALIYUN_OSS"; + } + + @Override + public boolean isEnabled() { + return Boolean.TRUE.equals(aliyunOssConfig.getEnabled()) + && ossClientProvider.getIfAvailable() != null + && StringUtils.hasText(aliyunOssConfig.getBucketName()); + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) { + return uploadStream(objectName, inputStream, fileSize, contentType); + } + + @Override + public String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType) { + OSS ossClient = requireClient(); + ObjectMetadata metadata = new ObjectMetadata(); + if (fileSize >= 0) { + metadata.setContentLength(fileSize); + } + if (StringUtils.hasText(contentType)) { + metadata.setContentType(contentType); + } + ossClient.putObject(new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, inputStream, metadata)); + log.info("Aliyun OSS backup uploaded: {}", objectName); + return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; + } + + @Override + public InputStream downloadFile(String objectName) { + OSS ossClient = requireClient(); + return ossClient.getObject(aliyunOssConfig.getBucketName(), objectName).getObjectContent(); + } + + @Override + public void deleteFile(String objectName) { + OSS ossClient = requireClient(); + ossClient.deleteObject(aliyunOssConfig.getBucketName(), objectName); + } + + @Override + public String getFileUrl(String objectName) { + return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName) { + return getPresignedUrl(objectName, aliyunOssConfig.getSignedUrlExpireMinutes()); + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { + OSS ossClient = requireClient(); + Date expiration = new Date(System.currentTimeMillis() + + resolveExpireMinutes(expiryTimeInMinutes) * 60L * 1000L); + GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( + aliyunOssConfig.getBucketName(), + objectName, + HttpMethod.GET + ); + request.setExpiration(expiration); + URL url = ossClient.generatePresignedUrl(request); + return url.toString(); + } + + private int resolveExpireMinutes(Integer expiryTimeInMinutes) { + if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { + return expiryTimeInMinutes; + } + return aliyunOssConfig.getSignedUrlExpireMinutes(); + } + + private OSS requireClient() { + OSS ossClient = ossClientProvider.getIfAvailable(); + if (ossClient == null) { + throw new IllegalStateException("Aliyun OSS is not enabled or not configured"); + } + return ossClient; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ChunkUploadServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ChunkUploadServiceImpl.java new file mode 100644 index 00000000..50edd843 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ChunkUploadServiceImpl.java @@ -0,0 +1,996 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ChunkUploadService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ChunkUploadSessionVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Slf4j +@Service +@RequiredArgsConstructor +/** + * ChunkUploadServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ChunkUploadServiceImpl implements ChunkUploadService { + + // Keep each chunk comfortably below the common 1 MB gateway/body limit. + private static final int CHUNK_SIZE = 512 * 1024; + /** + * Purpose: SESSION_EXPIRE_HOURS supports ChunkUploadServiceImpl.java by holding or executing the session expire hours business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long SESSION_EXPIRE_HOURS = 24; + /** + * Purpose: METADATA_FILE_NAME supports ChunkUploadServiceImpl.java by holding or executing the metadata file name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String METADATA_FILE_NAME = "metadata.json"; + /** + * Purpose: CHUNK_FILE_PREFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHUNK_FILE_PREFIX = "chunk-"; + /** + * Purpose: CHUNK_FILE_SUFFIX supports ChunkUploadServiceImpl.java by holding or executing the chunk file suffix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHUNK_FILE_SUFFIX = ".part"; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + + @Override + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO); + } + + @Override + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); + } + + @Override + public ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, requestDTO); + } + + @Override + public ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.COMMENT_IMAGE, ownerId, requestDTO); + } + + @Override + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ + public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + public void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + public void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ + public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); + } + + @Override + public PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); + } + + @Override + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ + public void clearUserAvatarUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); + } + + @Override + public void clearUserProfileImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public void clearCommentImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ + private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateInitRequest(ownerId, requestDTO); + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + cleanupExpiredSessionsQuietly(); + + String uploadId = buildUploadId(targetType, ownerId, requestDTO); + Path sessionDir = getSessionDir(uploadId); + int totalChunks = (int) Math.ceil((double) requestDTO.getFileSize() / CHUNK_SIZE); + + try { + Files.createDirectories(sessionDir); + + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + Files.createDirectories(sessionDir); + metadata = null; + } + + if (metadata == null) { + metadata = new UploadMetadata(); + metadata.setUploadId(uploadId); + metadata.setTargetType(targetType.name()); + metadata.setOwnerId(ownerId); + metadata.setFileName(requestDTO.getFileName()); + metadata.setContentType(requestDTO.getContentType()); + metadata.setFileSize(requestDTO.getFileSize()); + metadata.setFileFingerprint(requestDTO.getFileFingerprint()); + metadata.setScene(requestDTO.getScene()); + metadata.setChunkSize(CHUNK_SIZE); + metadata.setTotalChunks(totalChunks); + metadata.setCreatedAt(Instant.now().toEpochMilli()); + } + metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + writeMetadata(sessionDir, metadata); + + ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO(); + sessionVO.setUploadId(uploadId); + sessionVO.setChunkSize(metadata.getChunkSize()); + sessionVO.setTotalChunks(metadata.getTotalChunks()); + sessionVO.setUploadedChunks(getUploadedChunks(sessionDir, metadata.getTotalChunks())); + return sessionVO; + } catch (IOException e) { + log.error("初始化分片上传失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("初始化上传失败"); + } + } + + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未获取到上传用户信息"); + } + if (!StringUtils.hasText(uploadId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传标识不能为空"); + } + if (chunkIndex == null || chunkIndex < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片序号不合法"); + } + if (totalChunks == null || totalChunks <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片总数不合法"); + } + if (chunkFile == null || chunkFile.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传分片不能为空"); + } + + Path sessionDir = getSessionDir(uploadId); + UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片总数不匹配,请重新上传"); + } + if (chunkIndex >= metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("分片序号超出范围"); + } + + try { + Path chunkPath = getChunkPath(sessionDir, chunkIndex); + Path tempChunkPath = sessionDir.resolve(chunkPath.getFileName().toString() + ".tmp"); + try (InputStream inputStream = chunkFile.getInputStream()) { + Files.copy(inputStream, tempChunkPath, StandardCopyOption.REPLACE_EXISTING); + } + Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + writeMetadata(sessionDir, metadata); + } catch (IOException e) { + log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传分片失败"); + } + } + + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private PreparedUploadFile result consumed by the caller or returned to the frontend + */ + private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) { + Path sessionDir = getSessionDir(uploadId); + UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + List uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks()); + if (uploadedChunks.size() != metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件尚未上传完成,请稍后再试"); + } + + try { + Path mergedFilePath = Files.createTempFile("fingertipdesigner-upload-", ".tmp"); + try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergedFilePath))) { + for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) { + Path chunkPath = getChunkPath(sessionDir, chunkIndex); + if (!Files.exists(chunkPath)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("缺少上传分片,请重新上传"); + } + Files.copy(chunkPath, outputStream); + } + } + return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize()); + } catch (IOException e) { + log.error("合并上传文件失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("合并上传文件失败"); + } + } + + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) { + Path sessionDir = getSessionDir(uploadId); + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + } + + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ + private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) { + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传会话不存在,请重新上传"); + } + if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权操作该上传会话"); + } + if (!uploadId.equals(metadata.getUploadId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传会话不匹配"); + } + return metadata; + } + + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未获取到上传用户信息"); + } + if (requestDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传参数不能为空"); + } + if (!StringUtils.hasText(requestDTO.getFileName())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件名不能为空"); + } + if (!StringUtils.hasText(requestDTO.getContentType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件类型不能为空"); + } + if (!StringUtils.hasText(requestDTO.getFileFingerprint())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件指纹不能为空"); + } + if (!StringUtils.hasText(requestDTO.getScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("上传场景不能为空"); + } + if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("文件大小不合法"); + } + } + + /** + * Run business method `isCompatible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param metadata parameter `metadata` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) { + return targetType.name().equals(metadata.getTargetType()) + && Objects.equals(ownerId, metadata.getOwnerId()) + && Objects.equals(metadata.getFileSize(), requestDTO.getFileSize()) + && Objects.equals(metadata.getTotalChunks(), totalChunks) + && Objects.equals(metadata.getFileFingerprint(), requestDTO.getFileFingerprint()) + && Objects.equals(metadata.getScene(), requestDTO.getScene()); + } + + /** + * Run business method `buildUploadId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint(); + return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param uploadId parameter `uploadId` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getSessionDir(String uploadId) { + return getUploadRoot().resolve(uploadId); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getUploadRoot() { + return Path.of(System.getProperty("java.io.tmpdir"), "fingertipdesigner", "chunk-upload"); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ + private Path getChunkPath(Path sessionDir, int chunkIndex) { + return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX); + } + + /** + * Run business method `readMetadataIfExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ + private UploadMetadata readMetadataIfExists(Path sessionDir) { + Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); + if (!Files.exists(metadataPath)) { + return null; + } + try { + return objectMapper.readValue(metadataPath.toFile(), UploadMetadata.class); + } catch (IOException e) { + log.warn("读取上传元数据失败: {}", metadataPath, e); + return null; + } + } + + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException { + Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); + objectMapper.writeValue(metadataPath.toFile(), metadata); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getUploadedChunks(Path sessionDir, int totalChunks) { + List uploadedChunks = new ArrayList<>(); + for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + if (Files.exists(getChunkPath(sessionDir, chunkIndex))) { + uploadedChunks.add(chunkIndex); + } + } + return uploadedChunks; + } + + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void cleanupExpiredSessionsQuietly() { + try { + Path uploadRoot = getUploadRoot(); + if (!Files.exists(uploadRoot)) { + return; + } + Instant expireAt = Instant.now().minus(SESSION_EXPIRE_HOURS, ChronoUnit.HOURS); + try (var stream = Files.list(uploadRoot)) { + stream.filter(Files::isDirectory) + .sorted(Comparator.comparing(Path::toString)) + .forEach(sessionDir -> cleanupExpiredSession(sessionDir, expireAt)); + } + } catch (IOException e) { + log.warn("清理过期上传会话失败", e); + } + } + + /** + * Run business method `cleanupExpiredSession`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param expireAt parameter `expireAt` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void cleanupExpiredSession(Path sessionDir, Instant expireAt) { + UploadMetadata metadata = readMetadataIfExists(sessionDir); + if (metadata == null) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + return; + } + Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt()); + if (updatedAt.isBefore(expireAt)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + deleteDirectory(sessionDir); + } + } + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param directory parameter `directory` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deleteDirectory(Path directory) { + if (directory == null || !Files.exists(directory)) { + return; + } + try (var walk = Files.walk(directory)) { + walk.sorted(Comparator.reverseOrder()).forEach(path -> { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + log.warn("删除上传临时文件失败: {}", path, e); + } + }); + } catch (IOException e) { + log.warn("删除上传目录失败: {}", directory, e); + } + } + + /** + * Purpose: UploadTargetType supports ChunkUploadServiceImpl.java by holding or executing the upload target type business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ + private enum UploadTargetType { + ADMIN_OBJECT_STORAGE, + USER_AVATAR, + USER_PROFILE_IMAGE, + COMMENT_IMAGE + } + + @Data + /** + * Purpose: UploadMetadata supports ChunkUploadServiceImpl.java by holding or executing the upload metadata business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class UploadMetadata { + /** + * Purpose: uploadId supports ChunkUploadServiceImpl.java by holding or executing the upload id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String uploadId; + /** + * Purpose: targetType supports ChunkUploadServiceImpl.java by holding or executing the target type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String targetType; + /** + * Purpose: ownerId supports ChunkUploadServiceImpl.java by holding or executing the owner id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long ownerId; + /** + * Purpose: fileName supports ChunkUploadServiceImpl.java by holding or executing the file name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fileName; + /** + * Purpose: contentType supports ChunkUploadServiceImpl.java by holding or executing the content type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String contentType; + /** + * Purpose: fileSize supports ChunkUploadServiceImpl.java by holding or executing the file size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fileSize; + /** + * Purpose: fileFingerprint supports ChunkUploadServiceImpl.java by holding or executing the file fingerprint business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fileFingerprint; + /** + * Purpose: scene supports ChunkUploadServiceImpl.java by holding or executing the scene business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String scene; + /** + * Purpose: chunkSize supports ChunkUploadServiceImpl.java by holding or executing the chunk size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer chunkSize; + /** + * Purpose: totalChunks supports ChunkUploadServiceImpl.java by holding or executing the total chunks business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer totalChunks; + /** + * Purpose: createdAt supports ChunkUploadServiceImpl.java by holding or executing the created at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createdAt; + /** + * Purpose: updatedAt supports ChunkUploadServiceImpl.java by holding or executing the updated at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long updatedAt; + } + + /** + * Purpose: LocalPreparedUploadFile supports ChunkUploadServiceImpl.java by holding or executing the local prepared upload file business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class LocalPreparedUploadFile implements PreparedUploadFile { + /** + * Variable `file`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final File file; + /** + * Variable `fileName`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String fileName; + /** + * Variable `contentType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String contentType; + /** + * Variable `fileSize`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final long fileSize; + + /** + * Run business method `LocalPreparedUploadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param file parameter `file` supplied by the caller + * @param fileName parameter `fileName` supplied by the caller + * @param contentType parameter `contentType` supplied by the caller + * @param fileSize parameter `fileSize` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) { + this.file = file; + this.fileName = fileName; + this.contentType = contentType; + this.fileSize = fileSize; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ + public File getFile() { + return file; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getFileName() { + return fileName; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getContentType() { + return contentType; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ + public long getFileSize() { + return fileSize; + } + + @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + public void close() { + if (file != null && file.exists() && !file.delete()) { + log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath()); + } + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/MinioObjectStorageProvider.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/MinioObjectStorageProvider.java new file mode 100644 index 00000000..72a240cb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/MinioObjectStorageProvider.java @@ -0,0 +1,119 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.file.config.MinioStorageConfig; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageProvider; +import io.minio.GetObjectArgs; +import io.minio.GetPresignedObjectUrlArgs; +import io.minio.MinioClient; +import io.minio.PutObjectArgs; +import io.minio.RemoveObjectArgs; +import io.minio.http.Method; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MinioObjectStorageProvider implements ObjectStorageProvider { + + private static final long UNKNOWN_SIZE_PART_SIZE = 10 * 1024 * 1024L; + + private final ObjectProvider minioClientProvider; + private final MinioStorageConfig minioStorageConfig; + + @Override + public String providerCode() { + return "MINIO"; + } + + @Override + public boolean isEnabled() { + return Boolean.TRUE.equals(minioStorageConfig.getEnabled()) + && minioClientProvider.getIfAvailable() != null + && StringUtils.hasText(minioStorageConfig.getBucketName()); + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + MinioClient minioClient = requireClient(); + PutObjectArgs.Builder builder = PutObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .stream(inputStream, fileSize, fileSize < 0 ? UNKNOWN_SIZE_PART_SIZE : -1L); + if (StringUtils.hasText(contentType)) { + builder.contentType(contentType); + } + minioClient.putObject(builder.build()); + log.info("MinIO object uploaded, objectName={}", objectName); + return getFileUrl(objectName); + } + + @Override + public InputStream downloadFile(String objectName) throws Exception { + return requireClient().getObject( + GetObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .build() + ); + } + + @Override + public void deleteFile(String objectName) throws Exception { + requireClient().removeObject( + RemoveObjectArgs.builder() + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .build() + ); + } + + @Override + public String getFileUrl(String objectName) { + return normalizeEndpoint(minioStorageConfig.getEndpoint()) + "/" + minioStorageConfig.getBucketName() + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { + if (!Boolean.TRUE.equals(minioStorageConfig.getPrivateBucket())) { + return getFileUrl(objectName); + } + return requireClient().getPresignedObjectUrl( + GetPresignedObjectUrlArgs.builder() + .method(Method.GET) + .bucket(minioStorageConfig.getBucketName()) + .object(objectName) + .expiry(resolveExpireMinutes(expiryTimeInMinutes), TimeUnit.MINUTES) + .build() + ); + } + + private MinioClient requireClient() { + MinioClient minioClient = minioClientProvider.getIfAvailable(); + if (minioClient == null) { + throw new IllegalStateException("MinIO is not enabled or not configured"); + } + return minioClient; + } + + private int resolveExpireMinutes(Integer expiryTimeInMinutes) { + if (expiryTimeInMinutes != null && expiryTimeInMinutes > 0) { + return expiryTimeInMinutes; + } + return minioStorageConfig.getSignedUrlExpireMinutes(); + } + + private String normalizeEndpoint(String endpoint) { + String normalized = endpoint.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + return normalized; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java new file mode 100644 index 00000000..6d4b516b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageBackupServiceImpl.java @@ -0,0 +1,78 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageBackupService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ObjectStorageBackupServiceImpl implements ObjectStorageBackupService { + + public static final int UPLOAD_STATUS_PENDING = 0; + public static final int UPLOAD_STATUS_SUCCEEDED = 1; + public static final int UPLOAD_STATUS_FAILED = 2; + + private static final int ACTIVE_STATUS = 1; + private static final int MAX_ERROR_LENGTH = 500; + + private final ObjectStorageFileMapper objectStorageFileMapper; + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + private final ObjectStorageFileService objectStorageFileService; + + @Override + public void backupFile(Long fileId) { + if (fileId == null || fileId <= 0) { + return; + } + ObjectStorageFileDO file = objectStorageFileMapper.selectById(fileId); + if (!shouldBackup(file)) { + return; + } + + try { + objectStorageOrchestrationService.completeReplicas(file); + markSucceeded(file); + } catch (Exception e) { + log.warn("Complete object storage replicas failed, fileId={}", fileId, e); + markFailed(file, e); + } + } + + private boolean shouldBackup(ObjectStorageFileDO file) { + return file != null + && Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus()) + && Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getPrimaryUploadStatus()) + && StringUtils.hasText(file.getObjectName()); + } + + private void markSucceeded(ObjectStorageFileDO file) { + file.setBackupUploadStatus(UPLOAD_STATUS_SUCCEEDED); + file.setBackupUploadedAt(LocalDateTime.now()); + file.setBackupLastError(null); + objectStorageFileMapper.updateById(file); + objectStorageFileService.evictObjectStorageFileCache(file.getId()); + } + + private void markFailed(ObjectStorageFileDO file, Exception e) { + file.setBackupUploadStatus(UPLOAD_STATUS_FAILED); + file.setBackupRetryCount((file.getBackupRetryCount() == null ? 0 : file.getBackupRetryCount()) + 1); + file.setBackupLastError(truncateError(e)); + file.setBackupLastRetryTime(LocalDateTime.now()); + objectStorageFileMapper.updateById(file); + objectStorageFileService.evictObjectStorageFileCache(file.getId()); + } + + private String truncateError(Exception e) { + String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); + return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java new file mode 100644 index 00000000..48493271 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -0,0 +1,309 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.mq.ObjectStorageBackupMessagePublisher; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +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; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 对象存储文件信息表 Service 实现 + * 对应数据库表 t_object_storage_file + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class ObjectStorageFileServiceImpl extends ServiceImpl implements ObjectStorageFileService { + + /** + * Purpose: FILE_DETAIL_CACHE_PREFIX supports ObjectStorageFileServiceImpl.java by holding or executing the file detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String FILE_DETAIL_CACHE_PREFIX = "cache:file:detail:"; + /** + * Variable `objectStorageFileMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileMapper objectStorageFileMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageReplicaService objectStorageReplicaService; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO) { + ObjectStorageFileDO objectStorageFileDO = new ObjectStorageFileDO(); + applyDTO(objectStorageFileDO, objectStorageFileDTO); + objectStorageFileMapper.insert(objectStorageFileDO); + objectStorageReplicaService.saveInitialReplicas(objectStorageFileDO.getId(), objectStorageFileDTO.getUploadAttempts()); + evictFileCache(objectStorageFileDO.getId()); + publishBackupIfNeeded(objectStorageFileDO); + return objectStorageFileDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateObjectStorageFile(Long id, ObjectStorageFileDTO objectStorageFileDTO) { + ObjectStorageFileDO objectStorageFileDO = objectStorageFileMapper.selectById(id); + if (objectStorageFileDO == null) { + return false; + } + applyDTO(objectStorageFileDO, objectStorageFileDTO); + boolean updated = objectStorageFileMapper.updateById(objectStorageFileDO) > 0; + if (updated) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictFileCache(id); + } + return updated; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteObjectStorageFile(Long id) { + boolean deleted = objectStorageFileMapper.deleteById(id) > 0; + if (deleted) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictFileCache(id); + } + return deleted; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ObjectStorageFileVO result consumed by the caller or returned to the frontend + */ + public ObjectStorageFileVO getObjectStorageFileById(Long id) { + return getObjectStorageFileMapByIds(Collections.singleton(id)).get(id); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return Map result consumed by the caller or returned to the frontend + */ + public Map getObjectStorageFileMapByIds(Collection ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyMap(); + } + + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getObjectStorageFile(); + Duration localTtl = Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()); + Duration redisTtl = Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()); + Map result = new LinkedHashMap<>(); + Set missingIds = new LinkedHashSet<>(); + + for (Long id : ids) { + if (id == null || id <= 0) { + continue; + } + MultiLevelCacheService.CacheLookup lookup = multiLevelCacheService.get( + buildDetailCacheKey(id), + localTtl, + new TypeReference() { + } + ); + if (lookup.isHit()) { + if (lookup.getValue() != null) { + result.put(id, lookup.getValue()); + } + continue; + } + missingIds.add(id); + } + + if (!missingIds.isEmpty()) { + Map 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 + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllObjectStorageFiles() { + List objectStorageFileDOs = objectStorageFileMapper.selectList(null); + return objectStorageFileDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listObjectStorageFilesByStatus(Integer status) { + List objectStorageFileDOs = objectStorageFileMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageFileDO.class) + .eq(ObjectStorageFileDO::getStatus, status) + ); + return objectStorageFileDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param objectStorageFileDO 文件DO + * @return 文件VO + */ + private ObjectStorageFileVO convertToVO(ObjectStorageFileDO objectStorageFileDO) { + ObjectStorageFileVO objectStorageFileVO = new ObjectStorageFileVO(); + objectStorageFileVO.setId(objectStorageFileDO.getId()); + objectStorageFileVO.setFileName(objectStorageFileDO.getFileName()); + objectStorageFileVO.setFileUrl(objectStorageFileDO.getFileUrl()); + objectStorageFileVO.setObjectName(objectStorageFileDO.getObjectName()); + objectStorageFileVO.setPrimaryProvider(objectStorageFileDO.getPrimaryProvider()); + objectStorageFileVO.setPrimaryUrl(objectStorageFileDO.getPrimaryUrl()); + objectStorageFileVO.setBackupProvider(objectStorageFileDO.getBackupProvider()); + objectStorageFileVO.setBackupUrl(objectStorageFileDO.getBackupUrl()); + objectStorageFileVO.setContentType(objectStorageFileDO.getContentType()); + objectStorageFileVO.setFileSize(objectStorageFileDO.getFileSize()); + objectStorageFileVO.setPrimaryUploadStatus(objectStorageFileDO.getPrimaryUploadStatus()); + objectStorageFileVO.setBackupUploadStatus(objectStorageFileDO.getBackupUploadStatus()); + objectStorageFileVO.setBackupRetryCount(objectStorageFileDO.getBackupRetryCount()); + objectStorageFileVO.setBackupLastError(objectStorageFileDO.getBackupLastError()); + objectStorageFileVO.setBackupUploadedAt(objectStorageFileDO.getBackupUploadedAt()); + objectStorageFileVO.setBackupLastRetryTime(objectStorageFileDO.getBackupLastRetryTime()); + objectStorageFileVO.setCreateTime(objectStorageFileDO.getCreateTime()); + objectStorageFileVO.setStatus(objectStorageFileDO.getStatus()); + objectStorageFileVO.setDeleteTime(objectStorageFileDO.getDeleteTime()); + objectStorageFileVO.setRecycleTime(objectStorageFileDO.getRecycleTime()); + return objectStorageFileVO; + } + + private void applyDTO(ObjectStorageFileDO objectStorageFileDO, ObjectStorageFileDTO objectStorageFileDTO) { + objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName()); + objectStorageFileDO.setFileUrl(objectStorageFileDTO.getFileUrl()); + objectStorageFileDO.setObjectName(objectStorageFileDTO.getObjectName()); + objectStorageFileDO.setPrimaryProvider(objectStorageFileDTO.getPrimaryProvider()); + objectStorageFileDO.setPrimaryUrl(objectStorageFileDTO.getPrimaryUrl()); + objectStorageFileDO.setBackupProvider(objectStorageFileDTO.getBackupProvider()); + objectStorageFileDO.setBackupUrl(objectStorageFileDTO.getBackupUrl()); + objectStorageFileDO.setContentType(objectStorageFileDTO.getContentType()); + objectStorageFileDO.setFileSize(objectStorageFileDTO.getFileSize()); + objectStorageFileDO.setPrimaryUploadStatus(objectStorageFileDTO.getPrimaryUploadStatus()); + objectStorageFileDO.setBackupUploadStatus(objectStorageFileDTO.getBackupUploadStatus()); + objectStorageFileDO.setBackupRetryCount(objectStorageFileDTO.getBackupRetryCount()); + objectStorageFileDO.setBackupLastError(objectStorageFileDTO.getBackupLastError()); + objectStorageFileDO.setBackupUploadedAt(objectStorageFileDTO.getBackupUploadedAt()); + objectStorageFileDO.setBackupLastRetryTime(objectStorageFileDTO.getBackupLastRetryTime()); + objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus()); + objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime()); + objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime()); + } + + private void publishBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) { + if (StringUtils.hasText(objectStorageFileDO.getObjectName()) + && objectStorageProperties.getProviderOrder().contains(objectStorageFileDO.getPrimaryProvider()) + && Integer.valueOf(1).equals(objectStorageFileDO.getPrimaryUploadStatus()) + && Integer.valueOf(0).equals(objectStorageFileDO.getBackupUploadStatus())) { + objectStorageBackupMessagePublisher.publish(objectStorageFileDO.getId()); + } + } + + @Override + public void evictObjectStorageFileCache(Long id) { + evictFileCache(id); + } + + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictFileCache(Long id) { + if (id != null && id > 0) { + multiLevelCacheService.evict(buildDetailCacheKey(id)); + } + } + + /** + * Run business method `buildDetailCacheKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDetailCacheKey(Long id) { + return FILE_DETAIL_CACHE_PREFIX + id; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java new file mode 100644 index 00000000..072d9aae --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java @@ -0,0 +1,226 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadOutcome; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageReplicaService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrchestrationService { + + private static final int MAX_ERROR_LENGTH = 500; + + private final List providers; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageReplicaService objectStorageReplicaService; + + @Override + public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + byte[] bytes = toBytes(inputStream); + List attempts = new ArrayList<>(); + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageProvider provider = requireProvider(providerCode); + try { + ensureEnabled(provider); + String objectUrl = provider.uploadStream( + new ByteArrayInputStream(bytes), + fileSize, + contentType, + objectName + ); + attempts.add(new ObjectStorageUploadAttempt( + provider.providerCode(), + objectName, + objectUrl, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED, + 0, + null + )); + return new ObjectStorageUploadOutcome(provider.providerCode(), objectUrl, attempts); + } catch (Exception e) { + lastFailure = e; + attempts.add(new ObjectStorageUploadAttempt( + provider.providerCode(), + objectName, + null, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED, + 1, + truncateError(e) + )); + log.warn("Upload object to provider failed, provider={}, objectName={}", provider.providerCode(), objectName, e); + } + } + throw new IllegalStateException("No available object storage provider for objectName=" + objectName, lastFailure); + } + + @Override + public void completeReplicas(ObjectStorageFileDO file) { + if (file == null || file.getId() == null || !StringUtils.hasText(file.getObjectName())) { + return; + } + List replicas = objectStorageReplicaService.listByFileId(file.getId()); + Map replicaMap = replicas.stream() + .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); + boolean completed = true; + for (String providerCode : objectStorageProperties.getReplicaRequiredProviders()) { + ObjectStorageReplicaDO existing = replicaMap.get(providerCode); + if (existing != null + && Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(existing.getUploadStatus())) { + continue; + } + completed = uploadReplica(file, providerCode, replicaMap) && completed; + } + if (!completed) { + throw new IllegalStateException("Object storage replicas are not fully completed for fileId=" + file.getId()); + } + } + + @Override + public String getPresignedUrl(Long fileId, String objectName, Integer expiryTimeInMinutes) { + if (fileId == null || fileId <= 0) { + return getPresignedUrl(objectName, expiryTimeInMinutes); + } + List replicas = objectStorageReplicaService.listByFileId(fileId); + if (CollectionUtils.isEmpty(replicas)) { + return getPresignedUrl(objectName, expiryTimeInMinutes); + } + Map replicaMap = replicas.stream() + .collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new)); + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageReplicaDO replica = replicaMap.get(providerCode); + if (replica == null + || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { + continue; + } + try { + return requireProvider(providerCode).getPresignedUrl(replica.getObjectName(), expiryTimeInMinutes); + } catch (Exception e) { + lastFailure = e; + log.warn("Generate object storage signed URL failed, fileId={}, provider={}", fileId, providerCode, e); + } + } + throw new IllegalStateException("No available object storage signed URL for fileId=" + fileId, lastFailure); + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) { + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + try { + ObjectStorageProvider provider = requireProvider(providerCode); + ensureEnabled(provider); + return provider.getPresignedUrl(objectName, expiryTimeInMinutes); + } catch (Exception e) { + lastFailure = e; + log.warn("Generate object storage signed URL by objectName failed, provider={}, objectName={}", providerCode, objectName, e); + } + } + throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure); + } + + private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map replicaMap) { + ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); + replicaDTO.setProvider(providerCode); + replicaDTO.setObjectName(file.getObjectName()); + boolean success = false; + try (InputStream inputStream = openReadableReplica(replicaMap, file.getObjectName())) { + ObjectStorageProvider targetProvider = requireProvider(providerCode); + ensureEnabled(targetProvider); + String objectUrl = targetProvider.uploadStream( + inputStream, + file.getFileSize() == null ? -1L : file.getFileSize(), + file.getContentType(), + file.getObjectName() + ); + replicaDTO.setObjectUrl(objectUrl); + replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED); + replicaDTO.setRetryCount(0); + replicaDTO.setUploadedAt(LocalDateTime.now()); + replicaDTO.setLastError(null); + success = true; + } catch (Exception e) { + ObjectStorageReplicaDO existing = replicaMap.get(providerCode); + replicaDTO.setObjectUrl(existing == null ? null : existing.getObjectUrl()); + replicaDTO.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED); + replicaDTO.setRetryCount((existing == null || existing.getRetryCount() == null ? 0 : existing.getRetryCount()) + 1); + replicaDTO.setLastRetryTime(LocalDateTime.now()); + replicaDTO.setLastError(truncateError(e)); + log.warn("Complete object storage replica failed, fileId={}, provider={}", file.getId(), providerCode, e); + } + objectStorageReplicaService.saveOrUpdateReplica(file.getId(), replicaDTO); + return success; + } + + private InputStream openReadableReplica(Map replicaMap, String objectName) throws Exception { + Exception lastFailure = null; + for (String providerCode : objectStorageProperties.getProviderOrder()) { + ObjectStorageReplicaDO replica = replicaMap.get(providerCode); + if (replica == null + || !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) { + continue; + } + try { + return requireProvider(providerCode).downloadFile(replica.getObjectName()); + } catch (Exception e) { + lastFailure = e; + log.warn("Download object storage readable replica failed, provider={}, objectName={}", providerCode, replica.getObjectName(), e); + } + } + throw new IllegalStateException("No readable object storage replica for objectName=" + objectName, lastFailure); + } + + private ObjectStorageProvider requireProvider(String providerCode) { + for (ObjectStorageProvider provider : providers) { + if (provider.providerCode().equals(providerCode)) { + return provider; + } + } + throw new IllegalStateException("Object storage provider is not registered: " + providerCode); + } + + private void ensureEnabled(ObjectStorageProvider provider) { + if (!provider.isEnabled()) { + throw new IllegalStateException("Object storage provider is disabled or incomplete: " + provider.providerCode()); + } + } + + private byte[] toBytes(InputStream inputStream) throws Exception { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, read); + } + return outputStream.toByteArray(); + } + } + + private String truncateError(Exception e) { + String message = e.getClass().getSimpleName() + ": " + (e.getMessage() == null ? "" : e.getMessage()); + return message.length() <= MAX_ERROR_LENGTH ? message : message.substring(0, MAX_ERROR_LENGTH); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java new file mode 100644 index 00000000..4c5adc64 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/ObjectStorageReplicaServiceImpl.java @@ -0,0 +1,104 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageReplicaDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ObjectStorageUploadAttempt; +import com.xiaowang.fingertipdesigner.core.modules.file.entity.ObjectStorageReplicaDO; +import com.xiaowang.fingertipdesigner.core.modules.file.mapper.ObjectStorageReplicaMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageReplicaService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class ObjectStorageReplicaServiceImpl implements ObjectStorageReplicaService { + + private final ObjectStorageReplicaMapper objectStorageReplicaMapper; + + @Override + public List listByFileId(Long fileId) { + if (fileId == null || fileId <= 0) { + return Collections.emptyList(); + } + return objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .eq(ObjectStorageReplicaDO::getFileId, fileId) + ); + } + + @Override + public Map> listMapByFileIds(Collection fileIds) { + if (CollectionUtils.isEmpty(fileIds)) { + return Collections.emptyMap(); + } + List replicas = objectStorageReplicaMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .in(ObjectStorageReplicaDO::getFileId, fileIds) + ); + return replicas.stream() + .collect(Collectors.groupingBy( + ObjectStorageReplicaDO::getFileId, + LinkedHashMap::new, + Collectors.toList() + )); + } + + @Override + public void saveInitialReplicas(Long fileId, List attempts) { + if (fileId == null || fileId <= 0 || CollectionUtils.isEmpty(attempts)) { + return; + } + for (ObjectStorageUploadAttempt attempt : attempts) { + ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); + replicaDTO.setProvider(attempt.getProvider()); + replicaDTO.setObjectName(attempt.getObjectName()); + replicaDTO.setObjectUrl(attempt.getObjectUrl()); + replicaDTO.setUploadStatus(attempt.getUploadStatus()); + replicaDTO.setRetryCount(attempt.getRetryCount()); + replicaDTO.setLastError(attempt.getLastError()); + if (Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(attempt.getUploadStatus())) { + replicaDTO.setUploadedAt(LocalDateTime.now()); + } + saveOrUpdateReplica(fileId, replicaDTO); + } + } + + @Override + public void saveOrUpdateReplica(Long fileId, ObjectStorageReplicaDTO replicaDTO) { + if (fileId == null || fileId <= 0 || replicaDTO == null) { + return; + } + ObjectStorageReplicaDO replica = objectStorageReplicaMapper.selectOne( + Wrappers.lambdaQuery(ObjectStorageReplicaDO.class) + .eq(ObjectStorageReplicaDO::getFileId, fileId) + .eq(ObjectStorageReplicaDO::getProvider, replicaDTO.getProvider()) + .last("LIMIT 1") + ); + if (replica == null) { + replica = new ObjectStorageReplicaDO(); + replica.setFileId(fileId); + replica.setProvider(replicaDTO.getProvider()); + } + replica.setObjectName(replicaDTO.getObjectName()); + replica.setObjectUrl(replicaDTO.getObjectUrl()); + replica.setUploadStatus(replicaDTO.getUploadStatus()); + replica.setRetryCount(replicaDTO.getRetryCount()); + replica.setLastError(replicaDTO.getLastError()); + replica.setUploadedAt(replicaDTO.getUploadedAt()); + replica.setLastRetryTime(replicaDTO.getLastRetryTime()); + if (replica.getId() == null) { + objectStorageReplicaMapper.insert(replica); + } else { + objectStorageReplicaMapper.updateById(replica); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java new file mode 100644 index 00000000..0be90006 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/service/impl/QiniuObjectStorageServiceImpl.java @@ -0,0 +1,136 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.service.impl; + +import com.qiniu.http.Response; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.UploadManager; +import com.qiniu.storage.model.DefaultPutRet; +import com.qiniu.util.Auth; +import com.qiniu.util.StringMap; +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.file.config.QiniuKodoConfig; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageProvider; +import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; +import java.io.ByteArrayOutputStream; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class QiniuObjectStorageServiceImpl implements PrimaryObjectStorageService, ObjectStorageProvider { + + private final QiniuKodoConfig qiniuKodoConfig; + private final ObjectStorageProperties objectStorageProperties; + private final Auth qiniuAuth; + private final UploadManager qiniuUploadManager; + private final BucketManager qiniuBucketManager; + + @Override + public String providerCode() { + return "QINIU_KODO"; + } + + @Override + public boolean isEnabled() { + return StringUtils.hasText(qiniuKodoConfig.getAccessKey()) + && StringUtils.hasText(qiniuKodoConfig.getSecretKey()) + && StringUtils.hasText(qiniuKodoConfig.getBucketName()) + && StringUtils.hasText(qiniuKodoConfig.getDomain()); + } + + @Override + public String uploadFile(MultipartFile file, String objectName) throws Exception { + try (InputStream inputStream = file.getInputStream()) { + return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName); + } + } + + @Override + public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { + byte[] bytes = toBytes(inputStream); + String uploadToken = qiniuAuth.uploadToken( + qiniuKodoConfig.getBucketName(), + objectName, + buildUploadPolicyExpirySeconds(), + new StringMap() + ); + Response response = qiniuUploadManager.put( + bytes, + objectName, + uploadToken, + null, + contentType, + false + ); + DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class); + log.info("七牛云文件上传成功, key={}", putRet.key); + return getFileUrl(objectName); + } + + @Override + public InputStream downloadFile(String objectName) throws Exception { + URL url = new URL(getPresignedUrl(objectName, objectStorageProperties.getSignedUrlExpireMinutes())); + return url.openStream(); + } + + @Override + public void deleteFile(String objectName) throws Exception { + qiniuBucketManager.delete(qiniuKodoConfig.getBucketName(), objectName); + log.info("七牛云文件删除成功, key={}", objectName); + } + + @Override + public String getFileUrl(String objectName) { + return normalizeDomain(qiniuKodoConfig.getDomain()) + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception { + if (!Boolean.TRUE.equals(qiniuKodoConfig.getPrivateBucket())) { + return getFileUrl(objectName); + } + int expireMinutes = expiryTimeInMinutes == null || expiryTimeInMinutes <= 0 + ? qiniuKodoConfig.getSignedUrlExpireMinutes() + : expiryTimeInMinutes; + return qiniuAuth.privateDownloadUrl( + getFileUrl(objectName), + TimeUnit.MINUTES.toSeconds(expireMinutes) + ); + } + + private long buildUploadPolicyExpirySeconds() { + return TimeUnit.MINUTES.toSeconds(qiniuKodoConfig.getSignedUrlExpireMinutes()); + } + + private byte[] toBytes(InputStream inputStream) throws Exception { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] buffer = new byte[8192]; + int read; + while ((read = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, read); + } + return outputStream.toByteArray(); + } + } + + private String normalizeDomain(String domain) { + String normalized = domain.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + if (!StringUtils.hasText(normalized)) { + throw new IllegalStateException("Qiniu domain is blank"); + } + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return "http://" + normalized; + } + return normalized; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/support/ObjectStorageUrlSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/support/ObjectStorageUrlSupport.java new file mode 100644 index 00000000..b08cf681 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/support/ObjectStorageUrlSupport.java @@ -0,0 +1,203 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.support; + +import com.xiaowang.fingertipdesigner.core.config.ObjectStorageProperties; +import com.xiaowang.fingertipdesigner.core.modules.file.config.QiniuKodoConfig; +import com.xiaowang.fingertipdesigner.core.modules.file.service.AliyunOssService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageOrchestrationService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.net.URI; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageUrlSupport { + + private static final int UPLOAD_STATUS_SUCCEEDED = 1; + + private final PrimaryObjectStorageService primaryObjectStorageService; + private final QiniuKodoConfig qiniuKodoConfig; + private final AliyunOssService aliyunOssService; + private final ObjectStorageProperties objectStorageProperties; + private final ObjectStorageOrchestrationService objectStorageOrchestrationService; + + public String toAccessibleUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + try { + return objectStorageOrchestrationService.getPresignedUrl( + objectName, + objectStorageProperties.getSignedUrlExpireMinutes() + ); + } catch (Exception e) { + log.warn("生成主对象存储访问链接失败, fileUrl={}", fileUrl, e); + return null; + } + } + + public String toAccessibleUrl(ObjectStorageFileVO file) { + return toAccessibleUrl(file, objectStorageProperties.getSignedUrlExpireMinutes()); + } + + public String toAccessibleUrl(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { + if (file == null) { + return null; + } + try { + return getSignedUrlOrThrow(file, expiryTimeInMinutes); + } catch (Exception e) { + String fallback = hasObjectStorageReference(file) ? null : firstText(file.getFileUrl(), file.getPrimaryUrl()); + log.warn("生成对象存储访问链接失败, fileId={}", file.getId(), e); + return fallback; + } + } + + public String getSignedUrlOrThrow(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { + if (file == null) { + throw new IllegalStateException("No available object storage signed URL: file is null"); + } + String objectName = resolveObjectName(file); + if (!StringUtils.hasText(objectName)) { + throw new IllegalStateException("No available object storage signed URL: objectName is empty"); + } + + Exception primaryFailure = null; + try { + return objectStorageOrchestrationService.getPresignedUrl(file.getId(), objectName, expiryTimeInMinutes); + } catch (Exception e) { + primaryFailure = e; + log.warn("生成主对象存储访问链接失败, fileId={}, objectName={}", file.getId(), objectName, e); + } + + if (Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getBackupUploadStatus())) { + try { + return aliyunOssService.getPresignedUrl(objectName); + } catch (Exception e) { + IllegalStateException failure = new IllegalStateException( + "No available object storage signed URL for fileId=" + file.getId(), + e + ); + failure.addSuppressed(primaryFailure); + throw failure; + } + } + + IllegalStateException failure = new IllegalStateException( + "No available object storage signed URL for fileId=" + file.getId() + ); + failure.addSuppressed(primaryFailure); + throw failure; + } + + public String toStoredUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + return primaryObjectStorageService.getFileUrl(objectName); + } + + public String extractObjectName(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return ""; + } + + String normalizedUrl = fileUrl.trim(); + if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { + return stripQuery(stripLeadingSlash(normalizedUrl)); + } + + try { + URI fileUri = URI.create(normalizedUrl); + URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain())); + if (!sameAuthority(fileUri, domainUri)) { + return ""; + } + return stripQuery(stripLeadingSlash(fileUri.getPath())); + } catch (Exception e) { + log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e); + return ""; + } + } + + private String resolveObjectName(ObjectStorageFileVO file) { + if (StringUtils.hasText(file.getObjectName())) { + return file.getObjectName(); + } + String objectName = extractObjectName(file.getPrimaryUrl()); + if (StringUtils.hasText(objectName)) { + return objectName; + } + return extractObjectName(file.getFileUrl()); + } + + private boolean hasObjectStorageReference(ObjectStorageFileVO file) { + return StringUtils.hasText(file.getObjectName()) + || StringUtils.hasText(extractObjectName(file.getPrimaryUrl())) + || StringUtils.hasText(extractObjectName(file.getFileUrl())); + } + + private String firstText(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value; + } + } + return null; + } + + private String normalizeDomain(String domain) { + String normalized = domain.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); + } + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return "http://" + normalized; + } + return normalized; + } + + private boolean sameAuthority(URI left, URI right) { + return left.getScheme() != null + && left.getScheme().equalsIgnoreCase(right.getScheme()) + && left.getHost() != null + && left.getHost().equalsIgnoreCase(right.getHost()) + && normalizedPort(left) == normalizedPort(right); + } + + private int normalizedPort(URI uri) { + if (uri.getPort() >= 0) { + return uri.getPort(); + } + return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; + } + + private String stripLeadingSlash(String rawValue) { + String normalized = rawValue; + while (normalized.startsWith("/")) { + normalized = normalized.substring(1); + } + return normalized; + } + + private String stripQuery(String rawValue) { + int queryIndex = rawValue.indexOf('?'); + return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ChunkUploadSessionVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ChunkUploadSessionVO.java new file mode 100644 index 00000000..e4fcef74 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ChunkUploadSessionVO.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.vo; + +import lombok.Data; + +import java.util.List; + +/** + * 分片上传会话信息 + */ +@Data +public class ChunkUploadSessionVO { + + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String uploadId; + + /** + * Field `chunkSize` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer chunkSize; + + /** + * Field `totalChunks` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer totalChunks; + + /** + * Field `uploadedChunks` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List uploadedChunks; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ObjectStorageFileVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ObjectStorageFileVO.java new file mode 100644 index 00000000..c28a44aa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/file/vo/ObjectStorageFileVO.java @@ -0,0 +1,82 @@ +package com.xiaowang.fingertipdesigner.core.modules.file.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 对象存储文件信息表 VO + * 用于前端展示文件信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ObjectStorageFileVO { + + /** + * 文件记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 文件名称 + */ + private String fileName; + + /** + * 文件访问链接 + */ + private String fileUrl; + + private String objectName; + + private String primaryProvider; + + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; + + private String contentType; + + private Long fileSize; + + private Integer primaryUploadStatus; + + private Integer backupUploadStatus; + + private Integer backupRetryCount; + + private String backupLastError; + + private LocalDateTime backupUploadedAt; + + private LocalDateTime backupLastRetryTime; + + /** + * 文件上传时间 + */ + private LocalDateTime createTime; + + /** + * 文件状态:1-可用,0-不可用,2-回收站 + */ + private Integer status; + + /** + * 文件状态名称 + */ + private String statusName; + + /** + * 文件删除时间(NULL表示未删除) + */ + private LocalDateTime deleteTime; + + /** + * 文件移入回收站时间(NULL表示未移入) + */ + private LocalDateTime recycleTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/controller/front/MessageHubPushConfigController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/controller/front/MessageHubPushConfigController.java new file mode 100644 index 00000000..0eca6009 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/controller/front/MessageHubPushConfigController.java @@ -0,0 +1,110 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.integration.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config", "/admin/messagehub-push-config"}) +/** + * MessageHubPushConfigController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigController { + /** + * Variable `configService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService configService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> list(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-create", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.createConfig(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-update", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateConfig(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("messagehub:config:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer enabled) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateStatus(currentUser, id, enabled)); + } + + @PostMapping("/admin/{id}/test") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-test", ttlSeconds = 8, message = "测试投递处理中,请勿重复提交") + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result test(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushTestDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.testConfig(currentUser, id, dto)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushConfigDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushConfigDTO.java new file mode 100644 index 00000000..f0222793 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushConfigDTO.java @@ -0,0 +1,85 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * MessageHubPushConfigDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigDTO { + + @NotBlank(message = "场景编码不能为空") + @Size(max = 80, message = "场景编码不能超过80个字符") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @NotBlank(message = "场景名称不能为空") + @Size(max = 100, message = "场景名称不能超过100个字符") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @NotBlank(message = "消息平台不能为空") + @Size(max = 20, message = "消息平台不能超过20个字符") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform = "SMS"; + + @NotBlank(message = "消息类型不能为空") + @Size(max = 30, message = "消息类型不能超过30个字符") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType = "VERIFICATION"; + + @NotBlank(message = "队列名称不能为空") + @Size(max = 100, message = "队列名称不能超过100个字符") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @NotBlank(message = "来源系统不能为空") + @Size(max = 80, message = "来源系统不能超过80个字符") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @NotBlank(message = "模板编码不能为空") + @Size(max = 100, message = "模板编码不能超过100个字符") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @Size(max = 30, message = "发送方式不能超过30个字符") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushTestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushTestDTO.java new file mode 100644 index 00000000..3e7fae55 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/MessageHubPushTestDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Data +/** + * MessageHubPushTestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushTestDTO { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java new file mode 100644 index 00000000..c6e802d5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniAutoLoginRequestDTO.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** + * 微信小程序自动登录请求。 + */ +@Data +public class WechatMiniAutoLoginRequestDTO { + + @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String wxCode; + + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long preferredShopId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java new file mode 100644 index 00000000..9934e05d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniConfirmLoginRequestDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +/** + * 微信小程序补选店铺后确认登录请求。 + */ +@Data +public class WechatMiniConfirmLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "登录票据不能为空") + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ticket; + + @NotNull(message = "店铺不能为空") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * Purpose: agreementAccepted supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports WechatMiniConfirmLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java new file mode 100644 index 00000000..6619f939 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/dto/WechatMiniPhoneLoginRequestDTO.java @@ -0,0 +1,49 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +/** + * 微信小程序手机号一键登录请求。 + */ +@Data +public class WechatMiniPhoneLoginRequestDTO implements AgreementAwareRequest { + + @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String wxCode; + + @NotBlank(message = "手机号授权凭证不能为空") + /** + * Field `phoneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phoneCode; + + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long preferredShopId; + + /** + * Purpose: agreementAccepted supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement accepted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean agreementAccepted; + + /** + * Purpose: agreementVersions supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the agreement versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map agreementVersions; + + /** + * Purpose: clientType supports WechatMiniPhoneLoginRequestDTO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/BusinessEventOutboxDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/BusinessEventOutboxDO.java new file mode 100644 index 00000000..7ef62935 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/BusinessEventOutboxDO.java @@ -0,0 +1,103 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_business_event_outbox") +/** + * Purpose: BusinessEventOutboxDO supports BusinessEventOutboxDO.java by holding or executing the business event outbox do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxDO extends BaseEntity { + + @TableField("event_key") + /** + * Purpose: eventKey supports BusinessEventOutboxDO.java by holding or executing the event key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String eventKey; + + @TableField("event_type") + /** + * Purpose: eventType supports BusinessEventOutboxDO.java by holding or executing the event type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String eventType; + + @TableField("business_type") + /** + * Purpose: businessType supports BusinessEventOutboxDO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + @TableField("business_id") + /** + * Purpose: businessId supports BusinessEventOutboxDO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + @TableField("payload_json") + /** + * Purpose: payloadJson supports BusinessEventOutboxDO.java by holding or executing the payload json business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String payloadJson; + + @TableField("status") + /** + * Purpose: status supports BusinessEventOutboxDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + + @TableField("retry_count") + /** + * Purpose: retryCount supports BusinessEventOutboxDO.java by holding or executing the retry count business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer retryCount; + + @TableField("next_retry_time") + /** + * Purpose: nextRetryTime supports BusinessEventOutboxDO.java by holding or executing the next retry time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime nextRetryTime; + + @TableField("last_error") + /** + * Purpose: lastError supports BusinessEventOutboxDO.java by holding or executing the last error business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String lastError; + + @TableField("claimed_at") + /** + * Purpose: claimedAt supports BusinessEventOutboxDO.java by holding or executing the claimed at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime claimedAt; + + @TableField("processed_at") + /** + * Purpose: processedAt supports BusinessEventOutboxDO.java by holding or executing the processed at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime processedAt; + + @TableField("is_delete") + /** + * Purpose: isDelete supports BusinessEventOutboxDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/MessageHubPushConfigDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/MessageHubPushConfigDO.java new file mode 100644 index 00000000..9f52a294 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/MessageHubPushConfigDO.java @@ -0,0 +1,93 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * FingertipDesigner 调用 MessageHub 的场景级配置。 + * + *

这里不保存 Spug、阿里云等供应商密钥;这些真实通道仍由 MessageHub 自己管理。 + * 本表只描述 FingertipDesigner 在某个业务功能里投递 MessageHub 时要携带的参数。

+ */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_messagehub_push_config") +public class MessageHubPushConfigDO extends BaseEntity { + + @TableField("scene_code") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @TableField("scene_name") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @TableField("platform") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + + @TableField("msg_type") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + + @TableField("queue_name") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @TableField("source_system") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @TableField("template_code") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + @TableField("channel_id") + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @TableField("send_method") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + @TableField("enabled") + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/WechatMiniBindingDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/WechatMiniBindingDO.java new file mode 100644 index 00000000..a1b3e98d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/entity/WechatMiniBindingDO.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 微信小程序用户绑定关系。 + */ +@Getter +@Setter +@TableName("t_wechat_mini_binding") +public class WechatMiniBindingDO extends BaseEntity { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("app_id") + /** + * Field `appId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String appId; + + @TableField("openid") + /** + * Field `openId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String openId; + + @TableField("unionid") + /** + * Field `unionId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String unionId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/BusinessEventOutboxMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/BusinessEventOutboxMapper.java new file mode 100644 index 00000000..17da9800 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/BusinessEventOutboxMapper.java @@ -0,0 +1,31 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.BusinessEventOutboxDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +/** + * Purpose: BusinessEventOutboxMapper supports BusinessEventOutboxMapper.java by holding or executing the business event outbox mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface BusinessEventOutboxMapper extends BaseMapper { + + @Select("SELECT * FROM t_business_event_outbox WHERE status IN ('PENDING', 'FAILED') AND is_delete = 0 AND (next_retry_time IS NULL OR next_retry_time <= #{now}) ORDER BY create_time ASC, id ASC LIMIT #{limit}") + List selectDueEvents(@Param("now") LocalDateTime now, @Param("limit") int limit); + + @Update("UPDATE t_business_event_outbox SET status = 'PROCESSING', claimed_at = #{now} WHERE id = #{id} AND status IN ('PENDING', 'FAILED') AND is_delete = 0") + int claimDueEvent(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_business_event_outbox SET status = 'SUCCEEDED', processed_at = #{now}, last_error = NULL WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") + int markSucceeded(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_business_event_outbox SET status = 'FAILED', retry_count = COALESCE(retry_count, 0) + 1, next_retry_time = #{nextRetryTime}, last_error = #{lastError} WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0") + int markFailed(@Param("id") Long id, @Param("nextRetryTime") LocalDateTime nextRetryTime, @Param("lastError") String lastError); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/MessageHubPushConfigMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/MessageHubPushConfigMapper.java new file mode 100644 index 00000000..93857e01 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/MessageHubPushConfigMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO; + +/** + * MessageHubPushConfigMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface MessageHubPushConfigMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/WechatMiniBindingMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/WechatMiniBindingMapper.java new file mode 100644 index 00000000..bebd18c4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/mapper/WechatMiniBindingMapper.java @@ -0,0 +1,10 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.WechatMiniBindingDO; + +/** + * 微信小程序绑定关系 Mapper。 + */ +public interface WechatMiniBindingMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/BusinessEventOutboxService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/BusinessEventOutboxService.java new file mode 100644 index 00000000..4361903f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/BusinessEventOutboxService.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + +/** + * Purpose: BusinessEventOutboxService supports BusinessEventOutboxService.java by holding or executing the business event outbox service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface BusinessEventOutboxService { + + void enqueueOrderCompleted(Long orderId); + + void processDueEvents(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MapService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MapService.java new file mode 100644 index 00000000..d9b4636f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MapService.java @@ -0,0 +1,15 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * Purpose: MapService supports MapService.java by holding or executing the map service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface MapService { + + String normalizeProvider(String provider); + + Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubClientService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubClientService.java new file mode 100644 index 00000000..524da1b6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubClientService.java @@ -0,0 +1,30 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * MessageHub客户端服务接口 + * 用于调用MessageHub服务发送消息 + * + * @author xiaowang + * @date 2026-03-03 + */ +public interface MessageHubClientService { + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + void sendSmsVerificationCode(String phone, String code); + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + void sendSmsVerificationCode(String sceneCode, String phone, String code); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubPushConfigService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubPushConfigService.java new file mode 100644 index 00000000..acf870ff --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/MessageHubPushConfigService.java @@ -0,0 +1,71 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.vo.MessageHubPushConfigVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * MessageHubPushConfigService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface MessageHubPushConfigService { + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listConfigs(UserDO currentUser); + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto); + + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer enabled); + + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + MessageHubPushConfigDO getEnabledConfig(String sceneCode); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniAuthService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniAuthService.java new file mode 100644 index 00000000..a438e527 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniAuthService.java @@ -0,0 +1,44 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.vo.WechatMiniLoginResultVO; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 微信小程序登录编排服务。 + */ +public interface WechatMiniAuthService { + + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO); + + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO); + + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO); + + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void invalidateBindingsByUserId(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniClientService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniClientService.java new file mode 100644 index 00000000..167853d1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/WechatMiniClientService.java @@ -0,0 +1,43 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service; + + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 微信小程序开放接口客户端。 + */ +public interface WechatMiniClientService { + + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ + SessionInfo code2Session(String wxCode); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ + String getPhoneNumber(String phoneCode); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + String getConfiguredAppId(); + + /** + * Run business method `SessionInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param sessionKey parameter `sessionKey` supplied by the caller + * @return record result consumed by the caller or returned to the frontend + */ + record SessionInfo(String openId, String unionId, String sessionKey) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java new file mode 100644 index 00000000..866cb276 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxProcessor.java @@ -0,0 +1,92 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.BusinessEventOutboxDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.BusinessEventOutboxMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.modules.order.service.impl.OrderServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService; +@Component +@RequiredArgsConstructor +/** + * Purpose: BusinessEventOutboxProcessor supports BusinessEventOutboxProcessor.java by holding or executing the business event outbox processor business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxProcessor { + + /** + * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxProcessor.java by holding or executing the event order completed business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; + /** + * Purpose: PROCESS_BATCH_SIZE supports BusinessEventOutboxProcessor.java by holding or executing the process batch size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int PROCESS_BATCH_SIZE = 20; + + /** + * Purpose: outboxMapper supports BusinessEventOutboxProcessor.java by holding or executing the outbox mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final BusinessEventOutboxMapper outboxMapper; + /** + * Purpose: orderMapper supports BusinessEventOutboxProcessor.java by holding or executing the order mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OrderMapper orderMapper; + /** + * Purpose: orderService supports BusinessEventOutboxProcessor.java by holding or executing the order service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final OrderServiceImpl orderService; + + @Scheduled(fixedDelay = 2000L) + @Transactional + /** + * Purpose: processDueEvents supports BusinessEventOutboxProcessor.java by holding or executing the process due events business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processDueEvents() { + LocalDateTime now = LocalDateTime.now(); + List events = outboxMapper.selectDueEvents(now, PROCESS_BATCH_SIZE); + for (BusinessEventOutboxDO event : events) { + processOne(event); + } + } + + @Transactional + /** + * Purpose: processOne supports BusinessEventOutboxProcessor.java by holding or executing the process one business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processOne(BusinessEventOutboxDO event) { + if (event == null || event.getId() == null) { + return; + } + LocalDateTime now = LocalDateTime.now(); + if (outboxMapper.claimDueEvent(event.getId(), now) == 0) { + return; + } + try { + if (EVENT_ORDER_COMPLETED.equals(event.getEventType())) { + OrderDO order = orderMapper.selectById(event.getBusinessId()); + orderService.createPendingArtistReviewTasksAndNotifyFromOutbox(order); + } + outboxMapper.markSucceeded(event.getId(), LocalDateTime.now()); + } catch (Exception exception) { + int retryCount = event.getRetryCount() == null ? 0 : event.getRetryCount(); + LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(Math.min(300L, (long) Math.pow(2, retryCount) * 10L)); + outboxMapper.markFailed(event.getId(), nextRetryTime, + BusinessEventOutboxServiceImpl.limit(exception.getMessage(), 500)); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java new file mode 100644 index 00000000..a00d842f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/BusinessEventOutboxServiceImpl.java @@ -0,0 +1,85 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.BusinessEventOutboxDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.BusinessEventOutboxMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.BusinessEventOutboxService; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +/** + * Purpose: BusinessEventOutboxServiceImpl supports BusinessEventOutboxServiceImpl.java by holding or executing the business event outbox service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class BusinessEventOutboxServiceImpl implements BusinessEventOutboxService { + + /** + * Purpose: EVENT_ORDER_COMPLETED supports BusinessEventOutboxServiceImpl.java by holding or executing the event order completed business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED"; + /** + * Purpose: BUSINESS_ORDER supports BusinessEventOutboxServiceImpl.java by holding or executing the business order business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BUSINESS_ORDER = "ORDER"; + /** + * Purpose: STATUS_PENDING supports BusinessEventOutboxServiceImpl.java by holding or executing the status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String STATUS_PENDING = "PENDING"; + + /** + * Purpose: outboxMapper supports BusinessEventOutboxServiceImpl.java by holding or executing the outbox mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final BusinessEventOutboxMapper outboxMapper; + + @Override + /** + * Purpose: enqueueOrderCompleted supports BusinessEventOutboxServiceImpl.java by holding or executing the enqueue order completed business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void enqueueOrderCompleted(Long orderId) { + if (orderId == null) { + return; + } + BusinessEventOutboxDO event = new BusinessEventOutboxDO(); + event.setEventKey("ORDER:" + orderId + ":COMPLETED"); + event.setEventType(EVENT_ORDER_COMPLETED); + event.setBusinessType(BUSINESS_ORDER); + event.setBusinessId(orderId); + event.setPayloadJson("{\"orderId\":" + orderId + "}"); + event.setStatus(STATUS_PENDING); + event.setRetryCount(0); + event.setNextRetryTime(LocalDateTime.now()); + event.setIsDelete(0); + try { + outboxMapper.insert(event); + } catch (DuplicateKeyException ignored) { + // The order-completed event is idempotent by event_key. + } + } + + @Override + /** + * Purpose: processDueEvents supports BusinessEventOutboxServiceImpl.java by holding or executing the process due events business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void processDueEvents() { + // Processing is owned by BusinessEventOutboxProcessor. This method remains on + // the public service contract for callers that only need enqueue capability. + } + + static String limit(String value, int max) { + if (!StringUtils.hasText(value) || value.length() <= max) { + return value; + } + return value.substring(0, max); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MapServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MapServiceImpl.java new file mode 100644 index 00000000..faad99cd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MapServiceImpl.java @@ -0,0 +1,61 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MapService; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriUtils; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +@Service +/** + * Purpose: MapServiceImpl supports MapServiceImpl.java by holding or executing the map service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class MapServiceImpl implements MapService { + + @Override + /** + * Purpose: normalizeProvider supports MapServiceImpl.java by holding or executing the normalize provider business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String normalizeProvider(String provider) { + if (!StringUtils.hasText(provider)) { + return "TENCENT"; + } + String value = provider.trim().toUpperCase(); + return "AMAP".equals(value) || "TENCENT".equals(value) ? value : "TENCENT"; + } + + @Override + /** + * Purpose: buildNavigationUrls supports MapServiceImpl.java by holding or executing the build navigation urls business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude) { + Map urls = new LinkedHashMap<>(); + if (longitude == null || latitude == null) { + return urls; + } + String name = encode(StringUtils.hasText(shopName) ? shopName : "店铺位置"); + String addr = encode(StringUtils.hasText(address) ? address : ""); + String lon = longitude.stripTrailingZeros().toPlainString(); + String lat = latitude.stripTrailingZeros().toPlainString(); + + urls.put("AMAP", "https://uri.amap.com/navigation?to=" + lon + "," + lat + "," + name + "&mode=car&policy=1&src=fingertipdesigner&coordinate=gaode&callnative=1"); + urls.put("TENCENT", "https://apis.map.qq.com/uri/v1/routeplan?type=drive&tocoord=" + lat + "," + lon + "&to=" + name + "&referer=fingertipdesigner"); + urls.put("BROWSER", "https://apis.map.qq.com/uri/v1/marker?marker=coord:" + lat + "," + lon + ";title:" + name + ";addr:" + addr + "&referer=fingertipdesigner"); + return urls; + } + + /** + * Purpose: encode supports MapServiceImpl.java by holding or executing the encode business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String encode(String value) { + return UriUtils.encode(value, StandardCharsets.UTF_8); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubClientServiceImpl.java new file mode 100644 index 00000000..d428d31c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -0,0 +1,171 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.fingertipdesigner.core.config.BrandProperties; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.core.Message; +import org.springframework.amqp.core.MessageBuilder; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * FingertipDesigner 到 MessageHub 的投递客户端。 + * + *

FingertipDesigner 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、 + * 阿里云等短信供应商。真实通道选择和供应商密钥仍归 MessageHub 管理。

+ */ +@Slf4j +@Service +@RefreshScope +@RequiredArgsConstructor +public class MessageHubClientServiceImpl implements MessageHubClientService { + /** + * Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RabbitTemplate rabbitTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService messageHubPushConfigService; + /** + * 平台品牌文案配置。 + */ + private final BrandProperties brandProperties; + + @Value("${messagehub.client.sms-queue:smsQueue}") + /** + * Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String smsQueue; + + @Value("${messagehub.client.source-system:fingertipdesigner}") + /** + * Purpose: sourceSystem supports MessageHubClientServiceImpl.java by holding or executing the source system business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sourceSystem; + + @Value("${messagehub.client.verify-template-code:SPUG0001}") + /** + * Purpose: verifyTemplateCode supports MessageHubClientServiceImpl.java by holding or executing the verify template code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String verifyTemplateCode; + + @Value("${messagehub.client.send-method:SPUG}") + /** + * Purpose: sendMethod supports MessageHubClientServiceImpl.java by holding or executing the send method business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sendMethod; + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + public void sendSmsVerificationCode(String phone, String code) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + public void sendSmsVerificationCode(String sceneCode, String phone, String code) { + try { + MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); + String messageId = snowflakeIdGenerator.nextIdString(); + Map messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId); + String jsonBody = objectMapper.writeValueAsString(messageBody); + Message message = MessageBuilder + .withBody(jsonBody.getBytes(StandardCharsets.UTF_8)) + .setContentType("application/json") + .setContentEncoding(StandardCharsets.UTF_8.name()) + .setMessageId(messageId) + .build(); + + String queueName = config == null ? smsQueue : config.getQueueName(); + rabbitTemplate.convertAndSend(queueName, message); + log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", + sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); + } catch (Exception exception) { + log.error("发送短信验证码失败", exception); + throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); + } + } + + /** + * Run business method `buildSmsMessageBody`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map buildSmsMessageBody(MessageHubPushConfigDO config, String sceneCode, String phone, String code, String messageId) { + String platform = config == null ? "SMS" : config.getPlatform(); + String resolvedSendMethod = config == null ? sendMethod : config.getSendMethod(); + + Map messageBody = new HashMap<>(); + messageBody.put("receiver", phone); + messageBody.put("channelType", platform); + messageBody.put("platform", platform); + messageBody.put("msgType", config == null ? "VERIFICATION" : config.getMsgType()); + messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode()); + messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem()); + messageBody.put("uniqueId", messageId); + messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); + if (config != null && config.getChannelId() != null) { + messageBody.put("channelId", config.getChannelId()); + } + + Map templateParams = new HashMap<>(); + templateParams.put("name", brandProperties.getMessageTemplateName()); + templateParams.put("code", code); + templateParams.put("min", "5"); + templateParams.put("minutes", "5"); + templateParams.put("number", "5"); + templateParams.put("sceneCode", sceneCode); + messageBody.put("templateParams", templateParams); + return messageBody; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java new file mode 100644 index 00000000..d4ca0868 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java @@ -0,0 +1,329 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.MessageHubPushTestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.MessageHubPushConfigDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.MessageHubPushConfigMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.fingertipdesigner.core.modules.integration.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * MessageHubPushConfigServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigService { + /** + * Variable `configMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigMapper configMapper; + @Lazy + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubClientService messageHubClientService; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listConfigs(UserDO currentUser) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + return configMapper.selectList(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .orderByAsc(MessageHubPushConfigDO::getSceneCode)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + MessageHubPushConfigDO config = new MessageHubPushConfigDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + config.setIsDelete(0); + configMapper.insert(config); + return config.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .ne(MessageHubPushConfigDO::getId, id) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + configMapper.updateById(config); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer enabled) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + config.setEnabled(Integer.valueOf(1).equals(enabled) ? 1 : 0); + configMapper.updateById(config); + return true; + } + + @Override + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + messageHubClientService.sendSmsVerificationCode(config.getSceneCode(), dto.getPhone(), "123456"); + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + public MessageHubPushConfigDO getEnabledConfig(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + return null; + } + return configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, normalizeSceneCode(sceneCode)) + .eq(MessageHubPushConfigDO::getEnabled, 1) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(MessageHubPushConfigDO config, MessageHubPushConfigDTO dto, String sceneCode) { + config.setSceneCode(sceneCode); + config.setSceneName(dto.getSceneName().trim()); + config.setPlatform(normalizeUpper(dto.getPlatform(), "SMS")); + config.setMsgType(normalizeUpper(dto.getMsgType(), "VERIFICATION")); + config.setQueueName(dto.getQueueName().trim()); + config.setSourceSystem(dto.getSourceSystem().trim()); + config.setTemplateCode(dto.getTemplateCode().trim()); + config.setChannelId(dto.getChannelId()); + config.setSendMethod(StringUtils.hasText(dto.getSendMethod()) ? dto.getSendMethod().trim().toUpperCase(Locale.ROOT) : null); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + } + + /** + * Run business method `requireConfig`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigDO requireConfig(Long id) { + MessageHubPushConfigDO config = configMapper.selectById(id); + if (config == null || Integer.valueOf(1).equals(config.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("MessageHub 推送配置不存在"); + } + return config; + } + + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅平台管理员可以管理消息推送配置"); + } + } + + /** + * Run business method `normalizeSceneCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeSceneCode(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("场景编码不能为空"); + } + return sceneCode.trim().toUpperCase(Locale.ROOT); + } + + /** + * Run business method `normalizeUpper`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param fallback parameter `fallback` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeUpper(String value, String fallback) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @return private MessageHubPushConfigVO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigVO toVO(MessageHubPushConfigDO config) { + MessageHubPushConfigVO vo = new MessageHubPushConfigVO(); + vo.setId(config.getId()); + vo.setSceneCode(config.getSceneCode()); + vo.setSceneName(config.getSceneName()); + vo.setPlatform(config.getPlatform()); + vo.setMsgType(config.getMsgType()); + vo.setQueueName(config.getQueueName()); + vo.setSourceSystem(config.getSourceSystem()); + vo.setTemplateCode(config.getTemplateCode()); + vo.setChannelId(config.getChannelId()); + vo.setSendMethod(config.getSendMethod()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java new file mode 100644 index 00000000..404b42a4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -0,0 +1,763 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +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.fingertipdesigner.core.common.BusinessException; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.fingertipdesigner.core.modules.integration.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; +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; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 微信小程序登录编排服务实现。 + */ +@Service +@Slf4j +@RequiredArgsConstructor +public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { + + /** + * Purpose: PHONE_REGEX supports WechatMiniAuthServiceImpl.java by holding or executing the phone regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; + /** + * Purpose: TICKET_KEY_PREFIX supports WechatMiniAuthServiceImpl.java by holding or executing the ticket key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:"; + private static final Duration TICKET_TTL = Duration.ofMinutes(5); + /** + * Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniClientService wechatMiniClientService; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) { + 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("当前微信尚未绑定账号,请使用微信手机号一键登录。"); + } + + UserDO userDO = getAvailableBoundUser(bindingDO); + if (userDO == null) { + return WechatMiniLoginResultVO.needManualLogin("当前微信绑定已失效,请重新使用微信手机号一键登录。"); + } + + return loginOrSelectShop(userDO, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + + @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO) { + WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); + String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode())); + if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取到的微信手机号格式不正确"); + } + + WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId()); + if (bindingDO != null) { + UserDO boundUser = getAvailableBoundUser(bindingDO); + if (boundUser != null) { + UserDO phoneUser = findActiveUserByPhone(phone); + if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前微信已绑定其他账号,无法关联该手机号"); + } + return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + } + + UserDO phoneUser = findActiveUserByPhone(phone); + if (phoneUser != null) { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneUser parameter `phoneUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(phoneUser); + return loginOrSelectShop(phoneUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + + List shops = userShopBindingSupport.listAllActiveShopOptions(); + if (shops.isEmpty()) { + return WechatMiniLoginResultVO.needManualLogin("当前暂无可登录门店,请稍后再试。"); + } + return buildSelectShopResult( + "首次使用微信手机号一键登录,请先选择本次登录门店。", + shops, + new TicketPayload(null, phone, sessionInfo.openId(), sessionInfo.unionId(), true) + ); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ + public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) { + Long shopId = normalizeShopId(requestDTO.getShopId()); + if (shopId == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("请选择登录门店"); + } + + TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket()); + LoginResponseVO loginResponse; + if (ticketPayload.getUserId() != null) { + loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId); + } else if (StringUtils.hasText(ticketPayload.getPhone())) { + loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId); + } else { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("登录票据数据不完整,请重新发起微信一键登录"); + } + + ensureBinding(loginResponse.getUserInfo().getId(), ticketPayload.getOpenId(), ticketPayload.getUnionId()); + deleteTicketPayload(requestDTO.getTicket()); + return WechatMiniLoginResultVO.success( + Boolean.TRUE.equals(ticketPayload.getNewUser()) ? "注册并登录成功" : "登录成功", + loginResponse, + Boolean.TRUE.equals(ticketPayload.getNewUser()) + ); + } + + @Override + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void invalidateBindingsByUserId(Long userId) { + if (userId == null) { + return; + } + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getUserId, userId) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + } + + private WechatMiniLoginResultVO loginOrSelectShop( + UserDO userDO, + Long preferredShopId, + WechatMiniClientService.SessionInfo sessionInfo, + boolean newUser + ) { + if (Integer.valueOf(4).equals(userDO.getType())) { + List platformAdminShops = resolvePlatformAdminLoginShops(userDO); + if (platformAdminShops.isEmpty()) { + LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), null); + ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); + return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); + } + return buildSelectShopResult( + "平台管理员可选择任意门店作为本次登录门店。", + platformAdminShops, + new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) + ); + } + + List activeShops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (activeShops.isEmpty()) { + return WechatMiniLoginResultVO.needManualLogin("当前账号没有可登录的门店,请联系管理员处理。"); + } + + Long resolvedShopId = resolvePreferredOrOnlyShop(activeShops, preferredShopId); + if (resolvedShopId != null) { + LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), resolvedShopId); + ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId()); + return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser); + } + + return buildSelectShopResult( + "该账号绑定了多家门店,请选择本次登录门店。", + activeShops, + new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser) + ); + } + + /** + * Purpose: resolvePlatformAdminLoginShops supports WechatMiniAuthServiceImpl.java by holding or executing the resolve platform admin login shops business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List resolvePlatformAdminLoginShops(UserDO userDO) { + LoginShopSelectionVO selection = null; + if (StringUtils.hasText(userDO.getPhone())) { + selection = userService.getLoginShopSelectionByPhone(userDO.getPhone()); + } else if (StringUtils.hasText(userDO.getAccount())) { + selection = userService.getLoginShopSelectionByAccount(userDO.getAccount()); + } + return selection == null || selection.getShops() == null ? List.of() : selection.getShops(); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingDO parameter `bindingDO` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getAvailableBoundUser(WechatMiniBindingDO bindingDO) { + UserDO userDO = userMapper.selectById(bindingDO.getUserId()); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + deactivateBinding(bindingDO.getId()); + return null; + } + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + return userDO; + } + + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUserAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("账号已停用"); + } + } + + /** + * Run business method `findActiveUserByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO findActiveUserByPhone(String phone) { + if (!StringUtils.hasText(phone)) { + return null; + } + return userMapper.selectOne( + new LambdaQueryWrapper() + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + } + + /** + * Run business method `findBindingByOpenId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @return private WechatMiniBindingDO result consumed by the caller or returned to the frontend + */ + private WechatMiniBindingDO findBindingByOpenId(String openId) { + return wechatMiniBindingMapper.selectOne( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId()) + .eq(WechatMiniBindingDO::getOpenId, openId) + .eq(WechatMiniBindingDO::getStatus, 1) + .last("limit 1") + ); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listBindingsByOpenId(String appId, String openId) { + if (!StringUtils.hasText(openId)) { + return List.of(); + } + return wechatMiniBindingMapper.selectList( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getOpenId, openId) + .orderByDesc(WechatMiniBindingDO::getStatus) + .orderByDesc(WechatMiniBindingDO::getUpdateTime) + .orderByDesc(WechatMiniBindingDO::getCreateTime) + .orderByDesc(WechatMiniBindingDO::getId) + ); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listBindingsByUserId(String appId, Long userId) { + if (userId == null) { + return List.of(); + } + return wechatMiniBindingMapper.selectList( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getUserId, userId) + .orderByDesc(WechatMiniBindingDO::getStatus) + .orderByDesc(WechatMiniBindingDO::getUpdateTime) + .orderByDesc(WechatMiniBindingDO::getCreateTime) + .orderByDesc(WechatMiniBindingDO::getId) + ); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `ensureBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + */ + protected void ensureBinding(Long userId, String openId, String unionId) { + if (userId == null || !StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信绑定信息不完整"); + } + + String appId = wechatMiniClientService.getConfiguredAppId(); + List openIdBindings = listBindingsByOpenId(appId, openId); + List userBindings = listBindingsByUserId(appId, userId); + + /** + * Run business method `validateExclusiveActiveBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param openIdBindings parameter `openIdBindings` supplied by the caller + * @param userBindings parameter `userBindings` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateExclusiveActiveBinding(userId, openId, openIdBindings, userBindings); + + 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; + } + + targetBinding.setUserId(userId); + targetBinding.setAppId(appId); + targetBinding.setOpenId(openId); + targetBinding.setUnionId(unionId); + targetBinding.setStatus(1); + targetBinding.setUpdateTime(LocalDateTime.now()); + wechatMiniBindingMapper.updateById(targetBinding); + + deactivateDuplicateBindings(targetBinding.getId(), mergeBindings(openIdBindings, userBindings)); + } + + /** + * Run business method `deactivateBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingId parameter `bindingId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deactivateBinding(Long bindingId) { + if (bindingId == null) { + return; + } + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getId, bindingId) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + } + + private void validateExclusiveActiveBinding( + Long userId, + String openId, + List openIdBindings, + List userBindings + ) { + boolean openIdBoundToOtherUser = openIdBindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .anyMatch(binding -> !Objects.equals(binding.getUserId(), userId)); + if (openIdBoundToOtherUser) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前微信已绑定其他账号,无法完成登录"); + } + + boolean userBoundToOtherWechat = userBindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .anyMatch(binding -> !Objects.equals(binding.getOpenId(), openId)); + if (userBoundToOtherWechat) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("当前账号已绑定其他微信,请联系管理员处理"); + } + } + + private WechatMiniBindingDO pickTargetBinding( + Long userId, + String openId, + List openIdBindings, + List userBindings + ) { + List 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 mergeBindings( + List openIdBindings, + List userBindings + ) { + List 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; + } + + /** + * Run business method `appendUniqueBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param merged parameter `merged` supplied by the caller + * @param candidate parameter `candidate` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void appendUniqueBinding(List merged, WechatMiniBindingDO candidate) { + if (candidate == null) { + return; + } + boolean exists = merged.stream().anyMatch(item -> Objects.equals(item.getId(), candidate.getId())); + if (!exists) { + merged.add(candidate); + } + } + + /** + * Run business method `deactivateDuplicateBindings`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keepBindingId parameter `keepBindingId` supplied by the caller + * @param bindings parameter `bindings` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deactivateDuplicateBindings(Long keepBindingId, List bindings) { + bindings.stream() + .filter(binding -> binding.getId() != null && !Objects.equals(binding.getId(), keepBindingId)) + .forEach(binding -> deactivateBinding(binding.getId())); + } + + /** + * Run business method `resolvePreferredOrOnlyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param preferredShopId parameter `preferredShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolvePreferredOrOnlyShop(List shops, Long preferredShopId) { + Long normalizedPreferredShopId = normalizeShopId(preferredShopId); + if (normalizedPreferredShopId != null) { + boolean matched = shops.stream().anyMatch(shop -> Objects.equals(shop.getId(), normalizedPreferredShopId)); + if (matched) { + return normalizedPreferredShopId; + } + } + if (shops.size() == 1) { + return shops.get(0).getId(); + } + return null; + } + + private WechatMiniLoginResultVO buildSelectShopResult( + String message, + List shops, + TicketPayload ticketPayload + ) { + String ticket = storeTicketPayload(ticketPayload); + return WechatMiniLoginResultVO.selectShop(message, ticket, Boolean.TRUE.equals(ticketPayload.getNewUser()), shops); + } + + /** + * Run business method `storeTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticketPayload parameter `ticketPayload` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String storeTicketPayload(TicketPayload ticketPayload) { + String ticket = "wxmini_" + snowflakeIdGenerator.nextIdString(); + try { + redisTemplate.opsForValue().set( + TICKET_KEY_PREFIX + ticket, + objectMapper.writeValueAsString(ticketPayload), + TICKET_TTL + ); + return ticket; + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("生成微信登录票据失败", exception); + } + } + + /** + * Run business method `readTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private TicketPayload result consumed by the caller or returned to the frontend + */ + private TicketPayload readTicketPayload(String ticket) { + String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket); + if (!StringUtils.hasText(payloadJson)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("登录票据已失效,请重新发起微信一键登录"); + } + try { + return objectMapper.readValue(payloadJson, TicketPayload.class); + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("解析微信登录票据失败", exception); + } + } + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void deleteTicketPayload(String ticket) { + redisTemplate.delete(TICKET_KEY_PREFIX + ticket); + } + + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + /** + * Run business method `normalizePhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizePhone(String phone) { + return phone == null ? "" : phone.trim(); + } + + @Data + /** + * Purpose: TicketPayload supports WechatMiniAuthServiceImpl.java by holding or executing the ticket payload business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static class TicketPayload { + /** + * Purpose: userId supports WechatMiniAuthServiceImpl.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: phone supports WechatMiniAuthServiceImpl.java by holding or executing the phone business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String phone; + /** + * Purpose: openId supports WechatMiniAuthServiceImpl.java by holding or executing the open id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String openId; + /** + * Purpose: unionId supports WechatMiniAuthServiceImpl.java by holding or executing the union id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String unionId; + /** + * Purpose: newUser supports WechatMiniAuthServiceImpl.java by holding or executing the new user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean newUser; + + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return public result consumed by the caller or returned to the frontend + */ + public TicketPayload() { + } + + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param newUser parameter `newUser` supplied by the caller + * @return public result consumed by the caller or returned to the frontend + */ + public TicketPayload(Long userId, String phone, String openId, String unionId, Boolean newUser) { + this.userId = userId; + this.phone = phone; + this.openId = openId; + this.unionId = unionId; + this.newUser = newUser; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java new file mode 100644 index 00000000..8c9517dc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java @@ -0,0 +1,400 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.fingertipdesigner.core.common.BusinessException; +import com.xiaowang.fingertipdesigner.core.config.WechatMiniProperties; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniClientService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpEntity; +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; + +import java.time.Duration; +import java.util.Map; +import java.util.Objects; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * WeChat mini program API client. + */ +@Service +@RequiredArgsConstructor +public class WechatMiniClientServiceImpl implements WechatMiniClientService { + + /** + * Purpose: ACCESS_TOKEN_CACHE_KEY_PREFIX supports WechatMiniClientServiceImpl.java by holding or executing the access token cache key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ACCESS_TOKEN_CACHE_KEY_PREFIX = "wechat:mini:access-token:"; + /** + * Purpose: ACCESS_TOKEN_URL supports WechatMiniClientServiceImpl.java by holding or executing the access token url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; + /** + * Variable `restTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RestTemplate restTemplate; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectMapper objectMapper; + /** + * Variable `properties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniProperties properties; + + @Override + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ + public SessionInfo code2Session(String wxCode) { + if (!StringUtils.hasText(wxCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信登录凭证不能为空"); + } + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + Map response = readJsonResponse( + doGetForString( + UriComponentsBuilder.fromHttpUrl(properties.getCode2sessionUrl()) + .queryParam("appid", properties.getAppId()) + .queryParam("secret", properties.getAppSecret()) + .queryParam("js_code", wxCode) + .queryParam("grant_type", "authorization_code") + .build(true) + .toUriString(), + "获取微信登录身份失败" + ), + "获取微信登录身份失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信登录身份失败"); + String openId = asText(response.get("openid")); + if (!StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openid parameter `openid` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信登录身份失败:缺少 openid"); + } + return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key"))); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ + public String getPhoneNumber(String phoneCode) { + if (!StringUtils.hasText(phoneCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信手机号凭证不能为空"); + } + + String accessToken = getAccessToken(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + Map response = readJsonResponse( + doPostForString( + UriComponentsBuilder.fromHttpUrl(properties.getPhoneNumberUrl()) + .queryParam("access_token", accessToken) + .build(true) + .toUriString(), + new HttpEntity<>(Map.of("code", phoneCode), headers), + "获取微信手机号失败" + ), + "获取微信手机号失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信手机号失败"); + + Object phoneInfoRaw = response.get("phone_info"); + if (phoneInfoRaw == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + Map phoneInfo = objectMapper.convertValue(phoneInfoRaw, new TypeReference>() { + }); + if (phoneInfo == null || phoneInfo.isEmpty()) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + + String phoneNumber = asText(phoneInfo.get("phoneNumber")); + if (!StringUtils.hasText(phoneNumber)) { + phoneNumber = asText(phoneInfo.get("purePhoneNumber")); + } + if (!StringUtils.hasText(phoneNumber)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信手机号失败:未返回手机号信息"); + } + return phoneNumber; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ + public String getConfiguredAppId() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + return properties.getAppId(); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getAccessToken() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + requireConfiguredCredentials(); + String cacheKey = ACCESS_TOKEN_CACHE_KEY_PREFIX + properties.getAppId(); + String cachedToken = redisTemplate.opsForValue().get(cacheKey); + if (StringUtils.hasText(cachedToken)) { + return cachedToken; + } + + Map response = readJsonResponse( + doGetForString( + UriComponentsBuilder.fromHttpUrl(ACCESS_TOKEN_URL) + .queryParam("grant_type", "client_credential") + .queryParam("appid", properties.getAppId()) + .queryParam("secret", properties.getAppSecret()) + .build(true) + .toUriString(), + "获取微信 access_token 失败" + ), + "获取微信 access_token 失败" + ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertWechatResponseOk(response, "获取微信 access_token 失败"); + + String accessToken = asText(response.get("access_token")); + if (!StringUtils.hasText(accessToken)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param access_token parameter `access_token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("获取微信 access_token 失败:未返回 access_token"); + } + + long expiresIn = parseLong(response.get("expires_in"), 7200L); + long safeBuffer = Math.max(0L, Objects.requireNonNullElse(properties.getAccessTokenBufferSeconds(), 60)); + long ttlSeconds = Math.max(60L, expiresIn - safeBuffer); + redisTemplate.opsForValue().set(cacheKey, accessToken, Duration.ofSeconds(ttlSeconds)); + return accessToken; + } + + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void requireConfiguredCredentials() { + if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appIdappSecret parameter `appIdappSecret` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException("微信小程序登录未配置 appId/appSecret"); + } + } + + /** + * Run business method `doGetForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String doGetForString(String url, String defaultMessage) { + try { + return restTemplate.getForObject(url, String.class); + } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); + } + } + + /** + * Run business method `doPostForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param requestEntity parameter `requestEntity` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String doPostForString(String url, HttpEntity requestEntity, String defaultMessage) { + try { + return restTemplate.postForObject(url, requestEntity, String.class); + } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); + } + } + + /** + * Run business method `readJsonResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param responseBody parameter `responseBody` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map readJsonResponse(String responseBody, String defaultMessage) { + if (!StringUtils.hasText(responseBody)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务未返回数据"); + } + try { + return objectMapper.readValue(responseBody, new TypeReference>() { + }); + } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new BusinessException(defaultMessage + ":微信服务返回了无法解析的响应", exception); + } + } + + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertWechatResponseOk(Map response, String defaultMessage) { + long errCode = parseLong(response.get("errcode"), 0L); + if (errCode == 0L) { + return; + } + String errMsg = asText(response.get("errmsg")); + throw new BusinessException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode))); + } + + /** + * Run business method `parseLong`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param defaultValue parameter `defaultValue` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ + private long parseLong(Object value, long defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Long.parseLong(text); + } catch (NumberFormatException ignored) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * Run business method `asText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String asText(Object value) { + return value == null ? "" : String.valueOf(value).trim(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/MessageHubPushConfigVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/MessageHubPushConfigVO.java new file mode 100644 index 00000000..55b63a36 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/MessageHubPushConfigVO.java @@ -0,0 +1,69 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * MessageHubPushConfigVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/WechatMiniLoginResultVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/WechatMiniLoginResultVO.java new file mode 100644 index 00000000..6f646c1b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/integration/vo/WechatMiniLoginResultVO.java @@ -0,0 +1,110 @@ +package com.xiaowang.fingertipdesigner.core.modules.integration.vo; + +import lombok.Data; + +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +/** + * 微信小程序登录结果。 + */ +@Data +public class WechatMiniLoginResultVO { + + /** + * Purpose: STATUS_SUCCESS supports WechatMiniLoginResultVO.java by holding or executing the status success business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_SUCCESS = "SUCCESS"; + /** + * Purpose: STATUS_SELECT_SHOP supports WechatMiniLoginResultVO.java by holding or executing the status select shop business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_SELECT_SHOP = "SELECT_SHOP"; + /** + * Purpose: STATUS_NEED_MANUAL_LOGIN supports WechatMiniLoginResultVO.java by holding or executing the status need manual login business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String STATUS_NEED_MANUAL_LOGIN = "NEED_MANUAL_LOGIN"; + + /** + * Field `status` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String status; + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String message; + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ticket; + /** + * Field `newUser` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean newUser; + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops; + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String accessToken; + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String refreshToken; + /** + * Field `userInfo` (LoginResponseVO.UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LoginResponseVO.UserInfo userInfo; + /** + * Field `needSetPassword` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean needSetPassword; + + /** + * Purpose: success supports WechatMiniLoginResultVO.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static WechatMiniLoginResultVO success(String message, LoginResponseVO loginResponse, boolean newUser) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_SUCCESS); + resultVO.setMessage(message); + resultVO.setNewUser(newUser); + resultVO.setAccessToken(loginResponse.getAccessToken()); + resultVO.setRefreshToken(loginResponse.getRefreshToken()); + resultVO.setUserInfo(loginResponse.getUserInfo()); + resultVO.setNeedSetPassword(loginResponse.isNeedSetPassword()); + return resultVO; + } + + public static WechatMiniLoginResultVO selectShop( + String message, + String ticket, + boolean newUser, + List shops + ) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_SELECT_SHOP); + resultVO.setMessage(message); + resultVO.setTicket(ticket); + resultVO.setNewUser(newUser); + resultVO.setShops(shops); + return resultVO; + } + + /** + * Purpose: needManualLogin supports WechatMiniLoginResultVO.java by holding or executing the need manual login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static WechatMiniLoginResultVO needManualLogin(String message) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN); + resultVO.setMessage(message); + resultVO.setNewUser(false); + return resultVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/controller/admin/AdminInventoryController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/controller/admin/AdminInventoryController.java new file mode 100644 index 00000000..e3ee0a93 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/controller/admin/AdminInventoryController.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryAdjustDTO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryItemDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.service.InventoryService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.inventory.vo.InventoryItemVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/inventory") +@RequiredArgsConstructor +public class AdminInventoryController { + + private final InventoryService inventoryService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping("/list") + @RequirePermission("inventory:view") + public Result> list(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(inventoryService.listItems(shopId, page, size)); + } + + @PostMapping("/save") + @RequirePermission("inventory:manage") + public Result save(HttpServletRequest request, @RequestBody InventoryItemDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + return Result.success(inventoryService.saveItem(dto)); + } + + @PostMapping("/{id}/adjust") + @RequirePermission("inventory:manage") + public Result adjust(HttpServletRequest request, @PathVariable Long id, @RequestBody InventoryAdjustDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + InventoryItemVO result = inventoryService.adjustStock(currentUser.getId(), id, dto); + securityAuditSupport.success(request, SecurityAuditActions.INVENTORY_ADJUST, "itemId=" + id); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.INVENTORY_ADJUST, "itemId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryAdjustDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryAdjustDTO.java new file mode 100644 index 00000000..9ce3360c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryAdjustDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryAdjustDTO { + private String changeType; + private BigDecimal changeQuantity; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryItemDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryItemDTO.java new file mode 100644 index 00000000..cd4958af --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/dto/InventoryItemDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryItemDTO { + private Long shopId; + private String category; + private String itemName; + private String unit; + private BigDecimal stockQuantity; + private BigDecimal warningThreshold; + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryItemDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryItemDO.java new file mode 100644 index 00000000..14a099c5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryItemDO.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_inventory_item") +public class InventoryItemDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("category") + private String category; + @TableField("item_name") + private String itemName; + @TableField("unit") + private String unit; + @TableField("stock_quantity") + private BigDecimal stockQuantity; + @TableField("warning_threshold") + private BigDecimal warningThreshold; + @TableField("status") + private Integer status; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryRecordDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryRecordDO.java new file mode 100644 index 00000000..c5990766 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/entity/InventoryRecordDO.java @@ -0,0 +1,31 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_inventory_record") +public class InventoryRecordDO extends BaseEntity { + @TableField("inventory_item_id") + private Long inventoryItemId; + @TableField("shop_id") + private Long shopId; + @TableField("change_type") + private String changeType; + @TableField("change_quantity") + private BigDecimal changeQuantity; + @TableField("before_quantity") + private BigDecimal beforeQuantity; + @TableField("after_quantity") + private BigDecimal afterQuantity; + @TableField("operator_id") + private Long operatorId; + @TableField("remark") + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryItemMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryItemMapper.java new file mode 100644 index 00000000..438cd7f9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryItemMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.inventory.entity.InventoryItemDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface InventoryItemMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryRecordMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryRecordMapper.java new file mode 100644 index 00000000..8e0fb68e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/mapper/InventoryRecordMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.inventory.entity.InventoryRecordDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface InventoryRecordMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/InventoryService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/InventoryService.java new file mode 100644 index 00000000..9c4d98a3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/InventoryService.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.service; + +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryAdjustDTO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryItemDTO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.vo.InventoryItemVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; + +public interface InventoryService { + InventoryItemVO saveItem(InventoryItemDTO dto); + + InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto); + + PageResultVO listItems(Long shopId, Integer page, Integer size); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/impl/InventoryServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/impl/InventoryServiceImpl.java new file mode 100644 index 00000000..35dcc983 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/service/impl/InventoryServiceImpl.java @@ -0,0 +1,100 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryAdjustDTO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.InventoryItemDTO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.entity.InventoryItemDO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.entity.InventoryRecordDO; +import com.xiaowang.fingertipdesigner.core.modules.inventory.mapper.InventoryItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.inventory.mapper.InventoryRecordMapper; +import com.xiaowang.fingertipdesigner.core.modules.inventory.service.InventoryService; +import com.xiaowang.fingertipdesigner.core.modules.inventory.vo.InventoryItemVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +public class InventoryServiceImpl implements InventoryService { + + private final InventoryItemMapper inventoryItemMapper; + private final InventoryRecordMapper inventoryRecordMapper; + + @Override + @Transactional + public InventoryItemVO saveItem(InventoryItemDTO dto) { + if (dto == null || dto.getShopId() == null || dto.getItemName() == null || dto.getItemName().isBlank()) { + throw new RuntimeException("库存物料信息不完整"); + } + InventoryItemDO item = new InventoryItemDO(); + BeanUtils.copyProperties(dto, item); + item.setStockQuantity(dto.getStockQuantity() == null ? BigDecimal.ZERO : dto.getStockQuantity()); + item.setWarningThreshold(dto.getWarningThreshold() == null ? BigDecimal.ZERO : dto.getWarningThreshold()); + item.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + item.setIsDelete(0); + inventoryItemMapper.insert(item); + return toVO(item); + } + + @Override + @Transactional + public InventoryItemVO adjustStock(Long operatorId, Long itemId, InventoryAdjustDTO dto) { + InventoryItemDO item = inventoryItemMapper.selectById(itemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("库存物料不存在"); + } + BigDecimal before = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); + BigDecimal delta = dto == null || dto.getChangeQuantity() == null ? BigDecimal.ZERO : dto.getChangeQuantity(); + BigDecimal after = before.add(delta); + if (after.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("库存不能小于 0"); + } + item.setStockQuantity(after); + inventoryItemMapper.updateById(item); + InventoryRecordDO record = new InventoryRecordDO(); + record.setInventoryItemId(item.getId()); + record.setShopId(item.getShopId()); + record.setChangeType(dto == null ? null : dto.getChangeType()); + record.setChangeQuantity(delta); + record.setBeforeQuantity(before); + record.setAfterQuantity(after); + record.setOperatorId(operatorId); + record.setRemark(dto == null ? null : dto.getRemark()); + inventoryRecordMapper.insert(record); + return toVO(item); + } + + @Override + public PageResultVO listItems(Long shopId, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(InventoryItemDO::getIsDelete, 0) + .orderByDesc(InventoryItemDO::getCreateTime); + if (shopId != null) { + wrapper.eq(InventoryItemDO::getShopId, shopId); + } + Page result = inventoryItemMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + vo.setList(result.getRecords().stream().map(this::toVO).toList()); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private InventoryItemVO toVO(InventoryItemDO item) { + InventoryItemVO vo = new InventoryItemVO(); + BeanUtils.copyProperties(item, vo); + BigDecimal stock = item.getStockQuantity() == null ? BigDecimal.ZERO : item.getStockQuantity(); + BigDecimal warning = item.getWarningThreshold() == null ? BigDecimal.ZERO : item.getWarningThreshold(); + vo.setWarning(stock.compareTo(warning) <= 0); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/vo/InventoryItemVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/vo/InventoryItemVO.java new file mode 100644 index 00000000..1ab964b6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/inventory/vo/InventoryItemVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.inventory.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class InventoryItemVO { + private Long id; + private Long shopId; + private String category; + private String itemName; + private String unit; + private BigDecimal stockQuantity; + private BigDecimal warningThreshold; + private Boolean warning; + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/controller/admin/AdminManagerController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/controller/admin/AdminManagerController.java new file mode 100644 index 00000000..0a376cd9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/controller/admin/AdminManagerController.java @@ -0,0 +1,297 @@ +package com.xiaowang.fingertipdesigner.core.modules.manager.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO; +import com.xiaowang.fingertipdesigner.core.modules.manager.dto.ManagerCustomerCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningCalendarVO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.time.LocalDate; +import java.util.List; + +@RestController +@RequestMapping("/admin/manager") +@RequiredArgsConstructor +public class AdminManagerController { + + private final PlanningService planningService; + private final UserService userService; + private final NailArtistInfoService nailArtistInfoService; + private final ArtistScheduleService artistScheduleService; + private final ProductService productService; + private final ShopService shopService; + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/planning/calendar") + @RequirePermission("schedule:view") + public Result calendar(HttpServletRequest request, + @RequestParam(required = false) String startDate, + @RequestParam(required = false) String endDate, + @RequestParam(required = false) Long artistId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + LocalDate start = startDate == null || startDate.isBlank() ? LocalDate.now() : LocalDate.parse(startDate); + LocalDate end = endDate == null || endDate.isBlank() ? start : LocalDate.parse(endDate); + return Result.success(planningService.getCalendar(currentUser, start, end, artistId)); + } + + @PostMapping("/planning/appointments") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-create-appointment", ttlSeconds = 10, message = "预约创建处理中,请勿重复提交") + public Result createAppointment(HttpServletRequest request, + @RequestBody PlanningAppointmentCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.createAppointment(currentUser, dto)); + } + + @GetMapping("/planning/appointments/{orderItemId}") + @RequirePermission("order:view") + public Result appointment(HttpServletRequest request, + @PathVariable Long orderItemId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.getAppointment(currentUser, orderItemId)); + } + + @PutMapping("/planning/appointments/{orderItemId}/time-artist") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-move-appointment", ttlSeconds = 10, message = "预约调整处理中,请勿重复提交") + public Result moveAppointment(HttpServletRequest request, + @PathVariable Long orderItemId, + @RequestBody PlanningAppointmentMoveDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.moveAppointment(currentUser, orderItemId, dto)); + } + + @PutMapping("/planning/appointments/{orderId}/status") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-update-appointment-status", ttlSeconds = 10, message = "预约状态处理中,请勿重复提交") + public Result updateStatus(HttpServletRequest request, + @PathVariable Long orderId, + @RequestBody PlanningAppointmentStatusDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.updateStatus(currentUser, orderId, dto)); + } + + @GetMapping("/customers") + @RequirePermission("user:view") + public Result> customers(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Boolean hasOrder) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long resolvedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO result = userService.pageUsers(page, size, keyword, resolvedShopId, 0, null, null, null, null, null, null, null, null, hasOrder); + return Result.success(result); + } + + @GetMapping("/customers/{id}") + @RequirePermission("user:view") + public Result customer(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权查看其他店铺客户"); + return Result.success(userService.getUserById(id)); + } + + @PostMapping("/customers") + @RequirePermission("user:create") + @OperationGuard(action = "manager-customer-create", ttlSeconds = 10, message = "客户创建处理中,请勿重复提交") + public Result createCustomer(HttpServletRequest request, + @Valid @RequestBody ManagerCustomerCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再新增客户"); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + String phone = dto.getPhone().trim(); + UserDTO userDTO = new UserDTO(); + userDTO.setNickname(dto.getNickname().trim()); + userDTO.setPhone(phone); + userDTO.setContactPhone(phone); + userDTO.setAccount(phone); + userDTO.setType(0); + userDTO.setShopId(shopId); + userDTO.setShopIds(List.of(shopId)); + userDTO.setLevel("普通"); + userDTO.setVipId(0L); + return Result.success(userService.createUser(userDTO)); + } + + @GetMapping("/employees") + @RequirePermission("nail_artist:view") + public Result> employees(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + return Result.success(nailArtistInfoService.getAllNailArtists()); + } + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(nailArtistInfoService.getByShopId(shopId)); + } + + @GetMapping("/employees/{userId}") + @RequirePermission("nail_artist:view") + public Result employee(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺员工"); + } + return Result.success(nailArtistInfoService.getByUserId(userId)); + } + + @PostMapping("/employees") + @RequirePermission("nail_artist:edit") + @OperationGuard(action = "manager-nail-artist-save", ttlSeconds = 10, message = "员工信息保存处理中,请勿重复提交") + public Result saveEmployee(HttpServletRequest request, + @RequestBody NailArtistInfoDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getUserId(), "无权编辑其他店铺员工"); + } + return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(dto)); + } + + @PostMapping("/employees/users") + @RequirePermission("user:create") + @OperationGuard(action = "manager-user-create", ttlSeconds = 10, message = "员工账号创建处理中,请勿重复提交") + public Result createEmployeeUser(HttpServletRequest request, + @Valid @RequestBody UserDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setType(3); + adminScopeHelper.ensureAssignableUserType(currentUser, dto.getType()); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + dto.setShopId(managedShopId); + dto.setShopIds(List.of(managedShopId)); + } + return Result.success(userService.createUser(dto)); + } + + @GetMapping("/employees/schedules") + @RequirePermission("schedule:view") + public Result> schedules(HttpServletRequest request, + @RequestParam(required = false) Long artistId, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(artistScheduleService.listSchedules(shopId, artistId, startDate, endDate)); + } + + @PostMapping("/employees/schedules") + @RequirePermission("schedule:edit") + @OperationGuard(action = "manager-artist-schedule-save", ttlSeconds = 10, message = "排班保存处理中,请勿重复提交") + public Result saveSchedule(HttpServletRequest request, + @RequestBody ArtistScheduleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + return Result.success(artistScheduleService.saveSchedule(dto)); + } + + @GetMapping("/employees/schedule-rule") + @RequirePermission("schedule:view") + public Result scheduleRule(HttpServletRequest request, + @RequestParam Long artistId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(artistScheduleService.getRuleSetting(shopId, artistId)); + } + + @PostMapping("/employees/schedule-rule") + @RequirePermission("schedule:edit") + @OperationGuard(action = "manager-artist-schedule-rule-save", ttlSeconds = 10, message = "排班规则保存处理中,请勿重复提交") + public Result saveScheduleRule(HttpServletRequest request, + @RequestBody ArtistScheduleRuleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + return Result.success(artistScheduleService.saveRule(dto)); + } + + @PostMapping("/employees/schedule-exceptions") + @RequirePermission("schedule:edit") + @OperationGuard(action = "manager-artist-schedule-exception-save", ttlSeconds = 10, message = "排班例外保存处理中,请勿重复提交") + public Result saveScheduleException(HttpServletRequest request, + @RequestBody ArtistScheduleExceptionDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + return Result.success(artistScheduleService.saveException(dto)); + } + + @GetMapping("/products") + @RequirePermission("product:view") + public Result> products(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Long tagId, + @RequestParam(required = false) java.math.BigDecimal minPrice, + @RequestParam(required = false) java.math.BigDecimal maxPrice, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long resolvedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return Result.success(productService.pageProducts(page, size, keyword, resolvedShopId, tagId, minPrice, maxPrice, createdFrom, createdTo)); + } + + @GetMapping("/shop") + @RequirePermission("shop:view") + public Result shop(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + adminScopeHelper.requireShopContext(currentUser); + return Result.success(shopService.getShopById(shopId)); + } + + @PutMapping("/shop") + @RequirePermission("shop:edit") + @OperationGuard(action = "manager-shop-update", ttlSeconds = 10, message = "店铺设置保存处理中,请勿重复提交") + public Result updateShop(HttpServletRequest request, @RequestBody ShopDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + adminScopeHelper.requireShopContext(currentUser); + ShopVO shop = shopService.getShopById(shopId); + if (shop == null) { + return Result.success(false); + } + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + dto.setAuthorizationExpireTime(shop.getAuthorizationExpireTime()); + } + return Result.success(shopService.updateShop(shopId, dto)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/dto/ManagerCustomerCreateDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/dto/ManagerCustomerCreateDTO.java new file mode 100644 index 00000000..cf9f02b8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/manager/dto/ManagerCustomerCreateDTO.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.manager.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Data +public class ManagerCustomerCreateDTO { + + @NotBlank(message = "客户姓名不能为空") + private String nickname; + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + private String phone; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCampaignController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCampaignController.java new file mode 100644 index 00000000..faab4d07 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCampaignController.java @@ -0,0 +1,52 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CampaignDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CampaignService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CampaignVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/campaign") +@RequiredArgsConstructor +public class AdminCampaignController { + + private final CampaignService campaignService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping("/list") + @RequirePermission("campaign:view") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) Integer status, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(campaignService.listCampaigns(shopId, status, page, size)); + } + + @PostMapping("/save") + @RequirePermission("campaign:manage") + public Result save(HttpServletRequest request, @RequestBody CampaignDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId())); + try { + CampaignVO result = campaignService.saveCampaign(dto); + securityAuditSupport.success(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "campaignId=" + result.getId()); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.CAMPAIGN_PUBLISH, "reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCouponController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCouponController.java new file mode 100644 index 00000000..21fe8fbe --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/admin/AdminCouponController.java @@ -0,0 +1,182 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CouponVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 后台优惠券管理控制器 + */ +@RestController +@RequestMapping("/admin/coupon") +@RequiredArgsConstructor +public class AdminCouponController { + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponService couponService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建优惠券 + */ + @PostMapping("/create") + @RequirePermission("coupon:create") + @OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); + Long couponId = couponService.createCoupon(couponDTO, shopId); + return Result.success(couponId); + } + + /** + * 更新优惠券 + */ + @PutMapping("/update/{id}") + @RequirePermission("coupon:edit") + @OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); + Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); + shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); + boolean success = couponService.updateCoupon(id, couponDTO, shopId); + return Result.success(success); + } + + /** + * 删除优惠券 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("coupon:delete") + @OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.deleteCoupon(id, shopId); + return Result.success(success); + } + + /** + * 获取优惠券详情 + */ + @GetMapping("/detail/{id}") + @RequirePermission("coupon:view") + public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); + } + return Result.success(couponVO); + } + + /** + * 获取优惠券列表 + */ + @GetMapping("/list") + @RequirePermission("coupon:view") + public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO pageResult = couponService.listCoupons(page, size, shopId); + return Result.success(pageResult); + } + + /** + * 获取所有优惠券 + */ + @GetMapping("/list/all") + @RequirePermission("coupon:view") + public Result> listAllCoupons(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List coupons = couponService.listAllCoupons(); + Long resolvedShopId = shopId; + if (resolvedShopId != null) { + coupons = coupons.stream() + .filter(coupon -> resolvedShopId.equals(coupon.getShopId())) + .collect(Collectors.toList()); + } + return Result.success(coupons); + } + + /** + * 为用户分配优惠券 + */ + @PostMapping("/assign") + @RequirePermission("coupon:assign") + @OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.assignCouponToUser(userId, couponId, shopId); + return Result.success(success); + } + + /** + * 发放优惠券 + */ + @PostMapping("/distribute") + @RequirePermission("coupon:assign") + @OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + for (Long userId : userIds) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + } + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); + return Result.success(success); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/CouponController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/CouponController.java new file mode 100644 index 00000000..557452ff --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/CouponController.java @@ -0,0 +1,190 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CouponVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 优惠券控制器 + */ +@RestController +@RequestMapping("/coupon") +@RequiredArgsConstructor +public class CouponController { + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponService couponService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建优惠券 + */ + @PostMapping("/create") + @RequirePermission("coupon:create") + public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); + Long couponId = couponService.createCoupon(couponDTO, shopId); + return Result.success(couponId); + } + + /** + * 更新优惠券 + */ + @PutMapping("/update/{id}") + @RequirePermission("coupon:edit") + public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); + Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); + shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); + boolean success = couponService.updateCoupon(id, couponDTO, shopId); + return Result.success(success); + } + + /** + * 删除优惠券 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("coupon:delete") + public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.deleteCoupon(id, shopId); + return Result.success(success); + } + + /** + * 获取优惠券详情 + */ + @GetMapping("/detail/{id}") + @RequirePermission("coupon:view") + public Result getCouponById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(id); + if (couponVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); + } + return Result.success(couponVO); + } + + /** + * 获取优惠券列表 + */ + @GetMapping("/list") + @RequirePermission("coupon:view") + public Result> listCoupons(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO pageResult = couponService.listCoupons(page, size, shopId); + return Result.success(pageResult); + } + + /** + * 为用户分配优惠券 + */ + @PostMapping("/assign") + @RequirePermission("coupon:assign") + public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.assignCouponToUser(userId, couponId, shopId); + return Result.success(success); + } + + /** + * 获取用户优惠券列表 + */ + @GetMapping("/user/list") + public Result> listUserCoupons(@RequestParam(required = false) Integer status, @RequestAttribute("userId") Long userId) { + List userCoupons = couponService.listUserCoupons(userId, status); + return Result.success(userCoupons); + } + + /** + * 使用优惠券 + */ + @PostMapping("/use") + public Result useCoupon(@RequestParam Long userCouponId, @RequestAttribute("userId") Long userId) { + boolean success = couponService.useCoupon(userCouponId, userId); + return Result.success(success); + } + + /** + * 获取商品可用的优惠券 + */ + @GetMapping("/available") + public Result> getAvailableCoupons( + @RequestParam(required = false, defaultValue = "") String productTags, + @RequestParam Double productPrice, + @RequestParam(required = false) Long shopId, + @RequestAttribute("userId") Long userId + ) { + List availableCoupons = couponService.getAvailableCoupons(userId, productTags, productPrice, shopId); + return Result.success(availableCoupons); + } + + /** + * 发放优惠券 + */ + @PostMapping("/distribute") + @RequirePermission("coupon:assign") + public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + CouponVO couponVO = couponService.getCouponById(couponId); + if (couponVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); + for (Long userId : userIds) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); + } + shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); + boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); + return Result.success(success); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/GrowthController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/GrowthController.java new file mode 100644 index 00000000..1b1ed4f4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/GrowthController.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.GrowthService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.GrowthSummaryVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/growth") +@RequiredArgsConstructor +public class GrowthController { + + private final GrowthService growthService; + + @GetMapping("/summary") + public Result summary(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(growthService.getSummary(userId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/ProductLikeController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/ProductLikeController.java new file mode 100644 index 00000000..9cae854d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/ProductLikeController.java @@ -0,0 +1,65 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.ProductLikeService; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +/** + * 商品点赞控制器 + * + * @author xiaowang + * @date 2026-03-05 + */ +@RestController +@RequestMapping("/product-like") +@RequiredArgsConstructor +public class ProductLikeController { + /** + * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductLikeService productLikeService; + + /** + * 点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否成功 + */ + @PostMapping("/like/{productId}") + @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + productLikeService.addLike(userId, productId); + return Result.success(true); + } + + /** + * 取消点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否成功 + */ + @PostMapping("/unlike/{productId}") + @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + productLikeService.removeLike(userId, productId); + return Result.success(true); + } + + /** + * 检查用户是否已点赞商品 + * + * @param userId 当前用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + @GetMapping("/check/{productId}") + public Result checkLikeStatus(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { + boolean isLiked = productLikeService.isProductLiked(userId, productId); + return Result.success(isLiked); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipBenefitController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipBenefitController.java new file mode 100644 index 00000000..b3229e3b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipBenefitController.java @@ -0,0 +1,99 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipBenefitVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipBenefitService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * VIP权益信息表 Controller + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/vip-benefit", "/api/vip-benefit"}) +@RequiredArgsConstructor +public class VipBenefitController { + /** + * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitService vipBenefitService; + + /** + * 创建VIP权益 + * + * @param vipBenefitDTO VIP权益DTO + * @return VIP权益ID + */ + @PostMapping("/create") + public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { + Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); + return Result.success(id); + } + + /** + * 更新VIP权益 + * + * @param id VIP权益ID + * @param vipBenefitDTO VIP权益DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { + boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); + return Result.success(success); + } + + /** + * 删除VIP权益 + * + * @param id VIP权益ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteVipBenefit(@PathVariable Long id) { + boolean success = vipBenefitService.deleteVipBenefit(id); + return Result.success(success); + } + + /** + * 根据ID查询VIP权益 + * + * @param id VIP权益ID + * @return VIP权益VO + */ + @GetMapping("/get/{id}") + public Result getVipBenefitById(@PathVariable Long id) { + VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); + return Result.success(vipBenefitVO); + } + + /** + * 查询所有VIP权益 + * + * @return VIP权益VO列表 + */ + @GetMapping("/list/all") + public Result> listAllVipBenefits() { + List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); + return Result.success(vipBenefitVOs); + } + + /** + * 根据所需VIP等级查询VIP权益 + * + * @param requiredVipLevel 所需VIP等级 + * @return VIP权益VO列表 + */ + @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") + public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { + List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); + return Result.success(vipBenefitVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipInfoController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipInfoController.java new file mode 100644 index 00000000..28038386 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipInfoController.java @@ -0,0 +1,99 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipInfoVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipInfoService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户VIP信息表 Controller + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/vip-info", "/api/vip-info"}) +@RequiredArgsConstructor +public class VipInfoController { + /** + * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoService vipInfoService; + + /** + * 创建VIP信息 + * + * @param vipInfoDTO VIP信息DTO + * @return VIP信息ID + */ + @PostMapping("/create") + public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { + Long id = vipInfoService.createVipInfo(vipInfoDTO); + return Result.success(id); + } + + /** + * 更新VIP信息 + * + * @param id VIP信息ID + * @param vipInfoDTO VIP信息DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { + boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); + return Result.success(success); + } + + /** + * 删除VIP信息 + * + * @param id VIP信息ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteVipInfo(@PathVariable Long id) { + boolean success = vipInfoService.deleteVipInfo(id); + return Result.success(success); + } + + /** + * 根据ID查询VIP信息 + * + * @param id VIP信息ID + * @return VIP信息VO + */ + @GetMapping("/get/{id}") + public Result getVipInfoById(@PathVariable Long id) { + VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); + return Result.success(vipInfoVO); + } + + /** + * 查询所有VIP信息 + * + * @return VIP信息VO列表 + */ + @GetMapping("/list/all") + public Result> listAllVipInfos() { + List vipInfoVOs = vipInfoService.listAllVipInfos(); + return Result.success(vipInfoVOs); + } + + /** + * 根据VIP等级查询VIP信息 + * + * @param vipLevel VIP等级 + * @return VIP信息VO列表 + */ + @GetMapping("/list/vipLevel/{vipLevel}") + public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { + List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); + return Result.success(vipInfoVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipRechargePlanController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipRechargePlanController.java new file mode 100644 index 00000000..0c842175 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/VipRechargePlanController.java @@ -0,0 +1,113 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipRechargePlanService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan", "/admin/vip-recharge-plan"}) +/** + * VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanController { + /** + * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanService vipRechargePlanService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("user:vip:manage") + /** + * Purpose: listAdmin supports VipRechargePlanController.java by holding or executing the list admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); + } + + @PostMapping("/admin/create") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("user:vip:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(vipRechargePlanService.listMyPlans(userId)); + } + + @GetMapping({"/admin/vip-level-options", "/api/vip-recharge-plan/vip-level-options", "/vip-level-options"}) + /** + * Purpose: listVipLevelOptions supports VipRechargePlanController.java by holding or executing the list vip level options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listVipLevelOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.listVipLevelOptions(currentUser, shopId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/WishlistController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/WishlistController.java new file mode 100644 index 00000000..84c862ca --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/controller/front/WishlistController.java @@ -0,0 +1,100 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.WishlistService; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistInspirationVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestAttribute; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/wishlist") +public class WishlistController { + + @Autowired + private WishlistService wishlistService; + + @PostMapping("/add") + @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { + wishlistService.addToWishlist(userId, request.get("productId")); + return Result.success("ok"); + } + + @PostMapping("/add-with-group") + @OperationGuard(action = "wishlist-add-with-group", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result addToWishlistWithGroup(@RequestBody WishlistAddWithGroupDTO request, @RequestAttribute("userId") Long userId) { + wishlistService.addToWishlist(userId, request); + return Result.success("ok"); + } + + @PostMapping("/remove") + @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { + wishlistService.removeFromWishlist(userId, request.get("productId")); + return Result.success("ok"); + } + + @GetMapping("/check") + public Result checkWishlist(@RequestParam Long productId, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.isInWishlist(userId, productId)); + } + + @GetMapping("/list") + public Result> getWishlist(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.getWishlistByUserId(userId)); + } + + @GetMapping("/groups") + public Result> listGroups(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.listGroups(userId)); + } + + @PostMapping("/groups") + public Result createGroup(@RequestBody WishlistGroupDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.createGroup(userId, request)); + } + + @PutMapping("/groups/{id}") + public Result updateGroup( + @PathVariable Long id, + @RequestBody WishlistGroupDTO request, + @RequestAttribute("userId") Long userId + ) { + return Result.success(wishlistService.updateGroup(userId, id, request)); + } + + @DeleteMapping("/groups/{id}") + public Result deleteGroup(@PathVariable Long id, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.deleteGroup(userId, id)); + } + + @PostMapping("/move") + @OperationGuard(action = "wishlist-move", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + public Result moveWishlist(@RequestBody WishlistMoveDTO request, @RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.moveWishlist(userId, request)); + } + + @GetMapping("/inspiration") + public Result getInspiration(@RequestAttribute("userId") Long userId) { + return Result.success(wishlistService.getInspiration(userId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CampaignDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CampaignDTO.java new file mode 100644 index 00000000..83836c3b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CampaignDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class CampaignDTO { + private Long shopId; + private String title; + private String description; + private String scene; + private String productIds; + private String couponIds; + private Integer status; + private LocalDateTime startTime; + private LocalDateTime endTime; + private Integer sortOrder; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CouponDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CouponDTO.java new file mode 100644 index 00000000..34b34e71 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/CouponDTO.java @@ -0,0 +1,86 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 优惠券DTO + */ +@Data +public class CouponDTO { + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 所属店铺ID + */ + private Long shopId; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 可用标签ID列表 + */ + private List availableTagIds; + + /** + * 不可用标签ID列表 + */ + private List unavailableTagIds; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipBenefitDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipBenefitDTO.java new file mode 100644 index 00000000..7deb5299 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipBenefitDTO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * VIP权益信息表 DTO + * 用于VIP权益信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipBenefitDTO { + + /** + * 权益详情(如折扣、专属服务) + */ + private String benefitInfo; + + /** + * 所需VIP等级 + */ + private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipInfoDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipInfoDTO.java new file mode 100644 index 00000000..7daec346 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipInfoDTO.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户VIP信息表 DTO + * 用于VIP信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipInfoDTO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP等级(如青铜、白银) + */ + private String vipLevel; + + /** + * VIP开通时间 + */ + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + private Long benefitId; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipRechargePlanDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipRechargePlanDTO.java new file mode 100644 index 00000000..9ae06bce --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/VipRechargePlanDTO.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.math.BigDecimal; + +@Data +/** + * VipRechargePlanDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDTO { + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "充值档位标题不能为空") + @Size(max = 100, message = "充值档位标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotNull(message = "充值金额不能为空") + @DecimalMin(value = "0.01", message = "充值金额必须大于0") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @NotNull(message = "赠送金额不能为空") + @DecimalMin(value = "0.00", message = "赠送金额不能小于0") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @NotBlank(message = "VIP等级不能为空") + @Size(max = 20, message = "VIP等级不能超过20个字符") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @Size(max = 255, message = "说明不能超过255个字符") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status = 1; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistAddWithGroupDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistAddWithGroupDTO.java new file mode 100644 index 00000000..2b4ee646 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistAddWithGroupDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistAddWithGroupDTO { + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistDTO.java new file mode 100644 index 00000000..39dc9d38 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistDTO.java @@ -0,0 +1,43 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import lombok.Data; + +/** + * 收藏夹 DTO + * 用于收藏夹商品信息的传输 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class WishlistDTO { + + /** + * 收藏记录ID + */ + private Long id; + + /** + * 用户ID + */ + private Long userId; + + /** + * 商品ID + */ + private Long productId; + + private Long groupId; + + private String groupName; + + private String note; + + private Integer sortOrder; + + /** + * 商品详细信息 + */ + private ProductVO product; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistGroupDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistGroupDTO.java new file mode 100644 index 00000000..83b5b9d1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistGroupDTO.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistGroupDTO { + private String name; + private Integer sortOrder; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistMoveDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistMoveDTO.java new file mode 100644 index 00000000..cdbb49b5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/dto/WishlistMoveDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.dto; + +import lombok.Data; + +@Data +public class WishlistMoveDTO { + private Long wishlistId; + private Long productId; + private Long groupId; + private String note; + private Integer sortOrder; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CampaignDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CampaignDO.java new file mode 100644 index 00000000..1ce813a9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CampaignDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_campaign") +public class CampaignDO extends BaseEntity { + @TableField("shop_id") + private Long shopId; + @TableField("title") + private String title; + @TableField("description") + private String description; + @TableField("scene") + private String scene; + @TableField("product_ids") + private String productIds; + @TableField("coupon_ids") + private String couponIds; + @TableField("status") + private Integer status; + @TableField("start_time") + private LocalDateTime startTime; + @TableField("end_time") + private LocalDateTime endTime; + @TableField("sort_order") + private Integer sortOrder; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponDO.java new file mode 100644 index 00000000..47bc5409 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponDO.java @@ -0,0 +1,102 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 优惠券信息表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_coupon") +public class CouponDO extends BaseEntity { + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 已使用数量 + */ + private Integer usedCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-可用,2-已过期,3-已用完 + */ + private Integer status; + + /** + * 所属店铺ID + */ + private Long shopId; + + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponTagDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponTagDO.java new file mode 100644 index 00000000..e400b794 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/CouponTagDO.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 优惠券标签关联表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_coupon_tag") +public class CouponTagDO extends BaseEntity { + + /** + * 关联优惠券表主键 + */ + private Long couponId; + + /** + * 关联标签表主键 + */ + private Long tagId; + + /** + * 是否可用:1-可用,0-不可用 + */ + private Integer isAvailable; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/ProductLikeDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/ProductLikeDO.java new file mode 100644 index 00000000..b2c029b4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/ProductLikeDO.java @@ -0,0 +1,40 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 商品点赞记录表 DO + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_product_like") +public class ProductLikeDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 关联商品表主键 + */ + @TableField("product_id") + private Long productId; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/UserCouponDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/UserCouponDO.java new file mode 100644 index 00000000..5e2398c7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/UserCouponDO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户优惠券关联表 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_coupon") +public class UserCouponDO extends BaseEntity { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 关联优惠券表主键 + */ + private Long couponId; + + /** + * 状态:1-未使用,2-已使用,3-已过期 + */ + private Integer status; + + /** + * 获取时间 + */ + private LocalDateTime obtainTime; + + /** + * 使用时间 + */ + private LocalDateTime useTime; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipBenefitDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipBenefitDO.java new file mode 100644 index 00000000..d0530593 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipBenefitDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * VIP权益信息表 DO + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_benefit") +public class VipBenefitDO extends BaseEntity { + + /** + * 权益详情(如折扣、专属服务) + */ + @TableField("benefit_info") + private String benefitInfo; + + /** + * 所需VIP等级 + */ + @TableField("required_vip_level") + private String requiredVipLevel; + + @TableField("level_rank") + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + + @TableField("recharge_threshold") + /** + * Field `rechargeThreshold` (java.math.BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private java.math.BigDecimal rechargeThreshold; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipInfoDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipInfoDO.java new file mode 100644 index 00000000..ea000dba --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipInfoDO.java @@ -0,0 +1,64 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户VIP信息表 DO + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_info") +public class VipInfoDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP等级(如青铜、白银) + */ + @TableField("vip_level") + private String vipLevel; + + /** + * VIP开通时间 + */ + @TableField("start_time") + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + @TableField("expire_time") + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + @TableField("activation_method") + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + @TableField("benefit_id") + private Long benefitId; + + @TableField("manual_override") + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipRechargePlanDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipRechargePlanDO.java new file mode 100644 index 00000000..b7e2ef49 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/VipRechargePlanDO.java @@ -0,0 +1,75 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_recharge_plan") +/** + * VipRechargePlanDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("recharge_amount") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @TableField("gift_amount") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @TableField("vip_level") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @TableField("description") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistDO.java new file mode 100644 index 00000000..c75e3058 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@TableName("t_wishlist") +/** + * WishlistDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class WishlistDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + + @TableField("group_id") + private Long groupId; + + @TableField("note") + private String note; + + @TableField("sort_order") + private Integer sortOrder; + + @TableField("is_delete") + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistGroupDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistGroupDO.java new file mode 100644 index 00000000..091071f0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/entity/WishlistGroupDO.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_wishlist_group") +public class WishlistGroupDO extends BaseEntity { + + @TableField("user_id") + private Long userId; + + @TableField("name") + private String name; + + @TableField("sort_order") + private Integer sortOrder; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CampaignMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CampaignMapper.java new file mode 100644 index 00000000..1efd3420 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CampaignMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CampaignDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface CampaignMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponMapper.java new file mode 100644 index 00000000..b3ea649b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 优惠券Mapper + */ +@Mapper +public interface CouponMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponTagMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponTagMapper.java new file mode 100644 index 00000000..abc4a2d9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/CouponTagMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponTagDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 优惠券标签关联Mapper + */ +@Mapper +public interface CouponTagMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/ProductLikeMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/ProductLikeMapper.java new file mode 100644 index 00000000..dd8b1220 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/ProductLikeMapper.java @@ -0,0 +1,24 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.ProductLikeDO; +import org.apache.ibatis.annotations.Param; + +/** + * 商品点赞记录表 Mapper + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +public interface ProductLikeMapper extends BaseMapper { + + /** + * 检查用户是否已点赞商品 + * + * @param userId 用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + boolean isProductLiked(@Param("userId") Long userId, @Param("productId") Long productId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/UserCouponMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/UserCouponMapper.java new file mode 100644 index 00000000..e5d84ae5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/UserCouponMapper.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.UserCouponDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 用户优惠券Mapper + */ +@Mapper +public interface UserCouponMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipBenefitMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipBenefitMapper.java new file mode 100644 index 00000000..56c61275 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipBenefitMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipBenefitDO; + +/** + * VIP权益信息表 Mapper + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipBenefitMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipInfoMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipInfoMapper.java new file mode 100644 index 00000000..0d0702c1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipInfoMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipInfoDO; + +/** + * 用户VIP信息表 Mapper + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipInfoMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipRechargePlanMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipRechargePlanMapper.java new file mode 100644 index 00000000..195b2581 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/VipRechargePlanMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipRechargePlanDO; + +/** + * VipRechargePlanMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface VipRechargePlanMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistGroupMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistGroupMapper.java new file mode 100644 index 00000000..3fcce27f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistGroupMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistGroupDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WishlistGroupMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistMapper.java new file mode 100644 index 00000000..518fee50 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/mapper/WishlistMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * WishlistMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface WishlistMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CampaignService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CampaignService.java new file mode 100644 index 00000000..a7a5179b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CampaignService.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CampaignDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CampaignVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; + +public interface CampaignService { + CampaignVO saveCampaign(CampaignDTO dto); + + PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CouponService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CouponService.java new file mode 100644 index 00000000..95846941 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/CouponService.java @@ -0,0 +1,114 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CouponVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO; + +import java.util.List; + +/** + * 优惠券服务 + */ +public interface CouponService extends IService { + + /** + * 创建优惠券 + * @param couponDTO 优惠券DTO + * @param shopId 店铺ID + * @return 优惠券ID + */ + Long createCoupon(CouponDTO couponDTO, Long shopId); + + /** + * 更新优惠券 + * @param id 优惠券ID + * @param couponDTO 优惠券DTO + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId); + + /** + * 删除优惠券 + * @param id 优惠券ID + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean deleteCoupon(Long id, Long shopId); + + /** + * 获取优惠券详情 + * @param id 优惠券ID + * @return 优惠券VO + */ + CouponVO getCouponById(Long id); + + /** + * 获取优惠券列表 + * @param page 页码 + * @param size 每页大小 + * @param shopId 店铺ID + * @return 分页结果 + */ + PageResultVO listCoupons(Integer page, Integer size, Long shopId); + + /** + * 获取所有优惠券 + * @return 优惠券列表 + */ + List listAllCoupons(); + + /** + * 为用户分配优惠券 + * @param userId 用户ID + * @param couponId 优惠券ID + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean assignCouponToUser(Long userId, Long couponId, Long shopId); + + /** + * 获取用户优惠券列表 + * @param userId 用户ID + * @param status 状态 + * @return 用户优惠券列表 + */ + List listUserCoupons(Long userId, Integer status); + + /** + * 使用优惠券 + * @param userCouponId 用户优惠券ID + * @param userId 用户ID + * @return 是否成功 + */ + boolean useCoupon(Long userCouponId, Long userId); + + /** + * 获取商品可用的优惠券 + * @param userId 用户ID + * @param productTags 商品标签 + * @param productPrice 商品价格 + * @return 可用优惠券列表 + */ + List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId); + + /** + * 为新店铺初始化默认 VIP 自动券模板 + * + * @param shopId 店铺ID + */ + void initializeDefaultVipAutoCoupons(Long shopId); + + /** + * 发放优惠券 + * @param couponId 优惠券ID + * @param userIds 用户ID列表 + * @param quantity 发放数量 + * @param shopId 店铺ID + * @return 是否成功 + */ + boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/GrowthService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/GrowthService.java new file mode 100644 index 00000000..5bf9e889 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/GrowthService.java @@ -0,0 +1,7 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.GrowthSummaryVO; + +public interface GrowthService { + GrowthSummaryVO getSummary(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/ProductLikeService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/ProductLikeService.java new file mode 100644 index 00000000..a7a0f4d8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/ProductLikeService.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.ProductLikeDO; + +/** + * 商品点赞记录表 Service + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +public interface ProductLikeService extends IService { + + /** + * 添加点赞记录 + * + * @param userId 用户ID + * @param productId 商品ID + */ + void addLike(Long userId, Long productId); + + /** + * 取消点赞 + * + * @param userId 用户ID + * @param productId 商品ID + */ + void removeLike(Long userId, Long productId); + + /** + * 检查用户是否已点赞商品 + * + * @param userId 用户ID + * @param productId 商品ID + * @return 是否已点赞 + */ + boolean isProductLiked(Long userId, Long productId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipBenefitService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipBenefitService.java new file mode 100644 index 00000000..0b195a0e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipBenefitService.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipBenefitVO; + +import java.util.List; + +/** + * VIP权益信息表 Service + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipBenefitService extends IService { + + /** + * 创建VIP权益 + * + * @param vipBenefitDTO VIP权益DTO + * @return VIP权益ID + */ + Long createVipBenefit(VipBenefitDTO vipBenefitDTO); + + /** + * 更新VIP权益 + * + * @param id VIP权益ID + * @param vipBenefitDTO VIP权益DTO + * @return 是否更新成功 + */ + boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO); + + /** + * 删除VIP权益 + * + * @param id VIP权益ID + * @return 是否删除成功 + */ + boolean deleteVipBenefit(Long id); + + /** + * 根据ID查询VIP权益 + * + * @param id VIP权益ID + * @return VIP权益VO + */ + VipBenefitVO getVipBenefitById(Long id); + + /** + * 查询所有VIP权益 + * + * @return VIP权益VO列表 + */ + List listAllVipBenefits(); + + /** + * 根据所需VIP等级查询VIP权益 + * + * @param requiredVipLevel 所需VIP等级 + * @return VIP权益VO列表 + */ + List listVipBenefitsByRequiredVipLevel(String requiredVipLevel); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipInfoService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipInfoService.java new file mode 100644 index 00000000..63fc5ed3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipInfoService.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipInfoVO; + +import java.util.List; + +/** + * 用户VIP信息表 Service + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface VipInfoService extends IService { + + /** + * 创建VIP信息 + * + * @param vipInfoDTO VIP信息DTO + * @return VIP信息ID + */ + Long createVipInfo(VipInfoDTO vipInfoDTO); + + /** + * 更新VIP信息 + * + * @param id VIP信息ID + * @param vipInfoDTO VIP信息DTO + * @return 是否更新成功 + */ + boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO); + + /** + * 删除VIP信息 + * + * @param id VIP信息ID + * @return 是否删除成功 + */ + boolean deleteVipInfo(Long id); + + /** + * 根据ID查询VIP信息 + * + * @param id VIP信息ID + * @return VIP信息VO + */ + VipInfoVO getVipInfoById(Long id); + + /** + * 查询所有VIP信息 + * + * @return VIP信息VO列表 + */ + List listAllVipInfos(); + + /** + * 根据VIP等级查询VIP信息 + * + * @param vipLevel VIP等级 + * @return VIP信息VO列表 + */ + List listVipInfosByVipLevel(String vipLevel); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipRechargePlanService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipRechargePlanService.java new file mode 100644 index 00000000..499d108b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/VipRechargePlanService.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipRechargePlanVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * VipRechargePlanService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface VipRechargePlanService extends IService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createPlan(UserDO currentUser, VipRechargePlanDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto); + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer status); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminPlans(UserDO currentUser, Long shopId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPlans(Long userId); + + List listVipLevelOptions(UserDO currentUser, Long shopId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/WishlistService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/WishlistService.java new file mode 100644 index 00000000..d56154a6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/WishlistService.java @@ -0,0 +1,61 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistInspirationVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * WishlistService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface WishlistService extends IService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void addToWishlist(Long userId, Long productId); + void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void removeFromWishlist(Long userId, Long productId); + /** + * Run business method `isInWishlist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean isInWishlist(Long userId, Long productId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getWishlistByUserId(Long userId); + + List listGroups(Long userId); + + Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO); + + boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO); + + boolean deleteGroup(Long userId, Long groupId); + + boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO); + + WishlistInspirationVO getInspiration(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CampaignServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CampaignServiceImpl.java new file mode 100644 index 00000000..1421ede5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CampaignServiceImpl.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CampaignDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CampaignDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CampaignMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CampaignService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CampaignVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +public class CampaignServiceImpl implements CampaignService { + + private final CampaignMapper campaignMapper; + + @Override + @Transactional + public CampaignVO saveCampaign(CampaignDTO dto) { + if (dto == null || dto.getTitle() == null || dto.getTitle().isBlank()) { + throw new RuntimeException("活动标题不能为空"); + } + CampaignDO campaign = new CampaignDO(); + BeanUtils.copyProperties(dto, campaign); + campaign.setStatus(dto.getStatus() == null ? 1 : dto.getStatus()); + campaign.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + campaign.setIsDelete(0); + campaignMapper.insert(campaign); + return toVO(campaign); + } + + @Override + public PageResultVO listCampaigns(Long shopId, Integer status, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(CampaignDO::getIsDelete, 0) + .orderByAsc(CampaignDO::getSortOrder) + .orderByDesc(CampaignDO::getCreateTime); + if (shopId != null) { + wrapper.eq(CampaignDO::getShopId, shopId); + } + if (status != null) { + wrapper.eq(CampaignDO::getStatus, status); + } + Page result = campaignMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + vo.setList(result.getRecords().stream().map(this::toVO).toList()); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private CampaignVO toVO(CampaignDO campaign) { + CampaignVO vo = new CampaignVO(); + BeanUtils.copyProperties(campaign, vo); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CouponServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CouponServiceImpl.java new file mode 100644 index 00000000..0e638a54 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/CouponServiceImpl.java @@ -0,0 +1,1234 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.CouponDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponTagDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.UserCouponDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponTagMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.CouponVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +/** + * 优惠券服务实现 + */ +@Service +@RequiredArgsConstructor +public class CouponServiceImpl extends ServiceImpl implements CouponService { + + /** + * Purpose: COUPON_SOURCE_USER supports CouponServiceImpl.java by holding or executing the coupon source user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_USER = "USER_COUPON"; + /** + * Purpose: COUPON_SOURCE_SYSTEM_VIP supports CouponServiceImpl.java by holding or executing the coupon source system vip business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; + /** + * Purpose: COUPON_SCENE_VIP_AUTO supports CouponServiceImpl.java by holding or executing the coupon scene vip auto business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SCENE_VIP_AUTO = "VIP_AUTO"; + /** + * Purpose: DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT supports CouponServiceImpl.java by holding or executing the default vip auto coupon total count business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT = 999999; + private static final LocalDateTime DEFAULT_VIP_AUTO_COUPON_END_TIME = LocalDateTime.of(2099, 12, 31, 23, 59, 59); + private static final List DEFAULT_SHOP_VIP_AUTO_COUPONS = List.of( + new VipAutoCouponTemplate("BRONZE_95", "青铜VIP自动95折券", "青铜", BigDecimal.valueOf(9.5)), + new VipAutoCouponTemplate("SILVER_92", "白银VIP自动92折券", "白银", BigDecimal.valueOf(9.2)), + new VipAutoCouponTemplate("GOLD_90", "黄金VIP自动90折券", "黄金", BigDecimal.valueOf(9.0)) + ); + /** + * Purpose: VIP_LEVEL_NORMAL supports CouponServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Variable `couponTagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponTagMapper couponTagMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserCouponMapper userCouponMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + @Transactional + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createCoupon(CouponDTO couponDTO, Long shopId) { + // 创建优惠券 + CouponDO couponDO = new CouponDO(); + couponDO.setCouponCode(resolveCouponCodeForCreate(couponDTO.getCouponCode())); + couponDO.setCouponName(couponDTO.getCouponName()); + couponDO.setCouponType(couponDTO.getCouponType()); + couponDO.setDiscountValue(couponDTO.getDiscountValue()); + couponDO.setMinAmount(couponDTO.getMinAmount()); + couponDO.setReduceAmount(couponDTO.getReduceAmount()); + couponDO.setTotalCount(couponDTO.getTotalCount()); + couponDO.setUsedCount(0); + couponDO.setStartTime(couponDTO.getStartTime()); + couponDO.setEndTime(couponDTO.getEndTime()); + couponDO.setStatus(1); + couponDO.setShopId(shopId); + couponDO.setCouponScene(couponDTO.getCouponScene()); + couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); + couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(couponDO); + + // 处理标签关联 + handleCouponTags(couponDO.getId(), couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); + + return couponDO.getId(); + } + + @Override + @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId) { + // 更新优惠券 + CouponDO couponDO = getById(id); + if (couponDO == null) { + return false; + } + + couponDO.setCouponCode(resolveCouponCodeForUpdate(couponDO.getCouponCode(), couponDTO.getCouponCode())); + couponDO.setCouponName(couponDTO.getCouponName()); + couponDO.setCouponType(couponDTO.getCouponType()); + couponDO.setDiscountValue(couponDTO.getDiscountValue()); + couponDO.setMinAmount(couponDTO.getMinAmount()); + couponDO.setReduceAmount(couponDTO.getReduceAmount()); + couponDO.setTotalCount(couponDTO.getTotalCount()); + couponDO.setStartTime(couponDTO.getStartTime()); + couponDO.setEndTime(couponDTO.getEndTime()); + couponDO.setShopId(shopId); + couponDO.setCouponScene(couponDTO.getCouponScene()); + couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); + couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(id); + + // 处理标签关联 + handleCouponTags(id, couponDTO.getAvailableTagIds(), couponDTO.getUnavailableTagIds()); + + return true; + } + + @Override + @Transactional + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteCoupon(Long id, Long shopId) { + // 删除优惠券 + CouponDO couponDO = getById(id); + if (couponDO == null) { + return false; + } + couponDO.setIsDelete(1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return updateById(couponDO); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CouponVO result consumed by the caller or returned to the frontend + */ + public CouponVO getCouponById(Long id) { + CouponDO couponDO = getById(id); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return null; + } + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToCouponVO(couponDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO listCoupons(Integer page, Integer size, Long shopId) { + Page pageInfo = new Page<>(page, size); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .orderByDesc(CouponDO::getCreateTime); + if (shopId != null) { + wrapper.eq(CouponDO::getShopId, shopId); + } + IPage couponPage = page(pageInfo, wrapper); + + List couponVOs = couponPage.getRecords().stream() + .map(this::convertToCouponVO) + .collect(Collectors.toList()); + + PageResultVO pageResult = new PageResultVO<>(); + pageResult.setList(couponVOs); + pageResult.setTotal(couponPage.getTotal()); + pageResult.setPage(page); + pageResult.setSize(size); + + return pageResult; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllCoupons() { + List couponDOs = list(new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .orderByDesc(CouponDO::getCreateTime) + ); + return couponDOs.stream() + .map(this::convertToCouponVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional + /** + * Run business method `assignCouponToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean assignCouponToUser(Long userId, Long couponId, Long shopId) { + // 检查优惠券是否存在 + CouponDO couponDO = getById(couponId); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return false; + } + + // 检查优惠券是否可用 + if (couponDO.getStatus() != 1) { + return false; + } + if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { + return false; + } + if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); + } + if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { + return false; + } + + // 检查是否已经分配 + UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getCouponId, couponId) + .eq(UserCouponDO::getIsDelete, 0) + ); + if (existing != null) { + return false; + } + if (!hasRemainingDistributionStock(couponDO, 1)) { + return false; + } + + // 分配优惠券 + UserCouponDO userCouponDO = new UserCouponDO(); + userCouponDO.setUserId(userId); + userCouponDO.setCouponId(couponId); + userCouponDO.setStatus(1); + userCouponDO.setObtainTime(LocalDateTime.now()); + userCouponMapper.insert(userCouponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(couponId); + + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listUserCoupons(Long userId, Integer status) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getIsDelete, 0); + + if (status != null) { + queryWrapper.eq(UserCouponDO::getStatus, status); + } + + List userCouponDOs = userCouponMapper.selectList(queryWrapper); + return userCouponDOs.stream() + .map(userCouponDO -> { + CouponDO couponDO = getById(userCouponDO.getCouponId()); + return couponDO == null ? null : convertToUserCouponVO(userCouponDO, couponDO); + }) + .filter(java.util.Objects::nonNull) + .collect(Collectors.toList()); + } + + @Override + @Transactional + /** + * Run business method `useCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean useCoupon(Long userCouponId, Long userId) { + // 检查用户优惠券是否存在 + UserCouponDO userCouponDO = userCouponMapper.selectById(userCouponId); + if (userCouponDO == null || userCouponDO.getIsDelete() == 1) { + return false; + } + + // 检查是否属于当前用户 + if (!userCouponDO.getUserId().equals(userId)) { + return false; + } + + // 检查是否未使用 + if (userCouponDO.getStatus() != 1) { + return false; + } + + // 检查优惠券是否过期 + CouponDO couponDO = getById(userCouponDO.getCouponId()); + if (couponDO == null || couponDO.getEndTime().isBefore(LocalDateTime.now())) { + return false; + } + + // 使用优惠券 + userCouponDO.setStatus(2); + userCouponDO.setUseTime(LocalDateTime.now()); + userCouponMapper.updateById(userCouponDO); + + // 更新优惠券使用数量 + incrementCouponUsedCount(couponDO.getId()); + + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param productPrice parameter `productPrice` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId) { + BigDecimal orderAmount = productPrice == null ? BigDecimal.ZERO : BigDecimal.valueOf(productPrice); + LocalDateTime now = LocalDateTime.now(); + List availableCoupons = new ArrayList<>(); + + List userCouponDOs = userCouponMapper.selectList(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getStatus, 1) + .eq(UserCouponDO::getIsDelete, 0) + ); + + for (UserCouponDO userCouponDO : userCouponDOs) { + CouponDO couponDO = getById(userCouponDO.getCouponId()); + if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { + continue; + } + availableCoupons.add(convertToUserCouponVO(userCouponDO, couponDO)); + } + + UserDO userDO = userMapper.selectById(userId); + String currentVipLevel = userDO != null ? userDO.getLevel() : null; + if (currentVipLevel != null && !currentVipLevel.isBlank() && !VIP_LEVEL_NORMAL.equals(currentVipLevel)) { + List vipCoupons = listVipAutoCouponsByShop(currentVipLevel, shopId); + + for (CouponDO couponDO : vipCoupons) { + if (!isCouponApplicable(couponDO, now, orderAmount, productTags, shopId)) { + continue; + } + availableCoupons.add(convertToSystemVipCouponVO(couponDO)); + } + } + + availableCoupons.sort(Comparator + .comparing((UserCouponVO item) -> calculateDiscountAmount(item, orderAmount)).reversed() + .thenComparing(UserCouponVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))); + return availableCoupons; + } + + @Override + @Transactional + /** + * Run business method `initializeDefaultVipAutoCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + */ + public void initializeDefaultVipAutoCoupons(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + + LocalDateTime startTime = LocalDateTime.now(); + for (VipAutoCouponTemplate template : DEFAULT_SHOP_VIP_AUTO_COUPONS) { + String couponCode = buildShopVipAutoCouponCode(shopId, template.codeSuffix()); + CouponDO existingCoupon = lambdaQuery() + .eq(CouponDO::getCouponCode, couponCode) + .one(); + if (existingCoupon != null) { + continue; + } + + CouponDO couponDO = new CouponDO(); + couponDO.setCouponCode(couponCode); + couponDO.setCouponName(template.couponName()); + couponDO.setCouponType(1); + couponDO.setDiscountValue(template.discountValue()); + couponDO.setMinAmount(BigDecimal.ZERO); + couponDO.setReduceAmount(BigDecimal.ZERO); + couponDO.setTotalCount(DEFAULT_VIP_AUTO_COUPON_TOTAL_COUNT); + couponDO.setUsedCount(0); + couponDO.setStartTime(startTime); + couponDO.setEndTime(DEFAULT_VIP_AUTO_COUPON_END_TIME); + couponDO.setStatus(1); + couponDO.setShopId(shopId); + couponDO.setCouponScene(COUPON_SCENE_VIP_AUTO); + couponDO.setRequiredVipLevel(template.requiredVipLevel()); + couponDO.setAutoMatch(1); + couponDO.setIsDelete(0); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(couponDO); + } + } + + @Override + @Transactional + /** + * Run business method `distributeCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param quantity parameter `quantity` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId) { + // 检查优惠券是否存在 + CouponDO couponDO = getById(couponId); + if (couponDO == null || couponDO.getIsDelete() == 1) { + return false; + } + + // 检查优惠券是否可用 + if (couponDO.getStatus() != 1) { + return false; + } + if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); + } + + // 检查优惠券数量是否足够 + if (shopId != null && couponDO.getShopId() != null && !shopId.equals(couponDO.getShopId())) { + return false; + } + if (userIds == null || userIds.isEmpty() || quantity == null || quantity < 1) { + return false; + } + if (quantity > 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张"); + } + List targetUserIds = userIds.stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (targetUserIds.isEmpty()) { + return false; + } + + for (Long userId : targetUserIds) { + if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { + return false; + } + UserCouponDO existing = userCouponMapper.selectOne(new LambdaQueryWrapper() + .eq(UserCouponDO::getUserId, userId) + .eq(UserCouponDO::getCouponId, couponId) + .eq(UserCouponDO::getIsDelete, 0)); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户已持有该优惠券,不能重复发放"); + } + } + + int totalNeeded = targetUserIds.size() * quantity; + if (!hasRemainingDistributionStock(couponDO, totalNeeded)) { + return false; + } + + // 发放优惠券 + LocalDateTime obtainTime = LocalDateTime.now(); + for (Long userId : targetUserIds) { + UserCouponDO userCouponDO = new UserCouponDO(); + userCouponDO.setUserId(userId); + userCouponDO.setCouponId(couponId); + userCouponDO.setStatus(1); + userCouponDO.setObtainTime(obtainTime); + userCouponMapper.insert(userCouponDO); + } + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + refreshCouponDistributionStatus(couponId); + + return true; + } + + /** + * 处理优惠券标签关联 + */ + private void handleCouponTags(Long couponId, List availableTagIds, List unavailableTagIds) { + // 先查询所有现有的标签关联 + List existingTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponId) + .eq(CouponTagDO::getIsDelete, 0) + ); + + // 构建现有标签的映射,方便快速查找 + java.util.Map existingTagMap = new java.util.HashMap<>(); + for (CouponTagDO tag : existingTags) { + existingTagMap.put(tag.getTagId(), tag); + } + + // 处理可用标签 + if (availableTagIds != null) { + for (Long tagId : availableTagIds) { + if (existingTagMap.containsKey(tagId)) { + // 如果标签已存在,更新其状态 + CouponTagDO existingTag = existingTagMap.get(tagId); + if (existingTag.getIsAvailable() != 1) { + existingTag.setIsAvailable(1); + couponTagMapper.updateById(existingTag); + } + existingTagMap.remove(tagId); // 标记为已处理 + } else { + // 如果标签不存在,创建新的 + CouponTagDO couponTagDO = new CouponTagDO(); + couponTagDO.setCouponId(couponId); + couponTagDO.setTagId(tagId); + couponTagDO.setIsAvailable(1); + couponTagMapper.insert(couponTagDO); + } + } + } + + // 处理不可用标签 + if (unavailableTagIds != null) { + for (Long tagId : unavailableTagIds) { + if (existingTagMap.containsKey(tagId)) { + // 如果标签已存在,更新其状态 + CouponTagDO existingTag = existingTagMap.get(tagId); + if (existingTag.getIsAvailable() != 0) { + existingTag.setIsAvailable(0); + couponTagMapper.updateById(existingTag); + } + existingTagMap.remove(tagId); // 标记为已处理 + } else { + // 如果标签不存在,创建新的 + CouponTagDO couponTagDO = new CouponTagDO(); + couponTagDO.setCouponId(couponId); + couponTagDO.setTagId(tagId); + couponTagDO.setIsAvailable(0); + couponTagMapper.insert(couponTagDO); + } + } + } + + // 删除剩余的标签关联(这些是不在新列表中的标签) + for (CouponTagDO tagToDelete : existingTagMap.values()) { + couponTagMapper.deleteById(tagToDelete.getId()); + } + } + + /** + * 检查标签是否匹配 + */ + private boolean checkTagMatch(Long couponId, String productTags) { + if (productTags == null || productTags.isEmpty()) { + return true; + } + + // 解析商品标签 + String[] tagNames = productTags.split(","); + + // 查询所有标签 + List allTags = tagMapper.selectList(new LambdaQueryWrapper<>()); + + // 找到匹配的标签ID + List productTagIds = allTags.stream() + .filter(tag -> { + for (String tagName : tagNames) { + if (tag.getTagName() != null && tag.getTagName().equals(tagName.trim())) { + return true; + } + } + return false; + }) + .map(tag -> tag.getId()) + .collect(Collectors.toList()); + + if (productTagIds.isEmpty()) { + return true; + } + + // 查询优惠券的所有标签关联 + List couponTagDOs = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponId) + ); + + // 分离可用标签和不可用标签 + List availableTagIds = couponTagDOs.stream() + .filter(tag -> tag.getIsAvailable() == 1) + .map(tag -> tag.getTagId()) + .collect(Collectors.toList()); + + List unavailableTagIds = couponTagDOs.stream() + .filter(tag -> tag.getIsAvailable() == 0) + .map(tag -> tag.getTagId()) + .collect(Collectors.toList()); + + // 检查是否有不可用标签 + for (Long tagId : productTagIds) { + if (unavailableTagIds.contains(tagId)) { + return false; + } + } + + // 检查是否只包含可用标签(如果有可用标签配置) + if (!availableTagIds.isEmpty()) { + for (Long tagId : productTagIds) { + if (!availableTagIds.contains(tagId)) { + return false; + } + } + } + + return true; + } + + /** + * 转换为CouponVO + */ + private List listVipAutoCouponsByShop(String requiredVipLevel, Long shopId) { + if (shopId != null && shopId > 0) { + List shopCoupons = list(buildVipAutoCouponQuery(requiredVipLevel) + .eq(CouponDO::getShopId, shopId)); + if (!shopCoupons.isEmpty()) { + return shopCoupons; + } + return list(buildVipAutoCouponQuery(requiredVipLevel) + .isNull(CouponDO::getShopId)); + } + return list(buildVipAutoCouponQuery(requiredVipLevel)); + } + + /** + * Run business method `buildVipAutoCouponQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private LambdaQueryWrapper buildVipAutoCouponQuery(String requiredVipLevel) { + return new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0) + .eq(CouponDO::getStatus, 1) + .eq(CouponDO::getAutoMatch, 1) + .eq(CouponDO::getCouponScene, COUPON_SCENE_VIP_AUTO) + .eq(CouponDO::getRequiredVipLevel, requiredVipLevel) + .orderByDesc(CouponDO::getDiscountValue) + .orderByAsc(CouponDO::getEndTime); + } + + /** + * Run business method `buildShopVipAutoCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param codeSuffix parameter `codeSuffix` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildShopVipAutoCouponCode(Long shopId, String codeSuffix) { + return String.format("VIP_AUTO_SHOP_%d_%s", shopId, codeSuffix); + } + + /** + * Run business method `resolveCouponCodeForCreate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCouponCodeForCreate(String requestedCode) { + if (StringUtils.hasText(requestedCode)) { + return requestedCode.trim(); + } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ + return generateUniqueManualCouponCode(); + } + + /** + * Run business method `resolveCouponCodeForUpdate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param existingCode parameter `existingCode` supplied by the caller + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCouponCodeForUpdate(String existingCode, String requestedCode) { + if (StringUtils.hasText(requestedCode)) { + return requestedCode.trim(); + } + if (StringUtils.hasText(existingCode)) { + return existingCode.trim(); + } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ + return generateUniqueManualCouponCode(); + } + + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String generateUniqueManualCouponCode() { + for (int attempt = 0; attempt < 10; attempt++) { + String candidate = "CPN_" + snowflakeIdGenerator.nextBase36String(13); + if (lambdaQuery().eq(CouponDO::getCouponCode, candidate).count() == 0) { + return candidate; + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("生成优惠券编码失败,请稍后重试"); + } + + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private CouponVO result consumed by the caller or returned to the frontend + */ + private CouponVO convertToCouponVO(CouponDO couponDO) { + CouponVO couponVO = new CouponVO(); + couponVO.setId(couponDO.getId()); + couponVO.setCouponCode(couponDO.getCouponCode()); + couponVO.setCouponName(couponDO.getCouponName()); + couponVO.setCouponType(couponDO.getCouponType()); + couponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); + couponVO.setDiscountValue(couponDO.getDiscountValue()); + couponVO.setMinAmount(couponDO.getMinAmount()); + couponVO.setReduceAmount(couponDO.getReduceAmount()); + couponVO.setTotalCount(couponDO.getTotalCount()); + couponVO.setUsedCount(normalizeCount(couponDO.getUsedCount())); + couponVO.setRemainingCount(calculateRemainingDistributionCount(couponDO)); + couponVO.setStartTime(couponDO.getStartTime()); + couponVO.setEndTime(couponDO.getEndTime()); + couponVO.setStatus(couponDO.getStatus()); + couponVO.setShopId(couponDO.getShopId()); + couponVO.setCouponScene(couponDO.getCouponScene()); + couponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); + couponVO.setAutoMatch(couponDO.getAutoMatch()); + + // 获取店铺名称 + if (couponDO.getShopId() != null) { + com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO shopDO = shopMapper.selectById(couponDO.getShopId()); + if (shopDO != null) { + couponVO.setShopName(shopDO.getShopName()); + } + } + + switch (couponDO.getStatus()) { + case 1: + couponVO.setStatusName("可用"); + break; + case 2: + couponVO.setStatusName("已过期"); + break; + case 3: + couponVO.setStatusName("已用完"); + break; + default: + couponVO.setStatusName("未知"); + } + + // 获取可用标签 + List availableTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponDO.getId()) + .eq(CouponTagDO::getIsAvailable, 1) + ).stream() + .map(couponTag -> { + TagVO tagVO = new TagVO(); + tagVO.setId(couponTag.getTagId()); + return tagVO; + }) + .collect(Collectors.toList()); + couponVO.setAvailableTags(availableTags); + + // 获取不可用标签 + List unavailableTags = couponTagMapper.selectList(new LambdaQueryWrapper() + .eq(CouponTagDO::getCouponId, couponDO.getId()) + .eq(CouponTagDO::getIsAvailable, 0) + ).stream() + .map(couponTag -> { + TagVO tagVO = new TagVO(); + tagVO.setId(couponTag.getTagId()); + return tagVO; + }) + .collect(Collectors.toList()); + couponVO.setUnavailableTags(unavailableTags); + + return couponVO; + } + + /** + * 转换为UserCouponVO + */ + private UserCouponVO convertToUserCouponVO(UserCouponDO userCouponDO, CouponDO couponDO) { + UserCouponVO userCouponVO = buildCouponOption(userCouponDO.getId(), couponDO, COUPON_SOURCE_USER, false); + userCouponVO.setStatus(userCouponDO.getStatus()); + switch (userCouponDO.getStatus()) { + case 1: + userCouponVO.setStatusName("未使用"); + break; + case 2: + userCouponVO.setStatusName("已使用"); + break; + case 3: + userCouponVO.setStatusName("已过期"); + break; + default: + userCouponVO.setStatusName("未知"); + } + userCouponVO.setObtainTime(userCouponDO.getObtainTime()); + userCouponVO.setUseTime(userCouponDO.getUseTime()); + return userCouponVO; + } + + /** + * Run business method `convertToSystemVipCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ + private UserCouponVO convertToSystemVipCouponVO(CouponDO couponDO) { + UserCouponVO userCouponVO = buildCouponOption(couponDO.getId(), couponDO, COUPON_SOURCE_SYSTEM_VIP, true); + userCouponVO.setStatus(1); + userCouponVO.setStatusName("系统自动匹配"); + return userCouponVO; + } + + /** + * Run business method `buildCouponOption`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param optionId parameter `optionId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param autoMatched parameter `autoMatched` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ + private UserCouponVO buildCouponOption(Long optionId, CouponDO couponDO, String sourceType, boolean autoMatched) { + UserCouponVO userCouponVO = new UserCouponVO(); + userCouponVO.setId(optionId); + userCouponVO.setCouponId(couponDO.getId()); + userCouponVO.setCouponName(couponDO.getCouponName()); + userCouponVO.setCouponType(couponDO.getCouponType()); + userCouponVO.setCouponTypeName(couponDO.getCouponType() == 1 ? "折扣券" : "满减券"); + userCouponVO.setDiscountValue(couponDO.getDiscountValue() != null ? couponDO.getDiscountValue().toString() : ""); + userCouponVO.setMinAmount(couponDO.getMinAmount() != null ? couponDO.getMinAmount().toString() : ""); + userCouponVO.setReduceAmount(couponDO.getReduceAmount() != null ? couponDO.getReduceAmount().toString() : ""); + userCouponVO.setStartTime(couponDO.getStartTime()); + userCouponVO.setEndTime(couponDO.getEndTime()); + userCouponVO.setSourceType(sourceType); + userCouponVO.setRequiredVipLevel(couponDO.getRequiredVipLevel()); + userCouponVO.setAutoMatched(autoMatched); + return userCouponVO; + } + + /** + * Run business method `isCouponApplicable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param now parameter `now` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isCouponApplicable(CouponDO couponDO, LocalDateTime now, BigDecimal orderAmount, String productTags, Long shopId) { + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return false; + } + if (couponDO.getStatus() == null || couponDO.getStatus() != 1) { + return false; + } + if (couponDO.getStartTime() != null && now.isBefore(couponDO.getStartTime())) { + return false; + } + if (couponDO.getEndTime() != null && now.isAfter(couponDO.getEndTime())) { + return false; + } + if (!matchesShop(couponDO, shopId)) { + return false; + } + if (couponDO.getCouponType() == 2 + && couponDO.getMinAmount() != null + && couponDO.getMinAmount().compareTo(orderAmount) > 0) { + return false; + } + return checkTagMatch(couponDO.getId(), productTags); + } + + /** + * Run business method `matchesShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean matchesShop(CouponDO couponDO, Long shopId) { + if (shopId == null || couponDO.getShopId() == null) { + return true; + } + return shopId.equals(couponDO.getShopId()); + } + + /** + * Run business method `isVipAutoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVipAutoCoupon(CouponDO couponDO) { + return couponDO != null + && Integer.valueOf(1).equals(couponDO.getAutoMatch()) + && COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene()); + } + + /** + * Run business method `hasRemainingDistributionStock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param requiredCount parameter `requiredCount` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) { + return calculateRemainingDistributionCount(couponDO) >= requiredCount; + } + + /** + * Run business method `calculateRemainingDistributionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int calculateRemainingDistributionCount(CouponDO couponDO) { + if (couponDO == null || couponDO.getId() == null) { + return 0; + } + int totalCount = normalizeCount(couponDO.getTotalCount()); + long issuedCount = userCouponMapper.selectCount(new LambdaQueryWrapper() + .eq(UserCouponDO::getCouponId, couponDO.getId()) + .eq(UserCouponDO::getIsDelete, 0)); + return Math.max(0, totalCount - (int) issuedCount); + } + + /** + * Run business method `incrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void incrementCouponUsedCount(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null) { + return; + } + couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + + /** + * Run business method `decrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void decrementCouponUsedCount(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null) { + return; + } + couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1)); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + + /** + * Run business method `isUserEligibleForCouponDistribution`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) { + if (userId == null) { + return false; + } + + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (requestedShopId != null && !userShopBindingSupport.isUserAccessibleInShop(userId, requestedShopId)) { + return false; + } + if (couponDO != null && couponDO.getShopId() != null + && !userShopBindingSupport.isUserAccessibleInShop(userId, couponDO.getShopId())) { + return false; + } + return true; + } + + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void refreshCouponDistributionStatus(Long couponId) { + CouponDO couponDO = getById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return; + } + if (Integer.valueOf(2).equals(couponDO.getStatus())) { + return; + } + + int remainingCount = calculateRemainingDistributionCount(couponDO); + int targetStatus = remainingCount > 0 ? 1 : 3; + if (!Objects.equals(couponDO.getStatus(), targetStatus)) { + couponDO.setStatus(targetStatus); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateById(couponDO); + } + } + + /** + * Run business method `normalizeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizeCount(Integer count) { + return count == null ? 0 : count; + } + + /** + * Run business method `calculateDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponVO parameter `couponVO` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) { + if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + if (couponVO.getCouponType() == 1 && couponVO.getDiscountValue() != null && !couponVO.getDiscountValue().isBlank()) { + BigDecimal discountValue = new BigDecimal(couponVO.getDiscountValue()); + BigDecimal actualAmount = orderAmount.multiply(discountValue) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + return orderAmount.subtract(actualAmount); + } + if (couponVO.getCouponType() == 2 && couponVO.getReduceAmount() != null && !couponVO.getReduceAmount().isBlank()) { + return new BigDecimal(couponVO.getReduceAmount()); + } + return BigDecimal.ZERO; + } + + /** + * Purpose: VipAutoCouponTemplate supports CouponServiceImpl.java by holding or executing the vip auto coupon template business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + private record VipAutoCouponTemplate( + String codeSuffix, + String couponName, + String requiredVipLevel, + BigDecimal discountValue + ) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/GrowthServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/GrowthServiceImpl.java new file mode 100644 index 00000000..3fecccc0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/GrowthServiceImpl.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserGrowthRecordDO; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserGrowthRecordMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.GrowthService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.GrowthSummaryVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class GrowthServiceImpl implements GrowthService { + + private final UserGrowthRecordMapper userGrowthRecordMapper; + + @Override + public GrowthSummaryVO getSummary(Long userId) { + Integer growthValue = userGrowthRecordMapper.selectList(new LambdaQueryWrapper() + .eq(UserGrowthRecordDO::getUserId, userId)) + .stream() + .map(UserGrowthRecordDO::getGrowthValue) + .filter(value -> value != null) + .reduce(0, Integer::sum); + GrowthSummaryVO vo = new GrowthSummaryVO(); + vo.setUserId(userId); + vo.setGrowthValue(growthValue); + vo.setLevelName(growthValue >= 1000 ? "黄金会员" : growthValue >= 300 ? "白银会员" : "成长新客"); + vo.setAppointmentCount(0); + vo.setReviewCount(0); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/ProductLikeServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/ProductLikeServiceImpl.java new file mode 100644 index 00000000..5e91b61b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/ProductLikeServiceImpl.java @@ -0,0 +1,105 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.ProductLikeDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.ProductLikeMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.ProductLikeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 商品点赞记录表 Service 实现 + * 对应数据库表 t_product_like + * + * @author xiaowang + * @date 2026-03-05 + */ +@Service +public class ProductLikeServiceImpl extends ServiceImpl implements ProductLikeService { + + @Autowired + /** + * Purpose: productMapper supports ProductLikeServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Override + @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void addLike(Long userId, Long productId) { + // 检查是否已点赞 + if (isProductLiked(userId, productId)) { + return; + } + + // 添加点赞记录 + ProductLikeDO productLikeDO = new ProductLikeDO(); + productLikeDO.setUserId(userId); + productLikeDO.setProductId(productId); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productLikeDO parameter `productLikeDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + save(productLikeDO); + + // 增加商品点赞数 + productMapper.incrementLikeCount(productId); + } + + @Override + @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void removeLike(Long userId, Long productId) { + // 检查是否已点赞 + if (!isProductLiked(userId, productId)) { + return; + } + + // 删除点赞记录 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductLikeDO::getUserId, userId); + wrapper.eq(ProductLikeDO::getProductId, productId); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + remove(wrapper); + + // 减少商品点赞数 + productMapper.decrementLikeCount(productId); + } + + @Override + /** + * Run business method `isProductLiked`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isProductLiked(Long userId, Long productId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductLikeDO::getUserId, userId); + wrapper.eq(ProductLikeDO::getProductId, productId); + return count(wrapper) > 0; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipBenefitServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipBenefitServiceImpl.java new file mode 100644 index 00000000..65eec96a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipBenefitServiceImpl.java @@ -0,0 +1,142 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipBenefitDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipBenefitMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipBenefitService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipBenefitVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * VIP权益信息表 Service 实现 + * 对应数据库表 t_vip_benefit + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class VipBenefitServiceImpl extends ServiceImpl implements VipBenefitService { + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitMapper vipBenefitMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createVipBenefit(VipBenefitDTO vipBenefitDTO) { + VipBenefitDO vipBenefitDO = new VipBenefitDO(); + vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); + vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); + vipBenefitMapper.insert(vipBenefitDO); + return vipBenefitDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateVipBenefit(Long id, VipBenefitDTO vipBenefitDTO) { + VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); + if (vipBenefitDO == null) { + return false; + } + vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); + vipBenefitDO.setRequiredVipLevel(vipBenefitDTO.getRequiredVipLevel()); + return vipBenefitMapper.updateById(vipBenefitDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteVipBenefit(Long id) { + return vipBenefitMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipBenefitVO result consumed by the caller or returned to the frontend + */ + public VipBenefitVO getVipBenefitById(Long id) { + VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); + if (vipBenefitDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDO parameter `vipBenefitDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(vipBenefitDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllVipBenefits() { + List vipBenefitDOs = vipBenefitMapper.selectList(null); + return vipBenefitDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listVipBenefitsByRequiredVipLevel(String requiredVipLevel) { + List vipBenefitDOs = vipBenefitMapper.selectList( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getRequiredVipLevel, requiredVipLevel) + ); + return vipBenefitDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param vipBenefitDO VIP权益DO + * @return VIP权益VO + */ + private VipBenefitVO convertToVO(VipBenefitDO vipBenefitDO) { + VipBenefitVO vipBenefitVO = new VipBenefitVO(); + vipBenefitVO.setId(vipBenefitDO.getId()); + vipBenefitVO.setBenefitInfo(vipBenefitDO.getBenefitInfo()); + vipBenefitVO.setRequiredVipLevel(vipBenefitDO.getRequiredVipLevel()); + vipBenefitVO.setCreateTime(vipBenefitDO.getCreateTime()); + vipBenefitVO.setUpdateTime(vipBenefitDO.getUpdateTime()); + return vipBenefitVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipInfoServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipInfoServiceImpl.java new file mode 100644 index 00000000..a07a0006 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipInfoServiceImpl.java @@ -0,0 +1,157 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipInfoService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户VIP信息表 Service 实现 + * 对应数据库表 t_vip_info + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class VipInfoServiceImpl extends ServiceImpl implements VipInfoService { + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoMapper vipInfoMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createVipInfo(VipInfoDTO vipInfoDTO) { + VipInfoDO vipInfoDO = new VipInfoDO(); + vipInfoDO.setUserId(vipInfoDTO.getUserId()); + vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); + vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); + vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); + vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); + vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); + vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); + vipInfoMapper.insert(vipInfoDO); + return vipInfoDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO) { + VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); + if (vipInfoDO == null) { + return false; + } + vipInfoDO.setUserId(vipInfoDTO.getUserId()); + vipInfoDO.setVipLevel(vipInfoDTO.getVipLevel()); + vipInfoDO.setStartTime(vipInfoDTO.getStartTime()); + vipInfoDO.setExpireTime(vipInfoDTO.getExpireTime()); + vipInfoDO.setActivationMethod(vipInfoDTO.getActivationMethod()); + vipInfoDO.setBenefitId(vipInfoDTO.getBenefitId()); + vipInfoDO.setManualOverride(vipInfoDTO.getManualOverride()); + return vipInfoMapper.updateById(vipInfoDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteVipInfo(Long id) { + return vipInfoMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipInfoVO result consumed by the caller or returned to the frontend + */ + public VipInfoVO getVipInfoById(Long id) { + VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); + if (vipInfoDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDO parameter `vipInfoDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(vipInfoDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllVipInfos() { + List vipInfoDOs = vipInfoMapper.selectList(null); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listVipInfosByVipLevel(String vipLevel) { + List vipInfoDOs = vipInfoMapper.selectList( + Wrappers.lambdaQuery(VipInfoDO.class) + .eq(VipInfoDO::getVipLevel, vipLevel) + ); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param vipInfoDO VIP信息DO + * @return VIP信息VO + */ + private VipInfoVO convertToVO(VipInfoDO vipInfoDO) { + VipInfoVO vipInfoVO = new VipInfoVO(); + vipInfoVO.setId(vipInfoDO.getId()); + vipInfoVO.setUserId(vipInfoDO.getUserId()); + vipInfoVO.setVipLevel(vipInfoDO.getVipLevel()); + vipInfoVO.setStartTime(vipInfoDO.getStartTime()); + vipInfoVO.setExpireTime(vipInfoDO.getExpireTime()); + vipInfoVO.setActivationMethod(vipInfoDO.getActivationMethod()); + vipInfoVO.setBenefitId(vipInfoDO.getBenefitId()); + vipInfoVO.setManualOverride(vipInfoDO.getManualOverride()); + vipInfoVO.setCreateTime(vipInfoDO.getCreateTime()); + vipInfoVO.setUpdateTime(vipInfoDO.getUpdateTime()); + return vipInfoVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java new file mode 100644 index 00000000..ac9461db --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/VipRechargePlanServiceImpl.java @@ -0,0 +1,398 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.VipRechargePlanDTO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipRechargePlanMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.VipRechargePlanService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * VipRechargePlanServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanServiceImpl extends ServiceImpl implements VipRechargePlanService { + public static final List DEFAULT_VIP_LEVELS = List.of("普通", "青铜", "白银", "黄金"); + /** + * Variable `planMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanMapper planMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createPlan(UserDO currentUser, VipRechargePlanDTO dto) { + Long shopId = resolveManagedShopId(currentUser, dto.getShopId()); + VipRechargePlanDO plan = new VipRechargePlanDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + plan.setIsDelete(0); + planMapper.insert(plan); + return plan.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + Long shopId = resolveManagedShopId(currentUser, dto.getShopId() == null ? plan.getShopId() : dto.getShopId()); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + planMapper.updateById(plan); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer status) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + plan.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0); + planMapper.updateById(plan); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminPlans(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + if (scopedShopId != null && scopedShopId > 0) { + ensureDefaultPlans(scopedShopId); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByDesc(VipRechargePlanDO::getCreateTime); + if (scopedShopId != null && scopedShopId > 0) { + wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); + } + return toVOList(planMapper.selectList(wrapper)); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPlans(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + Set shopIds = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + shopIds.add(user.getShopId()); + } + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) shopIds.add(binding.getShopId()); + }); + if (shopIds.isEmpty()) { + return List.of(); + } + shopIds.forEach(this::ensureDefaultPlans); + return toVOList(planMapper.selectList(new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .eq(VipRechargePlanDO::getStatus, 1) + .in(VipRechargePlanDO::getShopId, shopIds) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByAsc(VipRechargePlanDO::getRechargeAmount))); + } + + @Override + /** + * Purpose: listVipLevelOptions supports VipRechargePlanServiceImpl.java by holding or executing the list vip level options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listVipLevelOptions(UserDO currentUser, Long shopId) { + Long scopedShopId = currentUser == null ? shopId : adminScopeHelper.resolveShopScope(currentUser, shopId); + if (scopedShopId != null && scopedShopId > 0) { + ensureDefaultPlans(scopedShopId); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .eq(VipRechargePlanDO::getStatus, 1) + .isNotNull(VipRechargePlanDO::getVipLevel) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByAsc(VipRechargePlanDO::getRechargeAmount); + if (scopedShopId != null && scopedShopId > 0) { + wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); + } + LinkedHashSet levels = new LinkedHashSet<>(DEFAULT_VIP_LEVELS); + planMapper.selectList(wrapper).stream() + .map(VipRechargePlanDO::getVipLevel) + .filter(level -> level != null && !level.trim().isEmpty()) + .map(String::trim) + .forEach(levels::add); + return List.copyOf(levels); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(VipRechargePlanDO plan, VipRechargePlanDTO dto, Long shopId) { + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopExists(shopId); + plan.setShopId(shopId); + plan.setTitle(dto.getTitle().trim()); + plan.setRechargeAmount(dto.getRechargeAmount()); + plan.setGiftAmount(dto.getGiftAmount()); + plan.setVipLevel(dto.getVipLevel().trim()); + plan.setDescription(dto.getDescription()); + plan.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + plan.setStatus(Integer.valueOf(0).equals(dto.getStatus()) ? 0 : 1); + } + + /** + * Run business method `resolveManagedShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveManagedShopId(UserDO currentUser, Long requestedShopId) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, requestedShopId); + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权维护其他店铺充值档位"); + return shopId; + } + + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlanAccessible(UserDO currentUser, VipRechargePlanDO plan) { + adminScopeHelper.ensureShopAccessible(currentUser, plan.getShopId(), "无权维护其他店铺充值档位"); + } + + /** + * Run business method `requirePlan`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private VipRechargePlanDO result consumed by the caller or returned to the frontend + */ + private VipRechargePlanDO requirePlan(Long id) { + VipRechargePlanDO plan = planMapper.selectById(id); + if (plan == null || Integer.valueOf(1).equals(plan.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("充值档位不存在"); + } + return plan; + } + + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureShopExists(Long shopId) { + ShopDO shop = shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺不存在"); + } + } + + /** + * Purpose: ensureDefaultPlans supports VipRechargePlanServiceImpl.java by holding or executing the ensure default plans business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensureDefaultPlans(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + createDefaultPlanIfMissing(shopId, "青铜", new BigDecimal("99.00"), 10); + createDefaultPlanIfMissing(shopId, "白银", new BigDecimal("299.00"), 20); + createDefaultPlanIfMissing(shopId, "黄金", new BigDecimal("599.00"), 30); + } + + /** + * Purpose: createDefaultPlanIfMissing supports VipRechargePlanServiceImpl.java by holding or executing the create default plan if missing business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void createDefaultPlanIfMissing(Long shopId, String vipLevel, BigDecimal rechargeAmount, int sortOrder) { + Long count = planMapper.selectCount(new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getShopId, shopId) + .eq(VipRechargePlanDO::getVipLevel, vipLevel) + .eq(VipRechargePlanDO::getIsDelete, 0)); + if (count != null && count > 0) { + return; + } + VipRechargePlanDO plan = new VipRechargePlanDO(); + plan.setShopId(shopId); + plan.setTitle(vipLevel + "会员充值"); + plan.setRechargeAmount(rechargeAmount); + plan.setGiftAmount(BigDecimal.ZERO); + plan.setVipLevel(vipLevel); + plan.setDescription("系统默认配置,可按门店实际规则修改"); + plan.setSortOrder(sortOrder); + plan.setStatus(1); + plan.setIsDelete(0); + planMapper.insert(plan); + } + + /** + * Run business method `toVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plans parameter `plans` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toVOList(List plans) { + Set shopIds = plans.stream().map(VipRechargePlanDO::getShopId).filter(Objects::nonNull).collect(Collectors.toSet()); + Map shopNameMap = shopIds.isEmpty() + ? Map.of() + : shopMapper.selectList(new LambdaQueryWrapper().in(ShopDO::getId, shopIds)) + .stream() + .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + return plans.stream().map(plan -> { + VipRechargePlanVO vo = new VipRechargePlanVO(); + vo.setId(plan.getId()); + vo.setShopId(plan.getShopId()); + vo.setShopName(shopNameMap.get(plan.getShopId())); + vo.setTitle(plan.getTitle()); + vo.setRechargeAmount(plan.getRechargeAmount()); + vo.setGiftAmount(plan.getGiftAmount()); + vo.setVipLevel(plan.getVipLevel()); + vo.setDescription(plan.getDescription()); + vo.setSortOrder(plan.getSortOrder()); + vo.setStatus(plan.getStatus()); + vo.setCreateTime(plan.getCreateTime()); + vo.setUpdateTime(plan.getUpdateTime()); + return vo; + }).collect(Collectors.toList()); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/WishlistServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/WishlistServiceImpl.java new file mode 100644 index 00000000..91071341 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/service/impl/WishlistServiceImpl.java @@ -0,0 +1,384 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistAddWithGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistGroupDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.WishlistGroupDO; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistGroupMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.WishlistMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.WishlistService; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.WishlistInspirationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class WishlistServiceImpl extends ServiceImpl implements WishlistService { + + private static final List PRESET_GROUP_NAMES = List.of( + "\u6700\u8fd1\u60f3\u505a", + "\u5a5a\u793c\u6b3e", + "\u590f\u5929\u6b3e" + ); + private static final int DEFAULT_SORT_ORDER = 100; + private static final int NOTE_MAX_LENGTH = 500; + + private final WishlistMapper wishlistMapper; + private final WishlistGroupMapper wishlistGroupMapper; + private final ProductService productService; + private final ProductMapper productMapper; + + @Override + @Transactional + public void addToWishlist(Long userId, Long productId) { + WishlistAddWithGroupDTO dto = new WishlistAddWithGroupDTO(); + dto.setProductId(productId); + addToWishlist(userId, dto); + } + + @Override + @Transactional + public void addToWishlist(Long userId, WishlistAddWithGroupDTO wishlistDTO) { + Long productId = wishlistDTO == null ? null : wishlistDTO.getProductId(); + ProductDO product = getValidProduct(productId); + if (product == null) { + throw new RuntimeException("\u5546\u54c1\u4e0d\u5b58\u5728\u6216\u5df2\u4e0b\u67b6"); + } + + WishlistGroupDO group = resolveTargetGroup(userId, wishlistDTO == null ? null : wishlistDTO.getGroupId()); + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { + WishlistDO wishlistDO = new WishlistDO(); + wishlistDO.setUserId(userId); + wishlistDO.setProductId(productId); + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistDTO == null ? null : wishlistDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistDTO == null ? null : wishlistDTO.getSortOrder())); + wishlistDO.setIsDelete(0); + wishlistMapper.insert(wishlistDO); + productMapper.incrementCollectCount(productId); + return; + } + + existing.setGroupId(group.getId()); + existing.setNote(normalizeNote(wishlistDTO.getNote())); + if (wishlistDTO.getSortOrder() != null) { + existing.setSortOrder(normalizeSortOrder(wishlistDTO.getSortOrder())); + } else if (existing.getSortOrder() == null) { + existing.setSortOrder(DEFAULT_SORT_ORDER); + } + wishlistMapper.updateById(existing); + } + + @Override + @Transactional + public void removeFromWishlist(Long userId, Long productId) { + WishlistDO existing = findActiveWishlistByUserAndProduct(userId, productId); + if (existing == null) { + return; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getProductId, productId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.delete(wrapper); + if (getValidProduct(productId) != null) { + productMapper.decrementCollectCount(productId); + } + } + + @Override + public boolean isInWishlist(Long userId, Long productId) { + if (getValidProduct(productId) == null) { + return false; + } + return findActiveWishlistByUserAndProduct(userId, productId) != null; + } + + @Override + public List getWishlistByUserId(Long userId) { + List groups = listGroups(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + return loadActiveWishlist(userId).stream() + .map(wishlistDO -> toWishlistDTO(wishlistDO, groupNames)) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public List listGroups(Long userId) { + return ensurePresetGroups(userId).stream() + .map(this::toGroupVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional + public Long createGroup(Long userId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + return group.getId(); + } + + @Override + @Transactional + public boolean updateGroup(Long userId, Long groupId, WishlistGroupDTO wishlistGroupDTO) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + group.setName(normalizeGroupName(wishlistGroupDTO == null ? null : wishlistGroupDTO.getName())); + group.setSortOrder(normalizeSortOrder(wishlistGroupDTO == null ? null : wishlistGroupDTO.getSortOrder())); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean deleteGroup(Long userId, Long groupId) { + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + return false; + } + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getGroupId, groupId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wishlistMapper.selectList(wrapper).forEach(wishlistDO -> { + wishlistDO.setGroupId(defaultGroup.getId()); + wishlistMapper.updateById(wishlistDO); + }); + group.setIsDelete(1); + return wishlistGroupMapper.updateById(group) > 0; + } + + @Override + @Transactional + public boolean moveWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + WishlistDO wishlistDO = findTargetWishlist(userId, wishlistMoveDTO); + if (wishlistDO == null) { + return false; + } + WishlistGroupDO group = resolveTargetGroup(userId, wishlistMoveDTO == null ? null : wishlistMoveDTO.getGroupId()); + wishlistDO.setGroupId(group.getId()); + wishlistDO.setNote(normalizeNote(wishlistMoveDTO == null ? null : wishlistMoveDTO.getNote())); + wishlistDO.setSortOrder(normalizeSortOrder(wishlistMoveDTO == null ? null : wishlistMoveDTO.getSortOrder())); + return wishlistMapper.updateById(wishlistDO) > 0; + } + + @Override + @Transactional + public WishlistInspirationVO getInspiration(Long userId) { + List groups = listGroups(userId); + Map groupMap = new LinkedHashMap<>(); + groups.forEach(group -> groupMap.put(group.getId(), group)); + + WishlistGroupDO defaultGroup = resolveDefaultGroup(userId); + Map groupNames = groups.stream() + .filter(group -> group.getId() != null) + .collect(Collectors.toMap(WishlistGroupVO::getId, WishlistGroupVO::getName, (left, right) -> left)); + + List items = loadActiveWishlist(userId).stream() + .map(wishlistDO -> { + if (wishlistDO.getGroupId() == null || !groupMap.containsKey(wishlistDO.getGroupId())) { + wishlistDO.setGroupId(defaultGroup.getId()); + } + return toWishlistDTO(wishlistDO, groupNames); + }) + .filter(wishlistDTO -> wishlistDTO.getProduct() != null) + .collect(Collectors.toList()); + + items.forEach(item -> { + WishlistGroupVO group = groupMap.get(item.getGroupId()); + if (group != null) { + group.getItems().add(item); + } + }); + groups.forEach(group -> group.setItemCount(group.getItems().size())); + + WishlistInspirationVO inspirationVO = new WishlistInspirationVO(); + inspirationVO.setTotal(items.size()); + inspirationVO.setGroups(groups); + return inspirationVO; + } + + private WishlistDTO toWishlistDTO(WishlistDO wishlistDO, Map groupNames) { + WishlistDTO wishlistDTO = new WishlistDTO(); + BeanUtils.copyProperties(wishlistDO, wishlistDTO); + wishlistDTO.setGroupName(groupNames.get(wishlistDO.getGroupId())); + ProductVO productVO = productService.getProductById(wishlistDO.getProductId()); + wishlistDTO.setProduct(productVO); + return wishlistDTO; + } + + private WishlistGroupVO toGroupVO(WishlistGroupDO groupDO) { + WishlistGroupVO groupVO = new WishlistGroupVO(); + groupVO.setId(groupDO.getId()); + groupVO.setName(groupDO.getName()); + groupVO.setSortOrder(normalizeSortOrder(groupDO.getSortOrder())); + groupVO.setItemCount(0); + groupVO.setItems(new ArrayList<>()); + return groupVO; + } + + private WishlistDO findTargetWishlist(Long userId, WishlistMoveDTO wishlistMoveDTO) { + if (wishlistMoveDTO == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + if (wishlistMoveDTO.getWishlistId() != null) { + wrapper.eq(WishlistDO::getId, wishlistMoveDTO.getWishlistId()); + } else if (wishlistMoveDTO.getProductId() != null) { + wrapper.eq(WishlistDO::getProductId, wishlistMoveDTO.getProductId()); + } else { + return null; + } + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private WishlistDO findActiveWishlistByUserAndProduct(Long userId, Long productId) { + if (userId == null || productId == null) { + return null; + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getProductId, productId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.last("LIMIT 1"); + return wishlistMapper.selectOne(wrapper); + } + + private List loadActiveWishlist(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistDO::getUserId, userId); + wrapper.eq(WishlistDO::getIsDelete, 0); + wrapper.orderByAsc(WishlistDO::getSortOrder); + wrapper.orderByDesc(WishlistDO::getCreateTime); + return wishlistMapper.selectList(wrapper); + } + + private List ensurePresetGroups(Long userId) { + List groups = loadActiveGroups(userId); + Map groupByName = groups.stream() + .collect(Collectors.toMap(WishlistGroupDO::getName, group -> group, (left, right) -> left)); + for (int index = 0; index < PRESET_GROUP_NAMES.size(); index++) { + String name = PRESET_GROUP_NAMES.get(index); + if (!groupByName.containsKey(name)) { + WishlistGroupDO group = new WishlistGroupDO(); + group.setUserId(userId); + group.setName(name); + group.setSortOrder((index + 1) * 10); + group.setIsDelete(0); + wishlistGroupMapper.insert(group); + groups.add(group); + groupByName.put(name, group); + } + } + return groups.stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + private WishlistGroupDO resolveDefaultGroup(Long userId) { + return ensurePresetGroups(userId).stream() + .filter(group -> PRESET_GROUP_NAMES.get(0).equals(group.getName())) + .findFirst() + .orElseThrow(() -> new RuntimeException("\u9ed8\u8ba4\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728")); + } + + private WishlistGroupDO resolveTargetGroup(Long userId, Long groupId) { + if (groupId == null) { + return resolveDefaultGroup(userId); + } + WishlistGroupDO group = findOwnedGroup(userId, groupId); + if (group == null) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u4e0d\u5b58\u5728"); + } + return group; + } + + private WishlistGroupDO findOwnedGroup(Long userId, Long groupId) { + if (userId == null || groupId == null) { + return null; + } + WishlistGroupDO group = wishlistGroupMapper.selectById(groupId); + if (group == null || Integer.valueOf(1).equals(group.getIsDelete()) || !userId.equals(group.getUserId())) { + return null; + } + return group; + } + + private List loadActiveGroups(Long userId) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(WishlistGroupDO::getUserId, userId); + wrapper.eq(WishlistGroupDO::getIsDelete, 0); + return wishlistGroupMapper.selectList(wrapper).stream() + .sorted(Comparator + .comparing((WishlistGroupDO group) -> normalizeSortOrder(group.getSortOrder())) + .thenComparing(WishlistGroupDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + private ProductDO getValidProduct(Long productId) { + if (productId == null) { + return null; + } + + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + return null; + } + + return product; + } + + private String normalizeGroupName(String name) { + if (!StringUtils.hasText(name)) { + throw new RuntimeException("\u6536\u85cf\u5206\u7ec4\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a"); + } + return name.trim(); + } + + private String normalizeNote(String note) { + if (!StringUtils.hasText(note)) { + return null; + } + String trimmedNote = note.trim(); + return trimmedNote.length() > NOTE_MAX_LENGTH ? trimmedNote.substring(0, NOTE_MAX_LENGTH) : trimmedNote; + } + + private Integer normalizeSortOrder(Integer sortOrder) { + return sortOrder == null ? DEFAULT_SORT_ORDER : sortOrder; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CampaignVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CampaignVO.java new file mode 100644 index 00000000..1a8befe3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CampaignVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class CampaignVO { + private Long id; + private Long shopId; + private String title; + private String description; + private String scene; + private String productIds; + private String couponIds; + private Integer status; + private LocalDateTime startTime; + private LocalDateTime endTime; + private Integer sortOrder; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CouponVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CouponVO.java new file mode 100644 index 00000000..7a0f99c6 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/CouponVO.java @@ -0,0 +1,122 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +/** + * 优惠券VO + */ +@Data +public class CouponVO { + + /** + * 优惠券ID + */ + private Long id; + + /** + * 优惠券编码 + */ + private String couponCode; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 优惠券类型名称 + */ + private String couponTypeName; + + /** + * 折扣值(如9.5表示95折) + */ + private BigDecimal discountValue; + + /** + * 满减券最低消费金额 + */ + private BigDecimal minAmount; + + /** + * 满减券减免金额 + */ + private BigDecimal reduceAmount; + + /** + * 优惠券总数量 + */ + private Integer totalCount; + + /** + * 已使用数量 + */ + private Integer usedCount; + + /** + * 剩余数量 + */ + private Integer remainingCount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-可用,2-已过期,3-已用完 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; + + /** + * 所属店铺ID + */ + private Long shopId; + + /** + * 所属店铺名称 + */ + private String shopName; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer autoMatch; + + /** + * 可用标签列表 + */ + private List availableTags; + + /** + * 不可用标签列表 + */ + private List unavailableTags; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/GrowthSummaryVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/GrowthSummaryVO.java new file mode 100644 index 00000000..5b27ab13 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/GrowthSummaryVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +@Data +public class GrowthSummaryVO { + private Long userId; + private Integer growthValue; + private String levelName; + private Integer appointmentCount; + private Integer reviewCount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/UserCouponVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/UserCouponVO.java new file mode 100644 index 00000000..f930d902 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/UserCouponVO.java @@ -0,0 +1,94 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户优惠券VO + */ +@Data +public class UserCouponVO { + + /** + * 关联ID + */ + private Long id; + + /** + * 优惠券ID + */ + private Long couponId; + + /** + * 优惠券名称 + */ + private String couponName; + + /** + * 优惠券类型:1-折扣券,2-满减券 + */ + private Integer couponType; + + /** + * 优惠券类型名称 + */ + private String couponTypeName; + + /** + * 折扣值(如9.5表示95折) + */ + private String discountValue; + + /** + * 满减券最低消费金额 + */ + private String minAmount; + + /** + * 满减券减免金额 + */ + private String reduceAmount; + + /** + * 开始时间 + */ + private LocalDateTime startTime; + + /** + * 结束时间 + */ + private LocalDateTime endTime; + + /** + * 状态:1-未使用,2-已使用,3-已过期 + */ + private Integer status; + + /** + * 状态名称 + */ + private String statusName; + + /** + * 获取时间 + */ + private LocalDateTime obtainTime; + + /** + * 使用时间 + */ + private LocalDateTime useTime; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String requiredVipLevel; + /** + * Field `autoMatched` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean autoMatched; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipBenefitVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipBenefitVO.java new file mode 100644 index 00000000..cc9b6af3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipBenefitVO.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * VIP权益信息表 VO + * 用于前端展示VIP权益信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipBenefitVO { + + /** + * VIP权益唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 权益详情(如折扣、专属服务) + */ + private String benefitInfo; + + /** + * 所需VIP等级 + */ + private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipInfoVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipInfoVO.java new file mode 100644 index 00000000..5cb6b872 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipInfoVO.java @@ -0,0 +1,70 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 用户VIP信息表 VO + * 用于前端展示VIP信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class VipInfoVO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * VIP信息唯一主键ID(雪花ID) + */ + private Long id; + + /** + * VIP等级(如青铜、白银) + */ + private String vipLevel; + + /** + * VIP开通时间 + */ + private LocalDateTime startTime; + + /** + * VIP到期时间 + */ + private LocalDateTime expireTime; + + /** + * VIP开通方式(如购买、赠送) + */ + private String activationMethod; + + /** + * 关联VIP权益信息表主键 + */ + private Long benefitId; + + /** + * 权益详情 + */ + private String benefitInfo; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer manualOverride; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipRechargePlanVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipRechargePlanVO.java new file mode 100644 index 00000000..151d15f3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/VipRechargePlanVO.java @@ -0,0 +1,62 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * VipRechargePlanVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistGroupVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistGroupVO.java new file mode 100644 index 00000000..c512b768 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistGroupVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.WishlistDTO; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistGroupVO { + private Long id; + private String name; + private Integer sortOrder; + private Integer itemCount; + private List items = new ArrayList<>(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistInspirationVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistInspirationVO.java new file mode 100644 index 00000000..7076e370 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/marketing/vo/WishlistInspirationVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.marketing.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class WishlistInspirationVO { + private Integer total; + private List groups = new ArrayList<>(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/AnnouncementController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/AnnouncementController.java new file mode 100644 index 00000000..7b04410d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/AnnouncementController.java @@ -0,0 +1,119 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.message.service.AnnouncementService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/announcement", "/api/announcement", "/admin/announcement"}) +/** + * AnnouncementController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementController { + /** + * Variable `announcementService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementService announcementService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("announcement:create") + @OperationGuard(action = "announcement-create", ttlSeconds = 8, message = "公告发布处理中,请勿重复提交") + // 后台发布公告时,targetType 决定“全平台 / 指定店铺 / 指定用户”的范围。 + // 前端只需要按 target-options 返回值组装表单即可。 + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody AnnouncementCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.publishAnnouncement(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("announcement:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listAdminAnnouncements(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("announcement:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdmin(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.getAdminAnnouncement(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("announcement:delete") + @OperationGuard(action = "announcement-revoke", ttlSeconds = 8, message = "公告撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.revokeAnnouncement(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("announcement:create") + /** + * Run business method `targetOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result targetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(announcementService.listMyAnnouncements(userId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/SystemMessageController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/SystemMessageController.java new file mode 100644 index 00000000..b325047b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/controller/front/SystemMessageController.java @@ -0,0 +1,181 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.message.service.SystemMessageService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageUnreadCountVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-message", "/api/system-message", "/admin/system-message"}) +/** + * SystemMessageController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageController { + /** + * Variable `systemMessageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageService systemMessageService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("message:create") + @OperationGuard(action = "system-message-create", ttlSeconds = 8, message = "消息发布处理中,请勿重复提交") + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody SystemMessageCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.publishMessage(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("message:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdminMessages(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listAdminMessages(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("message:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdminMessage(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.getAdminMessage(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("message:delete") + @OperationGuard(action = "system-message-revoke", ttlSeconds = 8, message = "消息撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.revokeMessage(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("message:create") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result listTargetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyMessages(userId)); + } + + @GetMapping("/my/popup") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyPopupMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyPopupMessages(userId)); + } + + @GetMapping("/my/unread-count") + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result countMyUnreadMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(new MessageUnreadCountVO(systemMessageService.countMyUnreadMessages(userId))); + } + + @GetMapping("/my/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyMessage(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.getMyMessage(userId, id)); + } + + @PutMapping("/my/{id}/popup-shown") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markPopupShown(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markPopupShown(userId, id)); + } + + @PutMapping("/my/{id}/read") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markRead(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markRead(userId, id)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/AnnouncementCreateDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/AnnouncementCreateDTO.java new file mode 100644 index 00000000..3ff20c39 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/AnnouncementCreateDTO.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * AnnouncementCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementCreateDTO { + + @NotBlank(message = "公告标题不能为空") + @Size(max = 100, message = "公告标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotBlank(message = "公告内容不能为空") + @Size(max = 1000, message = "公告内容不能超过1000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @NotBlank(message = "公告范围不能为空") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/SystemMessageCreateDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/SystemMessageCreateDTO.java new file mode 100644 index 00000000..a6178285 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/dto/SystemMessageCreateDTO.java @@ -0,0 +1,69 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.dto; + +import lombok.Data; + +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * SystemMessageCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageCreateDTO { + + @Size(max = 100, message = "消息标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @Size(max = 2000, message = "消息内容不能超过2000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled = 1; + + /** + * Purpose: businessType supports SystemMessageCreateDTO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + /** + * Purpose: businessId supports SystemMessageCreateDTO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + /** + * Purpose: actionPath supports SystemMessageCreateDTO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/AnnouncementDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/AnnouncementDO.java new file mode 100644 index 00000000..1f3e357d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/AnnouncementDO.java @@ -0,0 +1,87 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_announcement") +/** + * AnnouncementDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageDO.java new file mode 100644 index 00000000..9bbf4a78 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageDO.java @@ -0,0 +1,121 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_system_message") +/** + * SystemMessageDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("image_file_id") + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("business_type") + /** + * Purpose: businessType supports SystemMessageDO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + + @TableField("business_id") + /** + * Purpose: businessId supports SystemMessageDO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + + @TableField("action_path") + /** + * Purpose: actionPath supports SystemMessageDO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; + + @TableField("idempotency_key") + /** + * Purpose: idempotencyKey supports SystemMessageDO.java by holding or executing the idempotency key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String idempotencyKey; + + @TableField("popup_enabled") + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageUserStateDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageUserStateDO.java new file mode 100644 index 00000000..dbedff30 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/entity/SystemMessageUserStateDO.java @@ -0,0 +1,63 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_system_message_user_state") +/** + * SystemMessageUserStateDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageUserStateDO extends BaseEntity { + + @TableField("message_id") + /** + * Field `messageId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long messageId; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("popup_shown") + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + + @TableField("read_status") + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + + @TableField("popup_time") + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + + @TableField("read_time") + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/AnnouncementMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/AnnouncementMapper.java new file mode 100644 index 00000000..09fc75a5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/AnnouncementMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.AnnouncementDO; + +/** + * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface AnnouncementMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageMapper.java new file mode 100644 index 00000000..cb2c5fae --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageUserStateMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageUserStateMapper.java new file mode 100644 index 00000000..da5a26f9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/mapper/SystemMessageUserStateMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageUserStateDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageUserStateMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageUserStateMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/AnnouncementService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/AnnouncementService.java new file mode 100644 index 00000000..1aa067a0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/AnnouncementService.java @@ -0,0 +1,62 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * AnnouncementService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface AnnouncementService extends IService { + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminAnnouncements(UserDO currentUser); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id); + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeAnnouncement(UserDO currentUser, Long id); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyAnnouncements(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/SystemMessageService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/SystemMessageService.java new file mode 100644 index 00000000..8f35cca7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/SystemMessageService.java @@ -0,0 +1,111 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.SystemMessageVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * SystemMessageService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface SystemMessageService extends IService { + + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminMessages(UserDO currentUser); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId); + + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeMessage(UserDO currentUser, Long messageId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyMessages(Long userId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPopupMessages(Long userId); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getMyMessage(Long userId, Long messageId); + + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long countMyUnreadMessages(Long userId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markPopupShown(Long userId, Long messageId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markRead(Long userId, Long messageId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/AnnouncementServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/AnnouncementServiceImpl.java new file mode 100644 index 00000000..19ec7c9b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -0,0 +1,504 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.AnnouncementCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.service.AnnouncementService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.AnnouncementVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * AnnouncementServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementServiceImpl extends ServiceImpl implements AnnouncementService { + + /** + * Purpose: TARGET_PLATFORM_ALL supports AnnouncementServiceImpl.java by holding or executing the target platform all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + /** + * Purpose: TARGET_CURRENT_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target current shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + /** + * Purpose: TARGET_SHOP_ALL supports AnnouncementServiceImpl.java by holding or executing the target shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SHOP_ALL = "SHOP_ALL"; + /** + * Purpose: TARGET_SELECTED_SHOPS supports AnnouncementServiceImpl.java by holding or executing the target selected shops business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + /** + * Purpose: TARGET_SELECTED_USERS supports AnnouncementServiceImpl.java by holding or executing the target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `announcementMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementMapper announcementMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + AnnouncementDO announcement = new AnnouncementDO(); + announcement.setTitle(dto.getTitle().trim()); + announcement.setContent(dto.getContent().trim()); + announcement.setPublisherId(currentUser.getId()); + announcement.setPublisherName(resolvePublisherName(currentUser)); + announcement.setPublisherType(currentUser.getType()); + announcement.setTargetType(targetType); + announcement.setTargetIds(joinIds(targetIds)); + announcement.setStatus(1); + announcement.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + announcement.setPublishTime(LocalDateTime.now()); + announcement.setIsDelete(0); + announcementMapper.insert(announcement); + return announcement.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminAnnouncements(UserDO currentUser) { + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> canAdminSee(currentUser, item)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + public AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该公告"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param announcement parameter `announcement` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(announcement); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该公告"); + } + announcement.setStatus(0); + announcementMapper.updateById(announcement); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyAnnouncements(Long userId) { + UserDO user = requireUser(userId); + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .eq(AnnouncementDO::getStatus, 1) + .orderByDesc(AnnouncementDO::getSortOrder) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> isVisibleToUser(item, user)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, AnnouncementCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + if (TARGET_PLATFORM_ALL.equals(targetType)) return List.of(); + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) throw new RuntimeException("请选择公告店铺"); + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("公告范围不正确"); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布公告"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店公告或本店指定用户公告"); + } + + /** + * Run business method `isVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleToUser(AnnouncementDO item, UserDO user) { + String targetType = item.getTargetType(); + Set targetIds = parseIds(item.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) return true; + if (TARGET_SELECTED_USERS.equals(targetType)) return targetIds.contains(user.getId()); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return getUserShopIds(user).stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) ids.add(user.getShopId()); + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) ids.add(binding.getShopId()); + }); + return ids; + } + + /** + * Run business method `canAdminSee`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param item parameter `item` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSee(UserDO currentUser, AnnouncementDO item) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) return true; + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(item.getTargetType()) || TARGET_SHOP_ALL.equals(item.getTargetType()) || TARGET_SELECTED_SHOPS.equals(item.getTargetType())) { + return parseIds(item.getTargetIds()).contains(managedShopId); + } + return Objects.equals(item.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @return private AnnouncementVO result consumed by the caller or returned to the frontend + */ + private AnnouncementVO toVO(AnnouncementDO item) { + AnnouncementVO vo = new AnnouncementVO(); + vo.setId(item.getId()); + vo.setTitle(item.getTitle()); + vo.setContent(item.getContent()); + vo.setPublisherId(item.getPublisherId()); + vo.setPublisherName(item.getPublisherName()); + vo.setPublisherType(item.getPublisherType()); + vo.setTargetType(item.getTargetType()); + vo.setTargetTypeName(targetTypeName(item.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(item.getTargetIds()))); + vo.setStatus(item.getStatus()); + vo.setSortOrder(item.getSortOrder()); + vo.setPublishTime(item.getPublishTime()); + vo.setCreateTime(item.getCreateTime()); + return vo; + } + + /** + * Run business method `requireAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private AnnouncementDO result consumed by the caller or returned to the frontend + */ + private AnnouncementDO requireAnnouncement(Long id) { + AnnouncementDO item = announcementMapper.selectById(id); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) throw new RuntimeException("公告不存在"); + return item; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new RuntimeException("用户不存在"); + return user; + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) throw new RuntimeException("存在无效店铺"); + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) throw new RuntimeException("存在无效用户"); + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) throw new RuntimeException("公告范围不能为空"); + return targetType.trim().toUpperCase(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) return List.of(); + return ids.stream().filter(Objects::nonNull).filter(id -> id > 0).distinct().collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) return Set.of(); + return java.util.Arrays.stream(ids.split(",")).map(String::trim).filter(StringUtils::hasText).map(Long::valueOf).collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/SystemMessageServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/SystemMessageServiceImpl.java new file mode 100644 index 00000000..6e6ae342 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/service/impl/SystemMessageServiceImpl.java @@ -0,0 +1,888 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.SystemMessageCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageUserStateDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageUserStateMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.message.service.SystemMessageService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.MessageTargetOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.fingertipdesigner.core.modules.message.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * SystemMessageServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageServiceImpl extends ServiceImpl implements SystemMessageService { + + /** + * Purpose: TARGET_PLATFORM_ALL supports SystemMessageServiceImpl.java by holding or executing the target platform all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + /** + * Purpose: TARGET_CURRENT_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target current shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + /** + * Purpose: TARGET_SHOP_ALL supports SystemMessageServiceImpl.java by holding or executing the target shop all business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SHOP_ALL = "SHOP_ALL"; + /** + * Purpose: TARGET_SELECTED_SHOPS supports SystemMessageServiceImpl.java by holding or executing the target selected shops business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + /** + * Purpose: TARGET_SELECTED_USERS supports SystemMessageServiceImpl.java by holding or executing the target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `systemMessageMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageMapper systemMessageMapper; + /** + * Variable `stateMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageUserStateMapper stateMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + String title = dto.getTitle() == null ? "" : dto.getTitle().trim(); + String content = dto.getContent() == null ? "" : dto.getContent().trim(); + if (!StringUtils.hasText(title)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息标题不能为空"); + } + if (!StringUtils.hasText(content) && dto.getImageFileId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请填写消息内容或上传消息图片"); + } + if (dto.getImageFileId() != null) { + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(dto.getImageFileId()); + if (imageFile == null || !Integer.valueOf(1).equals(imageFile.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息图片不存在或不可用"); + } + } + + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setImageFileId(dto.getImageFileId()); + message.setPublisherId(currentUser.getId()); + message.setPublisherName(resolvePublisherName(currentUser)); + message.setPublisherType(currentUser.getType()); + message.setTargetType(targetType); + message.setTargetIds(joinIds(targetIds)); + message.setBusinessType(trimToNull(dto.getBusinessType())); + message.setBusinessId(dto.getBusinessId()); + message.setActionPath(trimToNull(dto.getActionPath())); + message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + return message.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminMessages(UserDO currentUser) { + List messages = systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .orderByDesc(SystemMessageDO::getPublishTime)); + return messages.stream() + .filter(message -> canAdminSeeMessage(currentUser, message)) + .map(message -> toVO(message, null)) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该消息"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该消息"); + } + message.setStatus(0); + systemMessageMapper.updateById(message); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPopupMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> Integer.valueOf(1).equals(message.getPopupEnabled())) + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getPopupShown()); + }) + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getMyMessage(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = findState(userId, messageId); + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, state); + } + + @Override + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long countMyUnreadMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getReadStatus()); + }) + .count(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markPopupShown(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getPopupShown())) { + state.setPopupShown(1); + state.setPopupTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markRead(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getReadStatus())) { + state.setReadStatus(1); + state.setReadTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listVisibleMessages(UserDO user) { + return systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .eq(SystemMessageDO::getStatus, 1) + .orderByDesc(SystemMessageDO::getPublishTime)) + .stream() + .filter(message -> isMessageVisibleToUser(message, user)) + .collect(Collectors.toList()); + } + + /** + * Run business method `isMessageVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isMessageVisibleToUser(SystemMessageDO message, UserDO user) { + String targetType = message.getTargetType(); + Set targetIds = parseIds(message.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return true; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + return targetIds.contains(user.getId()); + } + Set userShopIds = getUserShopIds(user); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return userShopIds.stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + ids.add(user.getShopId()); + } + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + bindings.forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) { + ids.add(binding.getShopId()); + } + }); + return ids; + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, SystemMessageCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return resolveAdminTargets(targetType, dto); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布消息"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店全员或本店部分用户消息"); + } + + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAdminTargets(String targetType, SystemMessageCreateDTO dto) { + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return List.of(); + } + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收店铺"); + } + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员消息范围不正确"); + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效店铺"); + } + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效用户"); + } + } + + /** + * Run business method `canAdminSeeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSeeMessage(UserDO currentUser, SystemMessageDO message) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + return true; + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(message.getTargetType()) || TARGET_SHOP_ALL.equals(message.getTargetType()) || TARGET_SELECTED_SHOPS.equals(message.getTargetType())) { + return parseIds(message.getTargetIds()).contains(managedShopId); + } + return Objects.equals(message.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return private SystemMessageVO result consumed by the caller or returned to the frontend + */ + private SystemMessageVO toVO(SystemMessageDO message, SystemMessageUserStateDO state) { + SystemMessageVO vo = new SystemMessageVO(); + vo.setId(message.getId()); + vo.setTitle(message.getTitle()); + vo.setContent(message.getContent()); + vo.setImageFileId(message.getImageFileId()); + vo.setImageUrl(resolveImageUrl(message.getImageFileId())); + vo.setPublisherId(message.getPublisherId()); + vo.setPublisherName(message.getPublisherName()); + vo.setPublisherType(message.getPublisherType()); + vo.setTargetType(message.getTargetType()); + vo.setTargetTypeName(targetTypeName(message.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds()))); + vo.setBusinessType(message.getBusinessType()); + vo.setBusinessId(message.getBusinessId()); + vo.setActionPath(message.getActionPath()); + vo.setPopupEnabled(message.getPopupEnabled()); + vo.setStatus(message.getStatus()); + vo.setPublishTime(message.getPublishTime()); + vo.setCreateTime(message.getCreateTime()); + vo.setPopupShown(state == null ? 0 : state.getPopupShown()); + vo.setReadStatus(state == null ? 0 : state.getReadStatus()); + vo.setPopupTime(state == null ? null : state.getPopupTime()); + vo.setReadTime(state == null ? null : state.getReadTime()); + return vo; + } + + /** + * Run business method `resolveImageUrl`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param imageFileId parameter `imageFileId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveImageUrl(Long imageFileId) { + if (imageFileId == null || imageFileId <= 0) { + return null; + } + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(imageFileId); + if (imageFile == null || !StringUtils.hasText(imageFile.getFileUrl())) { + return null; + } + return objectStorageUrlSupport.toAccessibleUrl(imageFile); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO getOrCreateState(Long userId, Long messageId) { + SystemMessageUserStateDO state = findState(userId, messageId); + if (state != null) { + return state; + } + state = new SystemMessageUserStateDO(); + state.setMessageId(messageId); + state.setUserId(userId); + state.setPopupShown(0); + state.setReadStatus(0); + state.setIsDelete(0); + stateMapper.insert(state); + return state; + } + + /** + * Run business method `findState`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO findState(Long userId, Long messageId) { + return stateMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getMessageId, messageId) + .eq(SystemMessageUserStateDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `loadStateMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadStateMap(Long userId) { + return stateMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getIsDelete, 0)) + .stream() + .collect(Collectors.toMap(SystemMessageUserStateDO::getMessageId, Function.identity(), (a, b) -> a)); + } + + /** + * Run business method `requireMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageDO result consumed by the caller or returned to the frontend + */ + private SystemMessageDO requireMessage(Long messageId) { + SystemMessageDO message = systemMessageMapper.selectById(messageId); + if (message == null || Integer.valueOf(1).equals(message.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在"); + } + return message; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + return user; + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("接收范围不能为空"); + } + return targetType.trim().toUpperCase(); + } + + /** + * Purpose: trimToNull supports SystemMessageServiceImpl.java by holding or executing the trim to null business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String trimToNull(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return List.of(); + } + return ids.stream() + .filter(Objects::nonNull) + .filter(id -> id > 0) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) { + return Set.of(); + } + return java.util.Arrays.stream(ids.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(Long::valueOf) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + if (StringUtils.hasText(currentUser.getNickname())) { + return currentUser.getNickname(); + } + return currentUser.getAccount(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/AnnouncementVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/AnnouncementVO.java new file mode 100644 index 00000000..521dab64 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/AnnouncementVO.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * AnnouncementVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageTargetOptionsVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageTargetOptionsVO.java new file mode 100644 index 00000000..be233a35 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageTargetOptionsVO.java @@ -0,0 +1,69 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * MessageTargetOptionsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageTargetOptionsVO { + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops; + /** + * Field `users` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List users; + + @Data + /** + * Purpose: ShopOptionVO supports MessageTargetOptionsVO.java by holding or executing the shop option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class ShopOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + } + + @Data + /** + * Purpose: UserOptionVO supports MessageTargetOptionsVO.java by holding or executing the user option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class UserOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer type; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageUnreadCountVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageUnreadCountVO.java new file mode 100644 index 00000000..652a0f83 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/MessageUnreadCountVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +/** + * MessageUnreadCountVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageUnreadCountVO { + /** + * Field `unreadCount` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long unreadCount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/SystemMessageVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/SystemMessageVO.java new file mode 100644 index 00000000..9e35922d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/message/vo/SystemMessageVO.java @@ -0,0 +1,105 @@ +package com.xiaowang.fingertipdesigner.core.modules.message.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * SystemMessageVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + /** + * Field `imageUrl` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String imageUrl; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Purpose: businessType supports SystemMessageVO.java by holding or executing the business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String businessType; + /** + * Purpose: businessId supports SystemMessageVO.java by holding or executing the business id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long businessId; + /** + * Purpose: actionPath supports SystemMessageVO.java by holding or executing the action path business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String actionPath; + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminAfterSaleController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminAfterSaleController.java new file mode 100644 index 00000000..d1ce55ef --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminAfterSaleController.java @@ -0,0 +1,71 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleAuditDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.order.service.AfterSaleService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/after-sale") +@RequiredArgsConstructor +public class AdminAfterSaleController { + + private final AfterSaleService afterSaleService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping("/list") + @RequirePermission("after_sale:view") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) String status, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(afterSaleService.listAdmin(shopId, status, page, size)); + } + + @PutMapping("/{id}/approve") + @RequirePermission("after_sale:audit") + public Result approve(HttpServletRequest request, @PathVariable Long id, @RequestBody(required = false) AfterSaleAuditDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + AfterSaleVO result = afterSaleService.approve(currentUser.getId(), id, dto); + securityAuditSupport.success(request, SecurityAuditActions.AFTER_SALE_APPROVE, "afterSaleId=" + id); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.AFTER_SALE_APPROVE, "afterSaleId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/{id}/reject") + @RequirePermission("after_sale:audit") + public Result reject(HttpServletRequest request, @PathVariable Long id, @RequestBody(required = false) AfterSaleAuditDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + AfterSaleVO result = afterSaleService.reject(currentUser.getId(), id, dto); + securityAuditSupport.success(request, SecurityAuditActions.AFTER_SALE_REJECT, "afterSaleId=" + id); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.AFTER_SALE_REJECT, "afterSaleId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminOrderController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminOrderController.java new file mode 100644 index 00000000..40644182 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/admin/AdminOrderController.java @@ -0,0 +1,163 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 后台订单管理控制器 + */ +@RestController +@RequestMapping("/admin/order") +@RequiredArgsConstructor +public class AdminOrderController { + /** + * Variable `orderService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderService orderService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 获取订单列表(分页) + */ + @GetMapping("/list") + @RequirePermission("order:view") + public Result> listOrders( + HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Integer status + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + + List allOrders; + if (Integer.valueOf(3).equals(currentUser.getType())) { + allOrders = orderService.getOrdersByArtistId(currentUser.getId()); + } else { + allOrders = orderService.getAllOrders(); + } + if (scopedShopId != null && !Integer.valueOf(3).equals(currentUser.getType())) { + allOrders = allOrders.stream() + .filter(order -> scopedShopId.equals(order.getShopId())) + .toList(); + } + + if (keyword != null && !keyword.isEmpty()) { + allOrders = allOrders.stream() + .filter(order -> order.getOrderNo() != null && order.getOrderNo().contains(keyword)) + .toList(); + } + if (status != null) { + allOrders = allOrders.stream() + .filter(order -> order.getStatus() == status) + .toList(); + } + + int total = allOrders.size(); + int start = (page - 1) * size; + int end = Math.min(start + size, total); + List pageList = start < total ? allOrders.subList(start, end) : List.of(); + + PageResultVO result = new PageResultVO<>(); + result.setList(pageList); + result.setTotal((long) total); + result.setPage(page); + result.setSize(size); + + return Result.success(result); + } + + @GetMapping("/detail/{id}") + @RequirePermission("order:view") + /** + * Purpose: getOrderDetail supports AdminOrderController.java by holding or executing the get order detail business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result getOrderDetail(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List allOrders; + if (Integer.valueOf(3).equals(currentUser.getType())) { + allOrders = orderService.getOrdersByArtistId(currentUser.getId()); + } else { + allOrders = orderService.getAllOrders(); + } + OrderVO orderVO = allOrders.stream() + .filter(order -> id.equals(order.getId())) + .findFirst() + .orElseThrow(() -> new RuntimeException("订单不存在")); + if (!Integer.valueOf(3).equals(currentUser.getType())) { + adminScopeHelper.ensureShopAccessible(currentUser, orderVO.getShopId(), "无权查看其他店铺订单"); + } + return Result.success(orderVO); + } + + /** + * 更新订单状态 + */ + @PutMapping("/update-status/{id}") + @RequirePermission("order:process") + @OperationGuard(action = "admin-order-update-status", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result updateOrderStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (Integer.valueOf(3).equals(currentUser.getType())) { + if (!Integer.valueOf(2).equals(status)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师只能完成属于自己的订单"); + } + orderService.completeArtistOrder(id, currentUser.getId()); + return Result.success(true); + } + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + if (shopId != null) { + OrderVO orderVO = orderService.getAllOrders().stream() + .filter(order -> id.equals(order.getId())) + .findFirst() + .orElse(null); + if (orderVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, orderVO.getShopId(), "无权处理其他店铺订单"); + } + orderService.processOrder(id, status); + return Result.success(true); + } + + @PostMapping("/{id}/quote") + @RequirePermission("order:process") + @OperationGuard(action = "admin-order-quote-submit", ttlSeconds = 10, message = "报价处理中,请勿重复提交") + public Result submitQuote(HttpServletRequest request, + @PathVariable Long id, + @RequestBody OrderQuoteSubmitDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(orderService.submitShopQuote(id, currentUser.getId(), currentUser.getType(), dto)); + } + + @PutMapping("/{id}/quote/confirm") + @RequirePermission("order:process") + @OperationGuard(action = "admin-order-quote-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") + public Result confirmQuote(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(orderService.confirmShopQuote(id, currentUser.getId(), currentUser.getType())); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/AfterSaleController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/AfterSaleController.java new file mode 100644 index 00000000..1e4e7b4f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/AfterSaleController.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.service.AfterSaleService; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/after-sale") +@RequiredArgsConstructor +public class AfterSaleController { + + private final AfterSaleService afterSaleService; + + @PostMapping("/apply") + public Result apply(HttpServletRequest request, @RequestBody AfterSaleApplyDTO dto) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(afterSaleService.apply(userId, dto)); + } + + @GetMapping("/my") + public Result> listMy(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(afterSaleService.listMy(userId, page, size)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/CartController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/CartController.java new file mode 100644 index 00000000..bb4fb6aa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/CartController.java @@ -0,0 +1,116 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CartDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.service.CartService; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CartVO; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/cart") +/** + * CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class CartController { + + @Resource + /** + * Purpose: cartService supports CartController.java by holding or executing the cart service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartService cartService; + + @PostMapping("/add") + @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.addToCart(userId, cartDTO); + return Result.success(); + } + + @DeleteMapping("/remove/{productId}") + @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.removeFromCart(userId, productId); + return Result.success(); + } + + @PostMapping("/batch-remove") + @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartItemIds parameter `cartItemIds` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.batchRemoveFromCart(userId, cartItemIds); + return Result.success(); + } + + @PutMapping("/update") + @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.updateCartQuantity(userId, cartDTO); + return Result.success(); + } + + @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getCartList(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List cartList = cartService.getCartList(userId); + return Result.success(cartList); + } + + @DeleteMapping("/clear") + @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result clearCart(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + cartService.clearCart(userId); + return Result.success(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/OrderController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/OrderController.java new file mode 100644 index 00000000..c7692d35 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/controller/front/OrderController.java @@ -0,0 +1,459 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDate; +import java.util.Comparator; +import java.util.List; + +@RestController +@RequestMapping("/order") +/** + * OrderController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class OrderController { + + @Resource + /** + * Purpose: orderService supports OrderController.java by holding or executing the order service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderService orderService; + + @Resource + /** + * Purpose: userService supports OrderController.java by holding or executing the user service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserService userService; + + @Resource + /** + * Purpose: securityAuditSupport supports OrderController.java by holding or executing the security audit support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecurityAuditSupport securityAuditSupport; + + @PostMapping("/create") + @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + OrderVO orderVO = orderService.createOrder(userId, orderDTO); + return Result.success(orderVO); + } + + @PostMapping("/checkout-preview") + public Result checkoutPreview(@RequestBody CheckoutPreviewDTO checkoutPreviewDTO, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.checkoutPreview(userId, checkoutPreviewDTO)); + } + + @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getOrderList(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List orderList = orderService.getOrderList(userId); + return Result.success(orderList); + } + + @GetMapping("/detail/{orderId}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getOrderDetail(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + OrderVO orderVO = orderService.getOrderDetail(orderId, userId); + return Result.success(orderVO); + } + + @PutMapping("/cancel/{orderId}") + @OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击") + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + orderService.cancelOrder(orderId, userId); + return Result.success(); + } + + // 后台管理接口 + @PostMapping("/{orderId}/quote/reply") + @OperationGuard(action = "order-quote-reply", ttlSeconds = 10, message = "回复处理中,请勿重复提交") + public Result replyQuote(@PathVariable Long orderId, + @RequestBody(required = false) OrderQuoteReplyDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.replyQuote(orderId, userId, dto)); + } + + @PutMapping("/{orderId}/quote/confirm") + @OperationGuard(action = "order-quote-user-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") + public Result confirmUserQuote(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.confirmUserQuote(orderId, userId)); + } + + @RequirePermission("order:process") + @PostMapping("/{orderId}/quote/shop") + @OperationGuard(action = "order-shop-quote-submit", ttlSeconds = 10, message = "报价处理中,请勿重复提交") + public Result submitShopQuote(@PathVariable Long orderId, + @RequestBody OrderQuoteSubmitDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.submitShopQuote(orderId, userId, userType, dto)); + } + + @RequirePermission("order:process") + @PutMapping("/{orderId}/quote/shop/confirm") + @OperationGuard(action = "order-shop-quote-confirm", ttlSeconds = 10, message = "确认处理中,请勿重复提交") + public Result confirmShopQuote(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.confirmShopQuote(orderId, userId, userType)); + } + + @RequirePermission("order:view") + @GetMapping("/admin/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getAllOrders(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + List orderList; + if (Integer.valueOf(3).equals(userType)) { + orderList = orderService.getOrdersByArtistId(userId); + } else { + orderList = orderService.getAllOrders(); + } + if (!Integer.valueOf(4).equals(userType) && !Integer.valueOf(3).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定店铺"); + } + orderList = orderList.stream() + .filter(order -> currentUser.getShopId().equals(order.getShopId())) + .toList(); + } + return Result.success(orderList); + } + + @RequirePermission("order:process") + @PutMapping("/admin/process/{orderId}") + @OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (Integer.valueOf(3).equals(userType)) { + if (!Integer.valueOf(2).equals(status)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师只能完成属于自己的订单"); + } + try { + orderService.completeArtistOrder(orderId, userId); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } + if (!Integer.valueOf(4).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定店铺"); + } + OrderVO orderVO = orderService.getAllOrders().stream() + .filter(order -> orderId.equals(order.getId())) + .findFirst() + .orElse(null); + if (orderVO == null || !currentUser.getShopId().equals(orderVO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权处理其他店铺订单"); + } + } + try { + orderService.processOrder(orderId, status); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",reason=" + exception.getMessage()); + throw exception; + } + } + + // 美甲师查看自己的订单 + @RequirePermission("order:view") + @GetMapping("/artist/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getArtistOrders(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师可查看自己的订单"); + } + List orderList; + if (Integer.valueOf(2).equals(userType)) { + UserVO currentUser = userService.getUserById(userId); + if (currentUser == null || currentUser.getShopId() == null) { + throw new RuntimeException("当前账号未绑定店铺"); + } + orderList = orderService.getAllOrders().stream() + .filter(order -> currentUser.getShopId().equals(order.getShopId())) + .peek(order -> { + order.setArtistOrderSource("SHOP"); + order.setArtistOrderSourceText("本店美甲师订单"); + }) + .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } else { + orderList = orderService.getArtistWorkbenchOrders(userId); + } + return Result.success(orderList); + } + + @RequirePermission("order:view") + @GetMapping("/artist/calendar/recent") + // 调用示例:GET /order/artist/calendar/recent?days=7 + // 只返回当前登录美甲师/参与制作店长自己的预约,前端不用再做二次过滤。 + public Result getArtistCalendarRecent(@RequestParam(value = "days", required = false) Integer days, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarRecent(userId, userType, days)); + } + + @RequirePermission("order:view") + @GetMapping("/artist/calendar/day") + // 调用示例:GET /order/artist/calendar/day?date=2026-05-17 + // date 使用 yyyy-MM-dd,适合日历点选某一天后拉取详情。 + public Result getArtistCalendarDay(@RequestParam("date") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) + LocalDate date, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarDay(userId, userType, date)); + } + + @RequirePermission("order:process") + @PutMapping("/artist/complete/{orderId}") + @OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师可完成自己的订单"); + } + try { + orderService.completeArtistOrder(orderId, userId); + securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId); + return Result.success(); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/review/my-pending") + /** + * Purpose: listMyPendingReviews supports OrderController.java by holding or executing the list my pending reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listMyPendingReviews(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.listMyPendingReviews(userId)); + } + + @GetMapping("/{orderId}/reviews") + /** + * Purpose: listOrderReviews supports OrderController.java by holding or executing the list order reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listOrderReviews(@PathVariable Long orderId, HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listOrderReviews(orderId, userId, userType)); + } + + @PostMapping("/review/{reviewId}/submit") + @OperationGuard(action = "order-artist-review-submit", ttlSeconds = 15, message = "评价正在提交中,请勿重复操作") + public Result submitArtistReview(@PathVariable Long reviewId, + @RequestBody OrderArtistReviewSubmitDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.submitArtistReview(reviewId, userId, dto)); + } + + @RequirePermission("order:artist-change") + @GetMapping("/{orderId}/artist-change/options") + public Result getArtistChangeOptions(@PathVariable Long orderId, + @RequestParam Long orderItemId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistChangeOptions(orderId, orderItemId, userId, userType)); + } + + @RequirePermission("order:artist-change") + @PostMapping("/artist-change/request") + @OperationGuard(action = "order-artist-change-request", ttlSeconds = 15, message = "改派申请正在提交中,请勿重复操作") + public Result requestArtistChange(@RequestBody OrderArtistChangeRequestDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.requestArtistChange(userId, dto)); + } + + @GetMapping("/artist-change/my-pending") + /** + * Purpose: listMyPendingArtistChangeRequests supports OrderController.java by holding or executing the list my pending artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listMyPendingArtistChangeRequests(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType)); + } + + @GetMapping("/{orderId}/artist-change/requests") + /** + * Purpose: listOrderArtistChangeRequests returns pending and processed artist-change records for one order. + * Usage: call it from order pages to build a timeline after the caller has an authenticated session. + */ + public Result> listOrderArtistChangeRequests(@PathVariable Long orderId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.listOrderArtistChangeRequests(orderId, userId, userType)); + } + + @PutMapping("/artist-change/{requestId}/approve") + @OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") + public Result approveArtistChange(@PathVariable Long requestId, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + try { + OrderArtistChangeRequestVO result = orderService.approveArtistChange(requestId, userId, userType); + securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/artist-change/{requestId}/reject") + @OperationGuard(action = "order-artist-change-reject", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作") + public Result rejectArtistChange(@PathVariable Long requestId, + @RequestBody(required = false) OrderArtistChangeRejectDTO dto, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + try { + OrderArtistChangeRequestVO result = orderService.rejectArtistChange(requestId, userId, userType, dto); + securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleApplyDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleApplyDTO.java new file mode 100644 index 00000000..69965ce1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleApplyDTO.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class AfterSaleApplyDTO { + private Long orderId; + private Long orderItemId; + private String type; + private String reason; + private BigDecimal refundAmount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleAuditDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleAuditDTO.java new file mode 100644 index 00000000..6011b008 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/AfterSaleAuditDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +@Data +public class AfterSaleAuditDTO { + private String auditReason; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CartDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CartDTO.java new file mode 100644 index 00000000..780db2b8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CartDTO.java @@ -0,0 +1,24 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +/** + * 购物车 DTO + * 用于购物车商品信息的传输 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class CartDTO { + + /** + * 商品ID + */ + private Long productId; + + /** + * 商品数量 + */ + private Integer quantity; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CheckoutPreviewDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CheckoutPreviewDTO.java new file mode 100644 index 00000000..6c4eb8de --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/CheckoutPreviewDTO.java @@ -0,0 +1,28 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 结算预览请求,只做金额和优惠说明,不创建订单。 + */ +@Data +public class CheckoutPreviewDTO { + + /** + * 已选择的优惠选项ID:用户券传用户券ID,VIP自动券传券模板ID。 + */ + private Long couponId; + + /** + * 优惠来源:USER_COUPON、SYSTEM_VIP、NONE。 + */ + private String couponSourceType; + private String remark; + + /** + * 本次预览的商品列表。 + */ + private List items; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRejectDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRejectDTO.java new file mode 100644 index 00000000..9c006511 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRejectDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +@Data +/** + * Purpose: OrderArtistChangeRejectDTO supports OrderArtistChangeRejectDTO.java by holding or executing the order artist change reject dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRejectDTO { + /** + * Purpose: rejectReason supports OrderArtistChangeRejectDTO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRequestDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRequestDTO.java new file mode 100644 index 00000000..3e9dcf6c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistChangeRequestDTO.java @@ -0,0 +1,31 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +@Data +/** + * Purpose: OrderArtistChangeRequestDTO supports OrderArtistChangeRequestDTO.java by holding or executing the order artist change request dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestDTO { + /** + * Purpose: orderId supports OrderArtistChangeRequestDTO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeRequestDTO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: requestedArtistId supports OrderArtistChangeRequestDTO.java by holding or executing the requested artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requestedArtistId; + /** + * Purpose: reason supports OrderArtistChangeRequestDTO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistReviewSubmitDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistReviewSubmitDTO.java new file mode 100644 index 00000000..cdc00e32 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderArtistReviewSubmitDTO.java @@ -0,0 +1,29 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +/** + * Purpose: OrderArtistReviewSubmitDTO supports OrderArtistReviewSubmitDTO.java by holding or executing the order artist review submit dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewSubmitDTO { + /** + * Purpose: rating supports OrderArtistReviewSubmitDTO.java by holding or executing the rating business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal rating; + /** + * Purpose: content supports OrderArtistReviewSubmitDTO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + /** + * Purpose: imageFileIds supports OrderArtistReviewSubmitDTO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List imageFileIds; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderDTO.java new file mode 100644 index 00000000..a8357da7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderDTO.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 订单 DTO + * 用于订单创建请求 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class OrderDTO { + + /** + * 优惠券ID + */ + private Long couponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + private String remark; + private String clientRequestId; + + /** + * 订单商品列表 + */ + private List items; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderItemDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderItemDTO.java new file mode 100644 index 00000000..94bbe136 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderItemDTO.java @@ -0,0 +1,34 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +/** + * 订单商品项 DTO + * 用于订单中的单个商品信息 + * + * @author xiaowang + * @date 2026-03-12 + */ +@Data +public class OrderItemDTO { + + /** + * 商品ID + */ + private Long productId; + + /** + * 商品数量 + */ + private Integer quantity; + + /** + * 美甲师ID + */ + private Long artistId; + + /** + * 预约开始时间 + */ + private String appointmentTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteItemDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteItemDTO.java new file mode 100644 index 00000000..71ef9f67 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteItemDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OrderQuoteItemDTO { + private Long orderItemId; + private BigDecimal quotedPrice; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteReplyDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteReplyDTO.java new file mode 100644 index 00000000..7ee0b2f3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteReplyDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +@Data +public class OrderQuoteReplyDTO { + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteSubmitDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteSubmitDTO.java new file mode 100644 index 00000000..71bddf8a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/dto/OrderQuoteSubmitDTO.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.dto; + +import lombok.Data; + +import java.util.List; + +@Data +public class OrderQuoteSubmitDTO { + private String remark; + private List items; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleDO.java new file mode 100644 index 00000000..066a1b11 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleDO.java @@ -0,0 +1,46 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_after_sale") +public class AfterSaleDO extends BaseEntity { + @TableField("after_sale_no") + private String afterSaleNo; + @TableField("order_id") + private Long orderId; + @TableField("order_item_id") + private Long orderItemId; + @TableField("user_id") + private Long userId; + @TableField("shop_id") + private Long shopId; + @TableField("type") + private String type; + @TableField("reason") + private String reason; + @TableField("refund_amount") + private BigDecimal refundAmount; + @TableField("status") + private String status; + @TableField("audit_user_id") + private Long auditUserId; + @TableField("audit_reason") + private String auditReason; + @TableField("audit_time") + private LocalDateTime auditTime; + @TableField("refund_order_id") + private Long refundOrderId; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleLogDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleLogDO.java new file mode 100644 index 00000000..622353fb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/AfterSaleLogDO.java @@ -0,0 +1,27 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_after_sale_log") +public class AfterSaleLogDO extends BaseEntity { + @TableField("after_sale_id") + private Long afterSaleId; + @TableField("action") + private String action; + @TableField("from_status") + private String fromStatus; + @TableField("to_status") + private String toStatus; + @TableField("operator_id") + private Long operatorId; + @TableField("operator_type") + private String operatorType; + @TableField("remark") + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/CartDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/CartDO.java new file mode 100644 index 00000000..f184cea3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/CartDO.java @@ -0,0 +1,40 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@TableName("t_cart") +/** + * CartDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistChangeRequestDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistChangeRequestDO.java new file mode 100644 index 00000000..5eb8a4d1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistChangeRequestDO.java @@ -0,0 +1,138 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_artist_change_request") +/** + * Purpose: OrderArtistChangeRequestDO supports OrderArtistChangeRequestDO.java by holding or executing the order artist change request do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestDO extends BaseEntity { + + @TableField("order_id") + /** + * Purpose: orderId supports OrderArtistChangeRequestDO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + + @TableField("order_item_id") + /** + * Purpose: orderItemId supports OrderArtistChangeRequestDO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + + @TableField("product_id") + /** + * Purpose: productId supports OrderArtistChangeRequestDO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + + @TableField("shop_id") + /** + * Purpose: shopId supports OrderArtistChangeRequestDO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + + @TableField("customer_id") + /** + * Purpose: customerId supports OrderArtistChangeRequestDO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + + @TableField("from_artist_id") + /** + * Purpose: fromArtistId supports OrderArtistChangeRequestDO.java by holding or executing the from artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fromArtistId; + + @TableField("to_artist_id") + /** + * Purpose: toArtistId supports OrderArtistChangeRequestDO.java by holding or executing the to artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long toArtistId; + + @TableField("requester_id") + /** + * Purpose: requesterId supports OrderArtistChangeRequestDO.java by holding or executing the requester id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requesterId; + + @TableField("status") + /** + * Purpose: status supports OrderArtistChangeRequestDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + + @TableField("reason") + /** + * Purpose: reason supports OrderArtistChangeRequestDO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + + @TableField("reject_reason") + /** + * Purpose: rejectReason supports OrderArtistChangeRequestDO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; + + @TableField("message_id") + /** + * Purpose: messageId supports OrderArtistChangeRequestDO.java by holding or executing the message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long messageId; + + @TableField("pending_key") + /** + * Purpose: pendingKey supports OrderArtistChangeRequestDO.java by holding or executing the pending key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String pendingKey; + + @TableField("approved_time") + /** + * Purpose: approvedTime supports OrderArtistChangeRequestDO.java by holding or executing the approved time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime approvedTime; + + @TableField("rejected_time") + /** + * Purpose: rejectedTime supports OrderArtistChangeRequestDO.java by holding or executing the rejected time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime rejectedTime; + + @TableField("expire_time") + /** + * Purpose: expireTime supports OrderArtistChangeRequestDO.java by holding or executing the expire time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime expireTime; + + @TableField("is_delete") + /** + * Purpose: isDelete supports OrderArtistChangeRequestDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistReviewDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistReviewDO.java new file mode 100644 index 00000000..0ff86fc0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderArtistReviewDO.java @@ -0,0 +1,111 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_artist_review") +/** + * Purpose: OrderArtistReviewDO supports OrderArtistReviewDO.java by holding or executing the order artist review do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewDO extends BaseEntity { + + @TableField("order_id") + /** + * Purpose: orderId supports OrderArtistReviewDO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + + @TableField("order_item_id") + /** + * Purpose: orderItemId supports OrderArtistReviewDO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + + @TableField("product_id") + /** + * Purpose: productId supports OrderArtistReviewDO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + + @TableField("artist_id") + /** + * Purpose: artistId supports OrderArtistReviewDO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + + @TableField("shop_id") + /** + * Purpose: shopId supports OrderArtistReviewDO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + + @TableField("customer_id") + /** + * Purpose: customerId supports OrderArtistReviewDO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + + @TableField("status") + /** + * Purpose: status supports OrderArtistReviewDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + @TableField("rating_score") + /** + * Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal ratingScore; + + @TableField("content") + /** + * Purpose: content supports OrderArtistReviewDO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + @TableField("image_file_ids") + /** + * Purpose: imageFileIds supports OrderArtistReviewDO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String imageFileIds; + + @TableField("reminder_message_id") + /** + * Purpose: reminderMessageId supports OrderArtistReviewDO.java by holding or executing the reminder message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reminderMessageId; + + @TableField("submitted_at") + /** + * Purpose: submittedAt supports OrderArtistReviewDO.java by holding or executing the submitted at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submittedAt; + + @TableField("is_delete") + /** + * Purpose: isDelete supports OrderArtistReviewDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderDO.java new file mode 100644 index 00000000..79962242 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderDO.java @@ -0,0 +1,78 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@TableName("t_order") +/** + * OrderDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderDO extends BaseEntity { + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + private String paymentStatus; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private String paymentMethod; + private String paymentOrderNo; + private String refundStatus; + private String customerRemark; + private String quoteStatus; + private Integer quoteUserConfirmed; + private Integer quoteShopConfirmed; + private LocalDateTime quoteExpireTime; + private LocalDateTime quoteConfirmedTime; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderItemDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderItemDO.java new file mode 100644 index 00000000..78376ef0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderItemDO.java @@ -0,0 +1,60 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@TableName("t_order_item") +/** + * OrderItemDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderItemDO extends BaseEntity { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + + @TableField("appointment_time") + /** + * Field `appointmentTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentTime; + + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderQuoteMessageDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderQuoteMessageDO.java new file mode 100644 index 00000000..8c2e5b4b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/entity/OrderQuoteMessageDO.java @@ -0,0 +1,34 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_order_quote_message") +public class OrderQuoteMessageDO extends BaseEntity { + + @TableField("order_id") + private Long orderId; + + @TableField("actor_id") + private Long actorId; + + @TableField("actor_type") + private String actorType; + + @TableField("action") + private String action; + + @TableField("remark") + private String remark; + + @TableField("items_snapshot") + private String itemsSnapshot; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleLogMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleLogMapper.java new file mode 100644 index 00000000..1e58a2b8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleLogMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleLogDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AfterSaleLogMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleMapper.java new file mode 100644 index 00000000..36d6c583 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/AfterSaleMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface AfterSaleMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/CartMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/CartMapper.java new file mode 100644 index 00000000..bd1699a5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/CartMapper.java @@ -0,0 +1,39 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.CartDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +/** + * CartMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface CartMapper extends BaseMapper { + @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND is_delete = 0") + List selectByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND product_id = #{productId} AND is_delete = 0") + CartDO selectByUserIdAndProductId(@Param("userId") Long userId, @Param("productId") Long productId); + + @Select({ + "" + }) + List selectByUserIdAndProductIdsForUpdate( + @Param("userId") Long userId, + @Param("productIds") List productIds + ); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistChangeRequestMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistChangeRequestMapper.java new file mode 100644 index 00000000..0bf71723 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistChangeRequestMapper.java @@ -0,0 +1,47 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistChangeRequestDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDateTime; + +import java.util.List; + +@Mapper +/** + * Purpose: OrderArtistChangeRequestMapper supports OrderArtistChangeRequestMapper.java by holding or executing the order artist change request mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface OrderArtistChangeRequestMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_artist_change_request WHERE order_item_id = #{orderItemId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) LIMIT 1") + OrderArtistChangeRequestDO selectPendingByOrderItemId(@Param("orderItemId") Long orderItemId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE customer_id = #{userId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE (from_artist_id = #{artistId} OR to_artist_id = #{artistId} OR requester_id = #{artistId}) AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC") + List selectPendingByShopId(@Param("shopId") Long shopId); + + @Select("SELECT * FROM t_order_artist_change_request WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); + + @Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})") + int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime); + + @Update("UPDATE t_order_artist_change_request SET status = 'REJECTED', reject_reason = #{rejectReason}, rejected_time = #{rejectedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{rejectedTime})") + int rejectPending(@Param("id") Long id, @Param("rejectReason") String rejectReason, @Param("rejectedTime") LocalDateTime rejectedTime); + + @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") + int expirePendingById(@Param("id") Long id, @Param("now") LocalDateTime now); + + @Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}") + int expirePendingBefore(@Param("now") LocalDateTime now); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistReviewMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistReviewMapper.java new file mode 100644 index 00000000..615bba89 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderArtistReviewMapper.java @@ -0,0 +1,30 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.math.BigDecimal; +import java.util.List; + +@Mapper +/** + * Purpose: OrderArtistReviewMapper supports OrderArtistReviewMapper.java by holding or executing the order artist review mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface OrderArtistReviewMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_artist_review WHERE customer_id = #{userId} AND status = 0 AND is_delete = 0 ORDER BY create_time DESC, id DESC") + List selectPendingByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order_artist_review WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); + + @Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1") + OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId); + + @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0") + BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderItemMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderItemMapper.java new file mode 100644 index 00000000..cdae39de --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderItemMapper.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.time.LocalDateTime; +import java.util.List; + +@Mapper +/** + * OrderItemMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface OrderItemMapper extends BaseMapper { + @Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}") + List selectByOrderId(@Param("orderId") Long orderId); + + @Select("SELECT * FROM t_order_item WHERE id = #{id} FOR UPDATE") + OrderItemDO selectByIdForUpdate(@Param("id") Long id); + + @Select("SELECT oi.* FROM t_order_item oi " + + "INNER JOIN t_order o ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} " + + "AND oi.is_delete = 0 " + + "AND o.is_delete = 0 " + + "AND o.status = 1 " + + "AND oi.appointment_time IS NOT NULL") + List selectActiveAppointmentItemsByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT oi.* FROM t_order_item oi " + + "INNER JOIN t_order o ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} " + + "AND oi.is_delete = 0 " + + "AND o.is_delete = 0 " + + "AND o.status = 1 " + + "AND oi.appointment_time >= #{startTime} " + + "AND oi.appointment_time < #{endTime} " + + "ORDER BY oi.appointment_time ASC, oi.id ASC") + List selectArtistCalendarItems(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(DISTINCT oi.order_id) as count FROM t_order_item oi " + + "JOIN t_product p ON oi.product_id = p.id " + + "JOIN t_order o ON oi.order_id = o.id " + + "WHERE p.shop_id = #{shopId} AND o.create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND o.is_delete = 0") + java.util.Map countTodayOrdersByShopId(@Param("shopId") Long shopId, @Param("todayStart") String todayStart); + + @Select("SELECT COUNT(DISTINCT id) as count FROM t_order WHERE create_time >= STR_TO_DATE(#{todayStart}, '%Y-%m-%d %H:%i:%s') AND is_delete = 0") + java.util.Map countTodayOrders(@Param("todayStart") String todayStart); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderMapper.java new file mode 100644 index 00000000..5c2c0c13 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderMapper.java @@ -0,0 +1,34 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.util.List; + +@Mapper +/** + * OrderMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface OrderMapper extends BaseMapper { + @Select("SELECT * FROM t_order WHERE user_id = #{userId}") + List selectByUserId(@Param("userId") Long userId); + + @Select("SELECT * FROM t_order WHERE order_no = #{orderNo}") + OrderDO selectByOrderNo(@Param("orderNo") String orderNo); + + @Select("SELECT DISTINCT o.* FROM t_order o " + + "INNER JOIN t_order_item oi ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " + + "ORDER BY o.create_time DESC") + List selectByArtistId(@Param("artistId") Long artistId); + + @Update("UPDATE t_order SET status = #{toStatus} WHERE id = #{orderId} AND status = #{fromStatus} AND is_delete = 0") + int updateStatusIfCurrent(@Param("orderId") Long orderId, + @Param("fromStatus") Integer fromStatus, + @Param("toStatus") Integer toStatus); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderQuoteMessageMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderQuoteMessageMapper.java new file mode 100644 index 00000000..135aacee --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/mapper/OrderQuoteMessageMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderQuoteMessageDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +public interface OrderQuoteMessageMapper extends BaseMapper { + + @Select("SELECT * FROM t_order_quote_message WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC") + List selectByOrderId(@Param("orderId") Long orderId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/AfterSaleService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/AfterSaleService.java new file mode 100644 index 00000000..590eae29 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/AfterSaleService.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service; + +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleAuditDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; + +public interface AfterSaleService { + AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto); + + PageResultVO listMy(Long userId, Integer page, Integer size); + + PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size); + + AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); + + AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/CartService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/CartService.java new file mode 100644 index 00000000..604495c0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/CartService.java @@ -0,0 +1,54 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service; + +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CartDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CartVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * CartService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface CartService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + void addToCart(Long userId, CartDTO cartDTO); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + void removeFromCart(Long userId, Long productId); + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ + void batchRemoveFromCart(Long userId, List cartItemIds); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + void updateCartQuantity(Long userId, CartDTO cartDTO); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getCartList(Long userId); + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void clearCart(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/OrderService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/OrderService.java new file mode 100644 index 00000000..c4f81ff7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/OrderService.java @@ -0,0 +1,141 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service; + +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO; + +import java.time.LocalDate; +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * OrderService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface OrderService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + OrderVO createOrder(Long userId, OrderDTO orderDTO); + + /** + * Preview checkout pricing and coupon explanations without creating an order. + */ + CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getOrderList(Long userId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + OrderVO getOrderDetail(Long orderId, Long userId); + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ + void cancelOrder(Long orderId, Long userId); + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ + void processOrder(Long orderId, Integer status); + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ + void completeArtistOrder(Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + List getAllOrders(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getOrdersByArtistId(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistWorkbenchOrders(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarRecent(Long userId, Integer userType, Integer days); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarDay(Long userId, Integer userType, LocalDate date); + + List listMyPendingReviews(Long userId); + + List listOrderReviews(Long orderId, Long userId, Integer userType); + + OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto); + + OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType); + + OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto); + + List listMyPendingArtistChangeRequests(Long userId, Integer userType); + + List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType); + + OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType); + + OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto); + + OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto); + + OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType); + + OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto); + + OrderVO confirmUserQuote(Long orderId, Long userId); + + int expirePendingQuoteOrders(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/AfterSaleServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/AfterSaleServiceImpl.java new file mode 100644 index 00000000..c4e73ec3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/AfterSaleServiceImpl.java @@ -0,0 +1,172 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleApplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.AfterSaleAuditDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.AfterSaleLogDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleLogMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.AfterSaleMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.service.AfterSaleService; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.AfterSaleVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +public class AfterSaleServiceImpl implements AfterSaleService { + + private static final String STATUS_PENDING = "PENDING"; + private static final String STATUS_APPROVED = "APPROVED"; + private static final String STATUS_REJECTED = "REJECTED"; + + private final AfterSaleMapper afterSaleMapper; + private final AfterSaleLogMapper afterSaleLogMapper; + private final OrderMapper orderMapper; + private final SystemMessageMapper systemMessageMapper; + + @Override + @Transactional + public AfterSaleVO apply(Long userId, AfterSaleApplyDTO dto) { + if (dto == null || dto.getOrderId() == null) { + throw new RuntimeException("售后订单信息不完整"); + } + OrderDO order = orderMapper.selectById(dto.getOrderId()); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + throw new RuntimeException("无权申请该订单售后"); + } + if (Integer.valueOf(0).equals(order.getStatus())) { + throw new RuntimeException("询价预约确认价格前暂不能申请售后"); + } + AfterSaleDO afterSale = new AfterSaleDO(); + afterSale.setAfterSaleNo("AS" + System.currentTimeMillis() + dto.getOrderId()); + afterSale.setOrderId(order.getId()); + afterSale.setOrderItemId(dto.getOrderItemId()); + afterSale.setUserId(userId); + afterSale.setShopId(order.getShopId()); + afterSale.setType(dto.getType()); + afterSale.setReason(dto.getReason()); + afterSale.setRefundAmount(dto.getRefundAmount()); + afterSale.setStatus(STATUS_PENDING); + afterSale.setIsDelete(0); + afterSaleMapper.insert(afterSale); + writeLog(afterSale.getId(), "CREATE", null, STATUS_PENDING, userId, "USER", dto.getReason()); + return toVO(afterSale); + } + + @Override + public PageResultVO listMy(Long userId, Integer page, Integer size) { + return pageByWrapper(new LambdaQueryWrapper() + .eq(AfterSaleDO::getUserId, userId) + .eq(AfterSaleDO::getIsDelete, 0) + .orderByDesc(AfterSaleDO::getCreateTime), page, size); + } + + @Override + public PageResultVO listAdmin(Long shopId, String status, Integer page, Integer size) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(AfterSaleDO::getIsDelete, 0) + .orderByDesc(AfterSaleDO::getCreateTime); + if (shopId != null) { + wrapper.eq(AfterSaleDO::getShopId, shopId); + } + if (status != null && !status.isBlank()) { + wrapper.eq(AfterSaleDO::getStatus, status); + } + return pageByWrapper(wrapper, page, size); + } + + @Override + @Transactional + public AfterSaleVO approve(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { + return audit(operatorId, afterSaleId, dto, STATUS_APPROVED, "APPROVE"); + } + + @Override + @Transactional + public AfterSaleVO reject(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto) { + return audit(operatorId, afterSaleId, dto, STATUS_REJECTED, "REJECT"); + } + + private AfterSaleVO audit(Long operatorId, Long afterSaleId, AfterSaleAuditDTO dto, String targetStatus, String action) { + AfterSaleDO afterSale = afterSaleMapper.selectById(afterSaleId); + if (afterSale == null || Integer.valueOf(1).equals(afterSale.getIsDelete())) { + throw new RuntimeException("售后单不存在"); + } + if (!STATUS_PENDING.equals(afterSale.getStatus())) { + throw new RuntimeException("售后单已处理"); + } + String fromStatus = afterSale.getStatus(); + afterSale.setStatus(targetStatus); + afterSale.setAuditUserId(operatorId); + afterSale.setAuditReason(dto == null ? null : dto.getAuditReason()); + afterSale.setAuditTime(LocalDateTime.now()); + afterSaleMapper.updateById(afterSale); + writeLog(afterSale.getId(), action, fromStatus, targetStatus, operatorId, "ADMIN", afterSale.getAuditReason()); + notifyCustomer(afterSale, targetStatus); + return toVO(afterSale); + } + + private void writeLog(Long afterSaleId, String action, String fromStatus, String toStatus, + Long operatorId, String operatorType, String remark) { + AfterSaleLogDO log = new AfterSaleLogDO(); + log.setAfterSaleId(afterSaleId); + log.setAction(action); + log.setFromStatus(fromStatus); + log.setToStatus(toStatus); + log.setOperatorId(operatorId); + log.setOperatorType(operatorType); + log.setRemark(remark); + afterSaleLogMapper.insert(log); + } + + private void notifyCustomer(AfterSaleDO afterSale, String status) { + SystemMessageDO message = new SystemMessageDO(); + message.setTitle("售后处理进度更新"); + message.setContent("您的售后申请已更新为:" + status); + message.setTargetType("SELECTED_USERS"); + message.setTargetIds(String.valueOf(afterSale.getUserId())); + message.setBusinessType("AFTER_SALE_" + status); + message.setBusinessId(afterSale.getId()); + message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId()); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + } + + private PageResultVO pageByWrapper(LambdaQueryWrapper wrapper, Integer page, Integer size) { + int current = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 10 : size; + Page result = afterSaleMapper.selectPage(new Page<>(current, pageSize), wrapper); + PageResultVO vo = new PageResultVO<>(); + List list = result.getRecords().stream().map(this::toVO).toList(); + vo.setList(list); + vo.setTotal(result.getTotal()); + vo.setPage(current); + vo.setSize(pageSize); + return vo; + } + + private AfterSaleVO toVO(AfterSaleDO afterSale) { + AfterSaleVO vo = new AfterSaleVO(); + BeanUtils.copyProperties(afterSale, vo); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/CartServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/CartServiceImpl.java new file mode 100644 index 00000000..3e25fec3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/CartServiceImpl.java @@ -0,0 +1,362 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CartDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.CartDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.CartMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.service.CartService; +import com.xiaowang.fingertipdesigner.core.modules.product.service.TagService; +import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CartArtistVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CartVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +/** + * CartServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class CartServiceImpl implements CartService { + + @Resource + /** + * Purpose: cartMapper supports CartServiceImpl.java by holding or executing the cart mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartMapper cartMapper; + + @Resource + /** + * Purpose: productMapper supports CartServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Resource + /** + * Purpose: tagService supports CartServiceImpl.java by holding or executing the tag service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TagService tagService; + + @Resource + /** + * Purpose: userMapper supports CartServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Resource + /** + * Purpose: userShopBindingSupport supports CartServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Resource + /** + * Purpose: bookableArtistSupport supports CartServiceImpl.java by holding or executing the bookable artist support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BookableArtistSupport bookableArtistSupport; + + @Resource + /** + * Purpose: objectStorageUrlSupport supports CartServiceImpl.java by holding or executing the object storage url support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + public void addToCart(Long userId, CartDTO cartDTO) { + validateQuantity(cartDTO.getQuantity()); + + ProductDO product = productMapper.selectById(cartDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品不存在"); + } + + CartDO existingCart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); + if (existingCart != null) { + existingCart.setQuantity(existingCart.getQuantity() + cartDTO.getQuantity()); + cartMapper.updateById(existingCart); + return; + } + + CartDO newCart = new CartDO(); + newCart.setUserId(userId); + newCart.setProductId(cartDTO.getProductId()); + newCart.setQuantity(cartDTO.getQuantity()); + newCart.setIsDelete(0); + cartMapper.insert(newCart); + } + + @Override + @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ + public void removeFromCart(Long userId, Long productId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .eq("product_id", productId) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + @Override + @Transactional + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ + public void batchRemoveFromCart(Long userId, List cartItemIds) { + if (cartItemIds == null || cartItemIds.isEmpty()) { + return; + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .in("id", cartItemIds) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + @Override + @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ + public void updateCartQuantity(Long userId, CartDTO cartDTO) { + validateQuantity(cartDTO.getQuantity()); + CartDO cart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); + if (cart != null) { + cart.setQuantity(cartDTO.getQuantity()); + cartMapper.updateById(cart); + return; + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车商品不存在"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getCartList(Long userId) { + List cartList = cartMapper.selectByUserId(userId); + List cartVOList = new ArrayList<>(); + + for (CartDO cart : cartList) { + if (!Integer.valueOf(0).equals(cart.getIsDelete())) { + continue; + } + + ProductDO product = productMapper.selectById(cart.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + continue; + } + + CartVO cartVO = new CartVO(); + cartVO.setId(cart.getId()); + cartVO.setProductId(product.getId()); + cartVO.setShopId(product.getShopId()); + cartVO.setProductTitle(product.getTitle()); + + String imageFileIds = product.getImageFileIds(); + if (StringUtils.hasText(imageFileIds)) { + String firstImageId = imageFileIds.split(",")[0]; + cartVO.setProductImage("/api/file/get/" + firstImageId); + } + + cartVO.setPrice(product.getPrice()); + cartVO.setQuantity(cart.getQuantity()); + cartVO.setTotalPrice(product.getPrice().multiply(new BigDecimal(cart.getQuantity()))); + cartVO.setTags(product.getTags()); + cartVO.setTagNames(resolveTagNames(product.getTags())); + cartVO.setApproximateDuration(product.getApproximateDuration()); + + String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(product.getShopId(), product.getBookableArtists()); + List availableArtists = resolveAvailableArtists(product.getShopId(), product.getBookableArtists(), validBookableArtists); + cartVO.setBookableArtists(validBookableArtists); + cartVO.setAvailableBookableArtistCount(availableArtists.size()); + cartVO.setBookableArtistRestricted(StringUtils.hasText(product.getBookableArtists())); + cartVO.setAvailableArtists(availableArtists); + + cartVOList.add(cartVO); + } + + return cartVOList; + } + + @Override + @Transactional + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void clearCart(Long userId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId) + .eq("is_delete", 0); + cartMapper.delete(wrapper); + } + + /** + * Run business method `validateQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateQuantity(Integer quantity) { + if (quantity == null || quantity < 1 || quantity > 99) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车数量必须在 1 到 99 之间"); + } + } + + /** + * Run business method `resolveTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveTagNames(String tagIds) { + if (!StringUtils.hasText(tagIds)) { + return ""; + } + + return List.of(tagIds.split(";")).stream() + .map(String::trim) + .filter(tagId -> !tagId.isEmpty()) + .map(tagId -> { + try { + TagVO tagVO = tagService.getTagById(Long.parseLong(tagId)); + return tagVO != null ? tagVO.getTagName() : null; + } catch (NumberFormatException ex) { + return null; + } + }) + .filter(tagName -> tagName != null && !tagName.isBlank()) + .collect(Collectors.joining(",")); + } + + /** + * Run business method `resolveAvailableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param validBookableArtists parameter `validBookableArtists` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAvailableArtists(Long shopId, String rawBookableArtists, String validBookableArtists) { + LinkedHashSet candidateArtistIds = new LinkedHashSet<>(); + if (StringUtils.hasText(validBookableArtists)) { + for (String artistIdText : validBookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdText)) { + continue; + } + try { + candidateArtistIds.add(Long.parseLong(artistIdText.trim())); + } catch (NumberFormatException ignored) { + // Ignore invalid ids and keep valid artists only. + } + } + } else if (!StringUtils.hasText(rawBookableArtists) && shopId != null && shopId > 0) { + candidateArtistIds.addAll(userShopBindingSupport.listUserIdsByShopId(shopId, true)); + } + + if (candidateArtistIds.isEmpty()) { + return List.of(); + } + + List artistUsers = userMapper.selectList( + new QueryWrapper() + .in("id", candidateArtistIds) + .in("type", List.of(2, 3)) + .eq("status", 1) + .eq("is_delete", 0) + ); + if (artistUsers.isEmpty()) { + return List.of(); + } + + Map artistMap = artistUsers.stream() + .collect(Collectors.toMap(UserDO::getId, artist -> artist, (left, right) -> left)); + + return candidateArtistIds.stream() + .map(artistMap::get) + .filter(Objects::nonNull) + .filter(bookableArtistSupport::isBookableServiceUser) + .map(this::buildCartArtist) + .collect(Collectors.toList()); + } + + /** + * Run business method `buildCartArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artist parameter `artist` supplied by the caller + * @return private CartArtistVO result consumed by the caller or returned to the frontend + */ + private CartArtistVO buildCartArtist(UserDO artist) { + CartArtistVO cartArtistVO = new CartArtistVO(); + cartArtistVO.setId(artist.getId()); + cartArtistVO.setName(artist.getNickname()); + cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + cartArtistVO.setUserType(artist.getType()); + cartArtistVO.setRoleLabel(Integer.valueOf(2).equals(artist.getType()) ? "店长 · 参与制作" : "美甲师"); + cartArtistVO.setParticipateProduction(Integer.valueOf(2).equals(artist.getType())); + return cartArtistVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/OrderServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..71b3256e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/service/impl/OrderServiceImpl.java @@ -0,0 +1,4640 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.common.BusinessException; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.CheckoutPreviewDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRejectDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistChangeRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderArtistReviewSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderItemDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteItemDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteReplyDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.OrderQuoteSubmitDTO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.CartDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistChangeRequestDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderQuoteMessageDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.UserCouponDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.CartMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistChangeRequestMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderQuoteMessageMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.BusinessEventOutboxService; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService; +import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService; +import com.xiaowang.fingertipdesigner.core.modules.product.service.TagService; +import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStateMachine; +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistCalendarAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutCouponPreviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.CheckoutPreviewVO.CheckoutIssueVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeOptionsVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistChangeRequestVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderArtistReviewVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderItemVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderQuoteItemVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderQuoteMessageVO; +import com.xiaowang.fingertipdesigner.core.modules.order.vo.OrderVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.vo.UserCouponVO; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import javax.annotation.PreDestroy; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +/** + * OrderServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class OrderServiceImpl implements OrderService { + + private static final DateTimeFormatter ORDER_NO_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + private static final DateTimeFormatter APPOINTMENT_OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + /** + * Purpose: COUPON_SOURCE_NONE supports OrderServiceImpl.java by holding or executing the coupon source none business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_NONE = "NONE"; + /** + * Purpose: COUPON_SOURCE_USER supports OrderServiceImpl.java by holding or executing the coupon source user business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_USER = "USER_COUPON"; + /** + * Purpose: COUPON_SOURCE_SYSTEM_VIP supports OrderServiceImpl.java by holding or executing the coupon source system vip business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP"; + private static final int BOOKING_UNAVAILABLE_CODE = 409; + private static final String ISSUE_ORDER_ITEM = "ORDER_ITEM"; + private static final String ISSUE_PRODUCT_UNAVAILABLE = "PRODUCT_UNAVAILABLE"; + private static final String ISSUE_SHOP_MISMATCH = "SHOP_MISMATCH"; + private static final String ISSUE_ARTIST_UNAVAILABLE = "ARTIST_UNAVAILABLE"; + private static final String ISSUE_ARTIST_MISMATCH = "ARTIST_MISMATCH"; + private static final String ISSUE_APPOINTMENT_TIME = "APPOINTMENT_TIME"; + private static final String ISSUE_BUSINESS_HOURS = "BUSINESS_HOURS"; + private static final String ISSUE_ORDER_CONFLICT = "ORDER_CONFLICT"; + private static final String ISSUE_EXISTING_CONFLICT = "EXISTING_CONFLICT"; + private static final String QUOTE_STATUS_CONFIRMING = "CONFIRMING"; + private static final String QUOTE_STATUS_CONFIRMED = "CONFIRMED"; + private static final String QUOTE_STATUS_EXPIRED = "EXPIRED"; + private static final String QUOTE_ACTOR_USER = "USER"; + private static final String QUOTE_ACTOR_SHOP = "SHOP"; + private static final String QUOTE_ACTOR_SYSTEM = "SYSTEM"; + private static final String QUOTE_ACTION_CREATE = "CREATE"; + private static final String QUOTE_ACTION_SHOP_QUOTE = "SHOP_QUOTE"; + private static final String QUOTE_ACTION_USER_REPLY = "USER_REPLY"; + private static final String QUOTE_ACTION_USER_CONFIRM = "USER_CONFIRM"; + private static final String QUOTE_ACTION_SHOP_CONFIRM = "SHOP_CONFIRM"; + private static final String QUOTE_ACTION_SYSTEM_CONFIRM = "SYSTEM_CONFIRM"; + private static final String QUOTE_ACTION_SYSTEM_EXPIRE = "SYSTEM_EXPIRE"; + private static final String QUOTE_BUSINESS_TYPE = "ORDER_QUOTE"; + private static final int USER_TYPE_SHOP_OWNER = 2; + private static final int QUOTE_EXPIRE_HOURS = 24; + /** + * Purpose: REVIEW_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the review status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int REVIEW_STATUS_PENDING = 0; + /** + * Purpose: REVIEW_STATUS_SUBMITTED supports OrderServiceImpl.java by holding or executing the review status submitted business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int REVIEW_STATUS_SUBMITTED = 1; + /** + * Purpose: CHANGE_STATUS_PENDING supports OrderServiceImpl.java by holding or executing the change status pending business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_PENDING = "PENDING"; + /** + * Purpose: CHANGE_STATUS_APPROVED supports OrderServiceImpl.java by holding or executing the change status approved business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_APPROVED = "APPROVED"; + /** + * Purpose: CHANGE_STATUS_REJECTED supports OrderServiceImpl.java by holding or executing the change status rejected business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_REJECTED = "REJECTED"; + /** + * Purpose: CHANGE_STATUS_EXPIRED supports OrderServiceImpl.java by holding or executing the change status expired business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_STATUS_EXPIRED = "EXPIRED"; + /** + * Purpose: ARTIST_CHANGE_PENDING_KEY_PREFIX supports OrderServiceImpl.java by holding or executing the artist change pending key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ARTIST_CHANGE_PENDING_KEY_PREFIX = "ORDER_ITEM:"; + /** + * Purpose: MESSAGE_TARGET_SELECTED_USERS supports OrderServiceImpl.java by holding or executing the message target selected users business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String MESSAGE_TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Purpose: REVIEW_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the review business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String REVIEW_BUSINESS_TYPE = "ORDER_ARTIST_REVIEW"; + /** + * Purpose: CHANGE_BUSINESS_TYPE supports OrderServiceImpl.java by holding or executing the change business type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String CHANGE_BUSINESS_TYPE = "ORDER_ARTIST_CHANGE"; + /** + * Purpose: ORDER_CREATE_USER_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create user lock prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:"; + /** + * Purpose: ORDER_CREATE_ARTIST_LOCK_PREFIX supports OrderServiceImpl.java by holding or executing the order create artist lock prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:"; + private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15); + private static final long ORDER_CREATE_LOCK_TTL_MILLIS = ORDER_CREATE_LOCK_TTL.toMillis(); + /** + * Purpose: ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the order create lock renew interval millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS = 5000L; + /** + * Purpose: ARTIST_LOCK_RETRY_INTERVAL_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock retry interval millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ARTIST_LOCK_RETRY_INTERVAL_MILLIS = 150L; + /** + * Purpose: ARTIST_LOCK_WAIT_TIMEOUT_MILLIS supports OrderServiceImpl.java by holding or executing the artist lock wait timeout millis business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long ARTIST_LOCK_WAIT_TIMEOUT_MILLIS = 1500L; + private static final List APPOINTMENT_INPUT_FORMATTERS = Arrays.asList( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"), + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm") + ); + private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); + private static final Pattern BUSINESS_HOURS_PATTERN = Pattern.compile("^(\\d{1,2}:\\d{2})\\s*[-~至]\\s*(\\d{1,2}:\\d{2})$"); + /** + * Purpose: DEFAULT_SERVICE_DURATION_MINUTES supports OrderServiceImpl.java by holding or executing the default service duration minutes business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; + private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); + private static final DefaultRedisScript RENEW_LOCK_SCRIPT = new DefaultRedisScript<>(); + private static final ScheduledExecutorService LOCK_RENEW_EXECUTOR = Executors.newSingleThreadScheduledExecutor(new LockRenewThreadFactory()); + + static { + RELEASE_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else return 0 end" + ); + RELEASE_LOCK_SCRIPT.setResultType(Long.class); + + RENEW_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('pexpire', KEYS[1], ARGV[2]) " + + "else return 0 end" + ); + RENEW_LOCK_SCRIPT.setResultType(Long.class); + } + + @Resource + /** + * Purpose: orderMapper supports OrderServiceImpl.java by holding or executing the order mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderMapper orderMapper; + + @Resource + /** + * Purpose: orderItemMapper supports OrderServiceImpl.java by holding or executing the order item mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemMapper orderItemMapper; + + @Resource + /** + * Purpose: orderArtistReviewMapper supports OrderServiceImpl.java by holding or executing the order artist review mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewMapper orderArtistReviewMapper; + + @Resource + /** + * Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + + @Resource + private OrderQuoteMessageMapper orderQuoteMessageMapper; + + @Resource + /** + * Purpose: cartMapper supports OrderServiceImpl.java by holding or executing the cart mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CartMapper cartMapper; + + @Resource + /** + * Purpose: productMapper supports OrderServiceImpl.java by holding or executing the product mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductMapper productMapper; + + @Resource + /** + * Purpose: couponMapper supports OrderServiceImpl.java by holding or executing the coupon mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CouponMapper couponMapper; + + @Resource + /** + * Purpose: nailArtistInfoMapper supports OrderServiceImpl.java by holding or executing the nail artist info mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoMapper nailArtistInfoMapper; + + @Resource + /** + * Purpose: userCouponMapper supports OrderServiceImpl.java by holding or executing the user coupon mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserCouponMapper userCouponMapper; + + @Resource + /** + * Purpose: userMapper supports OrderServiceImpl.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserMapper userMapper; + + @Resource + /** + * Purpose: shopMapper supports OrderServiceImpl.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ShopMapper shopMapper; + + @Resource + /** + * Purpose: systemMessageMapper supports OrderServiceImpl.java by holding or executing the system message mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private SystemMessageMapper systemMessageMapper; + + @Resource + /** + * Purpose: couponService supports OrderServiceImpl.java by holding or executing the coupon service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private CouponService couponService; + + @Resource + /** + * Purpose: tagService supports OrderServiceImpl.java by holding or executing the tag service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TagService tagService; + + @Resource + /** + * Purpose: userShopBindingSupport supports OrderServiceImpl.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private UserShopBindingSupport userShopBindingSupport; + + @Resource + /** + * Purpose: bookableArtistSupport supports OrderServiceImpl.java by holding or executing the bookable artist support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BookableArtistSupport bookableArtistSupport; + + @Resource + /** + * Purpose: businessEventOutboxService supports OrderServiceImpl.java by holding or executing the business event outbox service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BusinessEventOutboxService businessEventOutboxService; + + @Resource + /** + * Purpose: snowflakeIdGenerator supports OrderServiceImpl.java by holding or executing the snowflake id generator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Resource + /** + * Purpose: stringRedisTemplate supports OrderServiceImpl.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private StringRedisTemplate stringRedisTemplate; + + @Resource + /** + * Purpose: objectStorageUrlSupport supports OrderServiceImpl.java by holding or executing the object storage url support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private ObjectStorageUrlSupport objectStorageUrlSupport; + + @Resource + /** + * Purpose: transactionTemplate supports OrderServiceImpl.java by holding or executing the transaction template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private TransactionTemplate transactionTemplate; + + @Resource + private AppointmentCapacityService appointmentCapacityService; + + @Resource + private AppointmentReservationMapper appointmentReservationMapper; + + @PreDestroy + /** + * Run business method `shutdownOrderLockRenewExecutor`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ + public void shutdownOrderLockRenewExecutor() { + LOCK_RENEW_EXECUTOR.shutdownNow(); + } + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + public OrderVO createOrder(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("订单项不能为空"); + } + + String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId; + String userLockToken = UUID.randomUUID().toString(); + if (!tryAcquireOrderLock(userLockKey, userLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单正在提交中,请勿重复点击"); + } + + LockLease userLockLease = startOrderLockRenewal(userLockKey, userLockToken); + + String artistLockKey = null; + String artistLockToken = null; + LockLease artistLockLease = null; + try { + Long artistId; + try { + artistId = resolveRequestedArtistId(orderDTO.getItems()); + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId; + artistLockToken = UUID.randomUUID().toString(); + if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("当前美甲师预约繁忙,请稍后再试"); + } + + artistLockLease = startOrderLockRenewal(artistLockKey, artistLockToken); + + OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO)); + if (orderVO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单创建失败,请稍后重试"); + } + notifyQuoteCreated(orderVO); + return orderVO; + } finally { + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockLease parameter `artistLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + stopOrderLockRenewal(artistLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockKey parameter `artistLockKey` supplied by the caller + * @param artistLockToken parameter `artistLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + releaseOrderLock(artistLockKey, artistLockToken); + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockLease parameter `userLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + stopOrderLockRenewal(userLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockKey parameter `userLockKey` supplied by the caller + * @param userLockToken parameter `userLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + releaseOrderLock(userLockKey, userLockToken); + } + } + + @Override + public CheckoutPreviewVO checkoutPreview(Long userId, CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = toOrderDTO(checkoutPreviewDTO); + CheckoutPricingContext pricingContext = buildCheckoutPricingContext(userId, orderDTO); + List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); + List availableCouponOptions = couponService.getAvailableCoupons( + userId, + pricingContext.getProductTagNames(), + pricingContext.getTotalAmount().doubleValue(), + pricingContext.getShopId() + ); + if (availableCouponOptions == null) { + availableCouponOptions = List.of(); + } + + List availableCoupons = availableCouponOptions.stream() + .map(coupon -> buildAvailableCouponPreview(coupon, pricingContext.getTotalAmount())) + .sorted(Comparator.comparing(CheckoutCouponPreviewVO::getDiscountAmount, Comparator.nullsLast(BigDecimal::compareTo)).reversed() + .thenComparing(CheckoutCouponPreviewVO::getEndTime, Comparator.nullsLast(LocalDateTime::compareTo))) + .toList(); + + CheckoutCouponPreviewVO bestCoupon = findBestCouponPreview(availableCoupons); + if (bestCoupon != null) { + bestCoupon.setBest(true); + } + + CheckoutCouponPreviewVO selectedCoupon = resolvePreviewSelectedCoupon(checkoutPreviewDTO, availableCoupons, bestCoupon); + BigDecimal savedAmount = selectedCoupon == null ? BigDecimal.ZERO : safeAmount(selectedCoupon.getDiscountAmount()); + BigDecimal payableAmount = pricingContext.getTotalAmount().subtract(savedAmount); + if (payableAmount.compareTo(BigDecimal.ZERO) < 0) { + payableAmount = BigDecimal.ZERO; + } + + CheckoutPreviewVO preview = new CheckoutPreviewVO(); + preview.setSubtotalAmount(scaleMoney(pricingContext.getTotalAmount())); + preview.setSavedAmount(scaleMoney(savedAmount)); + preview.setPayableAmount(scaleMoney(payableAmount)); + preview.setBestCoupon(bestCoupon); + preview.setAvailableCoupons(availableCoupons); + preview.setUnavailableCoupons(buildUnavailableCouponPreviews(availableCoupons, pricingContext)); + preview.setBookingAvailable(bookingIssues.isEmpty()); + preview.setBookingIssues(bookingIssues); + preview.setVipTip(buildVipTip(userId, pricingContext.getTotalAmount(), availableCoupons)); + preview.setSummaryText(buildCheckoutSummaryText(preview)); + return preview; + } + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("订单项不能为空"); + } + + List bookingIssues = collectCheckoutBookingIssues(userId, orderDTO); + if (!bookingIssues.isEmpty()) { + throw bookingUnavailable(bookingIssues.get(0).getMessage()); + } + + List orderItemDTOs = orderDTO.getItems(); + BigDecimal totalAmount = BigDecimal.ZERO; + List orderItems = new ArrayList<>(); + List requestedSlots = new ArrayList<>(); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + Set selectedTagNames = new LinkedHashSet<>(); + Long shopId = null; + Long selectedArtistId = null; + Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); + List requestedProductIds = new ArrayList<>(requestedQuantityByProductId.keySet()); + Map lockedCartItemMap = loadLockedCartItems(userId, requestedProductIds); + + try { + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + validateOrderQuantity(orderItemDTO.getQuantity()); + + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("商品不存在或已下架"); + } + productCache.put(product.getId(), product); + + CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId()); + if (cartItem == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先将商品加入购物车后再结算"); + } + Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId()); + if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); + } + + UserDO artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); + + if (shopId == null) { + shopId = product.getShopId(); + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateUserCanCreateOrderInShop(userId, shopId); + } else if (!shopId.equals(product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("跨店铺商品请分开下单"); + } + + if (selectedArtistId == null) { + selectedArtistId = artist.getId(); + } else if (!selectedArtistId.equals(artist.getId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw bookingUnavailable("不同美甲师的项目请分开下单"); + } + + LocalDateTime appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); + validateAppointmentTime(appointmentTime, product.getTitle()); + + long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); + LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); + validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); + requestedSlots.add(new AppointmentSlot(product.getTitle(), appointmentTime, appointmentEndTime)); + + collectTagNames(selectedTagNames, product.getTags()); + + BigDecimal itemTotal = product.getPrice().multiply(BigDecimal.valueOf(orderItemDTO.getQuantity())); + totalAmount = totalAmount.add(itemTotal); + + OrderItemDO orderItem = new OrderItemDO(); + orderItem.setProductId(product.getId()); + orderItem.setQuantity(orderItemDTO.getQuantity()); + orderItem.setPrice(product.getPrice()); + orderItem.setReferencePrice(product.getPrice()); + orderItem.setArtistId(orderItemDTO.getArtistId()); + orderItem.setAppointmentTime(appointmentTime); + orderItems.add(orderItem); + } + + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateRequestedSlotConflicts(requestedSlots); + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param selectedArtistId parameter `selectedArtistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateArtistScheduleConflicts(selectedArtistId, requestedSlots, productCache); + } catch (BusinessException exception) { + throw exception; + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + + if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单金额无效"); + } + + String productTagNames = String.join(",", selectedTagNames); + List availableCouponOptions = couponService.getAvailableCoupons( + userId, + productTagNames, + totalAmount.doubleValue(), + shopId + ); + + BigDecimal actualAmount = totalAmount; + Long couponId = null; + Long userCouponId = null; + String couponSourceType = null; + + CouponSelection couponSelection = resolveRequestedCoupon(orderDTO, availableCouponOptions); + if (couponSelection == null && !isExplicitNoCoupon(orderDTO)) { + couponSelection = selectBestAvailableCoupon(availableCouponOptions, totalAmount); + } + + if (couponSelection != null) { + CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); + if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete()) || coupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不存在或已失效"); + } + if (shopId != null && coupon.getShopId() != null && !shopId.equals(coupon.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该优惠券不适用于当前店铺"); + } + + actualAmount = applyCouponDiscount(totalAmount, coupon); + couponId = coupon.getId(); + userCouponId = couponSelection.getUserCouponId(); + couponSourceType = couponSelection.getSourceType(); + + } + + String orderNo = "ORD" + snowflakeIdGenerator.nextIdString(); + + OrderDO order = new OrderDO(); + order.setOrderNo(orderNo); + order.setUserId(userId); + order.setShopId(shopId); + order.setTotalAmount(totalAmount); + order.setActualAmount(actualAmount); + order.setCouponId(couponId); + order.setUserCouponId(userCouponId); + order.setCouponSourceType(couponSourceType); + order.setCustomerRemark(trimToNull(orderDTO.getRemark())); + order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + order.setQuoteExpireTime(LocalDateTime.now().plusHours(QUOTE_EXPIRE_HOURS)); + order.setPaymentStatus("UNPAID"); + order.setPayAmount(actualAmount); + order.setPaidAmount(BigDecimal.ZERO); + order.setStatus(OrderStatus.PRICE_CONFIRMING.getCode()); + order.setIsDelete(0); + orderMapper.insert(order); + + for (OrderItemDO item : orderItems) { + item.setOrderId(order.getId()); + item.setIsDelete(0); + orderItemMapper.insert(item); + ProductDO product = productCache.get(item.getProductId()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.reservePendingQuoteOrThrow( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + product == null ? null : product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes), + trimToNull(orderDTO.getClientRequestId()) + ); + } + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_CREATE, order.getCustomerRemark()); + + QueryWrapper cartWrapper = new QueryWrapper<>(); + cartWrapper.eq("user_id", userId) + .eq("is_delete", 0) + .in("product_id", requestedProductIds); + cartMapper.delete(cartWrapper); + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order); + } + + private OrderDTO toOrderDTO(CheckoutPreviewDTO checkoutPreviewDTO) { + OrderDTO orderDTO = new OrderDTO(); + if (checkoutPreviewDTO == null) { + return orderDTO; + } + orderDTO.setCouponId(checkoutPreviewDTO.getCouponId()); + orderDTO.setCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + orderDTO.setRemark(checkoutPreviewDTO.getRemark()); + orderDTO.setItems(checkoutPreviewDTO.getItems()); + return orderDTO; + } + + private CheckoutPricingContext buildCheckoutPricingContext(Long userId, OrderDTO orderDTO) { + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + throw new RuntimeException("订单项不能为空"); + } + + List orderItemDTOs = orderDTO.getItems(); + Map requestedQuantityByProductId = buildRequestedQuantityMap(orderItemDTOs); + BigDecimal totalAmount = BigDecimal.ZERO; + Set selectedTagNames = new LinkedHashSet<>(); + Long shopId = null; + + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + validateOrderQuantity(orderItemDTO.getQuantity()); + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + throw new RuntimeException("商品不存在或已下架"); + } + + CartDO cartItem = cartMapper.selectByUserIdAndProductId(userId, product.getId()); + Integer requestedQuantity = requestedQuantityByProductId.get(product.getId()); + if (cartItem == null || Integer.valueOf(1).equals(cartItem.getIsDelete())) { + throw new RuntimeException("请先将商品加入购物车后再结算"); + } + if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); + } + + if (shopId == null) { + shopId = product.getShopId(); + validateUserCanCreateOrderInShop(userId, shopId); + } else if (!shopId.equals(product.getShopId())) { + throw new RuntimeException("跨店铺商品请分开下单"); + } + + collectPreviewTagNames(selectedTagNames, product.getTags()); + BigDecimal price = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + totalAmount = totalAmount.add(price.multiply(BigDecimal.valueOf(orderItemDTO.getQuantity()))); + } + + if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + throw new RuntimeException("订单金额无效"); + } + return new CheckoutPricingContext(totalAmount, shopId, String.join(",", selectedTagNames)); + } + + private List collectCheckoutBookingIssues(Long userId, OrderDTO orderDTO) { + List issues = new ArrayList<>(); + if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项不能为空", (OrderItemDTO) null, (ProductDO) null)); + return issues; + } + + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + List requestedSlots = new ArrayList<>(); + Long shopId = null; + Long selectedArtistId = null; + + for (OrderItemDTO orderItemDTO : orderDTO.getItems()) { + if (orderItemDTO == null || orderItemDTO.getProductId() == null) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单项信息不完整", orderItemDTO, null)); + continue; + } + + ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + issues.add(checkoutIssue(ISSUE_PRODUCT_UNAVAILABLE, "商品不存在或已下架", orderItemDTO, null)); + continue; + } + productCache.put(product.getId(), product); + + if (orderItemDTO.getQuantity() == null || orderItemDTO.getQuantity() < 1) { + issues.add(checkoutIssue(ISSUE_ORDER_ITEM, "订单商品数量必须大于 0", orderItemDTO, product)); + continue; + } + + if (shopId == null) { + shopId = product.getShopId(); + } else if (!Objects.equals(shopId, product.getShopId())) { + issues.add(checkoutIssue(ISSUE_SHOP_MISMATCH, "跨店铺商品请分开下单", orderItemDTO, product)); + } + + UserDO artist = null; + try { + artist = validateArtistForProduct(product, orderItemDTO.getArtistId()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_ARTIST_UNAVAILABLE, bookingMessage(exception, "美甲师当前不可预约"), orderItemDTO, product)); + } + + if (artist != null) { + if (selectedArtistId == null) { + selectedArtistId = artist.getId(); + } else if (!selectedArtistId.equals(artist.getId())) { + issues.add(checkoutIssue(ISSUE_ARTIST_MISMATCH, "不同美甲师的项目请分开下单", orderItemDTO, product)); + } + } + + LocalDateTime appointmentTime; + try { + appointmentTime = parseAppointmentTime(orderItemDTO.getAppointmentTime()); + validateAppointmentTime(appointmentTime, product.getTitle()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_APPOINTMENT_TIME, bookingMessage(exception, "预约时间不正确"), orderItemDTO, product)); + continue; + } + + long serviceDurationMinutes = resolveServiceDurationMinutes(product) * orderItemDTO.getQuantity(); + LocalDateTime appointmentEndTime = appointmentTime.plusMinutes(serviceDurationMinutes); + try { + validateBusinessHours(getShopFromCache(product.getShopId(), shopCache), appointmentTime, appointmentEndTime, product.getTitle()); + } catch (RuntimeException exception) { + issues.add(checkoutIssue(ISSUE_BUSINESS_HOURS, bookingMessage(exception, "预约时间超出门店营业时间"), orderItemDTO, product)); + continue; + } + + requestedSlots.add(new BookingValidationSlot( + orderItemDTO.getProductId(), + product.getTitle(), + appointmentTime, + appointmentEndTime + )); + } + + collectRequestedSlotIssues(requestedSlots, issues); + collectExistingAppointmentIssues(selectedArtistId, requestedSlots, productCache, issues); + return issues; + } + + private void collectRequestedSlotIssues(List requestedSlots, List issues) { + if (requestedSlots.size() <= 1) { + return; + } + + List sortedSlots = new ArrayList<>(requestedSlots); + sortedSlots.sort(Comparator.comparing(BookingValidationSlot::getStartTime)); + for (int i = 1; i < sortedSlots.size(); i++) { + BookingValidationSlot previous = sortedSlots.get(i - 1); + BookingValidationSlot current = sortedSlots.get(i); + if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { + issues.add(checkoutIssue( + ISSUE_ORDER_CONFLICT, + "所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间", + current.getProductId(), + current.getProductTitle() + )); + } + } + } + + private void collectExistingAppointmentIssues(Long artistId, + List requestedSlots, + Map productCache, + List issues) { + if (artistId == null || requestedSlots.isEmpty()) { + return; + } + + Set occupiedSlotKeys = new LinkedHashSet<>(); + for (BookingValidationSlot requestedSlot : requestedSlots) { + int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( + artistId, + requestedSlot.getStartTime(), + requestedSlot.getEndTime() + ); + if (activeOccupancyCount > 0) { + occupiedSlotKeys.add(bookingSlotKey(requestedSlot)); + issues.add(checkoutIssue( + ISSUE_EXISTING_CONFLICT, + "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择", + requestedSlot.getProductId(), + requestedSlot.getProductTitle() + )); + } + } + + List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); + if (existingAppointments == null || existingAppointments.isEmpty()) { + return; + } + + for (OrderItemDO existingItem : existingAppointments) { + if (existingItem == null || existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { + continue; + } + + ProductDO existingProduct = getProductForBookingCheck(existingItem.getProductId(), productCache); + if (existingProduct == null) { + continue; + } + + int existingQuantity = existingItem.getQuantity() == null ? 1 : Math.max(1, existingItem.getQuantity()); + long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * existingQuantity; + LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); + + for (BookingValidationSlot requestedSlot : requestedSlots) { + if (occupiedSlotKeys.contains(bookingSlotKey(requestedSlot))) { + continue; + } + if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { + issues.add(checkoutIssue( + ISSUE_EXISTING_CONFLICT, + "商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择", + requestedSlot.getProductId(), + requestedSlot.getProductTitle() + )); + } + } + } + } + + private String bookingSlotKey(BookingValidationSlot requestedSlot) { + return requestedSlot.getProductId() + "|" + requestedSlot.getStartTime() + "|" + requestedSlot.getEndTime(); + } + + private ProductDO getProductForBookingCheck(Long productId, Map productCache) { + if (productId == null) { + return null; + } + if (productCache.containsKey(productId)) { + return productCache.get(productId); + } + + ProductDO product = productMapper.selectById(productId); + if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { + product = null; + } + productCache.put(productId, product); + return product; + } + + private CheckoutIssueVO checkoutIssue(String code, String message, OrderItemDTO orderItemDTO, ProductDO product) { + Long productId = product == null ? orderItemDTO == null ? null : orderItemDTO.getProductId() : product.getId(); + String productTitle = product == null ? "订单项" : resolveProductTitle(product); + return checkoutIssue(code, message, productId, productTitle); + } + + private CheckoutIssueVO checkoutIssue(String code, String message, Long productId, String productTitle) { + CheckoutIssueVO issue = new CheckoutIssueVO(); + issue.setCode(code); + issue.setMessage(normalizeBookingMessage(message)); + issue.setProductId(productId); + issue.setProductTitle(StringUtils.hasText(productTitle) ? productTitle : "订单项"); + return issue; + } + + private String resolveProductTitle(ProductDO product) { + return product != null && StringUtils.hasText(product.getTitle()) ? product.getTitle() : "订单项"; + } + + private String bookingMessage(RuntimeException exception, String fallbackMessage) { + if (exception != null && StringUtils.hasText(exception.getMessage())) { + return exception.getMessage(); + } + return fallbackMessage; + } + + private BusinessException bookingUnavailable(String message) { + return new BusinessException(BOOKING_UNAVAILABLE_CODE, normalizeBookingMessage(message)); + } + + private boolean isBookingValidationMessage(String message) { + if (!StringUtils.hasText(message)) { + return false; + } + return message.contains("订单项") + || message.contains("订单商品数量") + || message.contains("商品不存在") + || message.contains("跨店铺") + || message.contains("美甲师") + || message.contains("预约时间") + || message.contains("不可预约") + || message.contains("冲突") + || message.contains("營業時間") + || message.contains("营业时间") + || message.contains("涓嶅彲棰勭害") + || message.contains("宸茬害婊") + || message.contains("褰撳墠缇庣敳甯堣"); + } + + private String normalizeBookingMessage(String message) { + if (!StringUtils.hasText(message)) { + return "当前预约不可用,请重新选择预约时间"; + } + + String normalized = message.trim(); + if (normalized.contains("涓嶅彲棰勭害")) { + return "当前美甲师该时段不可预约,请重新选择预约时间"; + } + if (normalized.contains("宸茬害婊") || normalized.contains("褰撳墠缇庣敳甯堣")) { + return "当前美甲师该时间段已约满,请重新选择预约时间"; + } + return normalized; + } + + private void collectPreviewTagNames(Set tagNames, String tags) { + if (tagNames == null || tags == null || tags.isBlank()) { + return; + } + for (String rawTag : tags.split("[,;]")) { + if (rawTag == null || rawTag.isBlank()) { + continue; + } + String tagText = rawTag.trim(); + try { + Long tagId = Long.parseLong(tagText); + if (tagService != null) { + TagVO tagVO = tagService.getTagById(tagId); + if (tagVO != null && StringUtils.hasText(tagVO.getTagName())) { + tagNames.add(tagVO.getTagName()); + } + } + } catch (NumberFormatException ignored) { + tagNames.add(tagText); + } + } + } + + private CheckoutCouponPreviewVO buildAvailableCouponPreview(UserCouponVO coupon, BigDecimal totalAmount) { + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getCouponId()); + preview.setUserCouponId(COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null); + preview.setSourceType(coupon.getSourceType()); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(parseMoney(coupon.getDiscountValue())); + preview.setMinAmount(parseMoney(coupon.getMinAmount())); + preview.setReduceAmount(parseMoney(coupon.getReduceAmount())); + preview.setDiscountAmount(capDiscount(calculateCouponDiscountAmount(coupon, totalAmount), totalAmount)); + preview.setAvailable(true); + preview.setBest(false); + preview.setVipAuto(COUPON_SOURCE_SYSTEM_VIP.equals(coupon.getSourceType())); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setSavingText(buildSavingText(preview.getDiscountAmount())); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private CheckoutCouponPreviewVO findBestCouponPreview(List availableCoupons) { + if (availableCoupons == null || availableCoupons.isEmpty()) { + return null; + } + return availableCoupons.stream() + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + } + + private CheckoutCouponPreviewVO resolvePreviewSelectedCoupon(CheckoutPreviewDTO checkoutPreviewDTO, + List availableCoupons, + CheckoutCouponPreviewVO bestCoupon) { + if (checkoutPreviewDTO != null + && checkoutPreviewDTO.getCouponId() == null + && COUPON_SOURCE_NONE.equalsIgnoreCase(checkoutPreviewDTO.getCouponSourceType())) { + return null; + } + if (checkoutPreviewDTO == null || checkoutPreviewDTO.getCouponId() == null || checkoutPreviewDTO.getCouponId() <= 0) { + return bestCoupon; + } + + String requestedSourceType = normalizeCouponSourceType(checkoutPreviewDTO.getCouponSourceType()); + return availableCoupons.stream() + .filter(coupon -> checkoutPreviewDTO.getCouponId().equals(coupon.getId())) + .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) + .findFirst() + .orElseThrow(() -> new RuntimeException("当前订单不可使用所选优惠券")); + } + + private List buildUnavailableCouponPreviews(List availableCoupons, + CheckoutPricingContext pricingContext) { + Set availableCouponIds = availableCoupons == null ? Collections.emptySet() : availableCoupons.stream() + .map(CheckoutCouponPreviewVO::getCouponId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + List coupons = couponMapper.selectList(new LambdaQueryWrapper() + .eq(CouponDO::getIsDelete, 0)); + if (coupons == null || coupons.isEmpty()) { + return List.of(); + } + + LocalDateTime now = LocalDateTime.now(); + return coupons.stream() + .filter(coupon -> coupon != null && coupon.getId() != null) + .filter(coupon -> !availableCouponIds.contains(coupon.getId())) + .map(coupon -> buildUnavailableCouponPreview(coupon, pricingContext, now)) + .filter(Objects::nonNull) + .toList(); + } + + private CheckoutCouponPreviewVO buildUnavailableCouponPreview(CouponDO coupon, + CheckoutPricingContext pricingContext, + LocalDateTime now) { + String reason = resolveUnavailableCouponReason(coupon, pricingContext, now); + if (!StringUtils.hasText(reason)) { + reason = "本单暂不可用"; + } + + CheckoutCouponPreviewVO preview = new CheckoutCouponPreviewVO(); + preview.setId(coupon.getId()); + preview.setCouponId(coupon.getId()); + preview.setSourceType(isVipAutoCoupon(coupon) ? COUPON_SOURCE_SYSTEM_VIP : COUPON_SOURCE_USER); + preview.setCouponName(coupon.getCouponName()); + preview.setCouponType(coupon.getCouponType()); + preview.setCouponTypeName(resolveCouponTypeName(coupon.getCouponType())); + preview.setDiscountValue(coupon.getDiscountValue()); + preview.setMinAmount(coupon.getMinAmount()); + preview.setReduceAmount(coupon.getReduceAmount()); + preview.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + preview.setAvailable(false); + preview.setBest(false); + preview.setVipAuto(isVipAutoCoupon(coupon)); + preview.setDisplayText(buildCouponDisplayText(preview)); + preview.setUnavailableReason(reason); + preview.setStartTime(coupon.getStartTime()); + preview.setEndTime(coupon.getEndTime()); + return preview; + } + + private String resolveUnavailableCouponReason(CouponDO coupon, CheckoutPricingContext pricingContext, LocalDateTime now) { + if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete())) { + return "优惠券已失效"; + } + if (coupon.getStatus() == null || coupon.getStatus() != 1) { + return "优惠券已失效"; + } + if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) { + return "还未到可用时间"; + } + if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) { + return "优惠券已过期"; + } + if (coupon.getShopId() != null + && pricingContext.getShopId() != null + && !coupon.getShopId().equals(pricingContext.getShopId())) { + return "仅限其他门店使用"; + } + if (Integer.valueOf(2).equals(coupon.getCouponType()) + && coupon.getMinAmount() != null + && coupon.getMinAmount().compareTo(pricingContext.getTotalAmount()) > 0) { + return "还差 " + formatMoney(coupon.getMinAmount().subtract(pricingContext.getTotalAmount())) + " 可用"; + } + return "本单商品暂不适用"; + } + + private String buildVipTip(Long userId, BigDecimal totalAmount, List availableCoupons) { + CheckoutCouponPreviewVO vipCoupon = availableCoupons == null ? null : availableCoupons.stream() + .filter(coupon -> Boolean.TRUE.equals(coupon.getVipAuto())) + .max(Comparator.comparing(coupon -> safeAmount(coupon.getDiscountAmount()))) + .orElse(null); + UserDO userDO = userMapper.selectById(userId); + String vipLevel = userDO == null ? null : userDO.getLevel(); + if (vipCoupon != null && safeAmount(vipCoupon.getDiscountAmount()).compareTo(BigDecimal.ZERO) > 0) { + String levelText = StringUtils.hasText(vipLevel) ? vipLevel + "VIP" : "VIP"; + return levelText + "本单可省 " + formatMoney(vipCoupon.getDiscountAmount()) + ",已为你计算。"; + } + if (StringUtils.hasText(vipLevel) && !"普通".equals(vipLevel)) { + return vipLevel + "VIP暂无本单可用自动优惠,已为你保留其他可用优惠。"; + } + if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) { + return "开通VIP后,可在结算页自动匹配VIP优惠。"; + } + return null; + } + + private String buildCheckoutSummaryText(CheckoutPreviewVO preview) { + return "参考价小计 " + formatMoney(preview.getSubtotalAmount()) + + ",预估优惠 " + formatMoney(preview.getSavedAmount()) + + ",预估应付 " + formatMoney(preview.getPayableAmount()) + "。"; + } + + private String buildCouponDisplayText(CheckoutCouponPreviewVO coupon) { + String prefix = Boolean.TRUE.equals(coupon.getVipAuto()) ? "VIP自动优惠" : "优惠券"; + String benefit; + if (Integer.valueOf(1).equals(coupon.getCouponType()) && coupon.getDiscountValue() != null) { + benefit = coupon.getDiscountValue().stripTrailingZeros().toPlainString() + "折"; + } else if (Integer.valueOf(2).equals(coupon.getCouponType())) { + benefit = "满" + formatMoneyValue(coupon.getMinAmount()) + "减" + formatMoneyValue(coupon.getReduceAmount()); + } else { + benefit = "优惠"; + } + return prefix + ":" + coupon.getCouponName() + "," + benefit; + } + + private String buildSavingText(BigDecimal discountAmount) { + BigDecimal amount = safeAmount(discountAmount); + if (amount.compareTo(BigDecimal.ZERO) <= 0) { + return "本单暂不省钱"; + } + return "本单可省 " + formatMoney(amount); + } + + private boolean isVipAutoCoupon(CouponDO coupon) { + return coupon != null + && Integer.valueOf(1).equals(coupon.getAutoMatch()) + && "VIP_AUTO".equals(coupon.getCouponScene()); + } + + private String resolveCouponTypeName(Integer couponType) { + if (Integer.valueOf(1).equals(couponType)) { + return "折扣券"; + } + if (Integer.valueOf(2).equals(couponType)) { + return "满减券"; + } + return "优惠券"; + } + + private BigDecimal parseMoney(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return new BigDecimal(value.trim()); + } catch (NumberFormatException exception) { + return null; + } + } + + private BigDecimal capDiscount(BigDecimal discountAmount, BigDecimal totalAmount) { + BigDecimal discount = safeAmount(discountAmount); + BigDecimal total = safeAmount(totalAmount); + if (discount.compareTo(total) > 0) { + return scaleMoney(total); + } + return scaleMoney(discount); + } + + private BigDecimal safeAmount(BigDecimal amount) { + return amount == null ? BigDecimal.ZERO : amount; + } + + private BigDecimal scaleMoney(BigDecimal amount) { + return safeAmount(amount).setScale(2, RoundingMode.HALF_UP); + } + + private String formatMoney(BigDecimal amount) { + return "¥" + scaleMoney(amount).toPlainString(); + } + + private String formatMoneyValue(BigDecimal amount) { + return scaleMoney(amount).stripTrailingZeros().toPlainString(); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getOrderList(Long userId) { + List orderList = orderMapper.selectByUserId(userId); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + if (!Integer.valueOf(1).equals(order.getIsDelete())) { + orderVOList.add(buildOrderVO(order)); + } + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ + public OrderVO getOrderDetail(Long orderId, Long userId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看此订单"); + } + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order); + } + + @Override + @Transactional + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ + public void cancelOrder(Long orderId, Long userId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权操作此订单"); + } + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单状态不允许取消"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode()); + order.setStatus(3); + if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_SYSTEM_EXPIRE, "用户取消询价预约"); + } + orderMapper.updateById(order); + appointmentCapacityService.releaseByOrder(orderId); + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + restoreUserCoupon(order, userId); + } + + @Override + @Transactional + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ + public void processOrder(Long orderId, Integer status) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (status != 2 && status != 3) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无效的订单状态"); + } + OrderStatus targetStatus = OrderStatus.requireKnown(status); + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) + && !(Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status))) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单状态不允许处理"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), status); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } + order.setStatus(status); + if (targetStatus == OrderStatus.COMPLETED) { + businessEventOutboxService.enqueueOrderCompleted(order.getId()); + } + if (targetStatus == OrderStatus.CANCELLED) { + appointmentCapacityService.releaseByOrder(order.getId()); + restoreUserCoupon(order, order.getUserId()); + if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) { + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约已取消"); + } + } + } + + @Override + @Transactional + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ + public void completeArtistOrder(Long orderId, Long artistId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在"); + } + if (order.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前订单状态不允许完成"); + } + + List activeItems = orderItemMapper.selectByOrderId(orderId).stream() + .filter(item -> !Integer.valueOf(1).equals(item.getIsDelete())) + .toList(); + if (activeItems.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品不存在"); + } + + boolean allBelongToArtist = activeItems.stream().allMatch(item -> artistId.equals(item.getArtistId())); + if (!allBelongToArtist) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能完成全部由自己承接的订单"); + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode()); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } + order.setStatus(OrderStatus.COMPLETED.getCode()); + businessEventOutboxService.enqueueOrderCompleted(order.getId()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllOrders() { + List orderList = orderMapper.selectList(new QueryWrapper().eq("is_delete", 0)); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + orderVOList.add(buildOrderVO(order)); + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getOrdersByArtistId(Long artistId) { + List orderList = orderMapper.selectByArtistId(artistId); + List orderVOList = new ArrayList<>(); + for (OrderDO order : orderList) { + OrderVO orderVO = buildOrderVO(order, artistId); + if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { + orderVOList.add(orderVO); + } + } + return orderVOList; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistWorkbenchOrders(Long artistId) { + Map orderMap = new LinkedHashMap<>(); + List serviceOrders = orderMapper.selectByArtistId(artistId); + for (OrderDO order : serviceOrders) { + OrderVO orderVO = buildOrderVO(order, artistId); + if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { + orderVO.setArtistOrderSource("SERVICE"); + orderVO.setArtistOrderSourceText("客户预约我的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + } + + List selfOrders = orderMapper.selectByUserId(artistId); + for (OrderDO order : selfOrders) { + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + continue; + } + OrderVO existing = orderMap.get(order.getId()); + if (existing != null) { + existing.setArtistOrderSource("BOTH"); + existing.setArtistOrderSourceText("我下的订单 / 客户预约我的订单"); + continue; + } + OrderVO orderVO = buildOrderVO(order); + orderVO.setArtistOrderSource("SELF"); + orderVO.setArtistOrderSourceText("我下的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + + return orderMap.values().stream() + .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarRecent(Long userId, Integer userType, Integer days) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + int normalizedDays = days == null ? 7 : Math.max(1, Math.min(days, 31)); + LocalDate startDate = LocalDate.now(); + return listArtistCalendarAppointments(userId, startDate.atStartOfDay(), startDate.plusDays(normalizedDays).atStartOfDay()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarDay(Long userId, Integer userType, LocalDate date) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + LocalDate targetDate = date == null ? LocalDate.now() : date; + return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay()); + } + + @Override + /** + * Purpose: listMyPendingReviews supports OrderServiceImpl.java by holding or executing the list my pending reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listMyPendingReviews(Long userId) { + return orderArtistReviewMapper.selectPendingByUserId(userId).stream() + .map(this::buildArtistReviewVO) + .toList(); + } + + @Override + /** + * Purpose: listOrderReviews supports OrderServiceImpl.java by holding or executing the list order reviews business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listOrderReviews(Long orderId, Long userId, Integer userType) { + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("无权查看该订单评价"); + } + return orderArtistReviewMapper.selectByOrderId(orderId).stream() + .map(this::buildArtistReviewVO) + .toList(); + } + + @Override + @Transactional + /** + * Purpose: submitArtistReview supports OrderServiceImpl.java by holding or executing the submit artist review business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto) { + OrderArtistReviewDO review = orderArtistReviewMapper.selectById(reviewId); + if (review == null || Integer.valueOf(1).equals(review.getIsDelete())) { + throw new RuntimeException("评价任务不存在"); + } + if (!Objects.equals(userId, review.getCustomerId())) { + throw new RuntimeException("只能提交自己的评价"); + } + if (!Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { + throw new RuntimeException("评价已提交,不能重复提交"); + } + + BigDecimal rating = normalizeReviewRating(dto == null ? null : dto.getRating()); + review.setRatingScore(rating); + review.setContent(trimToNull(dto == null ? null : dto.getContent())); + review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds())); + review.setStatus(REVIEW_STATUS_SUBMITTED); + review.setSubmittedAt(LocalDateTime.now()); + orderArtistReviewMapper.updateById(review); + refreshArtistRating(review.getArtistId()); + return buildArtistReviewVO(review); + } + + @Override + @Transactional + public OrderVO submitShopQuote(Long orderId, Long operatorId, Integer operatorType, OrderQuoteSubmitDTO dto) { + OrderDO order = requireQuoteOrder(orderId); + ensureShopQuoteOperator(order, operatorId, operatorType); + if (dto == null || dto.getItems() == null || dto.getItems().isEmpty()) { + throw new RuntimeException("请至少填写一个作品报价"); + } + + Map itemMap = loadActiveOrderItemMap(order.getId()); + for (OrderQuoteItemDTO quoteItem : dto.getItems()) { + if (quoteItem == null || quoteItem.getOrderItemId() == null) { + continue; + } + OrderItemDO item = itemMap.get(quoteItem.getOrderItemId()); + if (item == null) { + throw new RuntimeException("报价作品不属于当前订单"); + } + BigDecimal quotedPrice = normalizeQuotePrice(quoteItem.getQuotedPrice()); + item.setQuotedPrice(quotedPrice); + if (item.getReferencePrice() == null) { + item.setReferencePrice(item.getPrice()); + } + orderItemMapper.updateById(item); + } + ensureAllItemsQuoted(order.getId()); + + order.setQuoteStatus(QUOTE_STATUS_CONFIRMING); + order.setQuoteShopConfirmed(1); + order.setQuoteUserConfirmed(0); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_QUOTE, trimToNull(dto.getRemark())); + notifyQuoteUser(order, "门店已回复询价预约", "门店已回复您的询价预约,请查看并确认价格。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO confirmShopQuote(Long orderId, Long operatorId, Integer operatorType) { + OrderDO order = requireQuoteOrder(orderId); + ensureShopQuoteOperator(order, operatorId, operatorType); + ensureAllItemsQuoted(order.getId()); + order.setQuoteShopConfirmed(1); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), operatorId, QUOTE_ACTOR_SHOP, QUOTE_ACTION_SHOP_CONFIRM, "店长确认当前报价"); + if (Integer.valueOf(1).equals(order.getQuoteUserConfirmed())) { + return finalizeConfirmedQuote(order, operatorId, QUOTE_ACTOR_SHOP); + } + notifyQuoteUser(order, "门店已确认询价价格", "门店已确认当前询价价格,请查看并确认。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO replyQuote(Long orderId, Long userId, OrderQuoteReplyDTO dto) { + OrderDO order = requireQuoteOrder(orderId); + ensureQuoteOwner(order, userId); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + String remark = trimToNull(dto == null ? null : dto.getRemark()); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_REPLY, remark); + notifyQuoteShopAndArtist(order, "用户已回复询价预约", "用户已回复询价预约,请查看备注并继续确认价格。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public OrderVO confirmUserQuote(Long orderId, Long userId) { + OrderDO order = requireQuoteOrder(orderId); + ensureQuoteOwner(order, userId); + ensureAllItemsQuoted(order.getId()); + order.setQuoteUserConfirmed(1); + orderMapper.updateById(order); + writeQuoteMessage(order.getId(), userId, QUOTE_ACTOR_USER, QUOTE_ACTION_USER_CONFIRM, "用户确认当前报价"); + if (Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { + return finalizeConfirmedQuote(order, userId, QUOTE_ACTOR_USER); + } + notifyQuoteShopAndArtist(order, "用户已确认询价价格", "用户已确认当前价格,请店长完成确认。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + @Override + @Transactional + public int expirePendingQuoteOrders() { + LocalDateTime now = LocalDateTime.now(); + List expiredOrders = orderMapper.selectList(new LambdaQueryWrapper() + .eq(OrderDO::getStatus, OrderStatus.PRICE_CONFIRMING.getCode()) + .eq(OrderDO::getQuoteStatus, QUOTE_STATUS_CONFIRMING) + .le(OrderDO::getQuoteExpireTime, now) + .eq(OrderDO::getIsDelete, 0)); + int expiredCount = 0; + for (OrderDO order : expiredOrders) { + order.setStatus(OrderStatus.CANCELLED.getCode()); + order.setQuoteStatus(QUOTE_STATUS_EXPIRED); + order.setQuoteUserConfirmed(0); + order.setQuoteShopConfirmed(0); + orderMapper.updateById(order); + appointmentCapacityService.releaseByOrder(order.getId()); + writeQuoteMessage(order.getId(), 0L, QUOTE_ACTOR_SYSTEM, QUOTE_ACTION_SYSTEM_EXPIRE, "询价预约超过24小时未确认,已自动取消"); + expiredCount++; + } + return expiredCount; + } + + @Scheduled(fixedDelay = 60000) + public void expirePendingQuoteOrdersScheduled() { + expirePendingQuoteOrders(); + } + + @Override + /** + * Purpose: getArtistChangeOptions supports OrderServiceImpl.java by holding or executing the get artist change options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType) { + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("无权查看该订单改派选项"); + } + OrderItemDO item = requireOrderItem(orderItemId, orderId); + ProductDO product = requireActiveProduct(item.getProductId()); + + OrderArtistChangeOptionsVO vo = new OrderArtistChangeOptionsVO(); + vo.setOrderId(orderId); + vo.setOrderItemId(orderItemId); + vo.setCurrentArtistId(item.getArtistId()); + UserDO currentArtist = item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); + vo.setCurrentArtistName(currentArtist == null ? null : currentArtist.getNickname()); + vo.setArtists(parseIdSet(product.getBookableArtists()).stream() + .filter(artistId -> !Objects.equals(artistId, item.getArtistId())) + .filter(artistId -> isArtistAvailableForItem(order.getShopId(), artistId, item, product)) + .map(this::buildArtistOptionVO) + .filter(Objects::nonNull) + .toList()); + return vo; + } + + @Override + @Transactional + /** + * Purpose: requestArtistChange supports OrderServiceImpl.java by holding or executing the request artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto) { + if (dto == null || dto.getOrderId() == null || dto.getOrderItemId() == null || dto.getRequestedArtistId() == null) { + throw new RuntimeException("改派申请信息不完整"); + } + ensureArtistChangeRequester(userId); + OrderDO order = requireActiveOrder(dto.getOrderId()); + if (!canAccessOrder(order, userId, null)) { + throw new RuntimeException("只能为自己的订单申请改派"); + } + if (!Integer.valueOf(1).equals(order.getStatus())) { + throw new RuntimeException("仅待服务订单允许申请改派"); + } + OrderItemDO item = requireOrderItemForUpdate(dto.getOrderItemId(), order.getId()); + if (!canRequestArtistChangeForItem(order, item, userId)) { + throw new RuntimeException("只能为自己承接的待服务订单项申请改派"); + } + if (item.getArtistId() == null) { + throw new RuntimeException("订单项未分配美甲师"); + } + if (Objects.equals(item.getArtistId(), dto.getRequestedArtistId())) { + throw new RuntimeException("新美甲师不能与原美甲师相同"); + } + if (orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()) != null) { + throw new RuntimeException("该订单项已有待处理改派申请"); + } + ProductDO product = requireActiveProduct(item.getProductId()); + validateRequestedArtistForItem(order.getShopId(), dto.getRequestedArtistId(), item, product); + + OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO(); + request.setOrderId(order.getId()); + request.setOrderItemId(item.getId()); + request.setProductId(item.getProductId()); + request.setShopId(order.getShopId()); + request.setCustomerId(order.getUserId()); + request.setFromArtistId(item.getArtistId()); + request.setToArtistId(dto.getRequestedArtistId()); + request.setRequesterId(userId); + request.setStatus(CHANGE_STATUS_PENDING); + request.setReason(trimToNull(dto.getReason())); + request.setPendingKey(buildArtistChangePendingKey(item.getId())); + request.setExpireTime(LocalDateTime.now().plusDays(2)); + request.setIsDelete(0); + try { + orderArtistChangeRequestMapper.insert(request); + } catch (DuplicateKeyException exception) { + throw new RuntimeException("该订单项已有待处理改派申请"); + } + createArtistChangeMessage(order, request); + return buildArtistChangeRequestVO(request, item); + } + + @Override + /** + * Purpose: listMyPendingArtistChangeRequests supports OrderServiceImpl.java by holding or executing the list my pending artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listMyPendingArtistChangeRequests(Long userId, Integer userType) { + expireDueArtistChangeRequests(); + List requests; + if (Integer.valueOf(2).equals(userType)) { + UserDO user = userMapper.selectById(userId); + requests = user != null && user.getShopId() != null + ? orderArtistChangeRequestMapper.selectPendingByShopId(user.getShopId()) + : orderArtistChangeRequestMapper.selectPendingByArtistId(userId); + } else if (Integer.valueOf(3).equals(userType)) { + requests = orderArtistChangeRequestMapper.selectPendingByArtistId(userId); + } else { + requests = orderArtistChangeRequestMapper.selectPendingByUserId(userId); + } + return requests.stream() + .map(this::buildArtistChangeRequestVO) + .toList(); + } + + @Override + /** + * Purpose: listOrderArtistChangeRequests returns every artist-change request for one accessible order. + * Usage: call it from order detail/list pages to build a customer-facing order timeline with pending and historical changes. + */ + public List listOrderArtistChangeRequests(Long orderId, Long userId, Integer userType) { + expireDueArtistChangeRequests(); + OrderDO order = requireActiveOrder(orderId); + if (!canAccessOrder(order, userId, userType)) { + throw new RuntimeException("[ORDER_ARTIST_CHANGE_FORBIDDEN] 无权查看该订单改派记录"); + } + return orderArtistChangeRequestMapper.selectByOrderId(orderId).stream() + .map(this::buildArtistChangeRequestVO) + .toList(); + } + + @Override + @Transactional + /** + * Purpose: approveArtistChange supports OrderServiceImpl.java by holding or executing the approve artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType) { + OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); + assertCanProcessArtistChange(request, userId, userType); + + OrderDO order = requireActiveOrder(request.getOrderId()); + if (!Integer.valueOf(1).equals(order.getStatus())) { + throw new RuntimeException("仅待服务订单允许改派"); + } + if (!Objects.equals(order.getUserId(), request.getCustomerId())) { + throw new RuntimeException("改派申请客户与订单不匹配"); + } + + OrderItemDO item = orderItemMapper.selectByIdForUpdate(request.getOrderItemId()); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), order.getId())) { + throw new RuntimeException("订单项不存在"); + } + if (!Objects.equals(item.getArtistId(), request.getFromArtistId())) { + throw new RuntimeException("原美甲师已变更,无法继续改派"); + } + + ProductDO product = requireActiveProduct(item.getProductId()); + validateRequestedArtistForItem(order.getShopId(), request.getToArtistId(), item, product); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + order.getShopId(), + request.getFromArtistId(), + request.getToArtistId(), + product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) + ); + + LocalDateTime approvedTime = LocalDateTime.now(); + if (orderArtistChangeRequestMapper.approvePending(request.getId(), approvedTime) == 0) { + throw new RuntimeException("改派申请已处理"); + } + item.setArtistId(request.getToArtistId()); + orderItemMapper.updateById(item); + request.setStatus(CHANGE_STATUS_APPROVED); + request.setApprovedTime(approvedTime); + request.setPendingKey(null); + return buildArtistChangeRequestVO(request, item); + } + + @Override + @Transactional + /** + * Purpose: rejectArtistChange supports OrderServiceImpl.java by holding or executing the reject artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto) { + OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId); + assertCanProcessArtistChange(request, userId, userType); + LocalDateTime rejectedTime = LocalDateTime.now(); + String rejectReason = trimToNull(dto == null ? null : dto.getRejectReason()); + if (orderArtistChangeRequestMapper.rejectPending(request.getId(), rejectReason, rejectedTime) == 0) { + throw new RuntimeException("改派申请已处理"); + } + request.setStatus(CHANGE_STATUS_REJECTED); + request.setRejectReason(rejectReason); + request.setRejectedTime(rejectedTime); + request.setPendingKey(null); + return buildArtistChangeRequestVO(request); + } + + /** + * Purpose: createPendingArtistReviewTasksAndNotifyFromOutbox supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify from outbox business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void createPendingArtistReviewTasksAndNotifyFromOutbox(OrderDO order) { + createPendingArtistReviewTasksAndNotify(order); + } + + /** + * Purpose: createPendingArtistReviewTasksAndNotify supports OrderServiceImpl.java by holding or executing the create pending artist review tasks and notify business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void createPendingArtistReviewTasksAndNotify(OrderDO order) { + if (order == null || order.getId() == null || !Integer.valueOf(2).equals(order.getStatus())) { + return; + } + List items = orderItemMapper.selectByOrderId(order.getId()); + if (items == null || items.isEmpty()) { + return; + } + for (OrderItemDO item : items) { + if (item == null + || item.getId() == null + || Integer.valueOf(1).equals(item.getIsDelete()) + || item.getArtistId() == null) { + continue; + } + if (orderArtistReviewMapper.selectByOrderItemId(item.getId()) != null) { + continue; + } + ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); + OrderArtistReviewDO review = new OrderArtistReviewDO(); + review.setOrderId(order.getId()); + review.setOrderItemId(item.getId()); + review.setProductId(item.getProductId()); + review.setShopId(order.getShopId()); + review.setArtistId(item.getArtistId()); + review.setCustomerId(order.getUserId()); + review.setStatus(REVIEW_STATUS_PENDING); + review.setIsDelete(0); + review = insertPendingArtistReview(review); + if (review == null || review.getId() == null) { + continue; + } + Long messageId = createReviewReminderMessage(order, item, product, review); + if (messageId != null) { + review.setReminderMessageId(messageId); + orderArtistReviewMapper.updateById(review); + } + } + } + + /** + * Purpose: insertPendingArtistReview supports OrderServiceImpl.java by holding or executing the insert pending artist review business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewDO insertPendingArtistReview(OrderArtistReviewDO review) { + try { + orderArtistReviewMapper.insert(review); + return review; + } catch (DuplicateKeyException exception) { + OrderArtistReviewDO existingReview = review == null || review.getOrderItemId() == null + ? null + : orderArtistReviewMapper.selectByOrderItemId(review.getOrderItemId()); + if (existingReview != null) { + return existingReview; + } + throw exception; + } + } + + /** + * Purpose: createReviewReminderMessage supports OrderServiceImpl.java by holding or executing the create review reminder message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createReviewReminderMessage(OrderDO order, OrderItemDO item, ProductDO product, OrderArtistReviewDO review) { + String productTitle = product == null ? "订单项目" : product.getTitle(); + UserDO artist = item == null || item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId()); + String artistName = artist == null || !StringUtils.hasText(artist.getNickname()) ? "美甲师" : artist.getNickname(); + return createSystemBusinessMessage( + order == null ? null : order.getUserId(), + "订单已完成,记得评价美甲师", + "您预约的「" + productTitle + "」已完成,请为" + artistName + "提交本次服务评价。", + REVIEW_BUSINESS_TYPE, + review == null ? null : review.getId(), + order == null ? null : "/orders?orderId=" + order.getId(), + 0L, + "系统通知", + 4 + ); + } + + /** + * Purpose: buildArtistReviewVO supports OrderServiceImpl.java by holding or executing the build artist review vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO buildArtistReviewVO(OrderArtistReviewDO review) { + if (review == null) { + return null; + } + OrderArtistReviewVO vo = new OrderArtistReviewVO(); + vo.setId(review.getId()); + vo.setOrderId(review.getOrderId()); + vo.setOrderItemId(review.getOrderItemId()); + vo.setProductId(review.getProductId()); + ProductDO product = getProductFromCache(review.getProductId(), new HashMap<>()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setArtistId(review.getArtistId()); + UserDO artist = review.getArtistId() == null ? null : userMapper.selectById(review.getArtistId()); + vo.setArtistName(artist == null ? null : artist.getNickname()); + vo.setArtistAvatar(artist == null ? null : objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + vo.setUserId(review.getCustomerId()); + vo.setCustomerId(review.getCustomerId()); + vo.setRating(review.getRatingScore()); + vo.setRatingScore(review.getRatingScore()); + vo.setContent(review.getContent()); + vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds()))); + vo.setStatus(review.getStatus()); + vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价"); + vo.setReminderMessageId(review.getReminderMessageId()); + vo.setSubmitTime(review.getSubmittedAt()); + vo.setSubmittedAt(review.getSubmittedAt()); + vo.setCreateTime(review.getCreateTime()); + return vo; + } + + /** + * Purpose: requireActiveOrder supports OrderServiceImpl.java by holding or executing the require active order business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderDO requireActiveOrder(Long orderId) { + if (orderId == null) { + throw new RuntimeException("订单信息不完整"); + } + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + return order; + } + + /** + * Purpose: canAccessOrder supports OrderServiceImpl.java by holding or executing the can access order business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean canAccessOrder(OrderDO order, Long userId, Integer userType) { + if (order == null || userId == null) { + return false; + } + if (Objects.equals(order.getUserId(), userId)) { + return true; + } + UserDO user = userMapper.selectById(userId); + Integer effectiveType = userType == null && user != null ? user.getType() : userType; + if (Integer.valueOf(4).equals(effectiveType)) { + return true; + } + if (order.getShopId() != null && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId())) { + return true; + } + List items = orderItemMapper.selectByOrderId(order.getId()); + return items != null && items.stream() + .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) + .anyMatch(item -> Objects.equals(item.getArtistId(), userId)); + } + + /** + * Purpose: normalizeReviewRating supports OrderServiceImpl.java by holding or executing the normalize review rating business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal normalizeReviewRating(BigDecimal rating) { + if (rating == null) { + throw new RuntimeException("评分不能为空"); + } + BigDecimal normalized; + try { + normalized = rating.setScale(1, RoundingMode.UNNECESSARY); + } catch (ArithmeticException exception) { + throw new RuntimeException("评分必须按0.5分递增"); + } + if (normalized.compareTo(new BigDecimal("0.5")) < 0 || normalized.compareTo(new BigDecimal("5.0")) > 0) { + throw new RuntimeException("评分必须在0.5到5分之间"); + } + BigDecimal doubled = normalized.multiply(new BigDecimal("2")); + if (doubled.stripTrailingZeros().scale() > 0) { + throw new RuntimeException("评分必须按0.5分递增"); + } + return normalized; + } + + /** + * Purpose: trimToNull supports OrderServiceImpl.java by holding or executing the trim to null business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String trimToNull(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + /** + * Purpose: joinLongIds supports OrderServiceImpl.java by holding or executing the join long ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String joinLongIds(List ids) { + if (ids == null || ids.isEmpty()) { + return null; + } + String joined = ids.stream() + .filter(Objects::nonNull) + .distinct() + .map(String::valueOf) + .collect(Collectors.joining(",")); + return joined.isBlank() ? null : joined; + } + + /** + * Purpose: parseIdSet supports OrderServiceImpl.java by holding or executing the parse id set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set parseIdSet(String rawIds) { + if (!StringUtils.hasText(rawIds)) { + return Collections.emptySet(); + } + LinkedHashSet result = new LinkedHashSet<>(); + for (String part : rawIds.split("[,;]")) { + if (!StringUtils.hasText(part)) { + continue; + } + try { + result.add(Long.parseLong(part.trim())); + } catch (NumberFormatException ignored) { + } + } + return result; + } + + /** + * Purpose: refreshArtistRating supports OrderServiceImpl.java by holding or executing the refresh artist rating business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void refreshArtistRating(Long artistId) { + if (artistId == null) { + return; + } + BigDecimal average = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId); + if (average == null) { + return; + } + NailArtistInfoDO artistInfo = getArtistInfoByUserId(artistId); + if (artistInfo == null) { + return; + } + artistInfo.setRating(average.setScale(1, RoundingMode.HALF_UP)); + nailArtistInfoMapper.updateById(artistInfo); + } + + /** + * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItem(Long orderItemId, Long orderId) { + return requireOrderItem(orderItemId, orderId, false); + } + + /** + * Purpose: requireOrderItemForUpdate supports OrderServiceImpl.java by holding or executing the require order item for update business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItemForUpdate(Long orderItemId, Long orderId) { + return requireOrderItem(orderItemId, orderId, true); + } + + /** + * Purpose: buildArtistChangePendingKey supports OrderServiceImpl.java by holding or executing the build artist change pending key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildArtistChangePendingKey(Long orderItemId) { + return orderItemId == null ? null : ARTIST_CHANGE_PENDING_KEY_PREFIX + orderItemId; + } + + /** + * Purpose: requireOrderItem supports OrderServiceImpl.java by holding or executing the require order item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderItemDO requireOrderItem(Long orderItemId, Long orderId, boolean forUpdate) { + if (orderItemId == null) { + throw new RuntimeException("订单项信息不完整"); + } + OrderItemDO item = forUpdate + ? orderItemMapper.selectByIdForUpdate(orderItemId) + : orderItemMapper.selectById(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), orderId)) { + throw new RuntimeException("订单项不存在"); + } + return item; + } + + /** + * Purpose: requireActiveProduct supports OrderServiceImpl.java by holding or executing the require active product business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private ProductDO requireActiveProduct(Long productId) { + ProductDO product = getProductFromCache(productId, new HashMap<>()); + if (product == null) { + throw new RuntimeException("商品不存在或已删除"); + } + return product; + } + + /** + * Purpose: isArtistAvailableForItem supports OrderServiceImpl.java by holding or executing the is artist available for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isArtistAvailableForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { + try { + validateRequestedArtistForItem(shopId, artistId, item, product); + return true; + } catch (RuntimeException exception) { + return false; + } + } + + private OrderArtistChangeOptionsVO.ArtistOptionVO buildArtistOptionVO(Long artistId) { + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) || !bookableArtistSupport.isBookableServiceUser(artist)) { + return null; + } + NailArtistInfoDO info = getArtistInfoByUserId(artistId); + OrderArtistChangeOptionsVO.ArtistOptionVO vo = new OrderArtistChangeOptionsVO.ArtistOptionVO(); + vo.setArtistId(artist.getId()); + vo.setArtistName(artist.getNickname()); + vo.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + vo.setUserType(artist.getType()); + vo.setParticipateProduction(info != null && Integer.valueOf(1).equals(info.getParticipateProduction())); + return vo; + } + + /** + * Purpose: validateRequestedArtistForItem supports OrderServiceImpl.java by holding or executing the validate requested artist for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validateRequestedArtistForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) { + validateArtistForProduct(product, artistId); + if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { + throw new RuntimeException("新美甲师不可预约或不属于当前店铺"); + } + if (item == null || item.getAppointmentTime() == null) { + return; + } + int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + long durationMinutes = resolveServiceDurationMinutes(product) * quantity; + LocalDateTime startTime = item.getAppointmentTime(); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + validateBusinessHours(getShopFromCache(shopId == null ? product.getShopId() : shopId, new HashMap<>()), startTime, endTime, product.getTitle()); + validateArtistScheduleConflicts(artistId, Collections.singletonList(new AppointmentSlot(product.getTitle(), startTime, endTime)), new HashMap<>()); + } + + /** + * Purpose: createArtistChangeMessage supports OrderServiceImpl.java by holding or executing the create artist change message business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long createArtistChangeMessage(OrderDO order, OrderArtistChangeRequestDO request) { + ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); + UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); + UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); + String fromName = fromArtist == null || !StringUtils.hasText(fromArtist.getNickname()) ? "原美甲师" : fromArtist.getNickname(); + String toName = toArtist == null || !StringUtils.hasText(toArtist.getNickname()) ? "新美甲师" : toArtist.getNickname(); + Long messageId = createSystemBusinessMessage( + request.getCustomerId(), + "美甲师改派申请待确认", + "您的订单项目「" + (product == null ? "订单项目" : product.getTitle()) + "」申请由" + fromName + "改派给" + toName + ",请在订单页确认。", + CHANGE_BUSINESS_TYPE, + request.getId(), + order == null ? null : "/orders?orderId=" + order.getId(), + request.getRequesterId(), + fromName, + 3 + ); + if (messageId != null) { + request.setMessageId(messageId); + orderArtistChangeRequestMapper.updateById(request); + } + return messageId; + } + + /** + * Purpose: buildArtistChangeRequestVO supports OrderServiceImpl.java by holding or executing the build artist change request vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) { + return buildArtistChangeRequestVO(request, null); + } + + /** + * Purpose: buildArtistChangeRequestVO converts a change request plus optional order item into the client timeline payload. + * Usage: pass the locked/current order item when the caller already has it so the conversion does not issue extra reads. + */ + private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request, OrderItemDO requestItem) { + if (request == null) { + return null; + } + OrderArtistChangeRequestVO vo = new OrderArtistChangeRequestVO(); + vo.setId(request.getId()); + vo.setOrderId(request.getOrderId()); + vo.setOrderItemId(request.getOrderItemId()); + vo.setProductId(request.getProductId()); + ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setShopId(request.getShopId()); + vo.setUserId(request.getCustomerId()); + vo.setCustomerId(request.getCustomerId()); + vo.setOriginalArtistId(request.getFromArtistId()); + vo.setFromArtistId(request.getFromArtistId()); + UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId()); + vo.setOriginalArtistName(fromArtist == null ? null : fromArtist.getNickname()); + vo.setFromArtistName(fromArtist == null ? null : fromArtist.getNickname()); + vo.setRequestedArtistId(request.getToArtistId()); + vo.setToArtistId(request.getToArtistId()); + UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId()); + vo.setRequestedArtistName(toArtist == null ? null : toArtist.getNickname()); + vo.setToArtistName(toArtist == null ? null : toArtist.getNickname()); + vo.setRequesterId(request.getRequesterId()); + UserDO requester = request.getRequesterId() == null ? null : userMapper.selectById(request.getRequesterId()); + vo.setRequesterName(requester == null ? null : requester.getNickname()); + vo.setStatus(request.getStatus()); + vo.setStatusText(resolveArtistChangeStatusText(request.getStatus())); + vo.setReason(request.getReason()); + vo.setRejectReason(request.getRejectReason()); + OrderItemDO item = requestItem != null ? requestItem : request.getOrderItemId() == null ? null : orderItemMapper.selectById(request.getOrderItemId()); + if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) { + vo.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + vo.setOriginalPrice(item.getPrice()); + vo.setNewPrice(item.getPrice()); + vo.setTimeAffected(false); + vo.setTimeImpactText("预约时间不变"); + vo.setPriceAffected(false); + vo.setPriceImpactText("订单价格不变"); + } else { + vo.setTimeImpactText("暂无法确认预约时间,请联系门店"); + vo.setPriceImpactText("暂无法确认订单价格,请联系门店"); + } + vo.setReviewerId(request.getCustomerId()); + vo.setMessageId(request.getMessageId()); + vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime()); + vo.setApprovedTime(request.getApprovedTime()); + vo.setRejectedTime(request.getRejectedTime()); + vo.setExpireTime(request.getExpireTime()); + vo.setCreateTime(request.getCreateTime()); + return vo; + } + + /** + * Purpose: requirePendingArtistChangeRequest supports OrderServiceImpl.java by holding or executing the require pending artist change request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestDO requirePendingArtistChangeRequest(Long requestId) { + if (requestId == null) { + throw new RuntimeException("改派申请信息不完整"); + } + OrderArtistChangeRequestDO request = orderArtistChangeRequestMapper.selectById(requestId); + if (request == null || Integer.valueOf(1).equals(request.getIsDelete())) { + throw new RuntimeException("改派申请不存在"); + } + if (!CHANGE_STATUS_PENDING.equals(request.getStatus())) { + throw new RuntimeException("改派申请已处理"); + } + LocalDateTime now = LocalDateTime.now(); + if (request.getExpireTime() != null && !request.getExpireTime().isAfter(now)) { + orderArtistChangeRequestMapper.expirePendingById(request.getId(), now); + request.setStatus(CHANGE_STATUS_EXPIRED); + request.setPendingKey(null); + throw new RuntimeException("改派申请已过期"); + } + return request; + } + + /** + * Purpose: assertCanProcessArtistChange supports OrderServiceImpl.java by holding or executing the assert can process artist change business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void assertCanProcessArtistChange(OrderArtistChangeRequestDO request, Long userId, Integer userType) { + if (request == null || userId == null || !Objects.equals(request.getCustomerId(), userId)) { + throw new RuntimeException("仅订单客户可以处理改派申请"); + } + } + + @org.springframework.scheduling.annotation.Scheduled(fixedDelay = 300000L) + /** + * Purpose: expireDueArtistChangeRequests supports OrderServiceImpl.java by holding or executing the expire due artist change requests business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void expireDueArtistChangeRequests() { + orderArtistChangeRequestMapper.expirePendingBefore(LocalDateTime.now()); + } + + /** + * Purpose: canRequestArtistChangeForItem supports OrderServiceImpl.java by holding or executing the can request artist change for item business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean canRequestArtistChangeForItem(OrderDO order, OrderItemDO item, Long userId) { + if (order == null || item == null || userId == null) { + return false; + } + if (Objects.equals(item.getArtistId(), userId)) { + return true; + } + UserDO user = userMapper.selectById(userId); + if (user == null || !Integer.valueOf(2).equals(user.getType())) { + return false; + } + NailArtistInfoDO info = getArtistInfoByUserId(userId); + return info != null + && Integer.valueOf(1).equals(info.getParticipateProduction()) + && order.getShopId() != null + && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId()); + } + + /** + * Purpose: ensureArtistChangeRequester supports OrderServiceImpl.java by holding or executing the ensure artist change requester business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensureArtistChangeRequester(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { + throw new RuntimeException("请先登录有效账号"); + } + if (Integer.valueOf(3).equals(user.getType())) { + return; + } + if (Integer.valueOf(2).equals(user.getType())) { + NailArtistInfoDO info = getArtistInfoByUserId(userId); + if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { + return; + } + } + throw new RuntimeException("仅美甲师或参与制作的店长可以申请改派"); + } + + /** + * Purpose: getArtistInfoByUserId supports OrderServiceImpl.java by holding or executing the get artist info by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private NailArtistInfoDO getArtistInfoByUserId(Long userId) { + if (userId == null) { + return null; + } + return nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Purpose: resolveArtistChangeStatusText supports OrderServiceImpl.java by holding or executing the resolve artist change status text business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveArtistChangeStatusText(String status) { + if (CHANGE_STATUS_APPROVED.equals(status)) { + return "已同意"; + } + if (CHANGE_STATUS_REJECTED.equals(status)) { + return "已拒绝"; + } + return "待确认"; + } + + private OrderDO requireQuoteOrder(Long orderId) { + OrderDO order = requireActiveOrder(orderId); + if (!Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + throw new RuntimeException("仅确认价格中的询价预约可以进行报价操作"); + } + if (QUOTE_STATUS_EXPIRED.equals(order.getQuoteStatus())) { + throw new RuntimeException("询价预约已过期"); + } + return order; + } + + private void ensureQuoteOwner(OrderDO order, Long userId) { + if (order == null || userId == null || !userId.equals(order.getUserId())) { + throw new RuntimeException("无权处理该询价预约"); + } + } + + private void ensureShopQuoteOperator(OrderDO order, Long operatorId, Integer operatorType) { + if (!Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(operatorType)) { + throw new RuntimeException("只有店长可以确认或回复价格"); + } + if (order == null || operatorId == null + || !userShopBindingSupport.canUserAccessShop(operatorId, order.getShopId(), true, operatorType)) { + throw new RuntimeException("无权处理其他店铺的询价预约"); + } + } + + private BigDecimal normalizeQuotePrice(BigDecimal price) { + if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("报价金额必须大于0"); + } + return scaleMoney(price); + } + + private Map loadActiveOrderItemMap(Long orderId) { + return orderItemMapper.selectByOrderId(orderId).stream() + .filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete())) + .collect(Collectors.toMap(OrderItemDO::getId, item -> item, (left, right) -> left, LinkedHashMap::new)); + } + + private List loadActiveOrderItems(Long orderId) { + return new ArrayList<>(loadActiveOrderItemMap(orderId).values()); + } + + private List ensureAllItemsQuoted(Long orderId) { + List items = loadActiveOrderItems(orderId); + if (items.isEmpty()) { + throw new RuntimeException("询价预约作品不存在"); + } + for (OrderItemDO item : items) { + if (item.getQuotedPrice() == null || item.getQuotedPrice().compareTo(BigDecimal.ZERO) <= 0) { + throw new RuntimeException("请先为每个作品填写报价"); + } + } + return items; + } + + private OrderVO finalizeConfirmedQuote(OrderDO order, Long actorId, String actorType) { + order = requireQuoteOrder(order.getId()); + if (!Integer.valueOf(1).equals(order.getQuoteUserConfirmed()) + || !Integer.valueOf(1).equals(order.getQuoteShopConfirmed())) { + return buildOrderVO(order); + } + + List items = ensureAllItemsQuoted(order.getId()); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + Set selectedTagNames = new LinkedHashSet<>(); + List requestedSlots = new ArrayList<>(); + BigDecimal finalTotal = BigDecimal.ZERO; + Long selectedArtistId = null; + + try { + for (OrderItemDO item : items) { + ProductDO product = requireActiveProduct(item.getProductId()); + productCache.put(product.getId(), product); + validateRequestedArtistForItem(order.getShopId(), item.getArtistId(), item, product); + if (selectedArtistId == null) { + selectedArtistId = item.getArtistId(); + } else if (!Objects.equals(selectedArtistId, item.getArtistId())) { + throw bookingUnavailable("不同美甲师的项目请分开确认"); + } + validateAppointmentTime(item.getAppointmentTime(), product.getTitle()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime endTime = item.getAppointmentTime().plusMinutes(durationMinutes); + validateBusinessHours(getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache), + item.getAppointmentTime(), endTime, product.getTitle()); + requestedSlots.add(new AppointmentSlot(product.getTitle(), item.getAppointmentTime(), endTime)); + collectTagNames(selectedTagNames, product.getTags()); + BigDecimal confirmedPrice = scaleMoney(item.getQuotedPrice()); + item.setPrice(confirmedPrice); + item.setConfirmedPrice(confirmedPrice); + finalTotal = finalTotal.add(confirmedPrice.multiply(BigDecimal.valueOf(Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity())))); + } + validateRequestedSlotConflicts(requestedSlots); + } catch (BusinessException exception) { + throw exception; + } catch (RuntimeException exception) { + if (isBookingValidationMessage(exception.getMessage())) { + throw bookingUnavailable(exception.getMessage()); + } + throw exception; + } + + CouponSelection couponSelection = resolveFinalCouponSelection(order, selectedTagNames, finalTotal); + BigDecimal actualAmount = finalTotal; + Long couponId = null; + Long userCouponId = null; + String couponSourceType = null; + if (couponSelection != null) { + CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); + if (coupon != null && !Integer.valueOf(1).equals(coupon.getIsDelete()) && coupon.getStatus() != null && coupon.getStatus() == 1) { + actualAmount = applyCouponDiscount(finalTotal, coupon); + couponId = coupon.getId(); + userCouponId = couponSelection.getUserCouponId(); + couponSourceType = couponSelection.getSourceType(); + if (COUPON_SOURCE_USER.equals(couponSourceType)) { + consumeUserCoupon(userCouponId, order.getUserId()); + } + } + } + + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()) == 0) { + throw new RuntimeException("询价预约状态已变化,请刷新后重试"); + } + + for (OrderItemDO item : items) { + orderItemMapper.updateById(item); + ProductDO product = productCache.get(item.getProductId()); + long durationMinutes = resolveServiceDurationMinutes(product) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + appointmentCapacityService.confirmReservationOrThrow( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + product == null ? null : product.getTitle(), + item.getAppointmentTime(), + item.getAppointmentTime() == null ? null : item.getAppointmentTime().plusMinutes(durationMinutes) + ); + } + + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setTotalAmount(scaleMoney(finalTotal)); + order.setActualAmount(scaleMoney(actualAmount)); + order.setCouponId(couponId); + order.setUserCouponId(userCouponId); + order.setCouponSourceType(couponSourceType); + order.setQuoteStatus(QUOTE_STATUS_CONFIRMED); + order.setQuoteUserConfirmed(1); + order.setQuoteShopConfirmed(1); + order.setQuoteConfirmedTime(LocalDateTime.now()); + order.setPaymentStatus(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? "PAID" : "UNPAID"); + order.setPayAmount(scaleMoney(actualAmount)); + order.setPaidAmount(actualAmount.compareTo(BigDecimal.ZERO) <= 0 ? scaleMoney(actualAmount) : BigDecimal.ZERO); + orderMapper.updateById(order); + + writeQuoteMessage(order.getId(), actorId, actorType, QUOTE_ACTION_SYSTEM_CONFIRM, "双方已确认价格,订单进入待完成"); + notifyQuoteUser(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); + notifyQuoteShopAndArtist(order, "询价预约价格已确认", "双方已确认价格,订单已进入待完成状态。"); + return buildOrderVO(orderMapper.selectById(order.getId())); + } + + private CouponSelection resolveFinalCouponSelection(OrderDO order, Set selectedTagNames, BigDecimal finalTotal) { + List availableCouponOptions = couponService.getAvailableCoupons( + order.getUserId(), + String.join(",", selectedTagNames), + finalTotal.doubleValue(), + order.getShopId() + ); + if (availableCouponOptions == null) { + availableCouponOptions = List.of(); + } + OrderDTO couponRequest = new OrderDTO(); + couponRequest.setCouponSourceType(order.getCouponSourceType()); + if (COUPON_SOURCE_USER.equals(order.getCouponSourceType())) { + couponRequest.setCouponId(order.getUserCouponId()); + } else if (COUPON_SOURCE_SYSTEM_VIP.equals(order.getCouponSourceType())) { + couponRequest.setCouponId(order.getCouponId()); + } + try { + CouponSelection selected = resolveRequestedCoupon(couponRequest, availableCouponOptions); + if (selected != null) { + return selected; + } + } catch (RuntimeException ignored) { + } + if (COUPON_SOURCE_NONE.equalsIgnoreCase(order.getCouponSourceType())) { + return null; + } + return selectBestAvailableCoupon(availableCouponOptions, finalTotal); + } + + private void writeQuoteMessage(Long orderId, Long actorId, String actorType, String action, String remark) { + OrderQuoteMessageDO message = new OrderQuoteMessageDO(); + message.setOrderId(orderId); + message.setActorId(actorId); + message.setActorType(actorType); + message.setAction(action); + message.setRemark(remark); + message.setItemsSnapshot(buildQuoteItemsSnapshot(orderId)); + message.setIsDelete(0); + orderQuoteMessageMapper.insert(message); + } + + private String buildQuoteItemsSnapshot(Long orderId) { + List items = buildQuoteItemVOs(orderId); + StringBuilder builder = new StringBuilder("["); + for (int i = 0; i < items.size(); i++) { + OrderQuoteItemVO item = items.get(i); + if (i > 0) { + builder.append(','); + } + builder.append('{'); + appendJsonField(builder, "orderItemId", item.getOrderItemId()); + builder.append(','); + appendJsonField(builder, "productId", item.getProductId()); + builder.append(','); + appendJsonField(builder, "productTitle", item.getProductTitle()); + builder.append(','); + appendJsonField(builder, "quantity", item.getQuantity()); + builder.append(','); + appendJsonField(builder, "referencePrice", item.getReferencePrice()); + builder.append(','); + appendJsonField(builder, "quotedPrice", item.getQuotedPrice()); + builder.append(','); + appendJsonField(builder, "confirmedPrice", item.getConfirmedPrice()); + builder.append('}'); + } + return builder.append(']').toString(); + } + + private void appendJsonField(StringBuilder builder, String name, Object value) { + builder.append('"').append(name).append('"').append(':'); + if (value == null) { + builder.append("null"); + return; + } + if (value instanceof Number) { + builder.append(value); + return; + } + builder.append('"').append(jsonEscape(String.valueOf(value))).append('"'); + } + + private String jsonEscape(String value) { + return value == null ? "" : value.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private List buildQuoteItemVOs(Long orderId) { + return loadActiveOrderItems(orderId).stream() + .map(item -> { + ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>()); + OrderQuoteItemVO vo = new OrderQuoteItemVO(); + vo.setOrderItemId(item.getId()); + vo.setProductId(item.getProductId()); + vo.setProductTitle(product == null ? null : product.getTitle()); + vo.setQuantity(item.getQuantity()); + vo.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); + vo.setQuotedPrice(item.getQuotedPrice()); + vo.setConfirmedPrice(item.getConfirmedPrice()); + return vo; + }) + .toList(); + } + + private OrderQuoteMessageVO buildQuoteMessageVO(OrderQuoteMessageDO message) { + OrderQuoteMessageVO vo = new OrderQuoteMessageVO(); + vo.setId(message.getId()); + vo.setOrderId(message.getOrderId()); + vo.setActorId(message.getActorId()); + vo.setActorType(message.getActorType()); + vo.setActorTypeText(resolveQuoteActorTypeText(message.getActorType())); + vo.setAction(message.getAction()); + vo.setActionText(resolveQuoteActionText(message.getAction())); + vo.setRemark(message.getRemark()); + vo.setItems(buildQuoteItemVOs(message.getOrderId())); + vo.setCreateTime(message.getCreateTime()); + return vo; + } + + private String resolveQuoteActorTypeText(String actorType) { + if (QUOTE_ACTOR_USER.equals(actorType)) { + return "用户"; + } + if (QUOTE_ACTOR_SHOP.equals(actorType)) { + return "门店"; + } + return "系统"; + } + + private String resolveQuoteActionText(String action) { + if (QUOTE_ACTION_CREATE.equals(action)) return "发起询价预约"; + if (QUOTE_ACTION_SHOP_QUOTE.equals(action)) return "门店报价"; + if (QUOTE_ACTION_USER_REPLY.equals(action)) return "用户回复"; + if (QUOTE_ACTION_USER_CONFIRM.equals(action)) return "用户确认"; + if (QUOTE_ACTION_SHOP_CONFIRM.equals(action)) return "店长确认"; + if (QUOTE_ACTION_SYSTEM_CONFIRM.equals(action)) return "价格已确认"; + if (QUOTE_ACTION_SYSTEM_EXPIRE.equals(action)) return "询价已过期"; + return "询价动态"; + } + + private String resolveQuoteStatusText(String quoteStatus, Integer orderStatus) { + if (QUOTE_STATUS_CONFIRMED.equals(quoteStatus)) { + return "价格已确认"; + } + if (QUOTE_STATUS_EXPIRED.equals(quoteStatus)) { + return "询价已过期"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(orderStatus)) { + return "确认价格中"; + } + return "价格已确认"; + } + + private void notifyQuoteCreated(OrderVO orderVO) { + if (orderVO == null || orderVO.getId() == null) { + return; + } + OrderDO order = orderMapper.selectById(orderVO.getId()); + notifyQuoteShopAndArtist(order, "新的询价预约", "用户发起了新的询价预约,请查看并确认价格。"); + } + + private void notifyQuoteUser(OrderDO order, String title, String content) { + if (order == null) { + return; + } + createQuoteNotification(order.getUserId(), title, content, "/orders?orderId=" + order.getId(), order.getId(), 0L, "系统通知", 4); + } + + private void notifyQuoteShopAndArtist(OrderDO order, String title, String content) { + if (order == null || order.getId() == null) { + return; + } + Set targetIds = new LinkedHashSet<>(); + if (order.getShopId() != null) { + List owners = userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getShopId, order.getShopId()) + .eq(UserDO::getType, USER_TYPE_SHOP_OWNER) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1)); + owners.stream().map(UserDO::getId).filter(Objects::nonNull).forEach(targetIds::add); + userShopBindingSupport.listUserIdsByShopId(order.getShopId(), true).forEach(userId -> { + UserDO user = userMapper.selectById(userId); + if (user != null && Integer.valueOf(USER_TYPE_SHOP_OWNER).equals(user.getType())) { + targetIds.add(userId); + } + }); + } + loadActiveOrderItems(order.getId()).stream() + .map(OrderItemDO::getArtistId) + .filter(Objects::nonNull) + .forEach(targetIds::add); + targetIds.remove(order.getUserId()); + targetIds.forEach(targetId -> createQuoteNotification( + targetId, + title, + content, + "/admin/orders?orderId=" + order.getId(), + order.getId(), + order.getUserId(), + "用户询价预约", + 0 + )); + } + + private void createQuoteNotification(Long targetUserId, + String title, + String content, + String actionPath, + Long businessId, + Long publisherId, + String publisherName, + Integer publisherType) { + if (targetUserId == null) { + return; + } + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setPublisherId(publisherId == null ? 0L : publisherId); + message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); + message.setPublisherType(publisherType == null ? 4 : publisherType); + message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); + message.setTargetIds(String.valueOf(targetUserId)); + message.setBusinessType(QUOTE_BUSINESS_TYPE); + message.setBusinessId(businessId); + message.setActionPath(actionPath); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + } + + private Long createSystemBusinessMessage(Long targetUserId, + String title, + String content, + String businessType, + Long businessId, + String actionPath, + Long publisherId, + String publisherName, + Integer publisherType) { + if (targetUserId == null) { + return null; + } + String targetIds = String.valueOf(targetUserId); + String idempotencyKey = buildSystemMessageIdempotencyKey(businessType, businessId, targetUserId); + if (StringUtils.hasText(idempotencyKey)) { + Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); + if (existingMessageId != null) { + return existingMessageId; + } + } + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setPublisherId(publisherId == null ? 0L : publisherId); + message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知"); + message.setPublisherType(publisherType == null ? 4 : publisherType); + message.setTargetType(MESSAGE_TARGET_SELECTED_USERS); + message.setTargetIds(targetIds); + message.setBusinessType(businessType); + message.setBusinessId(businessId); + message.setActionPath(actionPath); + message.setIdempotencyKey(idempotencyKey); + message.setPopupEnabled(1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + try { + systemMessageMapper.insert(message); + } catch (DuplicateKeyException exception) { + Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey); + if (existingMessageId != null) { + return existingMessageId; + } + throw exception; + } + return message.getId(); + } + + /** + * Purpose: buildSystemMessageIdempotencyKey supports OrderServiceImpl.java by holding or executing the build system message idempotency key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildSystemMessageIdempotencyKey(String businessType, Long businessId, Long targetUserId) { + if (!StringUtils.hasText(businessType) || businessId == null || targetUserId == null) { + return null; + } + return businessType + ":" + businessId + ":" + targetUserId; + } + + private Long findSystemBusinessMessageId(String businessType, + Long businessId, + String targetIds, + String idempotencyKey) { + if (!StringUtils.hasText(idempotencyKey)) { + return null; + } + SystemMessageDO existingMessage = systemMessageMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemMessageDO::getBusinessType, businessType) + .eq(SystemMessageDO::getBusinessId, businessId) + .eq(SystemMessageDO::getTargetType, MESSAGE_TARGET_SELECTED_USERS) + .eq(SystemMessageDO::getTargetIds, targetIds) + .eq(SystemMessageDO::getIsDelete, 0) + .and(wrapper -> wrapper + .eq(SystemMessageDO::getIdempotencyKey, idempotencyKey) + .or() + .isNull(SystemMessageDO::getIdempotencyKey)) + .last("LIMIT 1")); + return existingMessage == null ? null : existingMessage.getId(); + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO buildOrderVO(OrderDO order) { + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildOrderVO(order, null); + } + + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureCalendarAccess(Long userId, Integer userType) { + if (userId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录"); + } + if (Integer.valueOf(3).equals(userType)) { + return; + } + if (Integer.valueOf(2).equals(userType)) { + NailArtistInfoDO info = nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { + return; + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师或参与制作的店长可查看预约日历"); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listArtistCalendarAppointments(Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + List items = orderItemMapper.selectArtistCalendarItems(artistId, startTime, endTime); + if (items == null || items.isEmpty()) { + return Collections.emptyList(); + } + + Map userCache = new HashMap<>(); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + UserDO artist = getUserFromCache(artistId, userCache); + List result = new ArrayList<>(); + + for (OrderItemDO item : items) { + OrderDO order = orderMapper.selectById(item.getOrderId()); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || Integer.valueOf(3).equals(order.getStatus())) { + continue; + } + ProductDO product = getProductFromCache(item.getProductId(), productCache); + if (product == null || item.getAppointmentTime() == null) { + continue; + } + ShopDO shop = getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache); + UserDO customer = getUserFromCache(order.getUserId(), userCache); + long singleDuration = resolveServiceDurationMinutes(product); + int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + long durationMinutes = singleDuration * quantity; + + ArtistCalendarAppointmentVO vo = new ArtistCalendarAppointmentVO(); + vo.setOrderId(order.getId()); + vo.setOrderNo(order.getOrderNo()); + vo.setTotalAmount(order.getTotalAmount()); + vo.setActualAmount(order.getActualAmount()); + vo.setOrderStatus(order.getStatus()); + vo.setOrderStatusText(resolveOrderStatusText(order.getStatus())); + vo.setOrderItemId(item.getId()); + vo.setProductId(product.getId()); + vo.setProductTitle(product.getTitle()); + vo.setArtistId(artistId); + vo.setArtistName(artist == null ? null : artist.getNickname()); + vo.setCustomerNickname(resolveCustomerNickname(customer)); + vo.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); + vo.setShopId(order.getShopId() == null ? product.getShopId() : order.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setAppointmentStartTime(item.getAppointmentTime()); + vo.setAppointmentEndTime(item.getAppointmentTime().plusMinutes(durationMinutes)); + vo.setQuantity(item.getQuantity()); + vo.setDurationMinutes(durationMinutes); + result.add(vo); + } + result.sort(Comparator.comparing(ArtistCalendarAppointmentVO::getAppointmentStartTime)); + return result; + } + + /** + * Run business method `resolveOrderStatusText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveOrderStatusText(Integer status) { + if (Integer.valueOf(0).equals(status)) { + return "确认价格中"; + } + if (Integer.valueOf(1).equals(status)) { + return "待完成"; + } + if (Integer.valueOf(1).equals(status)) { + return "待服务"; + } + if (Integer.valueOf(2).equals(status)) { + return "已完成"; + } + if (Integer.valueOf(3).equals(status)) { + return "已取消"; + } + return "未知状态"; + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param artistIdFilter parameter `artistIdFilter` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ + private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) { + OrderVO orderVO = new OrderVO(); + Map userCache = new HashMap<>(); + orderVO.setId(order.getId()); + orderVO.setOrderNo(order.getOrderNo()); + orderVO.setUserId(order.getUserId()); + orderVO.setShopId(order.getShopId()); + if (order.getShopId() != null) { + ShopDO shop = shopMapper.selectById(order.getShopId()); + orderVO.setShopName(shop == null ? null : shop.getShopName()); + } + orderVO.setTotalAmount(order.getTotalAmount()); + orderVO.setActualAmount(order.getActualAmount()); + orderVO.setCouponId(order.getCouponId()); + orderVO.setUserCouponId(order.getUserCouponId()); + orderVO.setCouponSourceType(order.getCouponSourceType()); + orderVO.setPaymentStatus(order.getPaymentStatus()); + orderVO.setPayAmount(order.getPayAmount()); + orderVO.setPaidAmount(order.getPaidAmount()); + orderVO.setPayTime(order.getPayTime()); + orderVO.setPaymentMethod(order.getPaymentMethod()); + orderVO.setPaymentOrderNo(order.getPaymentOrderNo()); + orderVO.setRefundStatus(order.getRefundStatus()); + orderVO.setCustomerRemark(order.getCustomerRemark()); + orderVO.setQuoteStatus(order.getQuoteStatus()); + orderVO.setQuoteStatusText(resolveQuoteStatusText(order.getQuoteStatus(), order.getStatus())); + orderVO.setQuoteUserConfirmed(Integer.valueOf(1).equals(order.getQuoteUserConfirmed())); + orderVO.setQuoteShopConfirmed(Integer.valueOf(1).equals(order.getQuoteShopConfirmed())); + orderVO.setQuoteExpireTime(order.getQuoteExpireTime()); + orderVO.setQuoteConfirmedTime(order.getQuoteConfirmedTime()); + if (orderQuoteMessageMapper != null) { + orderVO.setQuoteMessages(orderQuoteMessageMapper.selectByOrderId(order.getId()).stream() + .map(this::buildQuoteMessageVO) + .toList()); + } + UserDO customer = getUserFromCache(order.getUserId(), userCache); + orderVO.setCustomerNickname(resolveCustomerNickname(customer)); + orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); + orderVO.setStatus(order.getStatus()); + + switch (order.getStatus()) { + case 0: + orderVO.setStatusText("确认价格中"); + break; + case 1: + orderVO.setStatusText("待使用"); + break; + case 2: + orderVO.setStatusText("已完成"); + break; + case 3: + orderVO.setStatusText("已取消"); + break; + default: + orderVO.setStatusText("未知状态"); + } + + if (Integer.valueOf(1).equals(order.getStatus())) { + orderVO.setStatusText("待完成"); + } + + if (artistIdFilter == null && order.getCouponId() != null && order.getCouponId() > 0) { + CouponDO coupon = couponMapper.selectById(order.getCouponId()); + if (coupon != null) { + orderVO.setCouponName(coupon.getCouponName()); + } + } + + orderVO.setCreateTime(order.getCreateTime()); + + List orderItemVOs = new ArrayList<>(); + BigDecimal filteredTotal = BigDecimal.ZERO; + List orderItems = orderItemMapper.selectByOrderId(order.getId()); + + for (OrderItemDO item : orderItems) { + if (Integer.valueOf(1).equals(item.getIsDelete())) { + continue; + } + if (artistIdFilter != null && !artistIdFilter.equals(item.getArtistId())) { + continue; + } + + ProductDO product = productMapper.selectById(item.getProductId()); + if (product == null) { + continue; + } + + OrderItemVO itemVO = new OrderItemVO(); + itemVO.setId(item.getId()); + itemVO.setProductId(product.getId()); + itemVO.setProductTitle(product.getTitle()); + + String imageFileIds = product.getImageFileIds(); + if (imageFileIds != null && !imageFileIds.isEmpty()) { + String firstImageId = imageFileIds.split(",")[0]; + itemVO.setProductImage("/api/file/get/" + firstImageId); + } + + itemVO.setQuantity(item.getQuantity()); + itemVO.setPrice(item.getPrice()); + itemVO.setReferencePrice(item.getReferencePrice() == null ? item.getPrice() : item.getReferencePrice()); + itemVO.setQuotedPrice(item.getQuotedPrice()); + itemVO.setConfirmedPrice(item.getConfirmedPrice()); + BigDecimal displayPrice = item.getConfirmedPrice() == null ? item.getPrice() : item.getConfirmedPrice(); + itemVO.setPrice(displayPrice); + itemVO.setTotalPrice(displayPrice.multiply(BigDecimal.valueOf(item.getQuantity()))); + itemVO.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + String occupancyStatus = resolveOrderItemOccupancyStatus(order); + itemVO.setOccupancyStatus(occupancyStatus); + itemVO.setCanEdit(canEditOrderItem(order)); + itemVO.setCanCancel(canCancelOrderItem(order)); + itemVO.setConflictReason(resolveOrderItemConflictReason(occupancyStatus)); + filteredTotal = filteredTotal.add(itemVO.getTotalPrice()); + + if (item.getArtistId() != null) { + itemVO.setArtistId(item.getArtistId()); + UserDO artist = getUserFromCache(item.getArtistId(), userCache); + if (artist != null) { + itemVO.setArtistName(artist.getNickname()); + itemVO.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + } + } + + OrderArtistReviewDO review = orderArtistReviewMapper.selectByOrderItemId(item.getId()); + if (review != null) { + OrderArtistReviewVO reviewVO = buildArtistReviewVO(review); + if (Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) { + itemVO.setPendingReview(reviewVO); + } else if (Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus())) { + itemVO.setReviewSummary(reviewVO); + } + } + + OrderArtistChangeRequestDO pendingChangeRequest = orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()); + if (pendingChangeRequest != null) { + itemVO.setPendingArtistChangeRequest(buildArtistChangeRequestVO(pendingChangeRequest)); + } + + orderItemVOs.add(itemVO); + } + + orderVO.setItems(orderItemVOs); + if (artistIdFilter != null) { + orderVO.setTotalAmount(filteredTotal); + orderVO.setActualAmount(filteredTotal); + } + return orderVO; + } + + private String resolveOrderItemOccupancyStatus(OrderDO order) { + if (order == null || order.getStatus() == null) { + return "UNKNOWN"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + return "PENDING_QUOTE"; + } + if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + return "CONFIRMED"; + } + if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + return "CANCELLED"; + } + if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { + return "COMPLETED"; + } + return "UNKNOWN"; + } + + private Boolean canEditOrderItem(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private Boolean canCancelOrderItem(OrderDO order) { + if (order == null || order.getStatus() == null) { + return false; + } + return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) + || Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()); + } + + private String resolveOrderItemConflictReason(String occupancyStatus) { + if ("PENDING_QUOTE".equals(occupancyStatus)) { + return "该时段已作为待报价预约保留"; + } + if ("CONFIRMED".equals(occupancyStatus)) { + return "该时段已确认占用"; + } + return null; + } + + /** + * Run business method `buildRequestedQuantityMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map buildRequestedQuantityMap(List orderItemDTOs) { + Map requestedQuantityByProductId = new HashMap<>(); + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + if (orderItemDTO == null || orderItemDTO.getProductId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品信息不完整"); + } + requestedQuantityByProductId.merge( + orderItemDTO.getProductId(), + orderItemDTO.getQuantity() == null ? 0 : orderItemDTO.getQuantity(), + Integer::sum + ); + } + return requestedQuantityByProductId; + } + + /** + * Run business method `loadLockedCartItems`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param requestedProductIds parameter `requestedProductIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadLockedCartItems(Long userId, List requestedProductIds) { + if (requestedProductIds == null || requestedProductIds.isEmpty()) { + return Collections.emptyMap(); + } + + List lockedCartItems = cartMapper.selectByUserIdAndProductIdsForUpdate(userId, requestedProductIds); + Map lockedCartItemMap = new HashMap<>(); + for (CartDO cartDO : lockedCartItems) { + if (cartDO != null && cartDO.getProductId() != null) { + lockedCartItemMap.put(cartDO.getProductId(), cartDO); + } + } + return lockedCartItemMap; + } + + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateUserCanCreateOrderInShop(Long userId, Long shopId) { + if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试"); + } + } + + /** + * Run business method `resolveRequestedArtistId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveRequestedArtistId(List orderItemDTOs) { + Long artistId = null; + for (OrderItemDTO orderItemDTO : orderItemDTOs) { + if (orderItemDTO == null || orderItemDTO.getArtistId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + if (artistId == null) { + artistId = orderItemDTO.getArtistId(); + continue; + } + if (!artistId.equals(orderItemDTO.getArtistId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不同美甲师的项目请分开下单"); + } + } + if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + return artistId; + } + + /** + * Run business method `tryAcquireOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean tryAcquireOrderLock(String lockKey, String lockToken) { + return Boolean.TRUE.equals( + stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL) + ); + } + + /** + * Run business method `tryAcquireArtistOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) { + long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS; + while (System.currentTimeMillis() <= deadline) { + if (tryAcquireOrderLock(lockKey, lockToken)) { + return true; + } + try { + Thread.sleep(ARTIST_LOCK_RETRY_INTERVAL_MILLIS); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + return false; + } + } + return false; + } + + // 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。 + /** + * Run business method `startOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private LockLease result consumed by the caller or returned to the frontend + */ + private LockLease startOrderLockRenewal(String lockKey, String lockToken) { + if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { + return null; + } + + LockLease lockLease = new LockLease(lockKey, lockToken); + ScheduledFuture future = LOCK_RENEW_EXECUTOR.scheduleWithFixedDelay( + () -> renewOrderLock(lockLease), + ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, + ORDER_CREATE_LOCK_RENEW_INTERVAL_MILLIS, + TimeUnit.MILLISECONDS + ); + lockLease.attachFuture(future); + return lockLease; + } + + /** + * Run business method `renewOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void renewOrderLock(LockLease lockLease) { + if (lockLease == null || !lockLease.isActive()) { + return; + } + try { + Long renewResult = stringRedisTemplate.execute( + RENEW_LOCK_SCRIPT, + Collections.singletonList(lockLease.getLockKey()), + lockLease.getLockToken(), + String.valueOf(ORDER_CREATE_LOCK_TTL_MILLIS) + ); + if (!Long.valueOf(1L).equals(renewResult)) { + lockLease.cancel(); + } + } catch (Exception ignored) { + } + } + + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void stopOrderLockRenewal(LockLease lockLease) { + if (lockLease == null) { + return; + } + lockLease.cancel(); + } + + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void releaseOrderLock(String lockKey, String lockToken) { + if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { + return; + } + stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userCache parameter `userCache` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getUserFromCache(Long userId, Map userCache) { + if (userId == null) { + return null; + } + if (userCache.containsKey(userId)) { + return userCache.get(userId); + } + UserDO userDO = userMapper.selectById(userId); + userCache.put(userId, userDO); + return userDO; + } + + /** + * Run business method `resolveCustomerNickname`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param customer parameter `customer` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveCustomerNickname(UserDO customer) { + if (customer == null) { + return "用户"; + } + if (StringUtils.hasText(customer.getNickname())) { + return customer.getNickname(); + } + if (StringUtils.hasText(customer.getAccount())) { + return customer.getAccount(); + } + return "用户"; + } + + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone)) { + return null; + } + String normalizedPhone = phone.trim(); + if (normalizedPhone.length() < 7) { + return normalizedPhone; + } + return normalizedPhone.substring(0, 3) + + "****" + + normalizedPhone.substring(normalizedPhone.length() - 4); + } + + /** + * Run business method `validateOrderQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateOrderQuantity(Integer quantity) { + if (quantity == null || quantity < 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单商品数量必须大于 0"); + } + } + + /** + * Run business method `validateArtistForProduct`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO validateArtistForProduct(ProductDO product, Long artistId) { + if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择美甲师"); + } + + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师不存在或已删除"); + } + if (!bookableArtistSupport.isBookableServiceUser(artist)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("指定用户不是可预约美甲服务人员"); + } + if (!Integer.valueOf(1).equals(artist.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("美甲师当前不可预约"); + } + if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该美甲师不属于当前商品店铺"); + } + + if (product.getBookableArtists() != null && !product.getBookableArtists().isEmpty()) { + String[] artistIds = product.getBookableArtists().split(","); + boolean isBookable = false; + for (String currentArtistId : artistIds) { + if (currentArtistId.trim().equals(artistId.toString())) { + isBookable = true; + break; + } + } + if (!isBookable) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该美甲师无法预约此商品"); + } + } + + return artist; + } + + /** + * Run business method `collectTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagNames parameter `tagNames` supplied by the caller + * @param tags parameter `tags` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void collectTagNames(Set tagNames, String tags) { + if (tags == null || tags.isBlank()) { + return; + } + + for (String tagId : tags.split(";")) { + if (tagId == null || tagId.isBlank()) { + continue; + } + try { + TagVO tagVO = tagService.getTagById(Long.parseLong(tagId.trim())); + if (tagVO != null && tagVO.getTagName() != null && !tagVO.getTagName().isBlank()) { + tagNames.add(tagVO.getTagName()); + } + } catch (NumberFormatException ignored) { + } + } + } + + /** + * Run business method `parseAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime parseAppointmentTime(String appointmentTime) { + if (appointmentTime == null || appointmentTime.isBlank()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请为每个商品选择预约时间"); + } + + String normalized = appointmentTime.trim(); + for (DateTimeFormatter formatter : APPOINTMENT_INPUT_FORMATTERS) { + try { + return LocalDateTime.parse(normalized, formatter); + } catch (DateTimeParseException ignored) { + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("预约时间格式不正确"); + } + + /** + * Run business method `validateAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateAppointmentTime(LocalDateTime appointmentTime, String productTitle) { + if (!appointmentTime.isAfter(LocalDateTime.now())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品「" + productTitle + "」的预约时间必须晚于当前时间"); + } + } + + /** + * Run business method `validateBusinessHours`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shop parameter `shop` supplied by the caller + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param appointmentEndTime parameter `appointmentEndTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateBusinessHours(ShopDO shop, LocalDateTime appointmentTime, LocalDateTime appointmentEndTime, String productTitle) { + if (shop == null || shop.getBusinessHours() == null || shop.getBusinessHours().isBlank()) { + return; + } + + String normalizedBusinessHours = shop.getBusinessHours() + .replace(':', ':') + .replace('-', '-') + .replace('—', '-') + .trim(); + Matcher matcher = BUSINESS_HOURS_PATTERN.matcher(normalizedBusinessHours); + if (!matcher.matches()) { + return; + } + + LocalTime openTime = LocalTime.parse(matcher.group(1), DateTimeFormatter.ofPattern("H:mm")); + LocalTime closeTime = LocalTime.parse(matcher.group(2), DateTimeFormatter.ofPattern("H:mm")); + if (!closeTime.isAfter(openTime)) { + return; + } + + if (!appointmentTime.toLocalDate().equals(appointmentEndTime.toLocalDate()) + || appointmentTime.toLocalTime().isBefore(openTime) + || appointmentEndTime.toLocalTime().isAfter(closeTime)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("商品「" + productTitle + "」的预约时间超出门店营业时间"); + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param shopCache parameter `shopCache` supplied by the caller + * @return private ShopDO result consumed by the caller or returned to the frontend + */ + private ShopDO getShopFromCache(Long shopId, Map shopCache) { + if (shopId == null) { + return null; + } + if (shopCache.containsKey(shopId)) { + return shopCache.get(shopId); + } + + ShopDO shop = shopMapper.selectById(shopId); + if (shop != null && Integer.valueOf(1).equals(shop.getIsDelete())) { + shop = null; + } + shopCache.put(shopId, shop); + return shop; + } + + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateRequestedSlotConflicts(List requestedSlots) { + if (requestedSlots.size() <= 1) { + return; + } + + requestedSlots.sort(Comparator.comparing(AppointmentSlot::getStartTime)); + for (int i = 1; i < requestedSlots.size(); i++) { + AppointmentSlot previous = requestedSlots.get(i - 1); + AppointmentSlot current = requestedSlots.get(i); + if (hasOverlap(previous.getStartTime(), previous.getEndTime(), current.getStartTime(), current.getEndTime())) { + throw new RuntimeException("所选预约时间存在冲突,请调整「" + previous.getProductTitle() + "」和「" + current.getProductTitle() + "」的预约时间"); + } + } + } + + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateArtistScheduleConflicts(Long artistId, List requestedSlots, Map productCache) { + if (artistId == null || requestedSlots.isEmpty()) { + return; + } + + for (AppointmentSlot requestedSlot : requestedSlots) { + int activeOccupancyCount = appointmentReservationMapper.countOverlappingActive( + artistId, + requestedSlot.getStartTime(), + requestedSlot.getEndTime() + ); + if (activeOccupancyCount > 0) { + throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约占用冲突,请重新选择"); + } + } + + List existingAppointments = orderItemMapper.selectActiveAppointmentItemsByArtistId(artistId); + if (existingAppointments == null || existingAppointments.isEmpty()) { + return; + } + + for (OrderItemDO existingItem : existingAppointments) { + if (existingItem.getAppointmentTime() == null || Integer.valueOf(1).equals(existingItem.getIsDelete())) { + continue; + } + + ProductDO existingProduct = getProductFromCache(existingItem.getProductId(), productCache); + if (existingProduct == null) { + continue; + } + + long existingDurationMinutes = resolveServiceDurationMinutes(existingProduct) * Math.max(1, existingItem.getQuantity()); + LocalDateTime existingEndTime = existingItem.getAppointmentTime().plusMinutes(existingDurationMinutes); + + for (AppointmentSlot requestedSlot : requestedSlots) { + if (hasOverlap(existingItem.getAppointmentTime(), existingEndTime, requestedSlot.getStartTime(), requestedSlot.getEndTime())) { + throw new RuntimeException("商品「" + requestedSlot.getProductTitle() + "」的预约时间与美甲师已有预约冲突,请重新选择"); + } + } + } + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private ProductDO result consumed by the caller or returned to the frontend + */ + private ProductDO getProductFromCache(Long productId, Map productCache) { + if (productId == null) { + return null; + } + if (productCache.containsKey(productId)) { + return productCache.get(productId); + } + + ProductDO product = productMapper.selectById(productId); + if (product != null && Integer.valueOf(1).equals(product.getIsDelete())) { + product = null; + } + productCache.put(productId, product); + return product; + } + + /** + * Run business method `resolveServiceDurationMinutes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ + private long resolveServiceDurationMinutes(ProductDO product) { + if (product == null || product.getApproximateDuration() == null || product.getApproximateDuration().isBlank()) { + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + Matcher matcher = DURATION_PATTERN.matcher(product.getApproximateDuration()); + if (matcher.find()) { + try { + return Math.max(1L, Long.parseLong(matcher.group(1))); + } catch (NumberFormatException ignored) { + } + } + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + /** + * Run business method `hasOverlap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param startA parameter `startA` supplied by the caller + * @param endA parameter `endA` supplied by the caller + * @param startB parameter `startB` supplied by the caller + * @param endB parameter `endB` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasOverlap(LocalDateTime startA, LocalDateTime endA, LocalDateTime startB, LocalDateTime endB) { + return startA.isBefore(endB) && startB.isBefore(endA); + } + + /** + * Run business method `formatAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String formatAppointmentTime(LocalDateTime appointmentTime) { + if (appointmentTime == null) { + return null; + } + return appointmentTime.format(APPOINTMENT_OUTPUT_FORMATTER); + } + + /** + * Run business method `resolveRequestedCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ + private CouponSelection resolveRequestedCoupon(OrderDTO orderDTO, List availableCoupons) { + if (orderDTO == null || orderDTO.getCouponId() == null || orderDTO.getCouponId() <= 0) { + return null; + } + + String requestedSourceType = normalizeCouponSourceType(orderDTO.getCouponSourceType()); + List matchedCoupons = availableCoupons.stream() + .filter(coupon -> orderDTO.getCouponId().equals(coupon.getId())) + .filter(coupon -> requestedSourceType == null || requestedSourceType.equals(coupon.getSourceType())) + .toList(); + + if (matchedCoupons.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前订单不可使用所选优惠券"); + } + + UserCouponVO selectedCoupon = matchedCoupons.stream() + .filter(coupon -> COUPON_SOURCE_USER.equals(coupon.getSourceType())) + .findFirst() + .orElse(matchedCoupons.get(0)); + + return new CouponSelection( + selectedCoupon.getSourceType(), + selectedCoupon.getCouponId(), + COUPON_SOURCE_USER.equals(selectedCoupon.getSourceType()) ? selectedCoupon.getId() : null + ); + } + + /** + * Run business method `selectBestAvailableCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ + private CouponSelection selectBestAvailableCoupon(List availableCoupons, BigDecimal totalAmount) { + return availableCoupons.stream() + .filter(coupon -> coupon.getCouponId() != null) + .max(Comparator.comparing(coupon -> calculateCouponDiscountAmount(coupon, totalAmount))) + .map(coupon -> new CouponSelection( + coupon.getSourceType(), + coupon.getCouponId(), + COUPON_SOURCE_USER.equals(coupon.getSourceType()) ? coupon.getId() : null + )) + .orElse(null); + } + + /** + * Run business method `normalizeCouponSourceType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponSourceType parameter `couponSourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeCouponSourceType(String couponSourceType) { + if (couponSourceType == null || couponSourceType.isBlank()) { + return null; + } + return couponSourceType.trim().toUpperCase(); + } + + /** + * Run business method `isExplicitNoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isExplicitNoCoupon(OrderDTO orderDTO) { + return orderDTO != null + && orderDTO.getCouponId() == null + && COUPON_SOURCE_NONE.equalsIgnoreCase(orderDTO.getCouponSourceType()); + } + + /** + * Run business method `calculateCouponDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param coupon parameter `coupon` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal calculateCouponDiscountAmount(UserCouponVO coupon, BigDecimal totalAmount) { + if (coupon == null || totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) { + return BigDecimal.ZERO; + } + + if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null && !coupon.getDiscountValue().isBlank()) { + BigDecimal discountValue = new BigDecimal(coupon.getDiscountValue()); + BigDecimal discountedAmount = totalAmount.multiply(discountValue) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + return totalAmount.subtract(discountedAmount); + } + + if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null && !coupon.getReduceAmount().isBlank()) { + return new BigDecimal(coupon.getReduceAmount()); + } + + return BigDecimal.ZERO; + } + + /** + * Run business method `applyCouponDiscount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param totalAmount parameter `totalAmount` supplied by the caller + * @param coupon parameter `coupon` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal applyCouponDiscount(BigDecimal totalAmount, CouponDO coupon) { + if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null) { + return totalAmount.multiply(coupon.getDiscountValue()) + .divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP); + } + if (coupon.getCouponType() == 2 && coupon.getReduceAmount() != null) { + BigDecimal actualAmount = totalAmount.subtract(coupon.getReduceAmount()); + return actualAmount.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : actualAmount; + } + return totalAmount; + } + + /** + * Run business method `consumeUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void consumeUserCoupon(Long userCouponId, Long userId) { + if (userCouponId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户优惠券信息缺失"); + } + + UserCouponDO userCoupon = userCouponMapper.selectById(userCouponId); + if (userCoupon == null || Integer.valueOf(1).equals(userCoupon.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不存在或已失效"); + } + if (!userId.equals(userCoupon.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券不属于当前用户"); + } + if (userCoupon.getStatus() == null || userCoupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("优惠券已被使用或不可用"); + } + + userCoupon.setStatus(2); + userCoupon.setUseTime(LocalDateTime.now()); + userCouponMapper.updateById(userCoupon); + updateCouponUsedCount(userCoupon.getCouponId(), 1); + } + + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void restoreUserCoupon(OrderDO order, Long userId) { + if (order == null + || !COUPON_SOURCE_USER.equals(order.getCouponSourceType()) + || order.getUserCouponId() == null + || userId == null) { + return; + } + + UserCouponDO userCoupon = userCouponMapper.selectById(order.getUserCouponId()); + if (userCoupon == null || !userId.equals(userCoupon.getUserId()) || userCoupon.getStatus() == null || userCoupon.getStatus() != 2) { + return; + } + + userCoupon.setStatus(1); + userCoupon.setUseTime(null); + userCouponMapper.updateById(userCoupon); + updateCouponUsedCount(userCoupon.getCouponId(), -1); + } + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param delta parameter `delta` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void updateCouponUsedCount(Long couponId, int delta) { + if (couponId == null || delta == 0) { + return; + } + + CouponDO couponDO = couponMapper.selectById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + return; + } + + int currentUsedCount = couponDO.getUsedCount() == null ? 0 : couponDO.getUsedCount(); + couponDO.setUsedCount(Math.max(0, currentUsedCount + delta)); + couponMapper.updateById(couponDO); + } + + /** + * Purpose: LockLease supports OrderServiceImpl.java by holding or executing the lock lease business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LockLease { + /** + * Variable `lockKey`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String lockKey; + /** + * Variable `lockToken`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String lockToken; + /** + * Purpose: future supports OrderServiceImpl.java by holding or executing the future business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private volatile ScheduledFuture future; + /** + * Purpose: active supports OrderServiceImpl.java by holding or executing the active business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private volatile boolean active = true; + + /** + * Run business method `LockLease`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private LockLease(String lockKey, String lockToken) { + this.lockKey = lockKey; + this.lockToken = lockToken; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getLockKey() { + return lockKey; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getLockToken() { + return lockToken; + } + + /** + * Run business method `isActive`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isActive() { + return active; + } + + /** + * Run business method `attachFuture`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param future parameter `future` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void attachFuture(ScheduledFuture future) { + this.future = future; + if (!active && future != null) { + future.cancel(false); + } + } + + /** + * Run business method `cancel`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void cancel() { + active = false; + ScheduledFuture currentFuture = future; + if (currentFuture != null) { + currentFuture.cancel(false); + } + } + } + + /** + * Purpose: LockRenewThreadFactory supports OrderServiceImpl.java by holding or executing the lock renew thread factory business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LockRenewThreadFactory implements ThreadFactory { + @Override + /** + * Run business method `newThread`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param runnable parameter `runnable` supplied by the caller + * @return Thread result consumed by the caller or returned to the frontend + */ + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "order-lock-renew"); + thread.setDaemon(true); + return thread; + } + } + + /** + * Purpose: CouponSelection supports OrderServiceImpl.java by holding or executing the coupon selection business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class CouponSelection { + /** + * Variable `sourceType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String sourceType; + /** + * Variable `couponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Long couponId; + /** + * Variable `userCouponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Long userCouponId; + + /** + * Run business method `CouponSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param userCouponId parameter `userCouponId` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private CouponSelection(String sourceType, Long couponId, Long userCouponId) { + this.sourceType = sourceType; + this.couponId = couponId; + this.userCouponId = userCouponId; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getSourceType() { + return sourceType; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getCouponId() { + return couponId; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long getUserCouponId() { + return userCouponId; + } + } + + private static final class CheckoutPricingContext { + private final BigDecimal totalAmount; + private final Long shopId; + private final String productTagNames; + + private CheckoutPricingContext(BigDecimal totalAmount, Long shopId, String productTagNames) { + this.totalAmount = totalAmount; + this.shopId = shopId; + this.productTagNames = productTagNames; + } + + private BigDecimal getTotalAmount() { + return totalAmount; + } + + private Long getShopId() { + return shopId; + } + + private String getProductTagNames() { + return productTagNames; + } + } + + private static final class BookingValidationSlot { + private final Long productId; + private final String productTitle; + private final LocalDateTime startTime; + private final LocalDateTime endTime; + + private BookingValidationSlot(Long productId, String productTitle, LocalDateTime startTime, LocalDateTime endTime) { + this.productId = productId; + this.productTitle = productTitle; + this.startTime = startTime; + this.endTime = endTime; + } + + private Long getProductId() { + return productId; + } + + private String getProductTitle() { + return productTitle; + } + + private LocalDateTime getStartTime() { + return startTime; + } + + private LocalDateTime getEndTime() { + return endTime; + } + } + + /** + * Purpose: AppointmentSlot supports OrderServiceImpl.java by holding or executing the appointment slot business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class AppointmentSlot { + /** + * Variable `productTitle`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String productTitle; + /** + * Variable `startTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LocalDateTime startTime; + /** + * Variable `endTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final LocalDateTime endTime; + + /** + * Run business method `AppointmentSlot`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productTitle parameter `productTitle` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ + private AppointmentSlot(String productTitle, LocalDateTime startTime, LocalDateTime endTime) { + this.productTitle = productTitle; + this.startTime = startTime; + this.endTime = endTime; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ + private String getProductTitle() { + return productTitle; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime getStartTime() { + return startTime; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ + private LocalDateTime getEndTime() { + return endTime; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStateMachine.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStateMachine.java new file mode 100644 index 00000000..72345599 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStateMachine.java @@ -0,0 +1,35 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.support; + +/** + * Purpose: OrderStateMachine supports OrderStateMachine.java by holding or executing the order state machine business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class OrderStateMachine { + + private OrderStateMachine() { + } + + /** + * Purpose: isAllowedTransition supports OrderStateMachine.java by holding or executing the is allowed transition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean isAllowedTransition(Integer fromStatus, Integer toStatus) { + OrderStatus from = OrderStatus.requireKnown(fromStatus); + OrderStatus to = OrderStatus.requireKnown(toStatus); + if (from == OrderStatus.PRICE_CONFIRMING) { + return to == OrderStatus.PENDING_SERVICE || to == OrderStatus.CANCELLED; + } + return from == OrderStatus.PENDING_SERVICE + && (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED); + } + + /** + * Purpose: requireAllowedTransition supports OrderStateMachine.java by holding or executing the require allowed transition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void requireAllowedTransition(Integer fromStatus, Integer toStatus) { + if (!isAllowedTransition(fromStatus, toStatus)) { + throw new RuntimeException("订单状态不允许处理"); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStatus.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStatus.java new file mode 100644 index 00000000..0675b0d0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/support/OrderStatus.java @@ -0,0 +1,43 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.support; + +import java.util.Arrays; + +/** + * Purpose: OrderStatus supports OrderStatus.java by holding or executing the order status business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ +public enum OrderStatus { + PRICE_CONFIRMING(0), + PENDING_SERVICE(1), + COMPLETED(2), + CANCELLED(3); + + /** + * Purpose: code supports OrderStatus.java by holding or executing the code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final int code; + + OrderStatus(int code) { + this.code = code; + } + + /** + * Purpose: getCode supports OrderStatus.java by holding or executing the get code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public int getCode() { + return code; + } + + /** + * Purpose: requireKnown supports OrderStatus.java by holding or executing the require known business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static OrderStatus requireKnown(Integer code) { + return Arrays.stream(values()) + .filter(status -> Integer.valueOf(status.code).equals(code)) + .findFirst() + .orElseThrow(() -> new RuntimeException("无效的订单状态")); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/AfterSaleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/AfterSaleVO.java new file mode 100644 index 00000000..f7cec39d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/AfterSaleVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class AfterSaleVO { + private Long id; + private String afterSaleNo; + private Long orderId; + private Long orderItemId; + private Long userId; + private Long shopId; + private String type; + private String reason; + private BigDecimal refundAmount; + private String status; + private Long auditUserId; + private String auditReason; + private LocalDateTime auditTime; + private Long refundOrderId; + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartArtistVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartArtistVO.java new file mode 100644 index 00000000..b18ee753 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartArtistVO.java @@ -0,0 +1,35 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +@Data +/** + * CartArtistVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartArtistVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `name` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String name; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String avatar; + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `participateProduction` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean participateProduction; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartVO.java new file mode 100644 index 00000000..2c144965 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CartVO.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +@Data +/** + * CartVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class CartVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productImage; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalPrice; + /** + * Field `tags` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String tags; + /** + * Field `tagNames` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String tagNames; + /** + * Field `approximateDuration` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String approximateDuration; + /** + * Field `bookableArtists` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String bookableArtists; + /** + * Field `availableBookableArtistCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer availableBookableArtistCount; + /** + * Field `bookableArtistRestricted` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean bookableArtistRestricted; + /** + * Field `availableArtists` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List availableArtists; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutCouponPreviewVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutCouponPreviewVO.java new file mode 100644 index 00000000..eba4ea5b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutCouponPreviewVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 结算预览里的单张优惠说明。 + */ +@Data +public class CheckoutCouponPreviewVO { + + private Long id; + + private Long couponId; + + private Long userCouponId; + + private String sourceType; + + private String couponName; + + private Integer couponType; + + private String couponTypeName; + + private BigDecimal discountValue; + + private BigDecimal minAmount; + + private BigDecimal reduceAmount; + + private BigDecimal discountAmount; + + private Boolean available; + + private Boolean best; + + private Boolean vipAuto; + + private String displayText; + + private String savingText; + + private String unavailableReason; + + private LocalDateTime startTime; + + private LocalDateTime endTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutPreviewVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutPreviewVO.java new file mode 100644 index 00000000..241e8584 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/CheckoutPreviewVO.java @@ -0,0 +1,47 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * 结算页展示用预览结果。 + */ +@Data +public class CheckoutPreviewVO { + + private BigDecimal subtotalAmount = BigDecimal.ZERO; + + private BigDecimal savedAmount = BigDecimal.ZERO; + + private BigDecimal payableAmount = BigDecimal.ZERO; + + private CheckoutCouponPreviewVO bestCoupon; + + private List availableCoupons = new ArrayList<>(); + + private List unavailableCoupons = new ArrayList<>(); + + private Boolean bookingAvailable; + + private List bookingIssues = new ArrayList<>(); + + private String vipTip; + + private String summaryText; + + @Data + public static class CheckoutIssueVO { + private String code; + + private String message; + + private Long itemId; + + private Long productId; + + private String productTitle; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeOptionsVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeOptionsVO.java new file mode 100644 index 00000000..aa5e3433 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeOptionsVO.java @@ -0,0 +1,71 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * Purpose: OrderArtistChangeOptionsVO supports OrderArtistChangeOptionsVO.java by holding or executing the order artist change options vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeOptionsVO { + /** + * Purpose: orderId supports OrderArtistChangeOptionsVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeOptionsVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: currentArtistId supports OrderArtistChangeOptionsVO.java by holding or executing the current artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long currentArtistId; + /** + * Purpose: currentArtistName supports OrderArtistChangeOptionsVO.java by holding or executing the current artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String currentArtistName; + /** + * Purpose: artists supports OrderArtistChangeOptionsVO.java by holding or executing the artists business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List artists; + + @Data + /** + * Purpose: ArtistOptionVO supports OrderArtistChangeOptionsVO.java by holding or executing the artist option vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class ArtistOptionVO { + /** + * Purpose: artistId supports OrderArtistChangeOptionsVO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + /** + * Purpose: artistName supports OrderArtistChangeOptionsVO.java by holding or executing the artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistName; + /** + * Purpose: artistAvatar supports OrderArtistChangeOptionsVO.java by holding or executing the artist avatar business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistAvatar; + /** + * Purpose: userType supports OrderArtistChangeOptionsVO.java by holding or executing the user type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer userType; + /** + * Purpose: participateProduction supports OrderArtistChangeOptionsVO.java by holding or executing the participate production business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Boolean participateProduction; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeRequestVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeRequestVO.java new file mode 100644 index 00000000..d925589e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistChangeRequestVO.java @@ -0,0 +1,194 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * Purpose: OrderArtistChangeRequestVO supports OrderArtistChangeRequestVO.java by holding or executing the order artist change request vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistChangeRequestVO { + /** + * Purpose: id supports OrderArtistChangeRequestVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: orderId supports OrderArtistChangeRequestVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistChangeRequestVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: productId supports OrderArtistChangeRequestVO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + /** + * Purpose: productTitle supports OrderArtistChangeRequestVO.java by holding or executing the product title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String productTitle; + /** + * Purpose: shopId supports OrderArtistChangeRequestVO.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + /** + * Purpose: userId supports OrderArtistChangeRequestVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: customerId supports OrderArtistChangeRequestVO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + /** + * Purpose: originalArtistId supports OrderArtistChangeRequestVO.java by holding or executing the original artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long originalArtistId; + /** + * Purpose: originalArtistName supports OrderArtistChangeRequestVO.java by holding or executing the original artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String originalArtistName; + /** + * Purpose: requestedArtistId supports OrderArtistChangeRequestVO.java by holding or executing the requested artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requestedArtistId; + /** + * Purpose: requestedArtistName supports OrderArtistChangeRequestVO.java by holding or executing the requested artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String requestedArtistName; + /** + * Purpose: fromArtistId supports OrderArtistChangeRequestVO.java by holding or executing the from artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long fromArtistId; + /** + * Purpose: fromArtistName supports OrderArtistChangeRequestVO.java by holding or executing the from artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String fromArtistName; + /** + * Purpose: toArtistId supports OrderArtistChangeRequestVO.java by holding or executing the to artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long toArtistId; + /** + * Purpose: toArtistName supports OrderArtistChangeRequestVO.java by holding or executing the to artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toArtistName; + /** + * Purpose: requesterId supports OrderArtistChangeRequestVO.java by holding or executing the requester id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long requesterId; + /** + * Purpose: requesterName supports OrderArtistChangeRequestVO.java by holding or executing the requester name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String requesterName; + /** + * Purpose: status supports OrderArtistChangeRequestVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String status; + /** + * Purpose: statusText supports OrderArtistChangeRequestVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + /** + * Purpose: reason supports OrderArtistChangeRequestVO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + /** + * Purpose: rejectReason supports OrderArtistChangeRequestVO.java by holding or executing the reject reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String rejectReason; + /** + * Purpose: appointmentTime exposes the affected order-item appointment for customer-facing timelines. + * Usage: render this value beside the change request so users can confirm the change does not move their booking. + */ + private String appointmentTime; + /** + * Purpose: timeAffected tells clients whether the artist change modifies the booking time. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean timeAffected; + /** + * Purpose: timeImpactText gives ready-to-display wording for the time impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String timeImpactText; + /** + * Purpose: originalPrice records the original order-item unit price for impact display. + * Usage: compare it with newPrice when rendering customer-facing price impact copy. + */ + private BigDecimal originalPrice; + /** + * Purpose: newPrice records the post-change order-item unit price for impact display. + * Usage: show it only when priceAffected is true or when detailed impact wording is needed. + */ + private BigDecimal newPrice; + /** + * Purpose: priceAffected tells clients whether the artist change modifies the order amount. + * Usage: use this boolean to choose the timeline impact label; current business rules keep it false. + */ + private Boolean priceAffected; + /** + * Purpose: priceImpactText gives ready-to-display wording for the price impact. + * Usage: show it in order timelines and confirmation panels without duplicating copy rules in each client. + */ + private String priceImpactText; + /** + * Purpose: reviewerId supports OrderArtistChangeRequestVO.java by holding or executing the reviewer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reviewerId; + /** + * Purpose: messageId supports OrderArtistChangeRequestVO.java by holding or executing the message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long messageId; + /** + * Purpose: reviewTime supports OrderArtistChangeRequestVO.java by holding or executing the review time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime reviewTime; + /** + * Purpose: approvedTime supports OrderArtistChangeRequestVO.java by holding or executing the approved time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime approvedTime; + /** + * Purpose: rejectedTime supports OrderArtistChangeRequestVO.java by holding or executing the rejected time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime rejectedTime; + /** + * Purpose: expireTime supports OrderArtistChangeRequestVO.java by holding or executing the expire time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime expireTime; + /** + * Purpose: createTime supports OrderArtistChangeRequestVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistReviewVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistReviewVO.java new file mode 100644 index 00000000..891732a3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderArtistReviewVO.java @@ -0,0 +1,115 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * Purpose: OrderArtistReviewVO supports OrderArtistReviewVO.java by holding or executing the order artist review vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OrderArtistReviewVO { + /** + * Purpose: id supports OrderArtistReviewVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: orderId supports OrderArtistReviewVO.java by holding or executing the order id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderId; + /** + * Purpose: orderItemId supports OrderArtistReviewVO.java by holding or executing the order item id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long orderItemId; + /** + * Purpose: productId supports OrderArtistReviewVO.java by holding or executing the product id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long productId; + /** + * Purpose: productTitle supports OrderArtistReviewVO.java by holding or executing the product title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String productTitle; + /** + * Purpose: artistId supports OrderArtistReviewVO.java by holding or executing the artist id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long artistId; + /** + * Purpose: artistName supports OrderArtistReviewVO.java by holding or executing the artist name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistName; + /** + * Purpose: artistAvatar supports OrderArtistReviewVO.java by holding or executing the artist avatar business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String artistAvatar; + /** + * Purpose: userId supports OrderArtistReviewVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: customerId supports OrderArtistReviewVO.java by holding or executing the customer id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long customerId; + /** + * Purpose: rating supports OrderArtistReviewVO.java by holding or executing the rating business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal rating; + /** + * Purpose: ratingScore supports OrderArtistReviewVO.java by holding or executing the rating score business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal ratingScore; + /** + * Purpose: content supports OrderArtistReviewVO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + /** + * Purpose: imageFileIds supports OrderArtistReviewVO.java by holding or executing the image file ids business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private List imageFileIds; + /** + * Purpose: status supports OrderArtistReviewVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + /** + * Purpose: statusText supports OrderArtistReviewVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + /** + * Purpose: reminderMessageId supports OrderArtistReviewVO.java by holding or executing the reminder message id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long reminderMessageId; + /** + * Purpose: submitTime supports OrderArtistReviewVO.java by holding or executing the submit time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submitTime; + /** + * Purpose: submittedAt supports OrderArtistReviewVO.java by holding or executing the submitted at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime submittedAt; + /** + * Purpose: createTime supports OrderArtistReviewVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderItemVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderItemVO.java new file mode 100644 index 00000000..cc03ea29 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderItemVO.java @@ -0,0 +1,79 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * OrderItemVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderItemVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productImage; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalPrice; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistName; + /** + * Field `artistAvatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistAvatar; + /** + * Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String appointmentTime; + private String occupancyStatus; + private Boolean canEdit; + private Boolean canCancel; + private String conflictReason; + /** + * Purpose: pendingReview supports OrderItemVO.java by holding or executing the pending review business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO pendingReview; + /** + * Purpose: reviewSummary supports OrderItemVO.java by holding or executing the review summary business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistReviewVO reviewSummary; + /** + * Purpose: pendingArtistChangeRequest supports OrderItemVO.java by holding or executing the pending artist change request business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private OrderArtistChangeRequestVO pendingArtistChangeRequest; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteItemVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteItemVO.java new file mode 100644 index 00000000..97f8a097 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteItemVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class OrderQuoteItemVO { + private Long orderItemId; + private Long productId; + private String productTitle; + private Integer quantity; + private BigDecimal referencePrice; + private BigDecimal quotedPrice; + private BigDecimal confirmedPrice; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteMessageVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteMessageVO.java new file mode 100644 index 00000000..d0b96de2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderQuoteMessageVO.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class OrderQuoteMessageVO { + private Long id; + private Long orderId; + private Long actorId; + private String actorType; + private String actorTypeText; + private String action; + private String actionText; + private String remark; + private List items; + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderVO.java new file mode 100644 index 00000000..180fe619 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/order/vo/OrderVO.java @@ -0,0 +1,107 @@ +package com.xiaowang.fingertipdesigner.core.modules.order.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * OrderVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class OrderVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Purpose: shopName supports OrderVO.java by holding or executing the shop name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String shopName; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponSourceType; + /** + * Field `couponName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String couponName; + private String paymentStatus; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private String paymentMethod; + private String paymentOrderNo; + private String refundStatus; + private String customerRemark; + private String quoteStatus; + private String quoteStatusText; + private Boolean quoteUserConfirmed; + private Boolean quoteShopConfirmed; + private LocalDateTime quoteExpireTime; + private LocalDateTime quoteConfirmedTime; + private List quoteMessages; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerPhoneMasked; + /** + * Field `artistOrderSource` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSource; + /** + * Field `artistOrderSourceText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSourceText; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `statusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String statusText; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `items` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List items; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/admin/AdminPaymentController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/admin/AdminPaymentController.java new file mode 100644 index 00000000..ced1f886 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/admin/AdminPaymentController.java @@ -0,0 +1,62 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.PaymentService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.RefundOrderVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/admin/payment") +@RequiredArgsConstructor +public class AdminPaymentController { + + private final PaymentService paymentService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; + + @PostMapping("/order/{orderId}/manual-confirm") + @RequirePermission("payment:manage") + public Result manualConfirm(HttpServletRequest request, + @PathVariable Long orderId, + @RequestParam(required = false) String remark) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + PaymentOrderVO result = paymentService.manualConfirmOrderPaid(currentUser.getId(), orderId, remark); + securityAuditSupport.success(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.PAYMENT_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PostMapping("/order/{orderId}/manual-refund") + @RequirePermission("refund:manage") + public Result manualRefund(HttpServletRequest request, + @PathVariable Long orderId, + @RequestParam(required = false) Long afterSaleId, + @RequestParam(required = false) String remark) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + RefundOrderVO result = paymentService.manualRefundOrder(currentUser.getId(), orderId, afterSaleId, remark); + securityAuditSupport.success(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId); + return Result.success(result); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.REFUND_MANUAL_CONFIRM, "orderId=" + orderId + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceChangeDetailController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceChangeDetailController.java new file mode 100644 index 00000000..0823b8b8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceChangeDetailController.java @@ -0,0 +1,99 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.BalanceChangeDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户余额变动明细表 Controller + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) +@RequiredArgsConstructor +public class BalanceChangeDetailController { + /** + * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailService balanceChangeDetailService; + + /** + * 创建余额变动明细 + * + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 余额变动明细ID + */ + @PostMapping("/create") + public Result createBalanceChangeDetail(@RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { + Long id = balanceChangeDetailService.createBalanceChangeDetail(balanceChangeDetailDTO); + return Result.success(id); + } + + /** + * 更新余额变动明细 + * + * @param id 余额变动明细ID + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateBalanceChangeDetail(@PathVariable Long id, @RequestBody BalanceChangeDetailDTO balanceChangeDetailDTO) { + boolean success = balanceChangeDetailService.updateBalanceChangeDetail(id, balanceChangeDetailDTO); + return Result.success(success); + } + + /** + * 删除余额变动明细 + * + * @param id 余额变动明细ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteBalanceChangeDetail(@PathVariable Long id) { + boolean success = balanceChangeDetailService.deleteBalanceChangeDetail(id); + return Result.success(success); + } + + /** + * 根据ID查询余额变动明细 + * + * @param id 余额变动明细ID + * @return 余额变动明细VO + */ + @GetMapping("/get/{id}") + public Result getBalanceChangeDetailById(@PathVariable Long id) { + BalanceChangeDetailVO balanceChangeDetailVO = balanceChangeDetailService.getBalanceChangeDetailById(id); + return Result.success(balanceChangeDetailVO); + } + + /** + * 查询所有余额变动明细 + * + * @return 余额变动明细VO列表 + */ + @GetMapping("/list/all") + public Result> listAllBalanceChangeDetails() { + List balanceChangeDetailVOs = balanceChangeDetailService.listAllBalanceChangeDetails(); + return Result.success(balanceChangeDetailVOs); + } + + /** + * 根据用户ID查询余额变动明细 + * + * @param userId 用户ID + * @return 余额变动明细VO列表 + */ + @GetMapping("/list/user/{userId}") + public Result> listBalanceChangeDetailsByUserId(@PathVariable Long userId) { + List balanceChangeDetailVOs = balanceChangeDetailService.listBalanceChangeDetailsByUserId(userId); + return Result.success(balanceChangeDetailVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceController.java new file mode 100644 index 00000000..cd0675bf --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/BalanceController.java @@ -0,0 +1,99 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.BalanceService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 用户余额信息表 Controller + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/balance", "/api/balance"}) +@RequiredArgsConstructor +public class BalanceController { + /** + * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceService balanceService; + + /** + * 创建余额 + * + * @param balanceDTO 余额DTO + * @return 余额ID + */ + @PostMapping("/create") + public Result createBalance(@RequestBody BalanceDTO balanceDTO) { + Long id = balanceService.createBalance(balanceDTO); + return Result.success(id); + } + + /** + * 更新余额 + * + * @param id 余额ID + * @param balanceDTO 余额DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateBalance(@PathVariable Long id, @RequestBody BalanceDTO balanceDTO) { + boolean success = balanceService.updateBalance(id, balanceDTO); + return Result.success(success); + } + + /** + * 删除余额 + * + * @param id 余额ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteBalance(@PathVariable Long id) { + boolean success = balanceService.deleteBalance(id); + return Result.success(success); + } + + /** + * 根据ID查询余额 + * + * @param id 余额ID + * @return 余额VO + */ + @GetMapping("/get/{id}") + public Result getBalanceById(@PathVariable Long id) { + BalanceVO balanceVO = balanceService.getBalanceById(id); + return Result.success(balanceVO); + } + + /** + * 查询所有余额 + * + * @return 余额VO列表 + */ + @GetMapping("/list/all") + public Result> listAllBalances() { + List balanceVOs = balanceService.listAllBalances(); + return Result.success(balanceVOs); + } + + /** + * 根据用户ID查询余额 + * + * @param userId 用户ID + * @return 余额VO + */ + @GetMapping("/get/user/{userId}") + public Result getBalanceByUserId(@PathVariable Long userId) { + BalanceVO balanceVO = balanceService.getBalanceByUserId(userId); + return Result.success(balanceVO); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/PaymentController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/PaymentController.java new file mode 100644 index 00000000..4c1d0049 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/controller/front/PaymentController.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.PaymentService; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequestMapping("/payment") +@RequiredArgsConstructor +public class PaymentController { + + private final PaymentService paymentService; + + @PostMapping("/order/{orderId}/prepare") + public Result prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(paymentService.prepareOrderPayment(userId, orderId)); + } + + @PostMapping("/order/{orderId}/mock-success") + public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceChangeDetailDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceChangeDetailDTO.java new file mode 100644 index 00000000..f279cf44 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceChangeDetailDTO.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 DTO + * 用于余额变动明细信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceChangeDetailDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + private String type; + + /** + * 变动后的当前余额 + */ + private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + /** + * 变动时间 + */ + private LocalDateTime changeTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceDTO.java new file mode 100644 index 00000000..c6890d63 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/dto/BalanceDTO.java @@ -0,0 +1,35 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 DTO + * 用于余额信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceDTO { + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 当前余额 + */ + private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceChangeDetailDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceChangeDetailDO.java new file mode 100644 index 00000000..4efca038 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceChangeDetailDO.java @@ -0,0 +1,106 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 DO + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@TableName("t_balance_change_detail") +public class BalanceChangeDetailDO { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + @TableField("amount") + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + @TableField("type") + private String type; + + /** + * 变动后的当前余额 + */ + @TableField("current_balance") + private BigDecimal currentBalance; + + /** + * 变动时间 + */ + @TableField("before_balance") + private BigDecimal beforeBalance; + + @TableField("after_balance") + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + + @TableField("change_scene") + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + + @TableField("related_order_id") + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + + @TableField("related_order_no") + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + + @TableField("external_order_no") + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + + @TableField("operator_id") + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("change_time") + /** + * Field `changeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime changeTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceDO.java new file mode 100644 index 00000000..e40bd7fc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/BalanceDO.java @@ -0,0 +1,67 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 DO + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@TableName("t_balance") +public class BalanceDO { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Purpose: id supports BalanceDO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + + @TableField(fill = FieldFill.INSERT) + /** + * Purpose: createTime supports BalanceDO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + + /** + * 关联用户表主键 + */ + @TableField("user_id") + private Long userId; + + /** + * 当前余额 + */ + @TableField("amount") + private BigDecimal amount; + + /** + * 最近一次更新时间 + */ + @TableField("total_recharge_amount") + private BigDecimal totalRechargeAmount; + + @TableField("last_recharge_time") + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + @TableField("last_update_time") + /** + * Field `lastUpdateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastUpdateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/PaymentOrderDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/PaymentOrderDO.java new file mode 100644 index 00000000..1baa7d04 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/PaymentOrderDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_payment_order") +public class PaymentOrderDO extends BaseEntity { + @TableField("pay_no") + private String payNo; + @TableField("order_id") + private Long orderId; + @TableField("order_no") + private String orderNo; + @TableField("user_id") + private Long userId; + @TableField("shop_id") + private Long shopId; + @TableField("channel") + private String channel; + @TableField("status") + private String status; + @TableField("pay_amount") + private BigDecimal payAmount; + @TableField("paid_amount") + private BigDecimal paidAmount; + @TableField("pay_time") + private LocalDateTime payTime; + @TableField("expire_time") + private LocalDateTime expireTime; + @TableField("operator_id") + private Long operatorId; + @TableField("remark") + private String remark; + @TableField("idempotency_key") + private String idempotencyKey; + @TableField("raw_payload") + private String rawPayload; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/RefundOrderDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/RefundOrderDO.java new file mode 100644 index 00000000..bb002b3e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/entity/RefundOrderDO.java @@ -0,0 +1,42 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_refund_order") +public class RefundOrderDO extends BaseEntity { + @TableField("refund_no") + private String refundNo; + @TableField("after_sale_id") + private Long afterSaleId; + @TableField("payment_order_id") + private Long paymentOrderId; + @TableField("order_id") + private Long orderId; + @TableField("status") + private String status; + @TableField("refund_amount") + private BigDecimal refundAmount; + @TableField("refund_time") + private LocalDateTime refundTime; + @TableField("channel") + private String channel; + @TableField("external_refund_no") + private String externalRefundNo; + @TableField("fail_reason") + private String failReason; + @TableField("idempotency_key") + private String idempotencyKey; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceChangeDetailMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceChangeDetailMapper.java new file mode 100644 index 00000000..4008825d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceChangeDetailMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceChangeDetailDO; + +/** + * 用户余额变动明细表 Mapper + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceChangeDetailMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceMapper.java new file mode 100644 index 00000000..63da1b20 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/BalanceMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceDO; + +/** + * 用户余额信息表 Mapper + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/PaymentOrderMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/PaymentOrderMapper.java new file mode 100644 index 00000000..cea49429 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/PaymentOrderMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.PaymentOrderDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +@Mapper +public interface PaymentOrderMapper extends BaseMapper { + @Select("SELECT * FROM t_payment_order WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time DESC, id DESC LIMIT 1") + PaymentOrderDO selectLatestByOrderId(@Param("orderId") Long orderId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/RefundOrderMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/RefundOrderMapper.java new file mode 100644 index 00000000..bce79d79 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/mapper/RefundOrderMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.RefundOrderDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface RefundOrderMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceChangeDetailService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceChangeDetailService.java new file mode 100644 index 00000000..e1b56d13 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceChangeDetailService.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; + +import java.util.List; + +/** + * 用户余额变动明细表 Service + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceChangeDetailService extends IService { + + /** + * 创建余额变动明细 + * + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 余额变动明细ID + */ + Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO); + + /** + * 更新余额变动明细 + * + * @param id 余额变动明细ID + * @param balanceChangeDetailDTO 余额变动明细DTO + * @return 是否更新成功 + */ + boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO); + + /** + * 删除余额变动明细 + * + * @param id 余额变动明细ID + * @return 是否删除成功 + */ + boolean deleteBalanceChangeDetail(Long id); + + /** + * 根据ID查询余额变动明细 + * + * @param id 余额变动明细ID + * @return 余额变动明细VO + */ + BalanceChangeDetailVO getBalanceChangeDetailById(Long id); + + /** + * 查询所有余额变动明细 + * + * @return 余额变动明细VO列表 + */ + List listAllBalanceChangeDetails(); + + /** + * 根据用户ID查询余额变动明细 + * + * @param userId 用户ID + * @return 余额变动明细VO列表 + */ + List listBalanceChangeDetailsByUserId(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceService.java new file mode 100644 index 00000000..4df2e7f0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/BalanceService.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceVO; + +import java.util.List; + +/** + * 用户余额信息表 Service + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface BalanceService extends IService { + + /** + * 创建余额 + * + * @param balanceDTO 余额DTO + * @return 余额ID + */ + Long createBalance(BalanceDTO balanceDTO); + + /** + * 更新余额 + * + * @param id 余额ID + * @param balanceDTO 余额DTO + * @return 是否更新成功 + */ + boolean updateBalance(Long id, BalanceDTO balanceDTO); + + /** + * 删除余额 + * + * @param id 余额ID + * @return 是否删除成功 + */ + boolean deleteBalance(Long id); + + /** + * 根据ID查询余额 + * + * @param id 余额ID + * @return 余额VO + */ + BalanceVO getBalanceById(Long id); + + /** + * 查询所有余额 + * + * @return 余额VO列表 + */ + List listAllBalances(); + + /** + * 根据用户ID查询余额 + * + * @param userId 用户ID + * @return 余额VO + */ + BalanceVO getBalanceByUserId(Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/PaymentService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/PaymentService.java new file mode 100644 index 00000000..f7a2f374 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/PaymentService.java @@ -0,0 +1,12 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service; + +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.RefundOrderVO; + +public interface PaymentService { + PaymentOrderVO prepareOrderPayment(Long userId, Long orderId); + + PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark); + + RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java new file mode 100644 index 00000000..cd65817d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceChangeDetailServiceImpl.java @@ -0,0 +1,173 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceChangeDetailDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.BalanceChangeDetailMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.BalanceChangeDetailService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户余额变动明细表 Service 实现 + * 对应数据库表 t_balance_change_detail + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class BalanceChangeDetailServiceImpl extends ServiceImpl implements BalanceChangeDetailService { + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailMapper balanceChangeDetailMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO) { + BalanceChangeDetailDO balanceChangeDetailDO = new BalanceChangeDetailDO(); + balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); + balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); + balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); + balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); + balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); + balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); + balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); + balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); + balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); + balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); + balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); + balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); + balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); + balanceChangeDetailMapper.insert(balanceChangeDetailDO); + return balanceChangeDetailDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateBalanceChangeDetail(Long id, BalanceChangeDetailDTO balanceChangeDetailDTO) { + BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); + if (balanceChangeDetailDO == null) { + return false; + } + balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); + balanceChangeDetailDO.setAmount(balanceChangeDetailDTO.getAmount()); + balanceChangeDetailDO.setType(balanceChangeDetailDTO.getType()); + balanceChangeDetailDO.setCurrentBalance(balanceChangeDetailDTO.getCurrentBalance()); + balanceChangeDetailDO.setBeforeBalance(balanceChangeDetailDTO.getBeforeBalance()); + balanceChangeDetailDO.setAfterBalance(balanceChangeDetailDTO.getAfterBalance()); + balanceChangeDetailDO.setChangeScene(balanceChangeDetailDTO.getChangeScene()); + balanceChangeDetailDO.setRelatedOrderId(balanceChangeDetailDTO.getRelatedOrderId()); + balanceChangeDetailDO.setRelatedOrderNo(balanceChangeDetailDTO.getRelatedOrderNo()); + balanceChangeDetailDO.setExternalOrderNo(balanceChangeDetailDTO.getExternalOrderNo()); + balanceChangeDetailDO.setOperatorId(balanceChangeDetailDTO.getOperatorId()); + balanceChangeDetailDO.setRemark(balanceChangeDetailDTO.getRemark()); + balanceChangeDetailDO.setChangeTime(balanceChangeDetailDTO.getChangeTime()); + return balanceChangeDetailMapper.updateById(balanceChangeDetailDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteBalanceChangeDetail(Long id) { + return balanceChangeDetailMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ + public BalanceChangeDetailVO getBalanceChangeDetailById(Long id) { + BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); + if (balanceChangeDetailDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDO parameter `balanceChangeDetailDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceChangeDetailDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllBalanceChangeDetails() { + List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList(null); + return balanceChangeDetailDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listBalanceChangeDetailsByUserId(Long userId) { + List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList( + Wrappers.lambdaQuery(BalanceChangeDetailDO.class) + .eq(BalanceChangeDetailDO::getUserId, userId) + ); + return balanceChangeDetailDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param balanceChangeDetailDO 余额变动明细DO + * @return 余额变动明细VO + */ + private BalanceChangeDetailVO convertToVO(BalanceChangeDetailDO balanceChangeDetailDO) { + BalanceChangeDetailVO balanceChangeDetailVO = new BalanceChangeDetailVO(); + balanceChangeDetailVO.setId(balanceChangeDetailDO.getId()); + balanceChangeDetailVO.setUserId(balanceChangeDetailDO.getUserId()); + balanceChangeDetailVO.setAmount(balanceChangeDetailDO.getAmount()); + balanceChangeDetailVO.setType(balanceChangeDetailDO.getType()); + balanceChangeDetailVO.setCurrentBalance(balanceChangeDetailDO.getCurrentBalance()); + balanceChangeDetailVO.setBeforeBalance(balanceChangeDetailDO.getBeforeBalance()); + balanceChangeDetailVO.setAfterBalance(balanceChangeDetailDO.getAfterBalance()); + balanceChangeDetailVO.setChangeScene(balanceChangeDetailDO.getChangeScene()); + balanceChangeDetailVO.setRelatedOrderId(balanceChangeDetailDO.getRelatedOrderId()); + balanceChangeDetailVO.setRelatedOrderNo(balanceChangeDetailDO.getRelatedOrderNo()); + balanceChangeDetailVO.setExternalOrderNo(balanceChangeDetailDO.getExternalOrderNo()); + balanceChangeDetailVO.setOperatorId(balanceChangeDetailDO.getOperatorId()); + balanceChangeDetailVO.setRemark(balanceChangeDetailDO.getRemark()); + balanceChangeDetailVO.setChangeTime(balanceChangeDetailDO.getChangeTime()); + return balanceChangeDetailVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceServiceImpl.java new file mode 100644 index 00000000..e781d19a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/BalanceServiceImpl.java @@ -0,0 +1,158 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.BalanceDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.BalanceMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.BalanceService; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户余额信息表 Service 实现 + * 对应数据库表 t_balance + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class BalanceServiceImpl extends ServiceImpl implements BalanceService { + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceMapper balanceMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createBalance(BalanceDTO balanceDTO) { + BalanceDO balanceDO = new BalanceDO(); + balanceDO.setUserId(balanceDTO.getUserId()); + balanceDO.setAmount(balanceDTO.getAmount()); + balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); + balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); + balanceDO.setLastUpdateTime(LocalDateTime.now()); + balanceMapper.insert(balanceDO); + return balanceDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateBalance(Long id, BalanceDTO balanceDTO) { + BalanceDO balanceDO = balanceMapper.selectById(id); + if (balanceDO == null) { + return false; + } + balanceDO.setUserId(balanceDTO.getUserId()); + balanceDO.setAmount(balanceDTO.getAmount()); + balanceDO.setTotalRechargeAmount(balanceDTO.getTotalRechargeAmount()); + balanceDO.setLastRechargeTime(balanceDTO.getLastRechargeTime()); + balanceDO.setLastUpdateTime(LocalDateTime.now()); + return balanceMapper.updateById(balanceDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteBalance(Long id) { + return balanceMapper.deleteById(id) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ + public BalanceVO getBalanceById(Long id) { + BalanceDO balanceDO = balanceMapper.selectById(id); + if (balanceDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllBalances() { + List balanceDOs = balanceMapper.selectList(null); + return balanceDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ + public BalanceVO getBalanceByUserId(Long userId) { + BalanceDO balanceDO = balanceMapper.selectOne( + Wrappers.lambdaQuery(BalanceDO.class) + .eq(BalanceDO::getUserId, userId) + ); + if (balanceDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(balanceDO); + } + + /** + * 将 DO 转换为 VO + * + * @param balanceDO 余额DO + * @return 余额VO + */ + private BalanceVO convertToVO(BalanceDO balanceDO) { + BalanceVO balanceVO = new BalanceVO(); + balanceVO.setId(balanceDO.getId()); + balanceVO.setUserId(balanceDO.getUserId()); + balanceVO.setAmount(balanceDO.getAmount()); + balanceVO.setTotalRechargeAmount(balanceDO.getTotalRechargeAmount()); + balanceVO.setLastRechargeTime(balanceDO.getLastRechargeTime()); + balanceVO.setCreateTime(balanceDO.getCreateTime()); + balanceVO.setLastUpdateTime(balanceDO.getLastUpdateTime()); + return balanceVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/PaymentServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/PaymentServiceImpl.java new file mode 100644 index 00000000..0061642d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/service/impl/PaymentServiceImpl.java @@ -0,0 +1,157 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.PaymentOrderDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.RefundOrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.PaymentOrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.RefundOrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.service.PaymentService; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.PaymentOrderVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.RefundOrderVO; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class PaymentServiceImpl implements PaymentService { + + private static final String CHANNEL_MANUAL = "MANUAL"; + private static final String STATUS_UNPAID = "UNPAID"; + private static final String STATUS_PAYING = "PAYING"; + private static final String STATUS_PAID = "PAID"; + private static final String STATUS_REFUNDED = "REFUNDED"; + + private final OrderMapper orderMapper; + private final PaymentOrderMapper paymentOrderMapper; + private final RefundOrderMapper refundOrderMapper; + + @Override + @Transactional + public PaymentOrderVO prepareOrderPayment(Long userId, Long orderId) { + OrderDO order = requirePayableOrder(userId, orderId); + PaymentOrderDO latest = paymentOrderMapper.selectLatestByOrderId(orderId); + if (latest != null && (STATUS_PAYING.equals(latest.getStatus()) || STATUS_PAID.equals(latest.getStatus()))) { + return toVO(latest); + } + PaymentOrderDO payment = new PaymentOrderDO(); + payment.setPayNo("PAY" + System.currentTimeMillis() + orderId); + payment.setOrderId(order.getId()); + payment.setOrderNo(order.getOrderNo()); + payment.setUserId(order.getUserId()); + payment.setShopId(order.getShopId()); + payment.setChannel(CHANNEL_MANUAL); + payment.setStatus(STATUS_PAYING); + payment.setPayAmount(order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()); + payment.setPaidAmount(BigDecimal.ZERO); + payment.setExpireTime(LocalDateTime.now().plusMinutes(30)); + payment.setIdempotencyKey("PAY:" + order.getId()); + payment.setIsDelete(0); + paymentOrderMapper.insert(payment); + order.setPaymentStatus(STATUS_PAYING); + order.setPaymentOrderNo(payment.getPayNo()); + order.setPayAmount(payment.getPayAmount()); + orderMapper.updateById(order); + return toVO(payment); + } + + @Override + @Transactional + public PaymentOrderVO manualConfirmOrderPaid(Long operatorId, Long orderId, String remark) { + OrderDO order = requirePayableOrder(null, orderId); + PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); + if (payment == null) { + prepareOrderPayment(order.getUserId(), orderId); + payment = paymentOrderMapper.selectLatestByOrderId(orderId); + } + if (payment == null) { + throw new RuntimeException("支付单创建失败"); + } + payment.setStatus(STATUS_PAID); + payment.setPaidAmount(payment.getPayAmount()); + payment.setPayTime(LocalDateTime.now()); + payment.setOperatorId(operatorId); + payment.setRemark(remark); + paymentOrderMapper.updateById(payment); + + order.setPaymentStatus(STATUS_PAID); + order.setPaidAmount(payment.getPayAmount()); + order.setPayTime(payment.getPayTime()); + order.setPaymentMethod(payment.getChannel()); + order.setPaymentOrderNo(payment.getPayNo()); + orderMapper.updateById(order); + return toVO(payment); + } + + @Override + @Transactional + public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("璁㈠崟涓嶅瓨鍦?"); + } + if (!STATUS_PAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?"); + } + PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); + if (payment == null || !STATUS_PAID.equals(payment.getStatus())) { + throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?"); + } + RefundOrderDO refund = new RefundOrderDO(); + refund.setRefundNo("RF" + System.currentTimeMillis() + orderId); + refund.setAfterSaleId(afterSaleId); + refund.setPaymentOrderId(payment.getId()); + refund.setOrderId(order.getId()); + refund.setStatus(STATUS_REFUNDED); + refund.setRefundAmount(payment.getPaidAmount() == null ? payment.getPayAmount() : payment.getPaidAmount()); + refund.setRefundTime(LocalDateTime.now()); + refund.setChannel(payment.getChannel()); + refund.setExternalRefundNo(refund.getRefundNo()); + refund.setFailReason(remark); + refund.setIdempotencyKey("REFUND:" + order.getId() + ":" + (afterSaleId == null ? 0 : afterSaleId)); + refund.setIsDelete(0); + refundOrderMapper.insert(refund); + + order.setRefundStatus(STATUS_REFUNDED); + order.setPaymentStatus(STATUS_REFUNDED); + orderMapper.updateById(order); + return toVO(refund); + } + + private OrderDO requirePayableOrder(Long userId, Long orderId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + if (userId != null && !userId.equals(order.getUserId())) { + throw new RuntimeException("无权支付该订单"); + } + if (Integer.valueOf(0).equals(order.getStatus())) { + throw new RuntimeException("询价预约确认价格前暂不能支付"); + } + if (STATUS_PAID.equals(order.getPaymentStatus())) { + throw new RuntimeException("订单已支付"); + } + if (order.getPaymentStatus() == null) { + order.setPaymentStatus(STATUS_UNPAID); + } + return order; + } + + private PaymentOrderVO toVO(PaymentOrderDO payment) { + PaymentOrderVO vo = new PaymentOrderVO(); + BeanUtils.copyProperties(payment, vo); + return vo; + } + + private RefundOrderVO toVO(RefundOrderDO refund) { + RefundOrderVO vo = new RefundOrderVO(); + BeanUtils.copyProperties(refund, vo); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceChangeDetailVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceChangeDetailVO.java new file mode 100644 index 00000000..46fadcf0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceChangeDetailVO.java @@ -0,0 +1,84 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额变动明细表 VO + * 用于前端展示余额变动明细信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceChangeDetailVO { + + /** + * 变动记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 本次变动金额(正数为增加,负数为减少) + */ + private BigDecimal amount; + + /** + * 变动类型(如充值、消费、退款) + */ + private String type; + + /** + * 变动后的当前余额 + */ + private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + /** + * 变动时间 + */ + private LocalDateTime changeTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceVO.java new file mode 100644 index 00000000..0031d537 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/BalanceVO.java @@ -0,0 +1,55 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +/** + * 用户余额信息表 VO + * 用于前端展示余额信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class BalanceVO { + + /** + * 余额记录唯一主键ID(雪花ID) + */ + private Long id; + + /** + * 关联用户表主键 + */ + private Long userId; + + /** + * 用户昵称 + */ + private String userNickname; + + /** + * 当前余额 + */ + private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + /** + * 余额账户创建时间 + */ + private LocalDateTime createTime; + + /** + * 最近一次更新时间 + */ + private LocalDateTime lastUpdateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/PaymentOrderVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/PaymentOrderVO.java new file mode 100644 index 00000000..3682ea53 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/PaymentOrderVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class PaymentOrderVO { + private Long id; + private String payNo; + private Long orderId; + private String orderNo; + private Long userId; + private Long shopId; + private String channel; + private String status; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private LocalDateTime payTime; + private LocalDateTime expireTime; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/RefundOrderVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/RefundOrderVO.java new file mode 100644 index 00000000..1eb39fbd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/payment/vo/RefundOrderVO.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.core.modules.payment.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +public class RefundOrderVO { + private Long id; + private String refundNo; + private Long afterSaleId; + private Long paymentOrderId; + private Long orderId; + private String status; + private BigDecimal refundAmount; + private LocalDateTime refundTime; + private String channel; + private String externalRefundNo; + private String failReason; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/controller/admin/AdminPlanningController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/controller/admin/AdminPlanningController.java new file mode 100644 index 00000000..b4b7ce36 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/controller/admin/AdminPlanningController.java @@ -0,0 +1,83 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningCalendarVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDate; + +@RestController +@RequestMapping("/admin/planning") +@RequiredArgsConstructor +public class AdminPlanningController { + + private final PlanningService planningService; + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/calendar") + @RequirePermission("schedule:view") + public Result calendar(HttpServletRequest request, + @RequestParam(required = false) String startDate, + @RequestParam(required = false) String endDate, + @RequestParam(required = false) Long artistId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + LocalDate start = startDate == null || startDate.isBlank() ? LocalDate.now() : LocalDate.parse(startDate); + LocalDate end = endDate == null || endDate.isBlank() ? start : LocalDate.parse(endDate); + return Result.success(planningService.getCalendar(currentUser, start, end, artistId)); + } + + @PostMapping("/appointments") + @RequirePermission("order:process") + @OperationGuard(action = "admin-planning-create-appointment", ttlSeconds = 10, message = "预约创建处理中,请勿重复提交") + public Result createAppointment(HttpServletRequest request, + @RequestBody PlanningAppointmentCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.createAppointment(currentUser, dto)); + } + + @GetMapping("/appointments/{orderItemId}") + @RequirePermission("order:view") + public Result appointment(HttpServletRequest request, + @PathVariable Long orderItemId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.getAppointment(currentUser, orderItemId)); + } + + @PutMapping("/appointments/{orderItemId}/time-artist") + @RequirePermission("order:process") + @OperationGuard(action = "admin-planning-move-appointment", ttlSeconds = 10, message = "预约调整处理中,请勿重复提交") + public Result moveAppointment(HttpServletRequest request, + @PathVariable Long orderItemId, + @RequestBody PlanningAppointmentMoveDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.moveAppointment(currentUser, orderItemId, dto)); + } + + @PutMapping("/appointments/{orderId}/status") + @RequirePermission("order:process") + @OperationGuard(action = "admin-planning-update-appointment-status", ttlSeconds = 10, message = "预约状态处理中,请勿重复提交") + public Result updateStatus(HttpServletRequest request, + @PathVariable Long orderId, + @RequestBody PlanningAppointmentStatusDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.updateStatus(currentUser, orderId, dto)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentCreateDTO.java new file mode 100644 index 00000000..1a937a9a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -0,0 +1,28 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class PlanningAppointmentCreateDTO { + private Long customerUserId; + private String customerName; + private String phone; + private Long productId; + private Integer quantity; + private Long artistId; + private String appointmentDate; + private String appointmentTime; + private String appointmentStartTime; + private Integer durationMinutes; + private String manualProductTitle; + private BigDecimal manualProductPrice; + private String manualProductDescription; + private String manualProductTags; + private String manualProductTargetAudience; + private String manualProductPrecautions; + private String manualProductImageFileIds; + private String remark; + private String clientRequestId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentMoveDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentMoveDTO.java new file mode 100644 index 00000000..2c85331d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentMoveDTO.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.dto; + +import lombok.Data; + +@Data +public class PlanningAppointmentMoveDTO { + private Long artistId; + private String appointmentDate; + private String appointmentTime; + private String appointmentStartTime; + private Integer durationMinutes; + private String clientRequestId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentStatusDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentStatusDTO.java new file mode 100644 index 00000000..04237f8e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningAppointmentStatusDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.dto; + +import lombok.Data; + +@Data +public class PlanningAppointmentStatusDTO { + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningManagerRegisterDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningManagerRegisterDTO.java new file mode 100644 index 00000000..0740322f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/dto/PlanningManagerRegisterDTO.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class PlanningManagerRegisterDTO { + + private String phone; + + private String code; + + private String password; + + private String confirmPassword; + + private String shopName; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/entity/AppointmentReservationDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/entity/AppointmentReservationDO.java new file mode 100644 index 00000000..d4eccd3d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/entity/AppointmentReservationDO.java @@ -0,0 +1,37 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_appointment_reservation") +public class AppointmentReservationDO extends BaseEntity { + @TableField("order_id") + private Long orderId; + @TableField("order_item_id") + private Long orderItemId; + @TableField("shop_id") + private Long shopId; + @TableField("artist_id") + private Long artistId; + @TableField("product_title") + private String productTitle; + @TableField("appointment_start_time") + private LocalDateTime appointmentStartTime; + @TableField("appointment_end_time") + private LocalDateTime appointmentEndTime; + @TableField("status") + private String status; + @TableField("client_request_id") + private String clientRequestId; + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/mapper/AppointmentReservationMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/mapper/AppointmentReservationMapper.java new file mode 100644 index 00000000..adb62013 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/mapper/AppointmentReservationMapper.java @@ -0,0 +1,92 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Mapper +public interface AppointmentReservationMapper extends BaseMapper { + String ACTIVE_STATUS_SQL = "('LOCKED','PENDING_QUOTE','CONFIRMED')"; + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") + int countOverlappingActiveForUpdate(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND order_item_id <> #{orderItemId} AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") + int countOverlappingActiveForUpdateExcludingOrderItem(@Param("artistId") Long artistId, + @Param("orderItemId") Long orderItemId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime}") + int countOverlappingActive(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) FOR UPDATE") + int countActiveByArtistAndDateForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate); + + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + + "AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " + + "AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) " + + "AND (TIME(appointment_start_time) < #{startTime} OR TIME(appointment_end_time) > #{endTime}) FOR UPDATE") + int countActiveOutsideScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") java.time.LocalTime startTime, + @Param("endTime") java.time.LocalTime endTime); + + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + + "WHERE order_id = #{orderId} AND is_delete = 0") + int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int releaseByOrderItem(@Param("orderItemId") Long orderItemId, @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + + "artist_id = #{artistId}, product_title = #{productTitle}, " + + "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + + "status = #{status}, is_delete = 0, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int updateActiveReservationForOrderItem(@Param("orderItemId") Long orderItemId, + @Param("orderId") Long orderId, + @Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("productTitle") String productTitle, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime, + @Param("status") String status); + + @Update("UPDATE t_appointment_reservation SET order_id = #{orderId}, shop_id = #{shopId}, " + + "artist_id = #{artistId}, product_title = #{productTitle}, " + + "appointment_start_time = #{startTime}, appointment_end_time = #{endTime}, " + + "status = #{status}, client_request_id = COALESCE(#{clientRequestId}, client_request_id), is_delete = 0, update_time = NOW() " + + "WHERE order_item_id = #{orderItemId} AND is_delete = 0") + int updateActiveReservationForOrderItemWithClientRequest(@Param("orderItemId") Long orderItemId, + @Param("orderId") Long orderId, + @Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("productTitle") String productTitle, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime, + @Param("status") String status, + @Param("clientRequestId") String clientRequestId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/AppointmentCapacityService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/AppointmentCapacityService.java new file mode 100644 index 00000000..2486b653 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/AppointmentCapacityService.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.service; + +import java.time.LocalDateTime; + +public interface AppointmentCapacityService { + void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); + + void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); + + void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId); + + void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); + + void releaseByOrder(Long orderId); + + void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, + Long toArtistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/PlanningService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/PlanningService.java new file mode 100644 index 00000000..a3ebc003 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/PlanningService.java @@ -0,0 +1,22 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.service; + +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningCalendarVO; + +import java.time.LocalDate; + +public interface PlanningService { + PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId); + + PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto); + + PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); + + PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); + + Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java new file mode 100644 index 00000000..8d28ddb8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java @@ -0,0 +1,153 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl; + +import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class AppointmentCapacityServiceImpl implements AppointmentCapacityService { + + private static final int MIN_CAPACITY = 1; + public static final String STATUS_PENDING_QUOTE = "PENDING_QUOTE"; + private static final String STATUS_CONFIRMED = "CONFIRMED"; + private static final String STATUS_RELEASED = "RELEASED"; + private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; + private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; + + private final AppointmentReservationMapper reservationMapper; + private final ArtistScheduleMapper scheduleMapper; + + @Override + @Transactional + public void reserveOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, null, null); + } + + @Override + @Transactional + public void reservePendingQuoteOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_PENDING_QUOTE, clientRequestId, null); + } + + @Override + @Transactional + public void reserveConfirmedOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String clientRequestId) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, clientRequestId, null); + } + + @Override + @Transactional + public void confirmReservationOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + reserveWithStatusOrThrow(orderId, orderItemId, shopId, artistId, productTitle, startTime, endTime, + STATUS_CONFIRMED, null, orderItemId); + } + + private void reserveWithStatusOrThrow(Long orderId, Long orderItemId, Long shopId, Long artistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime, String status, + String clientRequestId, Long excludedOrderItemId) { + if (orderId == null || orderItemId == null || shopId == null || artistId == null || startTime == null || endTime == null) { + return; + } + assertCapacityAvailable(shopId, artistId, excludedOrderItemId, startTime, endTime); + int updated = reservationMapper.updateActiveReservationForOrderItemWithClientRequest( + orderItemId, + orderId, + shopId, + artistId, + productTitle, + startTime, + endTime, + status, + clientRequestId + ); + if (updated > 0) { + return; + } + AppointmentReservationDO reservation = new AppointmentReservationDO(); + reservation.setOrderId(orderId); + reservation.setOrderItemId(orderItemId); + reservation.setShopId(shopId); + reservation.setArtistId(artistId); + reservation.setProductTitle(productTitle); + reservation.setAppointmentStartTime(startTime); + reservation.setAppointmentEndTime(endTime); + reservation.setStatus(status); + reservation.setClientRequestId(clientRequestId); + reservation.setIsDelete(0); + reservationMapper.insert(reservation); + } + + @Override + @Transactional + public void releaseByOrder(Long orderId) { + if (orderId != null) { + reservationMapper.releaseByOrderId(orderId, STATUS_RELEASED); + } + } + + @Override + @Transactional + public void moveReservationForArtistChange(Long orderId, Long orderItemId, Long shopId, Long fromArtistId, + Long toArtistId, String productTitle, + LocalDateTime startTime, LocalDateTime endTime) { + if (orderItemId == null || orderId == null || shopId == null || toArtistId == null || startTime == null || endTime == null) { + return; + } + assertCapacityAvailable(shopId, toArtistId, orderItemId, startTime, endTime); + int updated = reservationMapper.updateActiveReservationForOrderItem( + orderItemId, + orderId, + shopId, + toArtistId, + productTitle, + startTime, + endTime, + STATUS_CONFIRMED + ); + if (updated == 0) { + reserveOrThrow(orderId, orderItemId, shopId, toArtistId, productTitle, startTime, endTime); + } + } + + private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId, + LocalDateTime startTime, LocalDateTime endTime) { + int capacity = resolveCapacity(shopId, artistId, startTime, endTime); + int used = excludedOrderItemId == null + ? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime) + : reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); + if (used >= capacity) { + throw new RuntimeException(FULL_MESSAGE); + } + } + + private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( + shopId, + artistId, + startTime.toLocalDate(), + startTime.toLocalTime(), + endTime.toLocalTime() + ); + if (schedule == null || Integer.valueOf(1).equals(schedule.getIsDelete()) + || !Integer.valueOf(1).equals(schedule.getStatus()) + || schedule.getCapacity() == null || schedule.getCapacity() < MIN_CAPACITY) { + throw new RuntimeException(UNAVAILABLE_MESSAGE); + } + return schedule.getCapacity(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/PlanningServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/PlanningServiceImpl.java new file mode 100644 index 00000000..5dd9ae49 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -0,0 +1,904 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentMoveDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO; +import com.xiaowang.fingertipdesigner.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.fingertipdesigner.core.modules.order.service.OrderService; +import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.order.support.OrderStatus; +import com.xiaowang.fingertipdesigner.core.modules.planning.support.PlanningCalendarSupport; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningAppointmentVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningArtistCountVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningArtistVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningCalendarVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningDaySummaryVO; +import com.xiaowang.fingertipdesigner.core.modules.planning.vo.PlanningScheduleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +public class PlanningServiceImpl implements PlanningService { + + private static final int DEFAULT_SLOT_MINUTES = 30; + private static final int DEFAULT_DURATION_MINUTES = 60; + private static final int MONTH_AVAILABLE_MINUTES = 90; + private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE"; + private static final String RESERVATION_CONFIRMED = "CONFIRMED"; + private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT"; + private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; + private static final List ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); + private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final List ARTIST_COLORS = List.of( + "#7BA7C7", "#8FB89A", "#A894C7", "#D7A86E", "#D98DA5", "#79A6A3", "#B9A16B", "#9BA9C8" + ); + + private final AdminScopeHelper adminScopeHelper; + private final UserMapper userMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; + private final ArtistScheduleMapper artistScheduleMapper; + private final AppointmentReservationMapper appointmentReservationMapper; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final ProductMapper productMapper; + private final ShopMapper shopMapper; + private final AppointmentCapacityService appointmentCapacityService; + private final OrderService orderService; + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + @Override + public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { + LocalDate start = startDate == null ? LocalDate.now() : startDate; + LocalDate end = endDate == null ? start : endDate; + if (end.isBefore(start)) { + end = start; + } + if (start.plusDays(61).isBefore(end)) { + end = start.plusDays(61); + } + + Long shopId = requirePlanningShopId(currentUser); + ShopDO shop = shopMapper.selectById(shopId); + PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( + shop == null ? null : shop.getBusinessHours() + ); + + List artists = listArtists(shopId, artistId); + List schedules = listSchedules(shopId, start, end, artistId); + List scheduleVos = schedules.stream() + .map(schedule -> toScheduleVO(schedule, artists)) + .sorted(Comparator.comparing(PlanningScheduleVO::getDate) + .thenComparing(PlanningScheduleVO::getStartTime) + .thenComparing(PlanningScheduleVO::getArtistName, Comparator.nullsLast(String::compareTo))) + .toList(); + + LocalDateTime rangeStart = start.atStartOfDay(); + LocalDateTime rangeEnd = end.plusDays(1).atStartOfDay(); + List appointments = listAppointments(shopId, rangeStart, rangeEnd, artistId, artists); + Map countByArtist = appointments.stream() + .filter(appointment -> appointment.getArtistId() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); + artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue())); + + PlanningCalendarVO vo = new PlanningCalendarVO(); + vo.setBusinessStartTime(businessHours.start().toString()); + vo.setBusinessEndTime(businessHours.end().toString()); + vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); + vo.setArtists(artists); + vo.setSchedules(scheduleVos); + vo.setAppointments(appointments); + vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments)); + return vo; + } + + @Override + @Transactional + public PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto) { + if (dto == null) { + throw new RuntimeException("预约信息不能为空"); + } + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new RuntimeException("美甲师账号只能查看预约,不能新建预约"); + } + Long shopId = requirePlanningShopId(currentUser); + requireAppointmentDuration(dto.getDurationMinutes()); + ProductDO product = resolveAppointmentProduct(dto, shopId); + UserDO artist = requireActiveArtist(dto.getArtistId(), shopId); + UserDO customer = resolveCustomer(shopId, dto); + + int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity; + LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(shopId, startTime, endTime); + + BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); + + OrderDO order = new OrderDO(); + order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); + order.setUserId(customer.getId()); + order.setShopId(shopId); + order.setTotalAmount(amount); + order.setActualAmount(amount); + order.setCustomerRemark(trimToNull(dto.getRemark())); + order.setQuoteStatus("CONFIRMED"); + order.setQuoteUserConfirmed(1); + order.setQuoteShopConfirmed(1); + order.setQuoteConfirmedTime(LocalDateTime.now()); + order.setPaymentStatus("UNPAID"); + order.setPayAmount(amount); + order.setPaidAmount(BigDecimal.ZERO); + order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setIsDelete(0); + orderMapper.insert(order); + + OrderItemDO item = new OrderItemDO(); + item.setOrderId(order.getId()); + item.setProductId(product.getId()); + item.setQuantity(quantity); + item.setPrice(unitPrice); + item.setArtistId(artist.getId()); + item.setAppointmentTime(startTime); + item.setIsDelete(0); + orderItemMapper.insert(item); + + appointmentCapacityService.reserveConfirmedOrThrow( + order.getId(), + item.getId(), + shopId, + artist.getId(), + product.getTitle(), + startTime, + endTime, + trimToNull(dto.getClientRequestId()) + ); + + return getAppointment(currentUser, item.getId()); + } + + @Override + public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) { + if (orderItemId == null) { + throw new RuntimeException("预约ID不能为空"); + } + OrderItemDO item = orderItemMapper.selectById(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("预约不存在"); + } + OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); + ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); + AppointmentReservationDO reservation = findActiveReservation(orderItemId); + Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); + Map customerMap = loadUsers(Set.of(order.getUserId())); + return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); + } + + @Override + @Transactional + public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) { + if (orderItemId == null || dto == null) { + throw new RuntimeException("改派信息不能为空"); + } + OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("预约不存在"); + } + OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); + ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId()); + Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId(); + UserDO artist = requireActiveArtist(targetArtistId, order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * + Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime()) + ? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()) + : item.getAppointmentTime(); + if (startTime == null) { + throw new RuntimeException("预约时间不能为空"); + } + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(order.getShopId(), startTime, endTime); + + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + order.getShopId(), + item.getArtistId(), + artist.getId(), + product.getTitle(), + startTime, + endTime + ); + + item.setArtistId(artist.getId()); + item.setAppointmentTime(startTime); + orderItemMapper.updateById(item); + return getAppointment(currentUser, item.getId()); + } + + @Override + @Transactional + public Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto) { + if (orderId == null || dto == null || dto.getStatus() == null) { + throw new RuntimeException("预约状态不能为空"); + } + OrderDO order = requireAccessibleOrder(currentUser, orderId); + int targetStatus = dto.getStatus(); + if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) { + if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); + } + return true; + } + orderService.processOrder(orderId, targetStatus); + return true; + } + + private Long requirePlanningShopId(UserDO currentUser) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + if (shopId == null || shopId <= 0) { + throw new RuntimeException("请先选择店铺后再查看规划"); + } + return shopId; + } + + private List listArtists(Long shopId, Long artistId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("shop_id", shopId) + .eq("type", 3) + .eq("is_delete", 0) + .orderByAsc("id"); + if (artistId != null && artistId > 0) { + wrapper.eq("id", artistId); + } + List artists = userMapper.selectList(wrapper); + if (artists == null || artists.isEmpty()) { + return List.of(); + } + Set artistIds = artists.stream().map(UserDO::getId).collect(Collectors.toCollection(HashSet::new)); + Map infoMap = loadArtistInfo(artistIds); + List result = new ArrayList<>(); + for (int i = 0; i < artists.size(); i++) { + UserDO user = artists.get(i); + NailArtistInfoDO info = infoMap.get(user.getId()); + PlanningArtistVO vo = new PlanningArtistVO(); + vo.setId(user.getId()); + vo.setName(firstNonBlank(user.getNickname(), user.getAccount(), "美甲师" + (i + 1))); + vo.setShortName(PlanningCalendarSupport.shortName(vo.getName())); + vo.setPhone(firstNonBlank(user.getContactPhone(), user.getPhone(), "")); + vo.setAvatar(user.getAvatar()); + vo.setColor(colorForArtist(user.getId(), i)); + vo.setStatus(info == null || info.getStatus() == null ? user.getStatus() : info.getStatus()); + vo.setStatusText(Integer.valueOf(0).equals(vo.getStatus()) ? "休息" : "可预约"); + vo.setWorkStartTime(info == null || info.getWorkStartTime() == null ? null : info.getWorkStartTime().toString()); + vo.setWorkEndTime(info == null || info.getWorkEndTime() == null ? null : info.getWorkEndTime().toString()); + vo.setRangeCount(0); + result.add(vo); + } + return result; + } + + private Map loadArtistInfo(Set artistIds) { + if (artistIds == null || artistIds.isEmpty()) { + return Map.of(); + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.in("user_id", artistIds).eq("is_delete", 0); + return nailArtistInfoMapper.selectList(wrapper).stream() + .collect(Collectors.toMap(NailArtistInfoDO::getUserId, Function.identity(), (a, b) -> a)); + } + + private List listSchedules(Long shopId, LocalDate start, LocalDate end, Long artistId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("shop_id", shopId) + .between("work_date", start, end) + .eq("is_delete", 0) + .orderByAsc("work_date") + .orderByAsc("start_time"); + if (artistId != null && artistId > 0) { + wrapper.eq("artist_id", artistId); + } + return artistScheduleMapper.selectList(wrapper); + } + + private PlanningScheduleVO toScheduleVO(ArtistScheduleDO schedule, List artists) { + Map artistNames = artists.stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, PlanningArtistVO::getName, (a, b) -> a)); + PlanningScheduleVO vo = new PlanningScheduleVO(); + vo.setId(schedule.getId()); + vo.setArtistId(schedule.getArtistId()); + vo.setArtistName(artistNames.get(schedule.getArtistId())); + vo.setDate(schedule.getWorkDate() == null ? null : schedule.getWorkDate().toString()); + vo.setStartTime(schedule.getStartTime() == null ? null : schedule.getStartTime().toString()); + vo.setEndTime(schedule.getEndTime() == null ? null : schedule.getEndTime().toString()); + vo.setCapacity(schedule.getCapacity()); + vo.setStatus(schedule.getStatus()); + vo.setStatusText(Integer.valueOf(1).equals(schedule.getStatus()) ? "可预约" : "请假"); + vo.setRemark(schedule.getRemark()); + return vo; + } + + private List listAppointments(Long shopId, LocalDateTime rangeStart, LocalDateTime rangeEnd, + Long artistId, List artists) { + QueryWrapper reservationWrapper = new QueryWrapper<>(); + reservationWrapper.eq("shop_id", shopId) + .eq("is_delete", 0) + .in("status", ACTIVE_RESERVATION_STATUS) + .lt("appointment_start_time", rangeEnd) + .gt("appointment_end_time", rangeStart) + .orderByAsc("appointment_start_time"); + if (artistId != null && artistId > 0) { + reservationWrapper.eq("artist_id", artistId); + } + List reservations = appointmentReservationMapper.selectList(reservationWrapper); + + QueryWrapper itemWrapper = new QueryWrapper<>(); + itemWrapper.eq("is_delete", 0) + .isNotNull("appointment_time") + .ge("appointment_time", rangeStart) + .lt("appointment_time", rangeEnd) + .orderByAsc("appointment_time"); + if (artistId != null && artistId > 0) { + itemWrapper.eq("artist_id", artistId); + } + List fallbackItems = orderItemMapper.selectList(itemWrapper); + + return buildAppointmentList(shopId, reservations, fallbackItems, artists); + } + + private List buildAppointmentList(Long shopId, List reservations, + List fallbackItems, List artists) { + Set itemIds = new HashSet<>(); + Set orderIds = new HashSet<>(); + for (AppointmentReservationDO reservation : safeList(reservations)) { + if (reservation.getOrderItemId() != null) { + itemIds.add(reservation.getOrderItemId()); + } + if (reservation.getOrderId() != null) { + orderIds.add(reservation.getOrderId()); + } + } + for (OrderItemDO item : safeList(fallbackItems)) { + if (item.getId() != null) { + itemIds.add(item.getId()); + } + if (item.getOrderId() != null) { + orderIds.add(item.getOrderId()); + } + } + + Map itemMap = loadOrderItems(itemIds); + Map orderMap = loadOrders(orderIds); + Set productIds = itemMap.values().stream() + .map(OrderItemDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Set customerIds = orderMap.values().stream() + .map(OrderDO::getUserId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + Map productMap = loadProducts(productIds); + Map customerMap = loadUsers(customerIds); + Map artistMap = artists.stream() + .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); + + List result = new ArrayList<>(); + Set reservationItemIds = new HashSet<>(); + for (AppointmentReservationDO reservation : safeList(reservations)) { + OrderItemDO item = itemMap.get(reservation.getOrderItemId()); + OrderDO order = orderMap.get(reservation.getOrderId()); + if (!isVisibleOrder(order, shopId)) { + continue; + } + ProductDO product = item == null ? null : productMap.get(item.getProductId()); + UserDO customer = customerMap.get(order.getUserId()); + result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); + if (reservation.getOrderItemId() != null) { + reservationItemIds.add(reservation.getOrderItemId()); + } + } + for (OrderItemDO item : safeList(fallbackItems)) { + if (item.getId() != null && reservationItemIds.contains(item.getId())) { + continue; + } + OrderDO order = orderMap.get(item.getOrderId()); + if (!isVisibleOrder(order, shopId)) { + continue; + } + ProductDO product = productMap.get(item.getProductId()); + UserDO customer = customerMap.get(order.getUserId()); + result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); + } + result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) + .thenComparing(PlanningAppointmentVO::getArtistName, Comparator.nullsLast(String::compareTo))); + return result; + } + + private PlanningAppointmentVO toAppointmentVO(AppointmentReservationDO reservation, OrderItemDO item, OrderDO order, + ProductDO product, UserDO customer, Map artistMap) { + LocalDateTime start = reservation == null ? null : reservation.getAppointmentStartTime(); + if (start == null && item != null) { + start = item.getAppointmentTime(); + } + int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); + LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime(); + if (end == null && start != null) { + end = start.plusMinutes(durationMinutes); + } + + Long artistId = reservation != null && reservation.getArtistId() != null + ? reservation.getArtistId() + : item == null ? null : item.getArtistId(); + PlanningArtistVO artist = artistId == null ? null : artistMap.get(artistId); + + PlanningAppointmentVO vo = new PlanningAppointmentVO(); + vo.setOrderId(order == null ? null : order.getId()); + vo.setOrderNo(order == null ? null : order.getOrderNo()); + vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId()); + vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId()); + vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); + vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); + vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId()); + vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle()) + ? reservation.getProductTitle() + : product == null ? "预约作品" : product.getTitle()); + vo.setArtistId(artistId); + vo.setArtistName(artist == null ? "未分配" : artist.getName()); + vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor()); + vo.setDate(start == null ? null : start.toLocalDate().toString()); + vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start)); + vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end)); + vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60); + vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes())); + vo.setStatus(order == null ? null : order.getStatus()); + vo.setStatusText(statusText(order == null ? null : order.getStatus())); + String occupancyStatus = resolveOccupancyStatus(reservation, order); + vo.setOccupancyStatus(occupancyStatus); + vo.setCanEdit(canEditAppointment(order, occupancyStatus)); + vo.setCanCancel(canCancelAppointment(order, occupancyStatus)); + vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus)); + vo.setAmount(order == null ? null : order.getActualAmount()); + vo.setRemark(order == null ? null : order.getCustomerRemark()); + return vo; + } + + private List buildDaySummaries(LocalDate start, LocalDate end, List artists, + List schedules, List appointments) { + Map> appointmentsByDate = appointments.stream() + .filter(appointment -> appointment.getDate() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getDate)); + Map> schedulesByDate = schedules.stream() + .filter(schedule -> schedule.getWorkDate() != null) + .collect(Collectors.groupingBy(schedule -> schedule.getWorkDate().toString())); + + List summaries = new ArrayList<>(); + LocalDate cursor = start; + while (!cursor.isAfter(end)) { + String date = cursor.toString(); + List dayAppointments = appointmentsByDate.getOrDefault(date, List.of()); + Map countByArtist = dayAppointments.stream() + .filter(appointment -> appointment.getArtistId() != null) + .collect(Collectors.groupingBy(PlanningAppointmentVO::getArtistId, Collectors.counting())); + List daySchedules = schedulesByDate.getOrDefault(date, List.of()); + Map scheduleByArtist = daySchedules.stream() + .collect(Collectors.toMap(ArtistScheduleDO::getArtistId, Function.identity(), (a, b) -> a)); + + List artistCounts = new ArrayList<>(); + int workingArtistCount = 0; + int fullWorkingArtistCount = 0; + for (PlanningArtistVO artist : artists) { + int count = countByArtist.getOrDefault(artist.getId(), 0L).intValue(); + ArtistScheduleDO schedule = scheduleByArtist.get(artist.getId()); + List artistAppointments = dayAppointments.stream() + .filter(appointment -> Objects.equals(appointment.getArtistId(), artist.getId())) + .toList(); + String artistStatus = resolveArtistDayStatus(artist, schedule, artistAppointments); + if (!"rest".equals(artistStatus)) { + workingArtistCount++; + if ("full".equals(artistStatus)) { + fullWorkingArtistCount++; + } + } + PlanningArtistCountVO countVO = new PlanningArtistCountVO(); + countVO.setArtistId(artist.getId()); + countVO.setArtistName(artist.getName()); + countVO.setShortName(artist.getShortName()); + countVO.setColor(artist.getColor()); + countVO.setCount(count); + countVO.setStatus(artistStatus); + artistCounts.add(countVO); + } + int total = dayAppointments.size(); + boolean hasWorkingSchedule = workingArtistCount > 0; + boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount; + + PlanningDaySummaryVO summary = new PlanningDaySummaryVO(); + summary.setDate(date); + summary.setTotalCount(total); + summary.setArtistCounts(artistCounts); + summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); + summaries.add(summary); + cursor = cursor.plusDays(1); + } + return summaries; + } + + private String resolveArtistDayStatus(PlanningArtistVO artist, ArtistScheduleDO schedule, List appointments) { + if (schedule != null && !Integer.valueOf(1).equals(schedule.getStatus())) { + return "rest"; + } + if (schedule == null || Integer.valueOf(0).equals(artist.getStatus())) { + return "rest"; + } + if (hasContinuousFreeWindow(schedule, appointments, MONTH_AVAILABLE_MINUTES)) { + return appointments.isEmpty() ? "free" : "working"; + } + return "full"; + } + + private boolean hasContinuousFreeWindow(ArtistScheduleDO schedule, List appointments, int requiredMinutes) { + if (schedule == null || schedule.getStartTime() == null || schedule.getEndTime() == null || requiredMinutes <= 0) { + return false; + } + int startMinute = schedule.getStartTime().toSecondOfDay() / 60; + int endMinute = schedule.getEndTime().toSecondOfDay() / 60; + if (endMinute - startMinute < requiredMinutes) { + return false; + } + int cursor = startMinute; + List ranges = appointments.stream() + .map(this::toTimeRange) + .filter(Objects::nonNull) + .filter(range -> range.endMinute() > startMinute && range.startMinute() < endMinute) + .map(range -> new TimeRange(Math.max(range.startMinute(), startMinute), Math.min(range.endMinute(), endMinute))) + .sorted(Comparator.comparing(TimeRange::startMinute).thenComparing(TimeRange::endMinute)) + .toList(); + for (TimeRange range : ranges) { + if (range.startMinute() - cursor >= requiredMinutes) { + return true; + } + cursor = Math.max(cursor, range.endMinute()); + } + return endMinute - cursor >= requiredMinutes; + } + + private TimeRange toTimeRange(PlanningAppointmentVO appointment) { + if (appointment == null) { + return null; + } + Integer startMinute = appointment.getStartMinute(); + Integer durationMinutes = appointment.getDurationMinutes(); + if (startMinute == null || durationMinutes == null || durationMinutes <= 0) { + return null; + } + return new TimeRange(startMinute, startMinute + durationMinutes); + } + + private record TimeRange(int startMinute, int endMinute) { + } + + private ProductDO requireActiveProduct(Long productId, Long shopId) { + if (productId == null) { + throw new RuntimeException("请选择预约作品"); + } + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete()) || !shopId.equals(product.getShopId())) { + throw new RuntimeException("预约作品不存在或不属于当前店铺"); + } + return product; + } + + private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + if (dto.getProductId() != null) { + return requireActiveProduct(dto.getProductId(), shopId); + } + return createManualAppointmentProduct(dto, shopId); + } + + private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + String title = trimToNull(dto.getManualProductTitle()); + if (!hasText(title)) { + throw new RuntimeException("请选择预约作品或填写手动作品名称"); + } + BigDecimal price = dto.getManualProductPrice(); + if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("手动作品价格不能小于0"); + } + int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); + ProductDO product = new ProductDO(); + product.setShopId(shopId); + product.setTitle(title); + product.setDescription(trimToNull(dto.getManualProductDescription())); + product.setTags(trimToNull(dto.getManualProductTags())); + product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); + product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); + product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + product.setPrice(price); + product.setLikeCount(0); + product.setCollectCount(0); + product.setApproximateDuration(durationMinutes + "分钟"); + product.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId())); + product.setFrontVisible(0); + product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); + product.setIsDelete(0); + productMapper.insert(product); + return product; + } + + private int requireAppointmentDuration(Integer durationMinutes) { + if (durationMinutes == null || durationMinutes <= 0) { + throw new RuntimeException("预约时长不能为空且必须大于0分钟"); + } + return durationMinutes; + } + + private UserDO requireActiveArtist(Long artistId, Long shopId) { + if (artistId == null) { + throw new RuntimeException("请选择美甲师"); + } + UserDO artist = userMapper.selectById(artistId); + if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) + || !Integer.valueOf(3).equals(artist.getType()) || !shopId.equals(artist.getShopId())) { + throw new RuntimeException("美甲师不存在或不属于当前店铺"); + } + return artist; + } + + private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { + if (dto.getCustomerUserId() != null) { + UserDO customer = userMapper.selectById(dto.getCustomerUserId()); + if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) { + throw new RuntimeException("客户不存在"); + } + return customer; + } + if (!hasText(dto.getPhone())) { + throw new RuntimeException("客户手机号不能为空"); + } + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("is_delete", 0) + .and(query -> query.eq("phone", dto.getPhone()).or().eq("contact_phone", dto.getPhone())) + .last("LIMIT 1"); + UserDO existing = userMapper.selectOne(wrapper); + if (existing != null) { + return existing; + } + UserDO customer = new UserDO(); + customer.setShopId(shopId); + customer.setNickname(firstNonBlank(dto.getCustomerName(), dto.getPhone())); + customer.setPhone(dto.getPhone()); + customer.setContactPhone(dto.getPhone()); + customer.setAccount(dto.getPhone()); + customer.setPassword(ENCODED_UNSET_PASSWORD); + customer.setType(0); + customer.setStatus(1); + customer.setIsDelete(0); + userMapper.insert(customer); + return customer; + } + + private OrderDO requireAccessibleOrder(UserDO currentUser, Long orderId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + throw new RuntimeException("订单不存在"); + } + adminScopeHelper.ensureShopAccessible(currentUser, order.getShopId(), "无权访问其他店铺预约"); + return order; + } + + private AppointmentReservationDO findActiveReservation(Long orderItemId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("order_item_id", orderItemId) + .eq("is_delete", 0) + .in("status", ACTIVE_RESERVATION_STATUS) + .orderByDesc("id") + .last("LIMIT 1"); + return appointmentReservationMapper.selectOne(wrapper); + } + + private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { + ShopDO shop = shopMapper.selectById(shopId); + PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours()); + LocalTime start = startTime.toLocalTime(); + LocalTime end = endTime.toLocalTime(); + if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { + throw new RuntimeException("预约时间超出店铺营业时间"); + } + } + + private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) { + if (hasText(appointmentStartTime)) { + String normalized = appointmentStartTime.trim().replace('T', ' '); + if (normalized.length() == 16) { + normalized = normalized + ":00"; + } + try { + return LocalDateTime.parse(normalized, DATE_TIME_FORMATTER); + } catch (DateTimeParseException ignored) { + return LocalDateTime.parse(appointmentStartTime.trim()); + } + } + if (!hasText(appointmentDate) || !hasText(appointmentTime)) { + throw new RuntimeException("请选择预约日期和时间"); + } + LocalDate date = LocalDate.parse(appointmentDate.trim()); + LocalTime time = LocalTime.parse(appointmentTime.trim().length() == 5 ? appointmentTime.trim() + ":00" : appointmentTime.trim()); + return LocalDateTime.of(date, time); + } + + private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) { + if (overrideMinutes != null && overrideMinutes > 0) { + return overrideMinutes; + } + return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES); + } + + private boolean isVisibleOrder(OrderDO order, Long shopId) { + return order != null + && !Integer.valueOf(1).equals(order.getIsDelete()) + && shopId.equals(order.getShopId()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private Map loadOrderItems(Set itemIds) { + if (itemIds == null || itemIds.isEmpty()) { + return Map.of(); + } + return orderItemMapper.selectBatchIds(itemIds).stream() + .collect(Collectors.toMap(OrderItemDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadOrders(Set orderIds) { + if (orderIds == null || orderIds.isEmpty()) { + return Map.of(); + } + return orderMapper.selectBatchIds(orderIds).stream() + .collect(Collectors.toMap(OrderDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadProducts(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return Map.of(); + } + return productMapper.selectBatchIds(productIds).stream() + .collect(Collectors.toMap(ProductDO::getId, Function.identity(), (a, b) -> a)); + } + + private Map loadUsers(Set userIds) { + if (userIds == null || userIds.isEmpty()) { + return Map.of(); + } + return userMapper.selectBatchIds(userIds).stream() + .collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a)); + } + + private String colorForArtist(Long artistId, int index) { + if (artistId == null) { + return ARTIST_COLORS.get(index % ARTIST_COLORS.size()); + } + int colorIndex = Math.abs(artistId.hashCode()) % ARTIST_COLORS.size(); + return ARTIST_COLORS.get(colorIndex); + } + + private String statusText(Integer status) { + if (Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(status)) { + return "已确认"; + } + if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) { + return "已完成"; + } + if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) { + return "已取消"; + } + if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) { + return "待确认"; + } + return "未知"; + } + + private String resolveOccupancyStatus(AppointmentReservationDO reservation, OrderDO order) { + if (reservation != null && hasText(reservation.getStatus())) { + return reservation.getStatus(); + } + if (order != null && Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())) { + return RESERVATION_PENDING_QUOTE; + } + if (order != null && Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { + return RESERVATION_CONFIRMED; + } + if (order != null && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) { + return "CANCELLED"; + } + if (order != null && Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { + return "COMPLETED"; + } + return "UNKNOWN"; + } + + private Boolean canEditAppointment(OrderDO order, String occupancyStatus) { + return order != null + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) { + return order != null + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) + && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); + } + + private String resolveAppointmentConflictReason(String occupancyStatus) { + if (RESERVATION_PENDING_QUOTE.equals(occupancyStatus)) { + return "该时段已有待报价预约占用"; + } + if (RESERVATION_CONFIRMED.equals(occupancyStatus)) { + return "该时段已有已确认预约占用"; + } + return null; + } + + private List safeList(List list) { + return list == null ? List.of() : list; + } + + private String firstNonBlank(String... values) { + for (String value : values) { + if (hasText(value)) { + return value.trim(); + } + } + return ""; + } + + private String trimToNull(String value) { + return hasText(value) ? value.trim() : null; + } + + private boolean hasText(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/support/PlanningCalendarSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/support/PlanningCalendarSupport.java new file mode 100644 index 00000000..435ae32a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/support/PlanningCalendarSupport.java @@ -0,0 +1,83 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.support; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalTime; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class PlanningCalendarSupport { + + private static final LocalTime DEFAULT_START = LocalTime.of(10, 0); + private static final LocalTime DEFAULT_END = LocalTime.of(22, 0); + private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+(?:\\.\\d+)?)"); + + private PlanningCalendarSupport() { + } + + public static String shortName(String name) { + if (name == null || name.trim().isEmpty()) { + return "?"; + } + String normalized = name.trim(); + if (normalized.startsWith("小") && normalized.length() > 1) { + return normalized.substring(1, 2); + } + if (normalized.endsWith("老师") && normalized.length() > 2) { + return normalized.substring(0, 1); + } + return normalized.substring(0, 1).toUpperCase(); + } + + public static BusinessHours parseBusinessHours(String businessHours) { + if (businessHours == null || businessHours.trim().isEmpty()) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + String[] parts = businessHours.trim().split("-"); + if (parts.length != 2) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + if (!start.isBefore(end)) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + return new BusinessHours(start, end); + } catch (RuntimeException ignored) { + return new BusinessHours(DEFAULT_START, DEFAULT_END); + } + } + + public static int parseDurationMinutes(String durationText, int defaultMinutes) { + if (durationText == null || durationText.trim().isEmpty()) { + return defaultMinutes; + } + Matcher matcher = NUMBER_PATTERN.matcher(durationText.trim()); + if (!matcher.find()) { + return defaultMinutes; + } + BigDecimal amount = new BigDecimal(matcher.group(1)); + if (durationText.contains("小时") || durationText.toLowerCase().contains("hour")) { + amount = amount.multiply(BigDecimal.valueOf(60)); + } + int minutes = amount.setScale(0, RoundingMode.HALF_UP).intValue(); + return minutes > 0 ? minutes : defaultMinutes; + } + + public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) { + if (!hasWorkingSchedule) { + return "rest"; + } + if (allWorkingArtistsBusy) { + return "full"; + } + if (totalCount <= 0) { + return "free"; + } + return "working"; + } + + public record BusinessHours(LocalTime start, LocalTime end) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningAppointmentVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningAppointmentVO.java new file mode 100644 index 00000000..0f8680ff --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningAppointmentVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class PlanningAppointmentVO { + private Long orderId; + private String orderNo; + private Long orderItemId; + private Long customerId; + private String customerName; + private String customerPhone; + private Long productId; + private String productTitle; + private Long artistId; + private String artistName; + private String artistColor; + private String date; + private String startTime; + private String endTime; + private Integer startMinute; + private Integer durationMinutes; + private Integer status; + private String statusText; + private String occupancyStatus; + private Boolean canEdit; + private Boolean canCancel; + private String conflictReason; + private BigDecimal amount; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistCountVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistCountVO.java new file mode 100644 index 00000000..e81b0a25 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistCountVO.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningArtistCountVO { + private Long artistId; + private String artistName; + private String shortName; + private String color; + private Integer count; + private String status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistVO.java new file mode 100644 index 00000000..573aa151 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningArtistVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningArtistVO { + private Long id; + private String name; + private String shortName; + private String phone; + private String avatar; + private String color; + private Integer status; + private String statusText; + private String workStartTime; + private String workEndTime; + private Integer rangeCount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningCalendarVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningCalendarVO.java new file mode 100644 index 00000000..8c452bbc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningCalendarVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class PlanningCalendarVO { + private String businessStartTime; + private String businessEndTime; + private Integer slotMinutes; + private List artists; + private List schedules; + private List appointments; + private List daySummaries; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningDaySummaryVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningDaySummaryVO.java new file mode 100644 index 00000000..5b686160 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningDaySummaryVO.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +import java.util.List; + +@Data +public class PlanningDaySummaryVO { + private String date; + private Integer totalCount; + private List artistCounts; + private String dayStatus; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningScheduleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningScheduleVO.java new file mode 100644 index 00000000..c32e430c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/planning/vo/PlanningScheduleVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.fingertipdesigner.core.modules.planning.vo; + +import lombok.Data; + +@Data +public class PlanningScheduleVO { + private Long id; + private Long artistId; + private String artistName; + private String date; + private String startTime; + private String endTime; + private Integer capacity; + private Integer status; + private String statusText; + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminProductController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminProductController.java new file mode 100644 index 00000000..2c3e5a1a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminProductController.java @@ -0,0 +1,133 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/admin/product") +@RequiredArgsConstructor +/** + * AdminProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminProductController { + /** + * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductService productService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/list") + @RequirePermission("product:view") + public Result> listProducts( + HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Long tagId, + @RequestParam(required = false) java.math.BigDecimal minPrice, + @RequestParam(required = false) java.math.BigDecimal maxPrice, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO result = productService.pageProducts(page, size, keyword, shopId, tagId, minPrice, maxPrice, createdFrom, createdTo); + return Result.success(result); + } + + @PostMapping("/create") + @RequirePermission("product:create") + @OperationGuard(action = "admin-product-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller yu + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); + Long id = productService.createProduct(productDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("product:edit") + @OperationGuard(action = "admin-product-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品"); + Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId(); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = productService.updateProduct(id, productDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("product:delete") + @OperationGuard(action = "admin-product-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品"); + boolean success = productService.deleteProduct(id); + return Result.success(success); + } + + @GetMapping("/list/all") + @RequirePermission("product:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllProducts(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + List products = shopId == null + ? productService.listAllProducts() + : productService.listProductsByShopId(shopId); + return Result.success(products); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminTagController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminTagController.java new file mode 100644 index 00000000..e6c65bcc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/admin/AdminTagController.java @@ -0,0 +1,119 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.TagDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.TagService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 后台标签管理控制器 + */ +@RestController +@RequestMapping("/admin/tag") +@RequiredArgsConstructor +public class AdminTagController { + /** + * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagService tagService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建标签 + */ + @PostMapping("/create") + @RequirePermission("tag:create") + @OperationGuard(action = "admin-tag-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId())); + Long id = tagService.createTag(tagDTO); + return Result.success(id); + } + + /** + * 更新标签 + */ + @PutMapping("/update/{id}") + @RequirePermission("tag:edit") + @OperationGuard(action = "admin-tag-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签"); + Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId(); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = tagService.updateTag(id, tagDTO); + return Result.success(success); + } + + /** + * 删除标签 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("tag:delete") + @OperationGuard(action = "admin-tag-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + public Result deleteTag(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签"); + boolean success = tagService.deleteTag(id); + return Result.success(success); + } + + /** + * 根据ID查询标签 + */ + @GetMapping("/get/{id}") + @RequirePermission("tag:view") + public Result getTagById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); + } + return Result.success(tagVO); + } + + /** + * 查询所有标签 + */ + @GetMapping("/list/all") + @RequirePermission("tag:view") + public Result> listAllTags(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + List tagVOs = shopId == null ? tagService.listAllTags() : tagService.listTagsByShopId(shopId); + return Result.success(tagVOs); + } + + /** + * 根据店铺ID查询标签 + */ + @GetMapping("/list/by-shop/{shopId}") + @RequirePermission("tag:view") + public Result> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List tagVOs = tagService.listTagsByShopId(shopId); + return Result.success(tagVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/EffectDiagramController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/EffectDiagramController.java new file mode 100644 index 00000000..b0667756 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/EffectDiagramController.java @@ -0,0 +1,111 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.EffectDiagramVO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.EffectDiagramService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 商品效果图信息表 Controller + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping({"/effect-diagram", "/api/effect-diagram"}) +@RequiredArgsConstructor +public class EffectDiagramController { + /** + * Variable `effectDiagramService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final EffectDiagramService effectDiagramService; + + /** + * 创建效果图 + * + * @param effectDiagramDTO 效果图DTO + * @return 效果图ID + */ + @PostMapping("/create") + public Result createEffectDiagram(@RequestBody EffectDiagramDTO effectDiagramDTO) { + Long id = effectDiagramService.createEffectDiagram(effectDiagramDTO); + return Result.success(id); + } + + /** + * 更新效果图 + * + * @param id 效果图ID + * @param effectDiagramDTO 效果图DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + public Result updateEffectDiagram(@PathVariable Long id, @RequestBody EffectDiagramDTO effectDiagramDTO) { + boolean success = effectDiagramService.updateEffectDiagram(id, effectDiagramDTO); + return Result.success(success); + } + + /** + * 删除效果图 + * + * @param id 效果图ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + public Result deleteEffectDiagram(@PathVariable Long id) { + boolean success = effectDiagramService.deleteEffectDiagram(id); + return Result.success(success); + } + + /** + * 根据ID查询效果图 + * + * @param id 效果图ID + * @return 效果图VO + */ + @GetMapping("/get/{id}") + public Result getEffectDiagramById(@PathVariable Long id) { + EffectDiagramVO effectDiagramVO = effectDiagramService.getEffectDiagramById(id); + return Result.success(effectDiagramVO); + } + + /** + * 查询所有效果图 + * + * @return 效果图VO列表 + */ + @GetMapping("/list/all") + public Result> listAllEffectDiagrams() { + List effectDiagramVOs = effectDiagramService.listAllEffectDiagrams(); + return Result.success(effectDiagramVOs); + } + + /** + * 根据商品ID查询效果图 + * + * @param productId 商品ID + * @return 效果图VO列表 + */ + @GetMapping("/list/product/{productId}") + public Result> listEffectDiagramsByProductId(@PathVariable Long productId) { + List effectDiagramVOs = effectDiagramService.listEffectDiagramsByProductId(productId); + return Result.success(effectDiagramVOs); + } + + /** + * 根据类别查询效果图 + * + * @param category 类别 + * @return 效果图VO列表 + */ + @GetMapping("/list/category/{category}") + public Result> listEffectDiagramsByCategory(@PathVariable String category) { + List effectDiagramVOs = effectDiagramService.listEffectDiagramsByCategory(category); + return Result.success(effectDiagramVOs); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/ProductController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/ProductController.java new file mode 100644 index 00000000..d0647a3a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/ProductController.java @@ -0,0 +1,225 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService; +import com.xiaowang.fingertipdesigner.core.utils.JwtUtil; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/product") +@RequiredArgsConstructor +/** + * ProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ProductController { + /** + * Purpose: AUTHORIZATION_HEADER supports ProductController.java by holding or executing the authorization header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String AUTHORIZATION_HEADER = "Authorization"; + /** + * Purpose: BEARER_PREFIX supports ProductController.java by holding or executing the bearer prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String BEARER_PREFIX = "Bearer "; + + /** + * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductService productService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: jwtUtil supports ProductController.java by holding or executing the jwt util business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtUtil jwtUtil; + /** + * Purpose: userSessionService supports ProductController.java by holding or executing the user session service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserSessionService userSessionService; + /** + * Purpose: userShopBindingSupport supports ProductController.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + @PostMapping("/create") + @RequirePermission("product:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); + Long id = productService.createProduct(productDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("product:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品"); + Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId(); + productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = productService.updateProduct(id, productDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("product:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ProductVO productVO = productService.getProductById(id); + if (productVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品"); + boolean success = productService.deleteProduct(id); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getProductById(@PathVariable Long id) { + ProductVO productVO = productService.getPublicProductById(id); + return Result.success(productVO); + } + + @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllProducts(HttpServletRequest request) { + Long currentShopId = resolveOptionalCurrentShopId(request); + List productVOs = currentShopId == null + ? productService.listPublicProducts() + : productService.listPublicProductsByShopId(currentShopId); + return Result.success(productVOs); + } + + @GetMapping("/list/shop/{shopId}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listProductsByShopId(@PathVariable Long shopId) { + List productVOs = productService.listPublicProductsByShopId(shopId); + return Result.success(productVOs); + } + + @GetMapping("/list/tag/{tag}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listProductsByTag(HttpServletRequest request, @PathVariable String tag) { + List productVOs = productService.listProductsByTag(tag, resolveOptionalCurrentShopId(request)); + return Result.success(productVOs); + } + + @GetMapping("/list/search") + /** + * Purpose: searchProducts supports ProductController.java by holding or executing the search products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> searchProducts(HttpServletRequest request, @RequestParam("keyword") String keyword) { + List productVOs = productService.searchProducts(keyword, resolveOptionalCurrentShopId(request)); + return Result.success(productVOs); + } + + @GetMapping("/list/page") + public Result> pagePublicProducts(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String tag, + @RequestParam(required = false) String tagIds) { + return Result.success(productService.pagePublicProducts(page, size, keyword, tag, tagIds, resolveOptionalCurrentShopId(request))); + } + + /** + * Purpose: resolveOptionalCurrentShopId supports ProductController.java by holding or executing the resolve optional current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long resolveOptionalCurrentShopId(HttpServletRequest request) { + if (request == null) { + return null; + } + String authHeader = request.getHeader(AUTHORIZATION_HEADER); + if (!StringUtils.hasText(authHeader) || !authHeader.startsWith(BEARER_PREFIX)) { + return null; + } + String token = authHeader.substring(BEARER_PREFIX.length()); + try { + if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) { + return null; + } + Long shopId = jwtUtil.getShopIdFromToken(token); + if (shopId == null || shopId <= 0) { + return null; + } + Long userId = jwtUtil.getUserIdFromToken(token); + String sessionId = jwtUtil.getSessionIdFromToken(token); + String jti = jwtUtil.getJtiFromToken(token); + if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { + return null; + } + return userShopBindingSupport.canUserAccessShop(userId, shopId, false, null) ? shopId : null; + } catch (RuntimeException exception) { + return null; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/TagController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/TagController.java new file mode 100644 index 00000000..d1135d72 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/controller/front/TagController.java @@ -0,0 +1,161 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.TagDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.product.service.TagService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 系统标签信息表 Controller + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping("/tag") +@RequiredArgsConstructor +public class TagController { + /** + * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagService tagService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建标签 + * + * @param tagDTO 标签DTO + * @return 标签ID + */ + @PostMapping("/create") + @RequirePermission("tag:create") + public Result createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId())); + Long id = tagService.createTag(tagDTO); + return Result.success(id); + } + + /** + * 更新标签 + * + * @param id 标签ID + * @param tagDTO 标签DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("tag:edit") + public Result updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签"); + Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId(); + tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); + boolean success = tagService.updateTag(id, tagDTO); + return Result.success(success); + } + + /** + * 删除标签 + * + * @param id 标签ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("tag:delete") + public Result deleteTag(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签"); + boolean success = tagService.deleteTag(id); + return Result.success(success); + } + + /** + * 根据ID查询标签 + * + * @param id 标签ID + * @return 标签VO + */ + @GetMapping("/get/{id}") + @RequirePermission("tag:view") + public Result getTagById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagById(id); + if (tagVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); + } + return Result.success(tagVO); + } + + /** + * 查询所有标签(公开接口,不需要权限) + * + * @return 标签VO列表 + */ + @GetMapping("/list/all") + public Result> listAllTags() { + List tagVOs = tagService.listAllTags(); + return Result.success(tagVOs); + } + + /** + * Purpose: listFilterOptions exposes customer-facing grouped tag filters. + * Usage: call it from public product pages, optionally passing shopId for a shop-scoped filter bar. + */ + @GetMapping("/list/filter-options") + public Result> listFilterOptions(@RequestParam(required = false) Long shopId) { + return Result.success(tagService.listFilterOptions(shopId)); + } + + /** + * 根据店铺ID查询标签 + * + * @param shopId 店铺ID + * @return 标签VO列表 + */ + @GetMapping("/list/by-shop/{shopId}") + @RequirePermission("tag:view") + public Result> listTagsByShopId(HttpServletRequest request, @PathVariable Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List tagVOs = tagService.listTagsByShopId(shopId); + return Result.success(tagVOs); + } + + /** + * 根据标签名称查询标签 + * + * @param tagName 标签名称 + * @return 标签VO + */ + @GetMapping("/get/tagName/{tagName}") + @RequirePermission("tag:view") + public Result getTagByTagName(HttpServletRequest request, @PathVariable String tagName) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + TagVO tagVO = tagService.getTagByTagName(tagName); + if (tagVO != null) { + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); + } + return Result.success(tagVO); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/EffectDiagramDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/EffectDiagramDTO.java new file mode 100644 index 00000000..0170f7bf --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/EffectDiagramDTO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * 商品效果图信息表 DTO + * 用于效果图信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class EffectDiagramDTO { + + /** + * 所属商品ID,关联商品表主键 + */ + private Long productId; + + /** + * 效果图类别 + */ + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 效果图描述 + */ + private String description; + + /** + * 效果图对应服务价格 + */ + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + private String duration; + + /** + * 效果图标签 + */ + private String tag; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/ProductDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/ProductDTO.java new file mode 100644 index 00000000..fff098ab --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/ProductDTO.java @@ -0,0 +1,91 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * 商品信息表 DTO + * 用于商品信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ProductDTO { + + /** + * 所属店铺ID,关联店铺表主键 + */ + private Long shopId; + + /** + * 商品标题 + */ + private String title; + + /** + * 商品描述 + */ + private String description; + + /** + * 适合人群说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String targetAudience; + + /** + * 注意事项说明;创建或更新作品时可选传入,留空时用户端隐藏该区块。 + */ + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 商品价格,保留2位小数 + */ + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + private String tags; + + /** + * 鍟嗗搧鐐硅禐鏁? + */ + private Integer likeCount; + + /** + * 鍟嗗搧鏀惰棌鏁? + */ + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + private String approximateDuration; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + private String bookableArtists; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + private Integer frontVisible; + + /** + * 来源类型 + */ + private String sourceType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/TagDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/TagDTO.java new file mode 100644 index 00000000..faab0915 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/dto/TagDTO.java @@ -0,0 +1,63 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.dto; + +import lombok.Data; + +/** + * 系统标签信息表 DTO + * 用于标签信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class TagDTO { + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + /** + * Purpose: sceneGroup groups tags into customer-facing scene filters. + * Usage: submit it from admin tag forms; empty values are treated as the default public group. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the short label customers see in filters. + * Usage: submit it from admin forms; empty values fall back to tagName. + */ + private String displayName; + + /** + * Purpose: sortOrder controls this tag's ordering inside its public filter group. + * Usage: lower values are shown first; omit it to use legacy ordering. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible marks whether the tag appears in public filter options. + * Usage: send 1 to show, 0 to hide; omitted values default to visible. + */ + private Integer frontVisible; + + /** + * 店铺ID + */ + private Long shopId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/EffectDiagramDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/EffectDiagramDO.java new file mode 100644 index 00000000..afa43e67 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/EffectDiagramDO.java @@ -0,0 +1,76 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 商品效果图信息表 DO + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_effect_diagram") +public class EffectDiagramDO extends BaseEntity { + + /** + * 所属商品ID,关联商品表主键 + */ + @TableField("product_id") + private Long productId; + + /** + * 效果图类别 + */ + @TableField("category") + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 效果图描述 + */ + @TableField("description") + private String description; + + /** + * 效果图对应服务价格 + */ + @TableField("price") + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + @TableField("duration") + private String duration; + + /** + * 效果图标签 + */ + @TableField("tag") + private String tag; + + /** + * 效果图点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/ProductDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/ProductDO.java new file mode 100644 index 00000000..83da02e4 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/ProductDO.java @@ -0,0 +1,120 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 商品信息表 DO + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_product") +public class ProductDO extends BaseEntity { + + /** + * 所属店铺ID,关联店铺表主键 + */ + @TableField("shop_id") + private Long shopId; + + /** + * 商品标题 + */ + @TableField("title") + private String title; + + /** + * 商品描述 + */ + @TableField("description") + private String description; + + /** + * 适合人群说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("target_audience") + private String targetAudience; + + /** + * 注意事项说明;后台创建或编辑作品时填写,用户详情页有值时展示。 + */ + @TableField("precautions") + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + /** + * 商品价格,保留2位小数 + */ + @TableField("price") + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + @TableField("tags") + private String tags; + + /** + * 商品点赞数 + */ + @TableField("like_count") + private Integer likeCount; + + /** + * 商品收藏数 + */ + @TableField("collect_count") + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + @TableField("approximate_duration") + private String approximateDuration; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + @TableField("bookable_artists") + private String bookableArtists; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + @TableField("available_coupons") + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + @TableField("front_visible") + private Integer frontVisible; + + /** + * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 + */ + @TableField("source_type") + private String sourceType; + + /** + * 逻辑删除标识:0-未删除,1-已删除 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/TagDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/TagDO.java new file mode 100644 index 00000000..93d4bc92 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/entity/TagDO.java @@ -0,0 +1,84 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 系统标签信息表 DO + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_tag") +public class TagDO extends BaseEntity { + + /** + * 标签名称 + */ + @TableField("tag_name") + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + @TableField("text_color") + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + @TableField("bg_color") + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + @TableField("border_color") + private String borderColor; + + /** + * Purpose: sceneGroup stores the customer-facing filter group, such as style or occasion. + * Usage: set it from admin tag forms and read it from public filter-option APIs. + */ + @TableField("scene_group") + private String sceneGroup; + + /** + * Purpose: displayName stores the shorter public label shown in scene filters. + * Usage: leave it empty to fall back to tagName in frontend and mini-program filters. + */ + @TableField("display_name") + private String displayName; + + /** + * Purpose: sortOrder controls tag order inside public filter groups. + * Usage: lower numbers appear first; null uses the default legacy ordering. + */ + @TableField("sort_order") + private Integer sortOrder; + + /** + * Purpose: frontVisible decides whether this tag is visible in public scene filters. + * Usage: set to 1 for visible tags and 0 to hide admin-only/internal tags. + */ + @TableField("front_visible") + private Integer frontVisible; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + private Integer isDelete; + + /** + * 店铺ID + */ + @TableField("shop_id") + private Long shopId; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/EffectDiagramMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/EffectDiagramMapper.java new file mode 100644 index 00000000..2e072198 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/EffectDiagramMapper.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.EffectDiagramDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +/** + * 商品效果图信息表 Mapper + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface EffectDiagramMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/ProductMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/ProductMapper.java new file mode 100644 index 00000000..2a27ee72 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/ProductMapper.java @@ -0,0 +1,56 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +/** + * 商品信息表 Mapper + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ProductMapper extends BaseMapper { + + /** + * 增加商品收藏数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET collect_count = collect_count + 1 WHERE id = #{productId}") + int incrementCollectCount(@Param("productId") Long productId); + + /** + * 减少商品收藏数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET collect_count = CASE WHEN collect_count > 0 THEN collect_count - 1 ELSE 0 END WHERE id = #{productId}") + int decrementCollectCount(@Param("productId") Long productId); + + /** + * 增加商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET like_count = like_count + 1 WHERE id = #{productId}") + int incrementLikeCount(@Param("productId") Long productId); + + /** + * 减少商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") + int decrementLikeCount(@Param("productId") Long productId); + + @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/TagMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/TagMapper.java new file mode 100644 index 00000000..50164ef7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/mapper/TagMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; + +/** + * 系统标签信息表 Mapper + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface TagMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/EffectDiagramService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/EffectDiagramService.java new file mode 100644 index 00000000..046d4bcd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/EffectDiagramService.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.EffectDiagramVO; + +import java.util.List; + +/** + * 商品效果图信息表 Service + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface EffectDiagramService extends IService { + + /** + * 创建效果图 + * + * @param effectDiagramDTO 效果图DTO + * @return 效果图ID + */ + Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO); + + /** + * 更新效果图 + * + * @param id 效果图ID + * @param effectDiagramDTO 效果图DTO + * @return 是否更新成功 + */ + boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO); + + /** + * 删除效果图 + * + * @param id 效果图ID + * @return 是否删除成功 + */ + boolean deleteEffectDiagram(Long id); + + /** + * 根据ID查询效果图 + * + * @param id 效果图ID + * @return 效果图VO + */ + EffectDiagramVO getEffectDiagramById(Long id); + + /** + * 查询所有效果图 + * + * @return 效果图VO列表 + */ + List listAllEffectDiagrams(); + + /** + * 根据商品ID查询效果图 + * + * @param productId 商品ID + * @return 效果图VO列表 + */ + List listEffectDiagramsByProductId(Long productId); + + /** + * 根据类别查询效果图 + * + * @param category 类别 + * @return 效果图VO列表 + */ + List listEffectDiagramsByCategory(String category); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/ProductService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/ProductService.java new file mode 100644 index 00000000..e13fb545 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/ProductService.java @@ -0,0 +1,141 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; + +import java.util.List; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 商品信息表 Service + * 对应数据库表 t_product + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ProductService extends IService { + + /** + * 创建商品 + * + * @param productDTO 商品DTO + * @return 商品ID + */ + Long createProduct(ProductDTO productDTO); + + /** + * 更新商品 + * + * @param id 商品ID + * @param productDTO 商品DTO + * @return 是否更新成功 + */ + boolean updateProduct(Long id, ProductDTO productDTO); + + /** + * 增加商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + int incrementLikeCount(Long productId); + + /** + * 减少商品点赞数 + * + * @param productId 商品ID + * @return 影响行数 + */ + int decrementLikeCount(Long productId); + + /** + * 删除商品 + * + * @param id 商品ID + * @return 是否删除成功 + */ + boolean deleteProduct(Long id); + + /** + * 根据ID查询商品 + * + * @param id 商品ID + * @return 商品VO + */ + ProductVO getProductById(Long id); + + ProductVO getPublicProductById(Long id); + + /** + * 查询所有商品 + * + * @return 商品VO列表 + */ + List listAllProducts(); + + List listPublicProducts(); + + /** + * 根据店铺ID查询商品 + * + * @param shopId 店铺ID + * @return 商品VO列表 + */ + List listProductsByShopId(Long shopId); + + List listPublicProductsByShopId(Long shopId); + + /** + * 根据标签查询商品 + * + * @param tag 标签 + * @return 商品VO列表 + */ + List listProductsByTag(String tag); + + List listProductsByTag(String tag, Long shopId); + + /** + * 前台按标题、描述、标签名搜索商品 + * + * @param keyword 搜索关键词 + * @return 商品列表 + */ + List searchProducts(String keyword); + + List searchProducts(String keyword, Long shopId); + + /** + * 分页查询商品 + * + * @param page 页码 + * @param size 每页大小 + * @param keyword 搜索关键词 + * @return 分页结果 + */ + PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId); + + PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); + + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId); + + /** + * Purpose: pagePublicProducts filters public product pages by legacy tag text and grouped tag ids. + * Usage: pass comma/semicolon separated tagIds from scene filters; keep tag for backward-compatible name filtering. + */ + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/TagService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/TagService.java new file mode 100644 index 00000000..66d9128b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/TagService.java @@ -0,0 +1,84 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.TagDTO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; + +import java.util.List; + +/** + * 系统标签信息表 Service + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface TagService extends IService { + + /** + * 创建标签 + * + * @param tagDTO 标签DTO + * @return 标签ID + */ + Long createTag(TagDTO tagDTO); + + /** + * 更新标签 + * + * @param id 标签ID + * @param tagDTO 标签DTO + * @return 是否更新成功 + */ + boolean updateTag(Long id, TagDTO tagDTO); + + /** + * 删除标签 + * + * @param id 标签ID + * @return 是否删除成功 + */ + boolean deleteTag(Long id); + + /** + * 根据ID查询标签 + * + * @param id 标签ID + * @return 标签VO + */ + TagVO getTagById(Long id); + + /** + * 查询所有标签 + * + * @return 标签VO列表 + */ + List listAllTags(); + + /** + * 根据标签名称查询标签 + * + * @param tagName 标签名称 + * @return 标签VO + */ + TagVO getTagByTagName(String tagName); + + /** + * 根据店铺ID查询标签 + * + * @param shopId 店铺ID + * @return 标签VO列表 + */ + List listTagsByShopId(Long shopId); + + /** + * Purpose: listFilterOptions returns public scene-filter groups for product browsing. + * Usage: call it from public Web or mini-program product pages, optionally scoped by shopId. + * + * @param shopId optional shop scope + * @return grouped public filter tags + */ + List listFilterOptions(Long shopId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/EffectDiagramServiceImpl.java new file mode 100644 index 00000000..31331963 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/EffectDiagramServiceImpl.java @@ -0,0 +1,181 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.EffectDiagramDTO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.service.EffectDiagramService; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.EffectDiagramVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 商品效果图信息表 Service 实现 + * 对应数据库表 t_effect_diagram + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class EffectDiagramServiceImpl extends ServiceImpl implements EffectDiagramService { + /** + * Variable `effectDiagramMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final EffectDiagramMapper effectDiagramMapper; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO) { + EffectDiagramDO effectDiagramDO = new EffectDiagramDO(); + effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); + effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); + effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); + effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); + effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); + effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); + effectDiagramDO.setTag(effectDiagramDTO.getTag()); + effectDiagramDO.setIsDelete(0); + effectDiagramMapper.insert(effectDiagramDO); + return effectDiagramDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateEffectDiagram(Long id, EffectDiagramDTO effectDiagramDTO) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return false; + } + effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); + effectDiagramDO.setCategory(effectDiagramDTO.getCategory()); + effectDiagramDO.setImageFileIds(effectDiagramDTO.getImageFileIds()); + effectDiagramDO.setDescription(effectDiagramDTO.getDescription()); + effectDiagramDO.setPrice(effectDiagramDTO.getPrice()); + effectDiagramDO.setDuration(effectDiagramDTO.getDuration()); + effectDiagramDO.setTag(effectDiagramDTO.getTag()); + return effectDiagramMapper.updateById(effectDiagramDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteEffectDiagram(Long id) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return false; + } + effectDiagramDO.setIsDelete(1); + return effectDiagramMapper.updateById(effectDiagramDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return EffectDiagramVO result consumed by the caller or returned to the frontend + */ + public EffectDiagramVO getEffectDiagramById(Long id) { + EffectDiagramDO effectDiagramDO = effectDiagramMapper.selectById(id); + if (effectDiagramDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param effectDiagramDO parameter `effectDiagramDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(effectDiagramDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllEffectDiagrams() { + List effectDiagramDOs = effectDiagramMapper.selectList(null); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listEffectDiagramsByProductId(Long productId) { + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class) + .eq(EffectDiagramDO::getProductId, productId) + ); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param category parameter `category` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listEffectDiagramsByCategory(String category) { + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class) + .eq(EffectDiagramDO::getCategory, category) + ); + return effectDiagramDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 将 DO 转换为 VO + * + * @param effectDiagramDO 效果图DO + * @return 效果图VO + */ + private EffectDiagramVO convertToVO(EffectDiagramDO effectDiagramDO) { + EffectDiagramVO effectDiagramVO = new EffectDiagramVO(); + effectDiagramVO.setId(effectDiagramDO.getId()); + effectDiagramVO.setProductId(effectDiagramDO.getProductId()); + effectDiagramVO.setCategory(effectDiagramDO.getCategory()); + effectDiagramVO.setImageFileIds(effectDiagramDO.getImageFileIds()); + effectDiagramVO.setDescription(effectDiagramDO.getDescription()); + effectDiagramVO.setPrice(effectDiagramDO.getPrice()); + effectDiagramVO.setDuration(effectDiagramDO.getDuration()); + effectDiagramVO.setTag(effectDiagramDO.getTag()); + effectDiagramVO.setLikeCount(effectDiagramDO.getLikeCount()); + effectDiagramVO.setCreateTime(effectDiagramDO.getCreateTime()); + effectDiagramVO.setUpdateTime(effectDiagramDO.getUpdateTime()); + return effectDiagramVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/ProductServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/ProductServiceImpl.java new file mode 100644 index 00000000..aeca71d2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/ProductServiceImpl.java @@ -0,0 +1,1313 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.ProductDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.product.service.ProductService; +import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.ProductVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagInfo; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +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.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * ProductServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ProductServiceImpl extends ServiceImpl implements ProductService { + /** + * Purpose: PRODUCT_DETAIL_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_DETAIL_CACHE_PREFIX = "cache:product:detail:"; + /** + * Purpose: PRODUCT_LIST_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_LIST_CACHE_PREFIX = "cache:product:list:"; + /** + * Purpose: PRODUCT_SEARCH_CACHE_PREFIX supports ProductServiceImpl.java by holding or executing the product search cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PRODUCT_SEARCH_CACHE_PREFIX = "cache:product:search:"; + /** + * Purpose: DEFAULT_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the default public page size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int DEFAULT_PUBLIC_PAGE_SIZE = 10; + /** + * Purpose: MAX_PUBLIC_PAGE_SIZE supports ProductServiceImpl.java by holding or executing the max public page size business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int MAX_PUBLIC_PAGE_SIZE = 30; + private static final Pattern DURATION_PATTERN = Pattern.compile("(\\d+)"); + private static final long DEFAULT_SERVICE_DURATION_MINUTES = 60L; + private static final int FRONT_VISIBLE = 1; + private static final String SOURCE_TYPE_BACKEND = "BACKEND"; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponMapper couponMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BookableArtistSupport bookableArtistSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDTO parameter `productDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createProduct(ProductDTO productDTO) { + validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); + validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); + ProductDO productDO = new ProductDO(); + productDO.setShopId(productDTO.getShopId()); + productDO.setTitle(productDTO.getTitle()); + productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); + productDO.setImageFileIds(productDTO.getImageFileIds()); + productDO.setPrice(productDTO.getPrice()); + productDO.setTags(productDTO.getTags()); + productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + productDO.setApproximateDuration(productDTO.getApproximateDuration()); + productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); + productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible())); + productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); + productDO.setIsDelete(0); + productMapper.insert(productDO); + evictPublicProductCaches(productDO.getId()); + return productDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateProduct(Long id, ProductDTO productDTO) { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null) { + return false; + } + validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); + validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); + productDO.setShopId(productDTO.getShopId()); + productDO.setTitle(productDTO.getTitle()); + productDO.setDescription(productDTO.getDescription()); + productDO.setTargetAudience(productDTO.getTargetAudience()); + productDO.setPrecautions(productDTO.getPrecautions()); + productDO.setImageFileIds(productDTO.getImageFileIds()); + productDO.setPrice(productDTO.getPrice()); + productDO.setTags(productDTO.getTags()); + if (productDTO.getLikeCount() != null) { + productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + } + if (productDTO.getCollectCount() != null) { + productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + } + productDO.setApproximateDuration(productDTO.getApproximateDuration()); + productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); + productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible())); + productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); + boolean updated = productMapper.updateById(productDO) > 0; + if (updated) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(id); + } + return updated; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteProduct(Long id) { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { + return false; + } + productDO.setIsDelete(1); + boolean deleted = productMapper.updateById(productDO) > 0; + if (deleted) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(id); + } + return deleted; + } + + @Override + /** + * Run business method `incrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ + public int incrementLikeCount(Long productId) { + int updated = productMapper.incrementLikeCount(productId); + if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(productId); + } + return updated; + } + + @Override + /** + * Run business method `decrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ + public int decrementLikeCount(Long productId) { + int updated = productMapper.decrementLikeCount(productId); + if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictPublicProductCaches(productId); + } + return updated; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ProductVO result consumed by the caller or returned to the frontend + */ + public ProductVO getProductById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); + return multiLevelCacheService.getOrLoad( + PRODUCT_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(productDO); + } + ); + } + + @Override + public ProductVO getPublicProductById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); + return multiLevelCacheService.getOrLoad( + PRODUCT_DETAIL_CACHE_PREFIX + "public:" + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null + || Integer.valueOf(1).equals(productDO.getIsDelete()) + || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { + return null; + } + return convertToVO(productDO); + } + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllProducts() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCreateTime) + )) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listProductsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List productDOs = productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getShopId, shopId) + .orderByDesc(ProductDO::getCreateTime) + ); + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toProductVOList(productDOs); + } + ); + } + + @Override + public List listPublicProducts() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "public:all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null))) + ); + } + + @Override + public List listPublicProductsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "public", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> toProductVOList(productMapper.selectList(buildFrontQuery(null, null, null, scopedShopId))) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listProductsByTag(String tag) { + return listProductsByTag(tag, null); + } + + @Override + /** + * Purpose: listProductsByTag supports ProductServiceImpl.java by holding or executing the list products by tag business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listProductsByTag(String tag, Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + String normalizedTag = normalizeOptionalKeyword(tag); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "tag:" + normalizedTag, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> loadProductsByTag(normalizedTag, scopedShopId) + ); + } + + @Override + /** + * Run business method `searchProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List searchProducts(String keyword) { + return searchProducts(keyword, null); + } + + @Override + /** + * Purpose: searchProducts supports ProductServiceImpl.java by holding or executing the search products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List searchProducts(String keyword, Long shopId) { + if (!StringUtils.hasText(keyword)) { + return new ArrayList<>(); + } + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch(); + String trimmedKeyword = keyword.trim(); + Long scopedShopId = normalizeShopId(shopId); + return multiLevelCacheService.getOrLoad( + PRODUCT_SEARCH_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + trimmedKeyword.toLowerCase(Locale.ROOT), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> searchFrontProducts(trimmedKeyword, scopedShopId) + ); + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ + private ProductVO convertToVO(ProductDO productDO) { + if (productDO == null) { + return null; + } + return toProductVOList(Collections.singletonList(productDO)).stream() + .findFirst() + .orElse(null); + } + + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toProductVOList(List productDOs) { + if (productDOs == null || productDOs.isEmpty()) { + return new ArrayList<>(); + } + ProductEnrichmentContext context = buildEnrichmentContext(productDOs); + return productDOs.stream() + .map(productDO -> convertToVO(productDO, context)) + .collect(Collectors.toList()); + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @param context parameter `context` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ + private ProductVO convertToVO(ProductDO productDO, ProductEnrichmentContext context) { + ProductVO productVO = new ProductVO(); + productVO.setId(productDO.getId()); + productVO.setShopId(productDO.getShopId()); + productVO.setShopName(context.shopNames().get(productDO.getShopId())); + productVO.setTitle(productDO.getTitle()); + productVO.setDescription(productDO.getDescription()); + productVO.setTargetAudience(productDO.getTargetAudience()); + productVO.setPrecautions(productDO.getPrecautions()); + productVO.setImageFileIds(productDO.getImageFileIds()); + productVO.setPrice(productDO.getPrice()); + productVO.setTags(productDO.getTags()); + productVO.setLikeCount(productDO.getLikeCount()); + productVO.setCollectCount(productDO.getCollectCount()); + productVO.setApproximateDuration(productDO.getApproximateDuration()); + productVO.setServiceDurationMinutes(resolveServiceDurationMinutes(productDO.getApproximateDuration())); + String validBookableArtists = bookableArtistSupport.filterValidBookableArtists(productDO.getShopId(), productDO.getBookableArtists()); + productVO.setBookableArtists(productDO.getBookableArtists()); + productVO.setAvailableBookableArtistCount(countBookableArtists(validBookableArtists)); + productVO.setBookableArtistRestricted(StringUtils.hasText(productDO.getBookableArtists())); + productVO.setAvailableCoupons(productDO.getAvailableCoupons()); + productVO.setFrontVisible(productDO.getFrontVisible()); + productVO.setSourceType(productDO.getSourceType()); + productVO.setCreateTime(productDO.getCreateTime()); + productVO.setUpdateTime(productDO.getUpdateTime()); + + List tagNames = new ArrayList<>(); + List 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); + + List imageUrls = new ArrayList<>(); + for (Long fileId : parseDelimitedLongIds(productDO.getImageFileIds(), ",")) { + ObjectStorageFileVO fileVO = context.files().get(fileId); + if (fileVO != null && StringUtils.hasText(fileVO.getFileUrl())) { + imageUrls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); + } + } + productVO.setImageUrls(imageUrls); + return productVO; + } + + private long resolveServiceDurationMinutes(String approximateDuration) { + if (!StringUtils.hasText(approximateDuration)) { + return DEFAULT_SERVICE_DURATION_MINUTES; + } + Matcher matcher = DURATION_PATTERN.matcher(approximateDuration); + if (matcher.find()) { + try { + return Math.max(1L, Long.parseLong(matcher.group(1))); + } catch (NumberFormatException ignored) { + } + } + return DEFAULT_SERVICE_DURATION_MINUTES; + } + + /** + * Run business method `buildEnrichmentContext`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private ProductEnrichmentContext result consumed by the caller or returned to the frontend + */ + private ProductEnrichmentContext buildEnrichmentContext(List productDOs) { + Set shopIds = new LinkedHashSet<>(); + Set tagIds = new LinkedHashSet<>(); + Set 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 + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId) { + return pageProducts(page, size, keyword, shopId, null, null, null, null, null); + } + + @Override + /** + * Purpose: pageProducts supports ProductServiceImpl.java by holding or executing the page products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId, Long tagId, java.math.BigDecimal minPrice, java.math.BigDecimal maxPrice, String createdFrom, String createdTo) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class); + wrapper.eq(ProductDO::getIsDelete, 0); + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(ProductDO::getTitle, keyword) + .or().like(ProductDO::getDescription, keyword)); + } + if (shopId != null && shopId > 0) { + wrapper.eq(ProductDO::getShopId, shopId); + } + if (tagId != null) { + wrapper.like(ProductDO::getTags, String.valueOf(tagId)); + } + if (minPrice != null) { + wrapper.ge(ProductDO::getPrice, minPrice); + } + if (maxPrice != null) { + wrapper.le(ProductDO::getPrice, maxPrice); + } + LocalDateTime createdFromTime = parseDateTime(createdFrom); + LocalDateTime createdToTime = parseDateTime(createdTo); + if (createdFromTime != null) { + wrapper.ge(ProductDO::getCreateTime, createdFromTime); + } + if (createdToTime != null) { + wrapper.le(ProductDO::getCreateTime, createdToTime); + } + wrapper.orderByDesc(ProductDO::getCreateTime); + + Page productPage = productMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(toProductVOList(productPage.getRecords())); + result.setTotal(productPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + /** + * Purpose: parseDateTime supports ProductServiceImpl.java by holding or executing the parse date time business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime parseDateTime(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return LocalDateTime.parse(value.replace(" ", "T")); + } catch (Exception ignored) { + try { + return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } catch (Exception secondIgnored) { + return null; + } + } + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag) { + return pagePublicProducts(page, size, keyword, tag, null); + } + + @Override + /** + * Purpose: pagePublicProducts supports ProductServiceImpl.java by holding or executing the page public products business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, Long shopId) { + return pagePublicProducts(page, size, keyword, tag, null, shopId); + } + + @Override + /** + * Purpose: pagePublicProducts supports grouped tag-id filters for public product browsing. + * Usage: pass tagIds from scene filter chips while keeping tag for legacy tag-name searches. + */ + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag, String tagIds, Long shopId) { + int normalizedPage = normalizePage(page); + int normalizedSize = normalizePageSize(size); + String normalizedKeyword = normalizeOptionalKeyword(keyword); + String normalizedTag = normalizeOptionalKeyword(tag); + String normalizedTagIds = normalizeOptionalKeyword(tagIds); + Long scopedShopId = normalizeShopId(shopId); + AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword) + ? appCacheProperties.getProductSearch() + : appCacheProperties.getProductList(); + String cacheKey = PRODUCT_LIST_CACHE_PREFIX + buildShopCacheSegment(scopedShopId) + "page:" + normalizedPage + + ":" + normalizedSize + + ":" + normalizedKeyword.toLowerCase(Locale.ROOT) + + ":" + normalizedTag.toLowerCase(Locale.ROOT) + + ":" + normalizedTagIds.toLowerCase(Locale.ROOT); + return multiLevelCacheService.getOrLoad( + cacheKey, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag, normalizedTagIds, scopedShopId) + ); + } + + /** + * Run business method `validateBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateBookableArtists(Long shopId, String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return; + } + + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("配置可预约美甲师前必须先选择店铺"); + } + + for (String artistIdStr : bookableArtists.split(",")) { + if (!StringUtils.hasText(artistIdStr)) { + continue; + } + + Long artistId; + try { + artistId = Long.parseLong(artistIdStr.trim()); + } catch (NumberFormatException ex) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("可预约美甲师配置格式不正确"); + } + + if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效、已停用或不属于当前店铺的美甲师配置"); + } + } + } + + /** + * Run business method `validateAvailableCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateAvailableCoupons(Long shopId, String availableCoupons) { + if (!StringUtils.hasText(availableCoupons)) { + return; + } + + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("配置可用优惠券前必须先选择店铺"); + } + + for (String couponIdStr : availableCoupons.split(",")) { + if (!StringUtils.hasText(couponIdStr)) { + continue; + } + + Long couponId; + try { + couponId = Long.parseLong(couponIdStr.trim()); + } catch (NumberFormatException exception) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("可用优惠券配置格式不正确"); + } + + CouponDO couponDO = couponMapper.selectById(couponId); + if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效的优惠券配置"); + } + if (!Integer.valueOf(1).equals(couponDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在已失效的优惠券配置"); + } + if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不可跨店铺配置可用优惠券"); + } + } + } + + /** + * Run business method `countBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int countBookableArtists(String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return 0; + } + return (int) java.util.Arrays.stream(bookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .count(); + } + + /** + * Run business method `normalizeInteractionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ + private Integer normalizeInteractionCount(Integer count) { + if (count == null || count < 0) { + return 0; + } + return count; + } + + /** + * Run business method `loadProductsByTag`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List loadProductsByTag(String tag, Long shopId) { + if (!StringUtils.hasText(tag)) { + return new ArrayList<>(); + } + Set matchedTagIds = findExactTagIds(tag); + if (matchedTagIds.isEmpty()) { + return new ArrayList<>(); + } + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .orderByDesc(ProductDO::getCreateTime); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + applyTagIdConditions(wrapper, matchedTagIds); + return toProductVOList(productMapper.selectList(wrapper)); + } + + /** + * Run business method `searchFrontProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List searchFrontProducts(String keyword, Long shopId) { + LambdaQueryWrapper wrapper = buildFrontQuery(keyword, null, null, shopId); + return toProductVOList(productMapper.selectList(wrapper)); + } + + /** + * Run business method `buildPublicProductPage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, Long shopId) { + return buildPublicProductPage(page, size, keyword, tag, null, shopId); + } + + /** + * Purpose: buildPublicProductPage creates the public product page with optional grouped tag ids. + * Usage: call from cache loaders after inputs have been normalized. + */ + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag, String tagIds, Long shopId) { + Set exactTagIds = null; + if (StringUtils.hasText(tag)) { + exactTagIds = findExactTagIds(tag); + if (exactTagIds.isEmpty()) { + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildEmptyPageResult(page, size); + } + } + Set selectedTagIds = parseTagIdFilter(tagIds); + + Page pageParam = new Page<>(page, size); + Page productPage = productMapper.selectPage(pageParam, buildFrontQuery(keyword, tag, exactTagIds, selectedTagIds, shopId)); + PageResultVO result = new PageResultVO<>(); + result.setList(toProductVOList(productPage.getRecords())); + result.setTotal(productPage.getTotal()); + result.setPage(page); + result.setSize(size); + return result; + } + + /** + * Run business method `buildFrontQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @param exactTagIds parameter `exactTagIds` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds) { + return buildFrontQuery(keyword, tag, exactTagIds, null); + } + + /** + * Purpose: buildFrontQuery supports ProductServiceImpl.java by holding or executing the build front query business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Long shopId) { + return buildFrontQuery(keyword, tag, exactTagIds, null, shopId); + } + + /** + * Purpose: buildFrontQuery adds product search, legacy tag, grouped tag-id, and shop filters. + * Usage: pass selectedTagIds when users tap scene-filter chips. + */ + private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); + if (shopId != null) { + wrapper.eq(ProductDO::getShopId, shopId); + } + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + applyKeywordFilter(wrapper, keyword); + if (StringUtils.hasText(tag)) { + applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds); + } + if (selectedTagIds != null && !selectedTagIds.isEmpty()) { + applyTagIdConditions(wrapper, selectedTagIds); + } + wrapper.orderByDesc(ProductDO::getCreateTime); + return wrapper; + } + + private Integer resolveFrontVisible(Integer frontVisible) { + return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; + } + + private String resolveSourceType(String sourceType) { + return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; + } + + private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { + if (nextFrontVisible != null) { + return resolveFrontVisible(nextFrontVisible); + } + return currentFrontVisible == null ? FRONT_VISIBLE : currentFrontVisible; + } + + private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { + if (StringUtils.hasText(nextSourceType)) { + return resolveSourceType(nextSourceType); + } + return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; + } + + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyKeywordFilter(LambdaQueryWrapper wrapper, String keyword) { + if (!StringUtils.hasText(keyword)) { + return; + } + Set matchedTagIds = findLikeTagIds(keyword); + wrapper.and(w -> { + w.like(ProductDO::getTitle, keyword) + .or() + .like(ProductDO::getDescription, keyword); + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param w parameter `w` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + appendOrTagIdConditions(w, matchedTagIds); + }); + } + + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyTagIdConditions(LambdaQueryWrapper wrapper, Set 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"); + } + }); + } + + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void appendOrTagIdConditions(LambdaQueryWrapper wrapper, Set 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); + } + } + + /** + * Run business method `loadShopNameMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadShopNameMap(Set 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)); + } + + /** + * Run business method `loadTagMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadTagMap(Set 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)); + } + + /** + * Run business method `parseDelimitedLongIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawValue parameter `rawValue` supplied by the caller + * @param delimiter parameter `delimiter` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List parseDelimitedLongIds(String rawValue, String delimiter) { + if (!StringUtils.hasText(rawValue)) { + return Collections.emptyList(); + } + List 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; + } + + /** + * Purpose: parseTagIdFilter converts scene-filter tag ids into a query-safe set. + * Usage: pass comma or semicolon separated frontend values; invalid chunks are ignored. + */ + private Set parseTagIdFilter(String rawValue) { + if (!StringUtils.hasText(rawValue)) { + return Collections.emptySet(); + } + return java.util.Arrays.stream(rawValue.split("[,;]")) + .map(String::trim) + .filter(StringUtils::hasText) + .filter(value -> { + try { + Long.parseLong(value); + return true; + } catch (NumberFormatException exception) { + return false; + } + }) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `findExactTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set findExactTagIds(String tag) { + if (!StringUtils.hasText(tag)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getTagName, tag) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Run business method `findLikeTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set findLikeTagIds(String keyword) { + if (!StringUtils.hasText(keyword)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .like(TagDO::getTagName, keyword) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ + private PageResultVO buildEmptyPageResult(int page, int size) { + PageResultVO result = new PageResultVO<>(); + result.setList(List.of()); + result.setTotal(0L); + result.setPage(page); + result.setSize(size); + return result; + } + + /** + * Run business method `normalizePage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizePage(Integer page) { + return page == null || page < 1 ? 1 : page; + } + + /** + * Run business method `normalizePageSize`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param size parameter `size` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ + private int normalizePageSize(Integer size) { + if (size == null || size < 1) { + return DEFAULT_PUBLIC_PAGE_SIZE; + } + return Math.min(size, MAX_PUBLIC_PAGE_SIZE); + } + + /** + * Run business method `normalizeOptionalKeyword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeOptionalKeyword(String value) { + return StringUtils.hasText(value) ? value.trim() : ""; + } + + /** + * Purpose: normalizeShopId supports ProductServiceImpl.java by holding or executing the normalize shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + /** + * Purpose: buildShopCacheSegment supports ProductServiceImpl.java by holding or executing the build shop cache segment business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildShopCacheSegment(Long shopId) { + return shopId == null ? "all:" : "shop:" + shopId + ":"; + } + + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictPublicProductCaches(Long productId) { + if (productId != null) { + multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId); + multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + "public:" + productId); + } + multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX); + multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX); + } + + /** + * Purpose: ProductEnrichmentContext supports ProductServiceImpl.java by holding or executing the product enrichment context business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + private record ProductEnrichmentContext( + Map shopNames, + Map tags, + Map files + ) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/TagServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/TagServiceImpl.java new file mode 100644 index 00000000..12f07499 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/service/impl/TagServiceImpl.java @@ -0,0 +1,546 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.TagDTO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.service.TagService; +import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagFilterGroupVO; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagVO; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 系统标签信息表 Service 实现 + * 对应数据库表 t_tag + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class TagServiceImpl extends ServiceImpl implements TagService { + /** + * Purpose: TAG_DETAIL_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TAG_DETAIL_CACHE_PREFIX = "cache:tag:detail:"; + /** + * Purpose: TAG_LIST_CACHE_PREFIX supports TagServiceImpl.java by holding or executing the tag list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:"; + /** + * Purpose: DEFAULT_FILTER_GROUP is the public group used for legacy tags without a scene group. + * Usage: keep old tags visible in filters without requiring data migration edits. + */ + private static final String DEFAULT_FILTER_GROUP = "其他"; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createTag(TagDTO tagDTO) { + String tagName = normalizeTagName(tagDTO.getTagName()); + Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureTagNameUniqueInShop(tagName, shopId, null); + + TagDO tagDO = new TagDO(); + tagDO.setTagName(tagName); + tagDO.setTextColor(tagDTO.getTextColor()); + tagDO.setBgColor(tagDTO.getBgColor()); + tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); + tagDO.setShopId(shopId); + tagDO.setIsDelete(0); + try { + tagMapper.insert(tagDO); + } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ + throw buildDuplicateTagException(tagName, shopId, null); + } + evictTagCaches(tagDO.getId(), shopId); + return tagDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateTag(Long id, TagDTO tagDTO) { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null) { + return false; + } + String tagName = normalizeTagName(tagDTO.getTagName()); + Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureTagNameUniqueInShop(tagName, shopId, id); + + tagDO.setTagName(tagName); + tagDO.setTextColor(tagDTO.getTextColor()); + tagDO.setBgColor(tagDTO.getBgColor()); + tagDO.setBorderColor(tagDTO.getBorderColor()); + tagDO.setSceneGroup(normalizeOptionalText(tagDTO.getSceneGroup())); + tagDO.setDisplayName(normalizeOptionalText(tagDTO.getDisplayName())); + tagDO.setSortOrder(tagDTO.getSortOrder()); + tagDO.setFrontVisible(normalizeFrontVisible(tagDTO.getFrontVisible())); + tagDO.setShopId(shopId); + try { + boolean updated = tagMapper.updateById(tagDO) > 0; + if (updated) { + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictTagCaches(id, shopId); + } + return updated; + } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ + throw buildDuplicateTagException(tagName, shopId, id); + } + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteTag(Long id) { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null) { + return false; + } + tagDO.setIsDelete(1); + boolean deleted = tagMapper.updateById(tagDO) > 0; + if (deleted) { + evictTagCaches(id, tagDO.getShopId()); + } + return deleted; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ + public TagVO getTagById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(tagDO); + } + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllTags() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listTagsByShopId(Long shopId) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getShopId, shopId) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * Purpose: listFilterOptions builds public scene-filter groups for customer browsing. + * Usage: call it from Web or mini-program product pages; pass shopId to limit groups to one shop. + */ + public List listFilterOptions(Long shopId) { + Long scopedShopId = shopId != null && shopId > 0 ? shopId : null; + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "filter:" + (scopedShopId == null ? "all" : scopedShopId), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildFilterOptions(scopedShopId) + ); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ + public TagVO getTagByTagName(String tagName) { + TagDO tagDO = tagMapper.selectOne( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getTagName, tagName) + ); + if (tagDO == null) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(tagDO); + } + + /** + * 将 DO 转换为 VO + * + * @param tagDO 标签DO + * @return 标签VO + */ + private TagVO convertToVO(TagDO tagDO) { + TagVO tagVO = new TagVO(); + tagVO.setId(tagDO.getId()); + tagVO.setTagName(tagDO.getTagName()); + tagVO.setTextColor(tagDO.getTextColor()); + tagVO.setBgColor(tagDO.getBgColor()); + tagVO.setBorderColor(tagDO.getBorderColor()); + tagVO.setSceneGroup(resolveSceneGroup(tagDO.getSceneGroup())); + tagVO.setDisplayName(resolveDisplayName(tagDO)); + tagVO.setSortOrder(tagDO.getSortOrder()); + tagVO.setFrontVisible(normalizeFrontVisible(tagDO.getFrontVisible())); + tagVO.setShopId(tagDO.getShopId()); + tagVO.setShopName(resolveShopName(tagDO.getShopId())); + tagVO.setCreateTime(tagDO.getCreateTime()); + tagVO.setUpdateTime(tagDO.getUpdateTime()); + return tagVO; + } + + /** + * Run business method `normalizeTagName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTagName(String tagName) { + if (!StringUtils.hasText(tagName)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("标签名称不能为空"); + } + return tagName.trim(); + } + + /** + * Purpose: buildFilterOptions groups visible tags while preserving legacy tags in a default group. + * Usage: call it only through the cache-backed public listFilterOptions method. + */ + private List buildFilterOptions(Long shopId) { + List tags = tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(shopId != null, TagDO::getShopId, shopId) + ); + Map> groupedTags = new LinkedHashMap<>(); + tags.stream() + .filter(tagDO -> !Integer.valueOf(0).equals(tagDO.getFrontVisible())) + .sorted(Comparator + .comparing((TagDO tagDO) -> resolveSceneGroup(tagDO.getSceneGroup()).equals(DEFAULT_FILTER_GROUP) ? 1 : 0) + .thenComparing(tagDO -> resolveSceneGroup(tagDO.getSceneGroup())) + .thenComparing(tagDO -> tagDO.getSortOrder() == null ? Integer.MAX_VALUE : tagDO.getSortOrder()) + .thenComparing(TagDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(TagDO::getId, Comparator.nullsLast(Long::compareTo))) + .forEach(tagDO -> groupedTags + .computeIfAbsent(resolveSceneGroup(tagDO.getSceneGroup()), ignored -> new ArrayList<>()) + .add(convertToVO(tagDO))); + return groupedTags.entrySet().stream() + .map(entry -> { + TagFilterGroupVO groupVO = new TagFilterGroupVO(); + groupVO.setGroupName(entry.getKey()); + groupVO.setTags(entry.getValue()); + return groupVO; + }) + .collect(Collectors.toList()); + } + + /** + * Purpose: normalizeOptionalText trims optional tag metadata. + * Usage: call before persisting sceneGroup or displayName so blank strings become null. + */ + private String normalizeOptionalText(String value) { + return StringUtils.hasText(value) ? value.trim() : null; + } + + /** + * Purpose: resolveSceneGroup keeps legacy tags usable in scene filters. + * Usage: call when serializing or grouping tags for public clients. + */ + private String resolveSceneGroup(String sceneGroup) { + return StringUtils.hasText(sceneGroup) ? sceneGroup.trim() : DEFAULT_FILTER_GROUP; + } + + /** + * Purpose: resolveDisplayName decides the public label for one tag. + * Usage: call when building TagVO so clients can render displayName directly. + */ + private String resolveDisplayName(TagDO tagDO) { + if (tagDO == null) { + return null; + } + return StringUtils.hasText(tagDO.getDisplayName()) ? tagDO.getDisplayName().trim() : tagDO.getTagName(); + } + + /** + * Purpose: normalizeFrontVisible defaults old rows to visible. + * Usage: call when saving and serializing the public visibility flag. + */ + private Integer normalizeFrontVisible(Integer frontVisible) { + return frontVisible == null ? 1 : frontVisible; + } + + /** + * Run business method `requireShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long requireShopId(Long shopId) { + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择所属店铺"); + } + return shopId; + } + + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureTagNameUniqueInShop(String tagName, Long shopId, Long excludeId) { + if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前店铺已存在同名标签"); + } + } + + /** + * Run business method `findActiveTagByNameAndShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private TagDO result consumed by the caller or returned to the frontend + */ + private TagDO findActiveTagByNameAndShopId(String tagName, Long shopId, Long excludeId) { + return tagMapper.selectOne( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getShopId, shopId) + .eq(TagDO::getTagName, tagName) + .ne(excludeId != null, TagDO::getId, excludeId) + .last("LIMIT 1") + ); + } + + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private RuntimeException result consumed by the caller or returned to the frontend + */ + private RuntimeException buildDuplicateTagException(String tagName, Long shopId, Long excludeId) { + if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ + return new RuntimeException("当前店铺已存在同名标签"); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ + return new RuntimeException("数据库仍使用旧的标签全局唯一约束,请先执行本次提供的 SQL 补丁"); + } + + /** + * Run business method `resolveShopName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveShopName(Long shopId) { + if (shopId == null || shopId <= 0) { + return null; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO == null ? null : shopDO.getShopName(); + } + + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagId parameter `tagId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictTagCaches(Long tagId, Long shopId) { + if (tagId != null) { + multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId); + } + if (shopId != null) { + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:" + shopId); + } + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all"); + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "filter:all"); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/EffectDiagramVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/EffectDiagramVO.java new file mode 100644 index 00000000..59c589d3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/EffectDiagramVO.java @@ -0,0 +1,83 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 商品效果图信息表 VO + * 用于前端展示效果图信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class EffectDiagramVO { + + /** + * 效果图唯一主键ID(雪花id) + */ + private Long id; + + /** + * 所属商品ID,关联商品表主键 + */ + private Long productId; + + /** + * 商品标题 + */ + private String productTitle; + + /** + * 效果图类别 + */ + private String category; + + /** + * 图片文件ID集合,多ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 图片URL列表 + */ + private List imageUrls; + + /** + * 效果图描述 + */ + private String description; + + /** + * 效果图对应服务价格 + */ + private BigDecimal price; + + /** + * 效果图对应服务耗时 + */ + private String duration; + + /** + * 效果图标签 + */ + private String tag; + + /** + * 效果图点赞数 + */ + private Integer likeCount; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/HotProductVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/HotProductVO.java new file mode 100644 index 00000000..a4346cc8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/HotProductVO.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * HotProductVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class HotProductVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal price; + /** + * Field `likeCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer likeCount; + /** + * Field `collectCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer collectCount; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/ProductVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/ProductVO.java new file mode 100644 index 00000000..48302735 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/ProductVO.java @@ -0,0 +1,148 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; +import com.xiaowang.fingertipdesigner.core.modules.product.vo.TagInfo; + +/** + * 商品信息表 VO + * 用于前端展示商品信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ProductVO { + + /** + * 商品唯一主键ID(雪花id) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键 + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 商品标题 + */ + private String title; + + /** + * 商品描述 + */ + private String description; + + /** + * 适合人群说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String targetAudience; + + /** + * 注意事项说明;作品详情接口返回后由 Web/小程序在有值时展示。 + */ + private String precautions; + + /** + * 图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 图片URL列表 + */ + private List imageUrls; + + /** + * 商品价格,保留2位小数 + */ + private BigDecimal price; + + /** + * 标签集合,多个标签以逗号分隔,最多5个 + */ + private String tags; + + /** + * 标签列表 + */ + private List tagList; + + /** + * 标签详情列表(包含样式信息) + */ + private List tagInfos; + + /** + * 商品点赞数 + */ + private Integer likeCount; + + /** + * 商品收藏数 + */ + private Integer collectCount; + + /** + * 商品对应的服务大约耗时(如"30分钟") + */ + private String approximateDuration; + + /** + * 实际用于预约排期计算的服务时长(分钟) + */ + private Long serviceDurationMinutes; + + /** + * 可预约的美甲师ID集合,多个ID以逗号分隔 + */ + private String bookableArtists; + + /** + * 当前仍可预约的美甲师数量 + */ + private Integer availableBookableArtistCount; + + /** + * 商品是否配置了限定美甲师 + */ + private Boolean bookableArtistRestricted; + + /** + * 可用的优惠券ID集合,多个ID以逗号分隔 + */ + private String availableCoupons; + + /** + * 前台是否展示:0-隐藏,1-展示 + */ + private Integer frontVisible; + + /** + * 来源类型 + */ + private String sourceType; + + /** + * 商品创建时间 + */ + private LocalDateTime createTime; + + /** + * 商品信息最后更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagFilterGroupVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagFilterGroupVO.java new file mode 100644 index 00000000..041044ba --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagFilterGroupVO.java @@ -0,0 +1,26 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: TagFilterGroupVO groups public tags for customer scene filters. + * Usage: return it from `/tag/list/filter-options` and render each group as one filter row. + */ +@Data +public class TagFilterGroupVO { + + /** + * Purpose: groupName is the customer-facing group title. + * Usage: display it above the group's tag chips. + */ + private String groupName; + + /** + * Purpose: tags holds visible tags in the current filter group. + * Usage: use each tag id for product filtering and displayName/tagName for chip text. + */ + private List tags = new ArrayList<>(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagInfo.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagInfo.java new file mode 100644 index 00000000..218e12b8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagInfo.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import lombok.Data; + +/** + * 标签信息 VO + * 用于前端展示标签,包含样式信息 + * + * @author xiaowang + * @date 2026-02-14 + */ +@Data +public class TagInfo { + + /** + * 标签ID + */ + private Long id; + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + public TagInfo() { + } + + public TagInfo(Long id, String tagName, String textColor, String bgColor, String borderColor) { + this.id = id; + this.tagName = tagName; + this.textColor = textColor; + this.bgColor = bgColor; + this.borderColor = borderColor; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagVO.java new file mode 100644 index 00000000..0d6b0676 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/product/vo/TagVO.java @@ -0,0 +1,85 @@ +package com.xiaowang.fingertipdesigner.core.modules.product.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 系统标签信息表 VO + * 用于前端展示标签信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class TagVO { + + /** + * 标签唯一主键ID + */ + private Long id; + + /** + * 标签名称 + */ + private String tagName; + + /** + * 标签文字颜色(16进制) + */ + private String textColor; + + /** + * 标签背景颜色(16进制) + */ + private String bgColor; + + /** + * 标签边框颜色(16进制) + */ + private String borderColor; + + /** + * Purpose: sceneGroup tells clients which public filter group this tag belongs to. + * Usage: read it from tag list APIs and group filter chips by this value. + */ + private String sceneGroup; + + /** + * Purpose: displayName is the public-facing tag label. + * Usage: show this value in filters; fall back to tagName if it is empty. + */ + private String displayName; + + /** + * Purpose: sortOrder controls the public order inside a group. + * Usage: sort lower values before higher values when rendering grouped filters. + */ + private Integer sortOrder; + + /** + * Purpose: frontVisible indicates whether the tag should appear in public filters. + * Usage: public filter APIs only return visible tags; admin screens may still display it. + */ + private Integer frontVisible; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 店铺ID + */ + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminPermissionController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminPermissionController.java new file mode 100644 index 00000000..d7d0cebd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminPermissionController.java @@ -0,0 +1,236 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.PermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/admin/permission") +@RequiredArgsConstructor +/** + * AdminPermissionController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminPermissionController { + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionService permissionService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: securityAuditSupport supports AdminPermissionController.java by holding or executing the security audit support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditSupport securityAuditSupport; + + @PostMapping("/create") + @RequirePermission("permission:create") + @OperationGuard(action = "admin-permission-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + try { + Long id = permissionService.createPermission(permissionDTO); + securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_CREATE, "permissionId=" + id); + return Result.success(id); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_CREATE, "reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/update/{id}") + @RequirePermission("permission:edit") + @OperationGuard(action = "admin-permission-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + try { + boolean success = permissionService.updatePermission(id, permissionDTO); + securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("permission:delete") + @OperationGuard(action = "admin-permission-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + try { + boolean success = permissionService.deletePermission(id); + securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/get/{id}") + @RequirePermission("permission:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getPermissionById(@PathVariable Long id) { + PermissionVO permissionVO = permissionService.getPermissionById(id); + return Result.success(permissionVO); + } + + @GetMapping("/list/all") + @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllPermissions() { + List permissionVOs = permissionService.listAllPermissions(); + return Result.success(permissionVOs); + } + + @GetMapping("/list/group/{permissionGroup}") + @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionGroup parameter `permissionGroup` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listPermissionsByGroup(@PathVariable String permissionGroup) { + List permissionVOs = permissionService.listPermissionsByGroup(permissionGroup); + return Result.success(permissionVOs); + } + + @GetMapping("/user/{userId}") + @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + UserDO targetUser = userService.getById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); + } + List permissionVOs = permissionService.listUserPermissions(userId); + return Result.success(permissionVOs); + } + + @GetMapping("/assignable/{userId}") + @RequirePermission("permission:assign") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAssignablePermissionIds(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户分配权限"); + } + Long currentUserId = (Long) request.getAttribute("userId"); + return Result.success(permissionService.listAssignablePermissionIds(userId, currentUserId)); + } + + @GetMapping("/user/current") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getCurrentUserPermissions(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + userService.syncManagedPermissions(userId); + List permissions = permissionService.listUserPermissions(userId); + return Result.success(permissions); + } + + @PostMapping("/assign/{userId}") + @RequirePermission("permission:assign") + @OperationGuard(action = "admin-permission-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result assignPermissions( + HttpServletRequest request, + @PathVariable Long userId, + @RequestBody UserPermissionDTO userPermissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户分配权限"); + } + Long currentUserId = (Long) request.getAttribute("userId"); + userPermissionDTO.setUserId(userId); + try { + boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId); + securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminSecurityAuditController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminSecurityAuditController.java new file mode 100644 index 00000000..d6903723 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminSecurityAuditController.java @@ -0,0 +1,71 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO; +import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +@RestController +@RequestMapping("/admin/security-audit") +@RequiredArgsConstructor +/** + * Purpose: AdminSecurityAuditController supports AdminSecurityAuditController.java by holding or executing the admin security audit controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AdminSecurityAuditController { + + private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + /** + * Purpose: securityAuditLogService supports AdminSecurityAuditController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + @GetMapping("/logs") + @RequirePermission("security:audit:view") + public Result> listLogs( + @RequestParam(required = false) String account, + @RequestParam(required = false) String action, + @RequestParam(required = false) String result, + @RequestParam(required = false) String startTime, + @RequestParam(required = false) String endTime, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "20") Integer size) { + return Result.success(securityAuditLogService.pageLogs( + account, + action, + result, + parseDateTime(startTime), + parseDateTime(endTime), + page, + size + )); + } + + /** + * Purpose: parseDateTime supports AdminSecurityAuditController.java by holding or executing the parse date time business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime parseDateTime(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + try { + return LocalDateTime.parse(value.trim(), DATE_TIME_FORMATTER); + } catch (DateTimeParseException exception) { + return LocalDateTime.parse(value.trim()); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminShopRoleController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminShopRoleController.java new file mode 100644 index 00000000..77dd9d49 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/admin/AdminShopRoleController.java @@ -0,0 +1,186 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.InviteCodeDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.ShopRoleDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.ShopRoleService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.ShopRoleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequestMapping("/admin/shop-role") +@RequiredArgsConstructor +/** + * AdminShopRoleController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminShopRoleController { + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionService permissionService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/list") + @RequirePermission("role:view") + // 店铺角色是“只在本店生效”的角色,不是全局后台角色; + // 所以这里要先按当前登录人的店铺范围裁剪,再返回列表。 + public Result> list(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listRoles(currentUser, shopId)); + } + + @PostMapping("/create") + @RequirePermission("role:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody ShopRoleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.createRole(currentUser, dto)); + } + + @PutMapping("/{id}") + @RequirePermission("role:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopRoleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateRole(currentUser, id, dto)); + } + + @DeleteMapping("/{id}") + @RequirePermission("role:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result delete(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.deleteRole(currentUser, id)); + } + + @PostMapping("/{id}/permissions") + @RequirePermission("role:edit") + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result assignPermissions(HttpServletRequest request, @PathVariable Long id, @RequestBody List permissionIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.assignPermissions(currentUser, id, permissionIds)); + } + + @PostMapping("/{id}/users") + @RequirePermission("role:edit") + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result assignUsers(HttpServletRequest request, @PathVariable Long id, @RequestBody List userIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.assignUsers(currentUser, id, userIds)); + } + + @GetMapping("/permission-options") + @RequirePermission("role:view") + /** + * Run business method `permissionOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> permissionOptions() { + return Result.success(permissionService.listAllPermissions()); + } + + @GetMapping("/invite-code/list") + @RequirePermission("user:relation:view") + /** + * Purpose: listInviteCodes supports AdminShopRoleController.java by holding or executing the list invite codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listInviteCodes(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listInviteCodes(currentUser, shopId)); + } + + @PostMapping("/invite-code/create") + @RequirePermission("user:relation:edit") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createInviteCode(HttpServletRequest request, @Valid @RequestBody InviteCodeDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.createInviteCode(currentUser, dto)); + } + + @PutMapping("/invite-code/{id}/status") + @RequirePermission("user:relation:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateInviteCodeStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateInviteCodeStatus(currentUser, id, status)); + } + + @GetMapping("/invite-code/resolve") + // 注册页输入邀请码时调用这个接口,用来提前展示“会归属到谁、哪个店”。 + /** + * Run business method `resolve`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resolve(@RequestParam String code) { + return Result.success(shopRoleService.resolveInviteCode(code)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/front/PermissionController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/front/PermissionController.java new file mode 100644 index 00000000..c7869425 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/controller/front/PermissionController.java @@ -0,0 +1,190 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.PermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * 系统权限表 Controller + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@RestController +@RequestMapping({"/permission", "/api/permission"}) +@RequiredArgsConstructor +public class PermissionController { + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionService permissionService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + /** + * 创建权限 + * + * @param permissionDTO 权限DTO + * @return 权限ID + */ + @PostMapping("/create") + @RequirePermission("permission:create") + public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + Long id = permissionService.createPermission(permissionDTO); + return Result.success(id); + } + + /** + * 更新权限 + * + * @param id 权限ID + * @param permissionDTO 权限DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("permission:edit") + public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + boolean success = permissionService.updatePermission(id, permissionDTO); + return Result.success(success); + } + + /** + * 删除权限 + * + * @param id 权限ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("permission:delete") + public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); + boolean success = permissionService.deletePermission(id); + return Result.success(success); + } + + /** + * 根据ID查询权限 + * + * @param id 权限ID + * @return 权限VO + */ + @GetMapping("/get/{id}") + @RequirePermission("permission:view") + public Result getPermissionById(@PathVariable Long id) { + PermissionVO permissionVO = permissionService.getPermissionById(id); + return Result.success(permissionVO); + } + + /** + * 查询所有权限 + * + * @return 权限VO列表 + */ + @GetMapping("/list/all") + @RequirePermission("permission:view") + public Result> listAllPermissions() { + List permissionVOs = permissionService.listAllPermissions(); + return Result.success(permissionVOs); + } + + /** + * 根据权限分组查询权限 + * + * @param permissionGroup 权限分组 + * @return 权限VO列表 + */ + @GetMapping("/list/group/{permissionGroup}") + @RequirePermission("permission:view") + public Result> listPermissionsByGroup(@PathVariable String permissionGroup) { + List permissionVOs = permissionService.listPermissionsByGroup(permissionGroup); + return Result.success(permissionVOs); + } + + /** + * 查询用户的权限列表 + * + * @param userId 用户ID + * @return 权限VO列表 + */ + @GetMapping("/list/user/{userId}") + @RequirePermission("permission:view") + public Result> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + UserDO targetUser = userService.getById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); + } + List permissionVOs = permissionService.listUserPermissions(userId); + return Result.success(permissionVOs); + } + + /** + * 分配权限给用户 + * + * @param userPermissionDTO 用户权限分配DTO + * @return 是否分配成功 + */ + @PostMapping("/assign") + @RequirePermission("permission:assign") + public Result assignPermissions(HttpServletRequest request, @RequestBody UserPermissionDTO userPermissionDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + UserDO targetUser = userService.getById(userPermissionDTO.getUserId()); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限"); + } + Long userId = (Long) request.getAttribute("userId"); + boolean success = permissionService.assignPermissions(userPermissionDTO, userId); + return Result.success(success); + } + + /** + * 获取当前登录用户的权限列表 + * + * @return 权限列表 + */ + @GetMapping("/list/user/current") + public Result> getCurrentUserPermissions(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + List permissions = permissionService.listUserPermissions(userId); + return Result.success(permissions); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/PermissionDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/PermissionDTO.java new file mode 100644 index 00000000..261d0de2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/PermissionDTO.java @@ -0,0 +1,34 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.dto; + +import lombok.Data; + +/** + * 系统权限表 DTO + * 用于权限信息的传输 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class PermissionDTO { + + /** + * 权限编码(唯一标识) + */ + private String permissionCode; + + /** + * 权限名称 + */ + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + private String permissionGroup; + + /** + * 权限描述 + */ + private String description; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/ShopRoleDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/ShopRoleDTO.java new file mode 100644 index 00000000..0d38f5ef --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/ShopRoleDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.List; + +@Data +/** + * ShopRoleDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "角色名不能为空") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/UserPermissionDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/UserPermissionDTO.java new file mode 100644 index 00000000..86ab6fd9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/dto/UserPermissionDTO.java @@ -0,0 +1,26 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.dto; + +import lombok.Data; + +import java.util.List; + +/** + * 用户权限分配 DTO + * 用于给用户分配权限 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class UserPermissionDTO { + + /** + * 用户ID + */ + private Long userId; + + /** + * 权限ID列表 + */ + private List permissionIds; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/PermissionDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/PermissionDO.java new file mode 100644 index 00000000..098ab8db --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/PermissionDO.java @@ -0,0 +1,52 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 系统权限表 DO + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_permission") +public class PermissionDO extends BaseEntity { + + /** + * 权限编码(唯一标识) + */ + @TableField("permission_code") + private String permissionCode; + + /** + * 权限名称 + */ + @TableField("permission_name") + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + @TableField("permission_group") + private String permissionGroup; + + /** + * 权限描述 + */ + @TableField("description") + private String description; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/SecurityAuditLogDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/SecurityAuditLogDO.java new file mode 100644 index 00000000..11227ab5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/SecurityAuditLogDO.java @@ -0,0 +1,76 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +import com.xiaowang.fingertipdesigner.core.common.Result; +@Getter +@Setter +@TableName("t_security_audit_log") +/** + * Purpose: SecurityAuditLogDO supports SecurityAuditLogDO.java by holding or executing the security audit log do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogDO extends BaseEntity { + + @TableField("user_id") + /** + * Purpose: userId supports SecurityAuditLogDO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + + @TableField("account") + /** + * Purpose: account supports SecurityAuditLogDO.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + + @TableField("action") + /** + * Purpose: action supports SecurityAuditLogDO.java by holding or executing the action business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String action; + + @TableField("result") + /** + * Purpose: result supports SecurityAuditLogDO.java by holding or executing the result business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String result; + + @TableField("reason") + /** + * Purpose: reason supports SecurityAuditLogDO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + + @TableField("ip_address") + /** + * Purpose: ipAddress supports SecurityAuditLogDO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + + @TableField("device_id") + /** + * Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + + @TableField("operate_time") + /** + * Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime operateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRoleDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRoleDO.java new file mode 100644 index 00000000..b42b1ded --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRoleDO.java @@ -0,0 +1,61 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role") +/** + * ShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_name") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRolePermissionDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRolePermissionDO.java new file mode 100644 index 00000000..222a7711 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/ShopRolePermissionDO.java @@ -0,0 +1,37 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role_permission") +/** + * ShopRolePermissionDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRolePermissionDO extends BaseEntity { + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("permission_id") + /** + * Field `permissionId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long permissionId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserPermissionDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserPermissionDO.java new file mode 100644 index 00000000..40f61f9a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserPermissionDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户权限关联表 DO + * 对应数据库表 t_user_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_permission") +public class UserPermissionDO extends BaseEntity { + + /** + * 用户ID + */ + @TableField("user_id") + private Long userId; + + /** + * 权限ID + */ + @TableField("permission_id") + private Long permissionId; + + /** + * 创建人ID + */ + @TableField("create_by") + private Long createBy; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserShopRoleDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserShopRoleDO.java new file mode 100644 index 00000000..5509950d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/entity/UserShopRoleDO.java @@ -0,0 +1,49 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_shop_role") +/** + * UserShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserShopRoleDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/PermissionMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/PermissionMapper.java new file mode 100644 index 00000000..e534739b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/PermissionMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 系统权限表 Mapper + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Mapper +public interface PermissionMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/SecurityAuditLogMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/SecurityAuditLogMapper.java new file mode 100644 index 00000000..ac0f5624 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/SecurityAuditLogMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.SecurityAuditLogDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: SecurityAuditLogMapper supports SecurityAuditLogMapper.java by holding or executing the security audit log mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SecurityAuditLogMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRoleMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRoleMapper.java new file mode 100644 index 00000000..6eb50353 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRoleDO; + +/** + * ShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRoleMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRolePermissionMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRolePermissionMapper.java new file mode 100644 index 00000000..f8f2a2e1 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/ShopRolePermissionMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRolePermissionDO; + +/** + * ShopRolePermissionMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRolePermissionMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserPermissionMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserPermissionMapper.java new file mode 100644 index 00000000..25ac08ff --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserPermissionMapper.java @@ -0,0 +1,16 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserPermissionDO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 用户权限关联表 Mapper + * 对应数据库表 t_user_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +@Mapper +public interface UserPermissionMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserShopRoleMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserShopRoleMapper.java new file mode 100644 index 00000000..53ab151c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/mapper/UserShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO; + +/** + * UserShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserShopRoleMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/PermissionService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/PermissionService.java new file mode 100644 index 00000000..97920b43 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/PermissionService.java @@ -0,0 +1,102 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.PermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO; + +import java.util.List; + +/** + * 系统权限表 Service + * 对应数据库表 t_permission + * + * @author xiaowang + * @date 2026-02-25 + */ +public interface PermissionService extends IService { + + /** + * 创建权限 + * + * @param permissionDTO 权限DTO + * @return 权限ID + */ + Long createPermission(PermissionDTO permissionDTO); + + /** + * 更新权限 + * + * @param id 权限ID + * @param permissionDTO 权限DTO + * @return 是否更新成功 + */ + boolean updatePermission(Long id, PermissionDTO permissionDTO); + + /** + * 删除权限 + * + * @param id 权限ID + * @return 是否删除成功 + */ + boolean deletePermission(Long id); + + /** + * 根据ID查询权限 + * + * @param id 权限ID + * @return 权限VO + */ + PermissionVO getPermissionById(Long id); + + /** + * 查询所有权限 + * + * @return 权限VO列表 + */ + List listAllPermissions(); + + /** + * 根据权限分组查询权限 + * + * @param permissionGroup 权限分组 + * @return 权限VO列表 + */ + List listPermissionsByGroup(String permissionGroup); + + /** + * 查询用户的权限列表 + * + * @param userId 用户ID + * @return 权限VO列表 + */ + List listUserPermissions(Long userId); + + /** + * 查询当前操作人可给目标用户分配的权限ID列表 + * + * @param targetUserId 目标用户ID + * @param currentUserId 当前操作人ID + * @return 可分配的权限ID列表 + */ + List listAssignablePermissionIds(Long targetUserId, Long currentUserId); + + /** + * 给用户分配权限 + * + * @param userPermissionDTO 用户权限分配DTO + * @param currentUserId 当前操作人ID + * @return 是否分配成功 + */ + boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId); + + /** + * 检查用户是否拥有指定权限 + * + * @param userId 用户ID + * @param permissionCode 权限编码 + * @return 是否拥有权限 + */ + boolean hasPermission(Long userId, String permissionCode); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/SecurityAuditLogService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/SecurityAuditLogService.java new file mode 100644 index 00000000..839bf8f3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/SecurityAuditLogService.java @@ -0,0 +1,25 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * Purpose: SecurityAuditLogService supports SecurityAuditLogService.java by holding or executing the security audit log service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SecurityAuditLogService { + + void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request); + + PageResultVO pageLogs(String account, + String action, + String result, + LocalDateTime startTime, + LocalDateTime endTime, + Integer page, + Integer size); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/ShopRoleService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/ShopRoleService.java new file mode 100644 index 00000000..c7682457 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/ShopRoleService.java @@ -0,0 +1,120 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.InviteCodeDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.ShopRoleDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserRelationUpdateDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRoleDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.ShopRoleVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * ShopRoleService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ShopRoleService extends IService { + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRoles(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createRole(UserDO currentUser, ShopRoleDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean deleteRole(UserDO currentUser, Long id); + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds); + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignUsers(UserDO currentUser, Long id, List userIds); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRelationOptions(UserDO currentUser, Long shopId); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listInviteCodes(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createInviteCode(UserDO currentUser, InviteCodeDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status); + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + InviteCodeVO resolveInviteCode(String code); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/PermissionServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/PermissionServiceImpl.java new file mode 100644 index 00000000..6dc9b981 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/PermissionServiceImpl.java @@ -0,0 +1,689 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.PermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.UserPermissionDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserPermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRolePermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.ShopRolePermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.service.PermissionService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionPolicy; +import com.xiaowang.fingertipdesigner.core.support.RequestShopContext; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.PermissionVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * PermissionServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class PermissionServiceImpl extends ServiceImpl implements PermissionService { + + private static final Set SHOP_BOOTSTRAP_PERMISSION_CODES = Set.of( + "shop:view", + "shop:create" + ); + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserPermissionMapper userPermissionMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + + @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createPermission(PermissionDTO permissionDTO) { + PermissionDO permissionDO = new PermissionDO(); + permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); + permissionDO.setPermissionName(permissionDTO.getPermissionName()); + permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); + permissionDO.setDescription(permissionDTO.getDescription()); + permissionDO.setIsDelete(0); + permissionMapper.insert(permissionDO); + return permissionDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePermission(Long id, PermissionDTO permissionDTO) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return false; + } + if (permissionDTO.getPermissionCode() != null) { + permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); + } + if (permissionDTO.getPermissionName() != null) { + permissionDO.setPermissionName(permissionDTO.getPermissionName()); + } + if (permissionDTO.getPermissionGroup() != null) { + permissionDO.setPermissionGroup(permissionDTO.getPermissionGroup()); + } + if (permissionDTO.getDescription() != null) { + permissionDO.setDescription(permissionDTO.getDescription()); + } + permissionDO.setUpdateTime(LocalDateTime.now()); + return permissionMapper.updateById(permissionDO) > 0; + } + + @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deletePermission(Long id) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return false; + } + permissionDO.setIsDelete(1); + permissionDO.setUpdateTime(LocalDateTime.now()); + return permissionMapper.updateById(permissionDO) > 0; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return PermissionVO result consumed by the caller or returned to the frontend + */ + public PermissionVO getPermissionById(Long id) { + PermissionDO permissionDO = permissionMapper.selectById(id); + if (permissionDO == null || Integer.valueOf(1).equals(permissionDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDO parameter `permissionDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(permissionDO); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllPermissions() { + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionGroup parameter `permissionGroup` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listPermissionsByGroup(String permissionGroup) { + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionGroup, permissionGroup) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listUserPermissions(Long userId) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return List.of(); + } + if (isShopBootstrapAdmin(userDO)) { + return listAllPermissions().stream() + .filter(permission -> PermissionCatalog.isAllowedForPlatformOverview(permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + List activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream() + .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + List userPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + if (userPermissions.isEmpty()) { + return List.of(); + } + + List permissionIds = userPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (permissionIds.isEmpty()) { + return List.of(); + } + + List permissionVOs = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + + return permissionVOs.stream() + .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAssignablePermissionIds(Long targetUserId, Long currentUserId) { + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + UserDO targetUser = userMapper.selectById(targetUserId); + if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + if (!hasPermission(currentUserId, "permission:assign")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,无法分配权限"); + } + + boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前角色不能维护该用户的权限"); + } + + if (!platformAdmin) { + if (currentUserId.equals(targetUserId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不允许给自己调整权限"); + } + if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(targetUserId, currentShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能给本店铺用户分配权限"); + } + } + + Set baseAllowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); + Set operatorPermissionCodes = platformAdmin + ? Collections.emptySet() + : listPermissionCodesByUserId(currentUserId); + Set assignablePermissionCodes = platformAdmin + ? baseAllowedPermissionCodes + : baseAllowedPermissionCodes.stream() + .filter(operatorPermissionCodes::contains) + .collect(Collectors.toSet()); + + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .filter(permission -> assignablePermissionCodes.contains(permission.getPermissionCode())) + .map(PermissionDO::getId) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userPermissionDTO parameter `userPermissionDTO` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean assignPermissions(UserPermissionDTO userPermissionDTO, Long currentUserId) { + Long userId = userPermissionDTO.getUserId(); + List permissionIds = userPermissionDTO.getPermissionIds() == null + ? Collections.emptyList() + : userPermissionDTO.getPermissionIds().stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + UserDO targetUser = userMapper.selectById(userId); + if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + if (!hasPermission(currentUserId, "permission:assign")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,无法分配权限"); + } + + boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前角色不能维护该用户的权限"); + } + + if (!platformAdmin) { + if (currentUserId.equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不允许给自己调整权限"); + } + if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(userId, currentShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只能给本店铺用户分配权限"); + } + } + + Set requestedPermissionCodes = resolvePermissionCodes(permissionIds); + Set allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); + if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标角色的权限配置超出允许范围"); + } + + if (!platformAdmin) { + Set operatorPermissionCodes = listPermissionCodesByUserId(currentUserId); + if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不能分配超出自己已有的权限"); + } + } + + userPermissionMapper.delete( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + + for (Long permissionId : permissionIds) { + UserPermissionDO userPermissionDO = new UserPermissionDO(); + userPermissionDO.setUserId(userId); + userPermissionDO.setPermissionId(permissionId); + userPermissionDO.setCreateBy(currentUserId); + userPermissionMapper.insert(userPermissionDO); + } + + return true; + } + + @Override + /** + * Run business method `hasPermission`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param permissionCode parameter `permissionCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean hasPermission(Long userId, String permissionCode) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (isShopBootstrapAdmin(userDO)) { + return PermissionCatalog.isAllowedForPlatformOverview(permissionCode); + } + if (!isPermissionAllowedForUserType(userDO, permissionCode)) { + return false; + } + + List activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return hasShopRolePermission(activeShopRoles, permissionCode); + } + + List userPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + ); + if (userPermissions.isEmpty()) { + return false; + } + + List permissionIds = userPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (permissionIds.isEmpty()) { + return false; + } + + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + ); + if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) { + return false; + } + + return true; + } + + /** + * Purpose: hasShopRolePermission supports PermissionServiceImpl.java by holding or executing the has shop role permission business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean hasShopRolePermission(List activeShopRoles, String permissionCode) { + List permissionIds = listPermissionIdsByShopRoles(activeShopRoles); + if (permissionIds.isEmpty()) { + return false; + } + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + .last("limit 1")); + return permissionDO != null && permissionIds.contains(permissionDO.getId()); + } + + /** + * Run business method `resolvePermissionCodes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set resolvePermissionCodes(List permissionIds) { + if (permissionIds == null || permissionIds.isEmpty()) { + return Collections.emptySet(); + } + + List permissionDOs = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ); + if (permissionDOs.size() != permissionIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效的权限配置"); + } + + return permissionDOs.stream() + .map(PermissionDO::getPermissionCode) + .collect(Collectors.toSet()); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set listPermissionCodesByUserId(Long userId) { + return listUserPermissions(userId).stream() + .map(PermissionVO::getPermissionCode) + .collect(Collectors.toSet()); + } + + /** + * Purpose: listActiveShopRoles supports PermissionServiceImpl.java by holding or executing the list active shop roles business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listActiveShopRoles(Long userId) { + if (userId == null) { + return List.of(); + } + + Long currentShopId = RequestShopContext.getCurrentShopId(); + List activeShopRoles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class) + .eq(UserShopRoleDO::getUserId, userId) + .eq(currentShopId != null, UserShopRoleDO::getShopId, currentShopId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)); + if (currentShopId == null) { + return activeShopRoles; + } + return activeShopRoles.stream() + .filter(role -> Objects.equals(currentShopId, role.getShopId())) + .collect(Collectors.toList()); + } + + /** + * Purpose: listPermissionIdsByShopRoles supports PermissionServiceImpl.java by holding or executing the list permission ids by shop roles business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listPermissionIdsByShopRoles(List activeShopRoles) { + if (activeShopRoles == null || activeShopRoles.isEmpty()) { + return List.of(); + } + + List roleIds = activeShopRoles.stream() + .map(UserShopRoleDO::getRoleId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (roleIds.isEmpty()) { + return List.of(); + } + + return shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class) + .in(ShopRolePermissionDO::getRoleId, roleIds) + .eq(ShopRolePermissionDO::getIsDelete, 0)) + .stream() + .filter(permission -> roleIds.contains(permission.getRoleId())) + .map(ShopRolePermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Purpose: listPermissionsByIds supports PermissionServiceImpl.java by holding or executing the list permissions by ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listPermissionsByIds(List permissionIds) { + if (permissionIds == null || permissionIds.isEmpty()) { + return List.of(); + } + + return permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getId, permissionIds) + .eq(PermissionDO::getIsDelete, 0) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * Purpose: usesShopRoleEffectivePermissions supports PermissionServiceImpl.java by holding or executing the uses shop role effective permissions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean usesShopRoleEffectivePermissions(UserDO userDO, List activeShopRoles) { + return !isPlatformAdmin(userDO) && activeShopRoles != null && !activeShopRoles.isEmpty(); + } + + /** + * Purpose: isPermissionAllowedForUserType supports PermissionServiceImpl.java by holding or executing the is permission allowed for user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isPermissionAllowedForUserType(UserDO userDO, String permissionCode) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + if (isPlatformAdmin(userDO)) { + return true; + } + return PermissionPolicy.getDefaultPermissionCodeSet(userDO.getType()).contains(permissionCode); + } + + /** + * Purpose: isPlatformAdmin supports PermissionServiceImpl.java by holding or executing the is platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isPlatformAdmin(UserDO userDO) { + return userDO != null && Integer.valueOf(4).equals(userDO.getType()); + } + + /** + * Run business method `isShopBootstrapAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isShopBootstrapAdmin(UserDO userDO) { + return userDO != null + && Integer.valueOf(4).equals(userDO.getType()) + && RequestShopContext.getCurrentShopId() == null; + } + + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDO parameter `permissionDO` supplied by the caller + * @return private PermissionVO result consumed by the caller or returned to the frontend + */ + private PermissionVO convertToVO(PermissionDO permissionDO) { + PermissionVO permissionVO = new PermissionVO(); + permissionVO.setId(permissionDO.getId()); + permissionVO.setPermissionCode(permissionDO.getPermissionCode()); + permissionVO.setPermissionName(permissionDO.getPermissionName()); + permissionVO.setPermissionGroup(permissionDO.getPermissionGroup()); + permissionVO.setDescription(permissionDO.getDescription()); + permissionVO.setCreateTime(permissionDO.getCreateTime()); + permissionVO.setUpdateTime(permissionDO.getUpdateTime()); + return permissionVO; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java new file mode 100644 index 00000000..92d2c766 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/SecurityAuditLogServiceImpl.java @@ -0,0 +1,136 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.SecurityAuditLogDO; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.SecurityAuditLogMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.SecurityAuditLogVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * Purpose: SecurityAuditLogServiceImpl supports SecurityAuditLogServiceImpl.java by holding or executing the security audit log service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { + + /** + * Purpose: auditLogMapper supports SecurityAuditLogServiceImpl.java by holding or executing the audit log mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogMapper auditLogMapper; + + @Override + /** + * Purpose: record supports SecurityAuditLogServiceImpl.java by holding or executing the record business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request) { + try { + SecurityAuditLogDO log = new SecurityAuditLogDO(); + log.setUserId(userId); + log.setAccount(limit(account, 80)); + log.setAction(limit(action, 80)); + log.setResult(limit(result, 20)); + log.setReason(limit(reason, 500)); + log.setIpAddress(limit(resolveClientIp(request), 80)); + log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); + log.setOperateTime(LocalDateTime.now()); + auditLogMapper.insert(log); + } catch (Exception ignored) { + // Audit failure must never block the main user flow. + } + } + + @Override + public PageResultVO pageLogs(String account, + String action, + String result, + LocalDateTime startTime, + LocalDateTime endTime, + Integer page, + Integer size) { + int pageNo = page == null || page < 1 ? 1 : page; + int pageSize = size == null || size < 1 ? 20 : Math.min(size, 100); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + if (StringUtils.hasText(account)) { + wrapper.like(SecurityAuditLogDO::getAccount, account.trim()); + } + if (StringUtils.hasText(action)) { + wrapper.eq(SecurityAuditLogDO::getAction, action.trim()); + } + if (StringUtils.hasText(result)) { + wrapper.eq(SecurityAuditLogDO::getResult, result.trim()); + } + if (startTime != null) { + wrapper.ge(SecurityAuditLogDO::getOperateTime, startTime); + } + if (endTime != null) { + wrapper.le(SecurityAuditLogDO::getOperateTime, endTime); + } + wrapper.orderByDesc(SecurityAuditLogDO::getOperateTime).orderByDesc(SecurityAuditLogDO::getId); + Page logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper); + + PageResultVO resultVO = new PageResultVO<>(); + resultVO.setList(logPage.getRecords().stream().map(this::toVO).toList()); + resultVO.setTotal(logPage.getTotal()); + resultVO.setPage(pageNo); + resultVO.setSize(pageSize); + return resultVO; + } + + /** + * Purpose: toVO supports SecurityAuditLogServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecurityAuditLogVO toVO(SecurityAuditLogDO log) { + SecurityAuditLogVO vo = new SecurityAuditLogVO(); + vo.setId(log.getId()); + vo.setUserId(log.getUserId()); + vo.setAccount(log.getAccount()); + vo.setAction(log.getAction()); + vo.setResult(log.getResult()); + vo.setReason(log.getReason()); + vo.setIpAddress(log.getIpAddress()); + vo.setDeviceId(log.getDeviceId()); + vo.setOperateTime(log.getOperateTime()); + return vo; + } + + /** + * Purpose: resolveClientIp supports SecurityAuditLogServiceImpl.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + /** + * Purpose: limit supports SecurityAuditLogServiceImpl.java by holding or executing the limit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String limit(String value, int max) { + if (value == null || value.length() <= max) { + return value; + } + return value.substring(0, max); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/ShopRoleServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/ShopRoleServiceImpl.java new file mode 100644 index 00000000..8d416b08 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/service/impl/ShopRoleServiceImpl.java @@ -0,0 +1,549 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.InviteCodeDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.ShopRoleDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserRelationUpdateDTO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRoleDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.ShopRolePermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserInviteCodeDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserRelationDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.ShopRoleMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.ShopRolePermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserInviteCodeMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.service.ShopRoleService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionPolicy; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.fingertipdesigner.core.modules.security.vo.ShopRoleVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; +@Service +@RequiredArgsConstructor +/** + * ShopRoleServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ShopRoleServiceImpl extends ServiceImpl implements ShopRoleService { + /** + * Variable `shopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleMapper shopRoleMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRoles(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return shopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRoleDO::getIsDelete, 0) + .eq(scopedShopId != null, ShopRoleDO::getShopId, scopedShopId) + .orderByAsc(ShopRoleDO::getSortOrder) + .orderByDesc(ShopRoleDO::getCreateTime)) + .stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createRole(UserDO currentUser, ShopRoleDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权创建其他店铺角色"); + ShopRoleDO role = new ShopRoleDO(); + role.setShopId(shopId); + role.setRoleName(dto.getRoleName().trim()); + role.setCreatorId(currentUser.getId()); + role.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + role.setRemark(dto.getRemark()); + role.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + role.setIsDelete(0); + shopRoleMapper.insert(role); + syncPermissions(role.getId(), dto.getPermissionIds()); + syncUsers(role.getId(), dto.getUserIds(), shopId); + return role.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权修改其他店铺角色"); + if (StringUtils.hasText(dto.getRoleName())) { + role.setRoleName(dto.getRoleName().trim()); + } + if (dto.getStatus() != null) { + role.setStatus(dto.getStatus() == 0 ? 0 : 1); + } + if (dto.getRemark() != null) { + role.setRemark(dto.getRemark()); + } + if (dto.getSortOrder() != null) { + role.setSortOrder(dto.getSortOrder()); + } + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + if (dto.getPermissionIds() != null) { + syncPermissions(role.getId(), dto.getPermissionIds()); + } + if (dto.getUserIds() != null) { + syncUsers(role.getId(), dto.getUserIds(), role.getShopId()); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean deleteRole(UserDO currentUser, Long id) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权删除其他店铺角色"); + role.setIsDelete(1); + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权分配其他店铺角色"); + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncPermissions(id, permissionIds); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignUsers(UserDO currentUser, Long id, List userIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权绑定其他店铺员工"); + syncUsers(id, userIds, role.getShopId()); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRelationOptions(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List users = userMapper.selectList(new LambdaQueryWrapper().eq(UserDO::getIsDelete, 0)); + if (scopedShopId != null) { + Set userIds = userShopBindingMapper.selectList(new LambdaQueryWrapper<>()) + .stream().filter(b -> Objects.equals(scopedShopId, b.getShopId()) && Integer.valueOf(1).equals(b.getStatus())) + .map(b -> b.getUserId()).collect(Collectors.toSet()); + users = users.stream().filter(u -> userIds.contains(u.getId())).collect(Collectors.toList()); + } + return users.stream().map(u -> { + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(u.getId()); + vo.setShopId(scopedShopId); + vo.setParentUserId(null); + vo.setParentUserName(u.getNickname()); + vo.setParentRoleType(u.getType()); + vo.setParentRoleTypeName(typeName(u.getType())); + vo.setSourceType("MANUAL"); + vo.setSourceTypeName("手动维护"); + return vo; + }).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权修改所属关系"); + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setIsDelete(0); + userRelationMapper.insert(relation); + } + relation.setShopId(dto.getShopId() == null ? user.getShopId() : dto.getShopId()); + relation.setParentUserId(dto.getParentUserId()); + relation.setParentRoleType(dto.getParentRoleType()); + relation.setSourceType(dto.getSourceType()); + relation.setCreatorId(currentUser.getId()); + relation.setUpdateTime(LocalDateTime.now()); + userRelationMapper.updateById(relation); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listInviteCodes(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return userInviteCodeMapper.selectList(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(scopedShopId != null, UserInviteCodeDO::getShopId, scopedShopId) + .orderByDesc(UserInviteCodeDO::getCreateTime)) + .stream().map(this::toInviteVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createInviteCode(UserDO currentUser, InviteCodeDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + UserInviteCodeDO code = new UserInviteCodeDO(); + code.setInviteCode(dto.getInviteCode().trim()); + code.setOwnerUserId(dto.getOwnerUserId()); + code.setShopId(shopId); + code.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + code.setUseCount(dto.getUseCount() == null ? 0 : dto.getUseCount()); + code.setExpireTime(dto.getExpireTime()); + code.setIsDelete(0); + userInviteCodeMapper.insert(code); + return code.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status) { + UserInviteCodeDO code = userInviteCodeMapper.selectById(id); + if (code == null || Integer.valueOf(1).equals(code.getIsDelete())) { + return false; + } + adminScopeHelper.ensureShopAccessible(currentUser, code.getShopId(), "无权修改其他店铺邀请码"); + code.setStatus(status == null || status == 0 ? 0 : 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + return true; + } + + @Override + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + public InviteCodeVO resolveInviteCode(String code) { + if (!StringUtils.hasText(code)) { + return null; + } + UserInviteCodeDO entity = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, code.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + return entity == null ? null : toInviteVO(entity); + } + + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncPermissions(Long roleId, List permissionIds) { + // 保存角色权限时采用“先清空再重建”的方式: + // 表单里传来的 permissionIds 就是最终状态,避免残留上一次勾选的权限。 + shopRolePermissionMapper.delete(new LambdaQueryWrapper().eq(ShopRolePermissionDO::getRoleId, roleId)); + if (permissionIds == null) { + return; + } + for (Long permissionId : permissionIds.stream().filter(Objects::nonNull).distinct().toList()) { + ShopRolePermissionDO item = new ShopRolePermissionDO(); + item.setRoleId(roleId); + item.setPermissionId(permissionId); + item.setIsDelete(0); + shopRolePermissionMapper.insert(item); + } + } + + /** + * Run business method `syncUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncUsers(Long roleId, List userIds, Long shopId) { + userShopRoleMapper.delete(new LambdaQueryWrapper().eq(UserShopRoleDO::getRoleId, roleId)); + if (userIds == null) { + return; + } + for (Long userId : userIds.stream().filter(Objects::nonNull).distinct().toList()) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + continue; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO::getUserId, userId) + .eq(com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO::getShopId, shopId) + .eq(com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO::getIsDelete, 0)); + if (!Objects.equals(shopId, user.getShopId()) && bindingCount <= 0) { + continue; + } + UserShopRoleDO item = new UserShopRoleDO(); + item.setRoleId(roleId); + item.setUserId(userId); + item.setShopId(shopId); + item.setStatus(1); + item.setIsDelete(0); + userShopRoleMapper.insert(item); + } + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param role parameter `role` supplied by the caller + * @return private ShopRoleVO result consumed by the caller or returned to the frontend + */ + private ShopRoleVO toVO(ShopRoleDO role) { + ShopRoleVO vo = new ShopRoleVO(); + vo.setId(role.getId()); + vo.setShopId(role.getShopId()); + ShopDO shop = shopMapper.selectById(role.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setRoleName(role.getRoleName()); + vo.setCreatorId(role.getCreatorId()); + UserDO creator = role.getCreatorId() == null ? null : userMapper.selectById(role.getCreatorId()); + vo.setCreatorName(creator == null ? null : creator.getNickname()); + vo.setStatus(role.getStatus()); + vo.setRemark(role.getRemark()); + vo.setSortOrder(role.getSortOrder()); + vo.setCreateTime(role.getCreateTime()); + vo.setUpdateTime(role.getUpdateTime()); + List permissions = shopRolePermissionMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRolePermissionDO::getRoleId, role.getId()) + .eq(ShopRolePermissionDO::getIsDelete, 0)); + vo.setPermissionIds(permissions.stream().map(ShopRolePermissionDO::getPermissionId).collect(Collectors.toList())); + Set permissionIds = vo.getPermissionIds().stream().collect(Collectors.toSet()); + if (!permissionIds.isEmpty()) { + vo.setPermissionCodes(permissionMapper.selectBatchIds(permissionIds).stream().map(PermissionDO::getPermissionCode).collect(Collectors.toList())); + } else { + vo.setPermissionCodes(List.of()); + } + vo.setUserIds(userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, role.getId()) + .eq(UserShopRoleDO::getIsDelete, 0)) + .stream().map(UserShopRoleDO::getUserId).collect(Collectors.toList())); + return vo; + } + + /** + * Run business method `toInviteVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return private InviteCodeVO result consumed by the caller or returned to the frontend + */ + private InviteCodeVO toInviteVO(UserInviteCodeDO code) { + InviteCodeVO vo = new InviteCodeVO(); + vo.setId(code.getId()); + vo.setInviteCode(code.getInviteCode()); + vo.setOwnerUserId(code.getOwnerUserId()); + vo.setOwnerUserName(code.getOwnerUserId() == null ? null : Optional.ofNullable(userMapper.selectById(code.getOwnerUserId())).map(UserDO::getNickname).orElse(null)); + vo.setShopId(code.getShopId()); + vo.setShopName(code.getShopId() == null ? null : Optional.ofNullable(shopMapper.selectById(code.getShopId())).map(ShopDO::getShopName).orElse(null)); + vo.setStatus(code.getStatus()); + vo.setUseCount(code.getUseCount()); + vo.setExpireTime(code.getExpireTime()); + vo.setCreateTime(code.getCreateTime()); + return vo; + } + + /** + * Run business method `requireRole`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private ShopRoleDO result consumed by the caller or returned to the frontend + */ + private ShopRoleDO requireRole(Long id) { + ShopRoleDO role = shopRoleMapper.selectById(id); + if (role == null || Integer.valueOf(1).equals(role.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("角色不存在"); + } + return role; + } + + /** + * Run business method `typeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String typeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/AdminScopeHelper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/AdminScopeHelper.java new file mode 100644 index 00000000..e3f865af --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/AdminScopeHelper.java @@ -0,0 +1,192 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.support; + +import com.xiaowang.fingertipdesigner.core.common.BusinessException; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; + +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.RequestShopContext; +@Component +@RequiredArgsConstructor +/** + * Purpose: AdminScopeHelper supports AdminScopeHelper.java by holding or executing the admin scope helper business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AdminScopeHelper { + + /** + * Purpose: userService supports AdminScopeHelper.java by holding or executing the user service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserService userService; + /** + * Purpose: userShopBindingSupport supports AdminScopeHelper.java by holding or executing the user shop binding support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingSupport userShopBindingSupport; + + /** + * Purpose: getCurrentUser supports AdminScopeHelper.java by holding or executing the get current user business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public UserDO getCurrentUser(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + throw new RuntimeException("未获取到当前用户信息"); + } + + UserDO currentUser = userService.getById(userId); + if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + throw new RuntimeException("当前用户不存在或已失效"); + } + + Long currentShopId = RequestShopContext.getCurrentShopId(request); + currentUser.setShopId(currentShopId); + + return currentUser; + } + + /** + * Purpose: isPlatformAdmin supports AdminScopeHelper.java by holding or executing the is platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isPlatformAdmin(UserDO currentUser) { + return currentUser != null && Integer.valueOf(4).equals(currentUser.getType()); + } + + /** + * Purpose: isPlatformOverviewMode supports AdminScopeHelper.java by holding or executing the is platform overview mode business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isPlatformOverviewMode(UserDO currentUser) { + return isPlatformAdmin(currentUser) + && (currentUser.getShopId() == null || currentUser.getShopId() <= 0); + } + + /** + * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireShopContext(UserDO currentUser) { + requireShopContext(currentUser, "请先选择店铺后再管理店铺细节"); + } + + /** + * Purpose: requireShopContext supports AdminScopeHelper.java by holding or executing the require shop context business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireShopContext(UserDO currentUser, String message) { + if (isPlatformOverviewMode(currentUser)) { + throw new RuntimeException(message); + } + if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: getManagedShopId supports AdminScopeHelper.java by holding or executing the get managed shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getManagedShopId(UserDO currentUser) { + if (isPlatformAdmin(currentUser)) { + return null; + } + + if (currentUser == null || currentUser.getShopId() == null || currentUser.getShopId() <= 0) { + throw new RuntimeException("当前账号未绑定店铺,无法访问后台业务数据"); + } + + return currentUser.getShopId(); + } + + /** + * Purpose: resolveShopScope supports AdminScopeHelper.java by holding or executing the resolve shop scope business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long resolveShopScope(UserDO currentUser, Long requestedShopId) { + Long managedShopId = getManagedShopId(currentUser); + if (managedShopId != null) { + return managedShopId; + } + if (requestedShopId != null && requestedShopId > 0) { + return requestedShopId; + } + if (currentUser != null && currentUser.getShopId() != null && currentUser.getShopId() > 0) { + return currentUser.getShopId(); + } + return null; + } + + /** + * Purpose: ensureShopAccessible supports AdminScopeHelper.java by holding or executing the ensure shop accessible business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureShopAccessible(UserDO currentUser, Long targetShopId, String message) { + Long managedShopId = getManagedShopId(currentUser); + if (managedShopId != null && !managedShopId.equals(targetShopId)) { + throw new BusinessException(403, message); + } + } + + /** + * Purpose: ensureUserAccessibleInCurrentShop supports AdminScopeHelper.java by holding or executing the ensure user accessible in current shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureUserAccessibleInCurrentShop(UserDO currentUser, Long targetUserId, String message) { + if (currentUser == null || targetUserId == null) { + throw new RuntimeException(message); + } + if (isPlatformAdmin(currentUser)) { + return; + } + Long managedShopId = getManagedShopId(currentUser); + if (!userShopBindingSupport.isUserAccessibleInShop(targetUserId, managedShopId)) { + throw new BusinessException(403, message); + } + } + + /** + * Purpose: requirePlatformAdmin supports AdminScopeHelper.java by holding or executing the require platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requirePlatformAdmin(UserDO currentUser, String message) { + if (!isPlatformAdmin(currentUser)) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: ensureAssignableUserType supports AdminScopeHelper.java by holding or executing the ensure assignable user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureAssignableUserType(UserDO currentUser, Integer targetType) { + if (targetType == null) { + throw new RuntimeException("用户类型不能为空"); + } + + if (isPlatformAdmin(currentUser)) { + return; + } + + if (Integer.valueOf(2).equals(currentUser.getType())) { + if (Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType)) { + return; + } + throw new RuntimeException("店长只能创建或维护普通用户、美甲师"); + } + + if (Integer.valueOf(3).equals(currentUser.getType())) { + if (Integer.valueOf(0).equals(targetType)) { + return; + } + throw new RuntimeException("美甲师只能创建或维护普通用户"); + } + + throw new RuntimeException("当前角色无权维护后台用户"); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionCatalog.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionCatalog.java new file mode 100644 index 00000000..e4717eb9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionCatalog.java @@ -0,0 +1,313 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.support; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 权限目录是后台权限编码、中文展示文案和默认角色矩阵的唯一真源。 + */ +public final class PermissionCatalog { + + private static final Map DEFINITIONS = buildDefinitions(); + + private static final List ADMIN_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "dashboard:view", + "workbench:view", + "user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete", + "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", + "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", + "shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage", + "permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign", + "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", + "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", + "comment:view", "comment:delete", + "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", "message:delete", + "announcement:view", "announcement:create", "announcement:delete", + "messagehub:config:manage", + "security:audit:view", + "legal_agreement:manage", + "schedule:view", "schedule:edit", + "payment:view", "payment:manage", "refund:view", "refund:manage", + "after_sale:view", "after_sale:audit", + "inventory:view", "inventory:manage", + "campaign:view", "campaign:manage", + "growth:view", "analytics:view", "performance:view" + ); + + private static final List SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "dashboard:view", + "workbench:view", + "user:view", "user:create", "user:edit", "user:unbind", "user:reset_password", + "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", + "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", + "shop:view", "shop:edit", "shop:staff:manage", + "permission:view", "permission:assign", + "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", + "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", + "comment:view", "comment:delete", + "order:view", "order:process", "order:edit", "order:delete", "order:artist-change", + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", + "announcement:view", "announcement:create", + "schedule:view", "schedule:edit", + "payment:view", "refund:view", + "after_sale:view", "after_sale:audit", + "inventory:view", "inventory:manage", + "campaign:view", "campaign:manage", + "analytics:view", "performance:view" + ); + + private static final List NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of( + "home:view", + "workbench:view", + "user:view", + "user:balance:view", + "product:view", + "shop:view", + "tag:view", + "coupon:view", + "comment:view", + "order:view", "order:process", "order:artist-change", + "schedule:view", "after_sale:view", "performance:view" + ); + + private static final Set PLATFORM_OVERVIEW_PREFIXES = Set.of( + "user:", + "shop:", + "permission:", + "message:", + "announcement:" + ); + + private static final Set PLATFORM_OVERVIEW_PERMISSIONS = Set.of( + "messagehub:config:manage", + "security:audit:view", + "legal_agreement:manage" + ); + + private static final Set MANAGED_PERMISSION_CODES = buildManagedPermissionCodes(); + + private PermissionCatalog() { + } + + /** + * Purpose: getDefaultPermissionCodes supports PermissionCatalog.java by holding or executing the get default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static List getDefaultPermissionCodes(Integer userType) { + return switch (userType == null ? -1 : userType) { + case 4 -> ADMIN_DEFAULT_PERMISSION_CODES; + case 2 -> SHOP_MANAGER_DEFAULT_PERMISSION_CODES; + case 3 -> NAIL_ARTIST_DEFAULT_PERMISSION_CODES; + default -> List.of(); + }; + } + + /** + * Purpose: getDefaultPermissionCodeSet supports PermissionCatalog.java by holding or executing the get default permission code set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getDefaultPermissionCodeSet(Integer userType) { + return Set.copyOf(getDefaultPermissionCodes(userType)); + } + + /** + * Purpose: getManagedPermissionCodes supports PermissionCatalog.java by holding or executing the get managed permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getManagedPermissionCodes() { + return MANAGED_PERMISSION_CODES; + } + + /** + * Purpose: getManagedDefinitions supports PermissionCatalog.java by holding or executing the get managed definitions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Collection getManagedDefinitions() { + return MANAGED_PERMISSION_CODES.stream() + .map(PermissionCatalog::getRequiredDefinition) + .toList(); + } + + /** + * Purpose: getDefinitionsByCode supports PermissionCatalog.java by holding or executing the get definitions by code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Map getDefinitionsByCode() { + return DEFINITIONS; + } + + /** + * Purpose: getRequiredDefinition supports PermissionCatalog.java by holding or executing the get required definition business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static PermissionDefinition getRequiredDefinition(String permissionCode) { + PermissionDefinition definition = DEFINITIONS.get(permissionCode); + if (definition == null) { + throw new IllegalArgumentException("Unknown permission code: " + permissionCode); + } + return definition; + } + + /** + * Purpose: isAllowedForPlatformOverview supports PermissionCatalog.java by holding or executing the is allowed for platform overview business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean isAllowedForPlatformOverview(String permissionCode) { + if (permissionCode == null || permissionCode.isBlank()) { + return true; + } + if ("dashboard:view".equals(permissionCode) || permissionCode.endsWith(":view")) { + return true; + } + if (PLATFORM_OVERVIEW_PERMISSIONS.contains(permissionCode)) { + return true; + } + return PLATFORM_OVERVIEW_PREFIXES.stream().anyMatch(permissionCode::startsWith); + } + + /** + * Purpose: canManageUserType supports PermissionCatalog.java by holding or executing the can manage user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean canManageUserType(Integer operatorType, Integer targetType) { + if (operatorType == null || targetType == null) { + return false; + } + + return switch (operatorType) { + case 4 -> true; + case 2 -> Integer.valueOf(0).equals(targetType) || Integer.valueOf(3).equals(targetType); + case 3 -> Integer.valueOf(0).equals(targetType); + default -> false; + }; + } + + /** + * Purpose: buildManagedPermissionCodes supports PermissionCatalog.java by holding or executing the build managed permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Set buildManagedPermissionCodes() { + LinkedHashSet permissionCodes = new LinkedHashSet<>(); + permissionCodes.addAll(ADMIN_DEFAULT_PERMISSION_CODES); + permissionCodes.addAll(SHOP_MANAGER_DEFAULT_PERMISSION_CODES); + permissionCodes.addAll(NAIL_ARTIST_DEFAULT_PERMISSION_CODES); + return Set.copyOf(permissionCodes); + } + + /** + * Purpose: buildDefinitions supports PermissionCatalog.java by holding or executing the build definitions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Map buildDefinitions() { + LinkedHashMap definitions = new LinkedHashMap<>(); + put(definitions, "home:view", "查看首页", "首页", "查看系统首页入口与概览"); + put(definitions, "dashboard:view", "查看仪表盘", "仪表盘", "查看后台仪表盘统计"); + put(definitions, "user:view", "查看用户", "用户管理", "查看用户列表与详情"); + put(definitions, "user:create", "新增用户", "用户管理", "创建用户账号"); + put(definitions, "user:edit", "编辑用户", "用户管理", "修改用户基础信息"); + put(definitions, "user:disable", "启停用户", "用户管理", "启用或禁用用户账号"); + put(definitions, "user:unbind", "解绑用户", "用户管理", "解绑用户与当前店铺的关系"); + put(definitions, "user:reset_password", "重置密码", "用户管理", "重置用户密码"); + put(definitions, "user:delete", "删除用户", "用户管理", "删除用户账号"); + put(definitions, "user:balance:view", "查看余额资产", "用户资产", "查看用户余额、累计充值与流水"); + put(definitions, "user:balance:manage", "调整余额", "用户资产", "充值、手工加减余额与关联订单"); + put(definitions, "user:vip:manage", "管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级"); + put(definitions, "role:view", "查看店铺角色", "角色管理", "查看店铺自定义角色"); + put(definitions, "role:create", "新增店铺角色", "角色管理", "创建店铺自定义角色"); + put(definitions, "role:edit", "编辑店铺角色", "角色管理", "编辑角色权限和绑定员工"); + put(definitions, "role:delete", "删除店铺角色", "角色管理", "删除店铺自定义角色"); + put(definitions, "user:relation:view", "查看用户所属", "用户管理", "查看用户归属关系"); + put(definitions, "user:relation:edit", "编辑用户所属", "用户管理", "调整用户店铺和直属上级"); + put(definitions, "product:view", "查看商品", "商品管理", "查看商品列表与详情"); + put(definitions, "product:create", "新增商品", "商品管理", "创建商品"); + put(definitions, "product:edit", "编辑商品", "商品管理", "编辑商品信息"); + put(definitions, "product:delete", "删除商品", "商品管理", "删除商品"); + put(definitions, "product:category:manage", "管理商品分类", "商品管理", "维护商品分类与归类信息"); + put(definitions, "shop:view", "查看店铺", "店铺管理", "查看店铺列表与详情"); + put(definitions, "shop:create", "新增店铺", "店铺管理", "创建店铺"); + put(definitions, "shop:edit", "编辑店铺", "店铺管理", "编辑店铺信息"); + put(definitions, "shop:delete", "删除店铺", "店铺管理", "删除店铺"); + put(definitions, "shop:staff:manage", "管理员工", "店铺管理", "管理店铺员工与归属"); + put(definitions, "permission:view", "查看权限", "权限管理", "查看权限清单"); + put(definitions, "permission:create", "新增权限", "权限管理", "新增系统权限定义"); + put(definitions, "permission:edit", "编辑权限", "权限管理", "编辑系统权限定义"); + put(definitions, "permission:delete", "删除权限", "权限管理", "删除系统权限定义"); + put(definitions, "permission:assign", "分配权限", "权限管理", "给用户分配后台权限"); + put(definitions, "tag:view", "查看标签", "标签管理", "查看标签列表与详情"); + put(definitions, "tag:create", "新增标签", "标签管理", "创建标签"); + put(definitions, "tag:edit", "编辑标签", "标签管理", "编辑标签"); + put(definitions, "tag:delete", "删除标签", "标签管理", "删除标签"); + put(definitions, "tag:assign", "分配标签", "标签管理", "给商品或优惠券分配标签"); + put(definitions, "coupon:view", "查看优惠券", "优惠券管理", "查看优惠券与发放情况"); + put(definitions, "coupon:create", "新增优惠券", "优惠券管理", "创建优惠券模板"); + put(definitions, "coupon:edit", "编辑优惠券", "优惠券管理", "编辑优惠券模板"); + put(definitions, "coupon:delete", "删除优惠券", "优惠券管理", "删除优惠券模板"); + put(definitions, "coupon:assign", "发放优惠券", "优惠券管理", "向用户发放普通优惠券"); + put(definitions, "comment:view", "查看评论", "评论管理", "查看作品评论与回复"); + put(definitions, "comment:delete", "删除评论", "评论管理", "删除不合规作品评论"); + put(definitions, "order:view", "查看订单", "订单管理", "查看订单列表与详情"); + put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单"); + put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限"); + put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限"); + put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请"); + put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口"); + put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息"); + put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知"); + put(definitions, "message:create", "发布消息", "消息管理", "发布站内消息"); + put(definitions, "message:delete", "撤回消息", "消息管理", "撤回已发布站内消息"); + put(definitions, "announcement:view", "查看公告", "公告管理", "查看公告列表与详情"); + put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告"); + put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告"); + put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数"); + put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志"); + put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本"); + put(definitions, "schedule:view", "查看排班", "排班管理", "查看美甲师排班和可约时段"); + put(definitions, "schedule:edit", "编辑排班", "排班管理", "维护美甲师班次、休息日和预约容量"); + put(definitions, "payment:view", "查看支付", "支付退款", "查看订单支付状态和支付单"); + put(definitions, "payment:manage", "确认支付", "支付退款", "手工确认支付或处理支付异常"); + put(definitions, "refund:view", "查看退款", "支付退款", "查看退款申请和退款单"); + put(definitions, "refund:manage", "处理退款", "支付退款", "手工确认退款或处理退款异常"); + put(definitions, "after_sale:view", "查看售后", "售后管理", "查看订单售后和客户反馈"); + put(definitions, "after_sale:audit", "处理售后", "售后管理", "审批或驳回售后申请"); + put(definitions, "inventory:view", "查看库存", "库存管理", "查看门店耗材库存和预警"); + put(definitions, "inventory:manage", "调整库存", "库存管理", "维护耗材、入库和库存调整"); + put(definitions, "campaign:view", "查看活动", "活动管理", "查看营销活动和推荐位"); + put(definitions, "campaign:manage", "管理活动", "活动管理", "创建、编辑和发布营销活动"); + put(definitions, "growth:view", "查看成长", "用户成长", "查看用户成长值和会员权益进度"); + put(definitions, "analytics:view", "查看经营分析", "经营分析", "查看订单漏斗和经营指标"); + put(definitions, "performance:view", "查看绩效", "绩效统计", "查看门店和美甲师服务绩效"); + put(definitions, "workbench:view", "查看工作台", "门店工作台", "查看今日订单、售后待办、排班和绩效摘要"); + return Map.copyOf(definitions); + } + + /** + * Purpose: put supports PermissionCatalog.java by holding or executing the put business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static void put(Map definitions, String code, String name, String group, String description) { + definitions.put(code, new PermissionDefinition(code, name, group, description)); + } + + /** + * Purpose: PermissionDefinition supports PermissionCatalog.java by holding or executing the permission definition business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record PermissionDefinition( + String permissionCode, + String permissionName, + String permissionGroup, + String description + ) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionPolicy.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionPolicy.java new file mode 100644 index 00000000..23b1a6eb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/PermissionPolicy.java @@ -0,0 +1,45 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.support; + +import java.util.List; +import java.util.Set; + +/** + * 后台角色默认权限与可分配策略。 + */ +public final class PermissionPolicy { + + private PermissionPolicy() { + } + + /** + * Purpose: getDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static List getDefaultPermissionCodes(Integer userType) { + return PermissionCatalog.getDefaultPermissionCodes(userType); + } + + /** + * Purpose: getDefaultPermissionCodeSet supports PermissionPolicy.java by holding or executing the get default permission code set business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getDefaultPermissionCodeSet(Integer userType) { + return PermissionCatalog.getDefaultPermissionCodeSet(userType); + } + + /** + * Purpose: getManagedDefaultPermissionCodes supports PermissionPolicy.java by holding or executing the get managed default permission codes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Set getManagedDefaultPermissionCodes() { + return PermissionCatalog.getManagedPermissionCodes(); + } + + /** + * Purpose: canManageUserType supports PermissionPolicy.java by holding or executing the can manage user type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static boolean canManageUserType(Integer operatorType, Integer targetType) { + return PermissionCatalog.canManageUserType(operatorType, targetType); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditActions.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditActions.java new file mode 100644 index 00000000..1ffaacb8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditActions.java @@ -0,0 +1,113 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.support; + +/** + * Purpose: SecurityAuditActions supports SecurityAuditActions.java by holding or executing the security audit actions business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class SecurityAuditActions { + + /** + * Purpose: SUCCESS supports SecurityAuditActions.java by holding or executing the success business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SUCCESS = "SUCCESS"; + /** + * Purpose: FAIL supports SecurityAuditActions.java by holding or executing the fail business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String FAIL = "FAIL"; + + /** + * Purpose: ORDER_PROCESS supports SecurityAuditActions.java by holding or executing the order process business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ORDER_PROCESS = "ORDER_PROCESS"; + /** + * Purpose: ARTIST_CHANGE_APPROVE supports SecurityAuditActions.java by holding or executing the artist change approve business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ARTIST_CHANGE_APPROVE = "ARTIST_CHANGE_APPROVE"; + /** + * Purpose: ARTIST_CHANGE_REJECT supports SecurityAuditActions.java by holding or executing the artist change reject business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ARTIST_CHANGE_REJECT = "ARTIST_CHANGE_REJECT"; + /** + * Purpose: SHOP_DELETE_BLOCKED supports SecurityAuditActions.java by holding or executing the shop delete blocked business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SHOP_DELETE_BLOCKED = "SHOP_DELETE_BLOCKED"; + /** + * Purpose: SHOP_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the shop status update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String SHOP_STATUS_UPDATE = "SHOP_STATUS_UPDATE"; + /** + * Purpose: PERMISSION_CREATE supports SecurityAuditActions.java by holding or executing the permission create business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_CREATE = "PERMISSION_CREATE"; + /** + * Purpose: PERMISSION_UPDATE supports SecurityAuditActions.java by holding or executing the permission update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_UPDATE = "PERMISSION_UPDATE"; + /** + * Purpose: PERMISSION_DELETE supports SecurityAuditActions.java by holding or executing the permission delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_DELETE = "PERMISSION_DELETE"; + /** + * Purpose: PERMISSION_ASSIGN supports SecurityAuditActions.java by holding or executing the permission assign business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PERMISSION_ASSIGN = "PERMISSION_ASSIGN"; + /** + * Purpose: USER_STATUS_UPDATE supports SecurityAuditActions.java by holding or executing the user status update business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_STATUS_UPDATE = "USER_STATUS_UPDATE"; + /** + * Purpose: USER_RESET_PASSWORD supports SecurityAuditActions.java by holding or executing the user reset password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_RESET_PASSWORD = "USER_RESET_PASSWORD"; + /** + * Purpose: USER_DELETE supports SecurityAuditActions.java by holding or executing the user delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_DELETE = "USER_DELETE"; + /** + * Purpose: USER_UNBIND supports SecurityAuditActions.java by holding or executing the user unbind business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_UNBIND = "USER_UNBIND"; + /** + * Purpose: USER_BALANCE_CHANGE supports SecurityAuditActions.java by holding or executing the user balance change business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_BALANCE_CHANGE = "USER_BALANCE_CHANGE"; + /** + * Purpose: USER_VIP_OVERRIDE supports SecurityAuditActions.java by holding or executing the user vip override business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_VIP_OVERRIDE = "USER_VIP_OVERRIDE"; + /** + * Purpose: USER_VIP_RECALCULATE supports SecurityAuditActions.java by holding or executing the user vip recalculate business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_VIP_RECALCULATE = "USER_VIP_RECALCULATE"; + public static final String SCHEDULE_UPDATE = "SCHEDULE_UPDATE"; + public static final String PAYMENT_MANUAL_CONFIRM = "PAYMENT_MANUAL_CONFIRM"; + public static final String REFUND_MANUAL_CONFIRM = "REFUND_MANUAL_CONFIRM"; + public static final String AFTER_SALE_CREATE = "AFTER_SALE_CREATE"; + public static final String AFTER_SALE_APPROVE = "AFTER_SALE_APPROVE"; + public static final String AFTER_SALE_REJECT = "AFTER_SALE_REJECT"; + public static final String INVENTORY_ADJUST = "INVENTORY_ADJUST"; + public static final String CAMPAIGN_PUBLISH = "CAMPAIGN_PUBLISH"; + public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; + public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; + + private SecurityAuditActions() { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditSupport.java new file mode 100644 index 00000000..325b13f7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/support/SecurityAuditSupport.java @@ -0,0 +1,75 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.support; + +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Component +@RequiredArgsConstructor +/** + * Purpose: SecurityAuditSupport supports SecurityAuditSupport.java by holding or executing the security audit support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditSupport { + + /** + * Purpose: securityAuditLogService supports SecurityAuditSupport.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + /** + * Purpose: success supports SecurityAuditSupport.java by holding or executing the success business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void success(HttpServletRequest request, String action, String reason) { + record(request, action, SecurityAuditActions.SUCCESS, reason); + } + + /** + * Purpose: fail supports SecurityAuditSupport.java by holding or executing the fail business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void fail(HttpServletRequest request, String action, String reason) { + record(request, action, SecurityAuditActions.FAIL, reason); + } + + /** + * Purpose: record supports SecurityAuditSupport.java by holding or executing the record business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void record(HttpServletRequest request, String action, String result, String reason) { + try { + Long userId = request == null ? null : asLong(request.getAttribute("userId")); + String account = request == null ? null : asString(request.getAttribute("account")); + securityAuditLogService.record(userId, account, action, result, reason, request); + } catch (Exception ignored) { + // Audit failure must never block the guarded business operation. + } + } + + /** + * Purpose: asLong supports SecurityAuditSupport.java by holding or executing the as long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long asLong(Object value) { + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Number) { + return ((Number) value).longValue(); + } + return null; + } + + /** + * Purpose: asString supports SecurityAuditSupport.java by holding or executing the as string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String asString(Object value) { + return value == null ? null : String.valueOf(value); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/PermissionVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/PermissionVO.java new file mode 100644 index 00000000..f4e4ed86 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/PermissionVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 系统权限表 VO + * 用于前端展示权限信息 + * + * @author xiaowang + * @date 2026-02-25 + */ +@Data +public class PermissionVO { + + /** + * 权限唯一主键ID + */ + private Long id; + + /** + * 权限编码(唯一标识) + */ + private String permissionCode; + + /** + * 权限名称 + */ + private String permissionName; + + /** + * 权限分组(商品管理、用户管理等) + */ + private String permissionGroup; + + /** + * 权限描述 + */ + private String description; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/SecurityAuditLogVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/SecurityAuditLogVO.java new file mode 100644 index 00000000..adc6b1b0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/SecurityAuditLogVO.java @@ -0,0 +1,60 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Data +/** + * Purpose: SecurityAuditLogVO supports SecurityAuditLogVO.java by holding or executing the security audit log vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SecurityAuditLogVO { + + /** + * Purpose: id supports SecurityAuditLogVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: userId supports SecurityAuditLogVO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: account supports SecurityAuditLogVO.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + /** + * Purpose: action supports SecurityAuditLogVO.java by holding or executing the action business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String action; + /** + * Purpose: result supports SecurityAuditLogVO.java by holding or executing the result business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String result; + /** + * Purpose: reason supports SecurityAuditLogVO.java by holding or executing the reason business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String reason; + /** + * Purpose: ipAddress supports SecurityAuditLogVO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + /** + * Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + /** + * Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime operateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/ShopRoleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/ShopRoleVO.java new file mode 100644 index 00000000..2e1057b7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/security/vo/ShopRoleVO.java @@ -0,0 +1,75 @@ +package com.xiaowang.fingertipdesigner.core.modules.security.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * ShopRoleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + /** + * Field `creatorName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String creatorName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `permissionCodes` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionCodes; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/admin/AdminShopController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/admin/AdminShopController.java new file mode 100644 index 00000000..939cf993 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/admin/AdminShopController.java @@ -0,0 +1,195 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/admin/shops") +@RequiredArgsConstructor +/** + * AdminShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminShopController { + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopService shopService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: securityAuditSupport supports AdminShopController.java by holding or executing the security audit support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping("/list") + @RequirePermission("shop:view") + public Result> listShops( + HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO result = shopService.pageShops(page, size, keyword, shopId); + return Result.success(result); + } + + @PostMapping("/create") + @RequirePermission("shop:create") + @OperationGuard(action = "admin-shop-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); + Long id = shopService.createShop(shopDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ShopVO shopVO = shopService.getShopById(id); + if (shopVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); + } + boolean success = shopService.updateShop(id, shopDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("shop:delete") + @OperationGuard(action = "admin-shop-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); + try { + boolean success = shopService.deleteShop(id); + securityAuditSupport.success(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/status/{id}") + @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param statusRequest parameter `statusRequest` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); + try { + boolean success = shopService.updateShopStatus(id, statusRequest.getStatus()); + securityAuditSupport.success(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus()); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus() + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/list/all") + @RequirePermission("shop:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllShops(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List shops; + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + shops = shopService.listAllShopsForAdmin(); + } else { + ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser)); + shops = currentShop == null ? List.of() : List.of(currentShop); + } + return Result.success(shops); + } + + @GetMapping("/{id}") + @RequirePermission("shop:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShop(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.ensureShopAccessible(currentUser, id, "无权查看其他店铺信息"); + ShopVO shop = shopService.getShopById(id); + return Result.success(shop); + } + + @Data + /** + * Purpose: StatusRequest supports AdminShopController.java by holding or executing the status request business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class StatusRequest { + /** + * Purpose: status supports AdminShopController.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ContactInfoController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ContactInfoController.java new file mode 100644 index 00000000..e26c3a09 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ContactInfoController.java @@ -0,0 +1,70 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ContactInfoService; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/contact-info", "/api/contact-info"}) +/** + * ContactInfoController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoController { + /** + * Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ContactInfoService contactInfoService; + + @GetMapping("/shop/{shopId}/manager") + /** + * Run business method `shopManager`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result shopManager(HttpServletRequest request, @PathVariable Long shopId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); + } + + @GetMapping("/product/{productId}/artist/{artistId}") + /** + * Run business method `productArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); + } + + @GetMapping("/order/{orderId}/artist") + /** + * Purpose: orderArtist supports ContactInfoController.java by holding or executing the order artist business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); + } + + @GetMapping("/platform") + /** + * Run business method `platform`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result result consumed by the caller or returned to the frontend + */ + public Result platform() { + return Result.success(contactInfoService.getPlatformContact()); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ShopController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ShopController.java new file mode 100644 index 00000000..bee981e0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/controller/front/ShopController.java @@ -0,0 +1,211 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/shop") +@RequiredArgsConstructor +/** + * ShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ShopController { + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopService shopService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/create") + @RequirePermission("shop:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); + Long id = shopService.createShop(shopDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ShopVO shopVO = shopService.getShopById(id); + if (shopVO == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); + } + boolean success = shopService.updateShop(id, shopDTO); + return Result.success(success); + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("shop:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); + boolean success = shopService.deleteShop(id); + return Result.success(success); + } + + @PutMapping("/status/{id}") + @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param statusRequest parameter `statusRequest` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); + boolean success = shopService.updateShopStatus(id, statusRequest.getStatus()); + return Result.success(success); + } + + @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShopById(@PathVariable Long id) { + ShopVO shopVO = shopService.getShopById(id); + return Result.success(shopVO); + } + + @GetMapping("/trust-profile/{id}") + /** + * Purpose: getShopTrustProfile returns public confidence signals for a shop detail page. + * Usage: anonymous clients can call this endpoint; phone data remains behind contact-info APIs. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getShopTrustProfile(@PathVariable Long id) { + return Result.success(shopService.getShopTrustProfile(id)); + } + + @GetMapping("/list/all") + @RequirePermission("shop:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAllShops(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List shopVOs; + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + shopVOs = shopService.listAllShopsForAdmin(); + } else { + ShopVO currentShop = shopService.getShopById(adminScopeHelper.getManagedShopId(currentUser)); + shopVOs = currentShop == null ? List.of() : List.of(currentShop); + } + return Result.success(shopVOs); + } + + @GetMapping("/list/shopName/{shopName}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listShopsByShopName(@PathVariable String shopName) { + List shopVOs = shopService.listShopsByShopName(shopName); + return Result.success(shopVOs); + } + + @GetMapping("/list/simple") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listShopsSimple() { + List shopVOs = shopService.listAllShops(); + List simpleVOs = shopVOs.stream() + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + return Result.success(simpleVOs); + } + + @GetMapping("/list") + /** + * Purpose: listPublicShopsCompat keeps the legacy /shop/list public catalog URL usable for anonymous clients. + * Usage: call from old Web or mini-program builds that still request /api/shop/list; new code may prefer /shop/list/public. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listPublicShopsCompat() { + return Result.success(shopService.listAllShops()); + } + + @GetMapping("/list/public") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listPublicShops() { + return Result.success(shopService.listAllShops()); + } + + @Data + /** + * Purpose: StatusRequest supports ShopController.java by holding or executing the status request business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class StatusRequest { + /** + * Purpose: status supports ShopController.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/dto/ShopDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/dto/ShopDTO.java new file mode 100644 index 00000000..ca8962dc --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/dto/ShopDTO.java @@ -0,0 +1,124 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.dto; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +/** + * 店铺信息表 DTO + * 用于店铺信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ShopDTO { + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 店铺描述 + */ + private String description; + + /** + * 店铺地址 + */ + private String address; + + /** + * Purpose: mapProvider supports ShopDTO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + /** + * Purpose: longitude supports ShopDTO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + /** + * Purpose: latitude supports ShopDTO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * 店铺营业时间 + */ + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + private String coverImageFileId; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * Purpose: themePrimaryColor supports ShopDTO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + /** + * Purpose: themeSecondaryColor supports ShopDTO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + /** + * Purpose: themeAccentColor supports ShopDTO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + /** + * Purpose: themePageBgColor supports ShopDTO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + /** + * Purpose: themeCardBgColor supports ShopDTO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + /** + * Purpose: themeBackgroundImageFileId supports ShopDTO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + private Integer status; + + /** + * Purpose: authorizationStartDate supports ShopDTO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + /** + * Purpose: authorizationDays supports ShopDTO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/ShopDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/ShopDO.java new file mode 100644 index 00000000..33611d8f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/ShopDO.java @@ -0,0 +1,165 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 店铺信息表 DO + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("t_shop") +public class ShopDO extends BaseEntity { + + /** + * 店铺唯一主键ID(雪花ID) + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 店铺名称 + */ + @TableField("shop_name") + private String shopName; + + /** + * 店铺描述 + */ + @TableField("description") + private String description; + + /** + * 店铺地址 + */ + @TableField("address") + private String address; + + @TableField("map_provider") + /** + * Purpose: mapProvider supports ShopDO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + @TableField("longitude") + /** + * Purpose: longitude supports ShopDO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + @TableField("latitude") + /** + * Purpose: latitude supports ShopDO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * 店铺营业时间 + */ + @TableField("business_hours") + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + @TableField("cover_image_file_id") + private String coverImageFileId; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + @TableField("image_file_ids") + private String imageFileIds; + + @TableField("theme_primary_color") + /** + * Purpose: themePrimaryColor supports ShopDO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + @TableField("theme_secondary_color") + /** + * Purpose: themeSecondaryColor supports ShopDO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + @TableField("theme_accent_color") + /** + * Purpose: themeAccentColor supports ShopDO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + @TableField("theme_page_bg_color") + /** + * Purpose: themePageBgColor supports ShopDO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + @TableField("theme_card_bg_color") + /** + * Purpose: themeCardBgColor supports ShopDO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + @TableField("theme_background_image_file_id") + /** + * Purpose: themeBackgroundImageFileId supports ShopDO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + @TableField("status") + private Integer status; + + @TableField("authorization_start_date") + /** + * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + @TableField("authorization_days") + /** + * Purpose: authorizationDays supports ShopDO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + @TableField("authorization_expire_time") + private LocalDateTime authorizationExpireTime; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/UserShopBindingDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/UserShopBindingDO.java new file mode 100644 index 00000000..050f1a60 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/entity/UserShopBindingDO.java @@ -0,0 +1,50 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 用户与店铺绑定关系。 + */ +@Getter +@Setter +@TableName("t_user_shop_binding") +public class UserShopBindingDO extends BaseEntity { + + @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + /** + * 绑定状态:1-正常,0-禁用。 + */ + @TableField("status") + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/ShopMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/ShopMapper.java new file mode 100644 index 00000000..f33811a8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/ShopMapper.java @@ -0,0 +1,19 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +/** + * 店铺信息表 Mapper + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ShopMapper extends BaseMapper { + + @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") + Long countPublicImageReference(@Param("fileId") Long fileId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/UserShopBindingMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/UserShopBindingMapper.java new file mode 100644 index 00000000..3717f524 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/mapper/UserShopBindingMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; + +/** + * UserShopBindingMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserShopBindingMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ContactInfoService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ContactInfoService.java new file mode 100644 index 00000000..a8df5396 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ContactInfoService.java @@ -0,0 +1,42 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.service; + +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ContactInfoVO; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * ContactInfoService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ContactInfoService { + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getShopManagerContact(Long userId, Long shopId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getPlatformContact(); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ShopService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ShopService.java new file mode 100644 index 00000000..3e420448 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/ShopService.java @@ -0,0 +1,113 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; + +import java.util.List; + +/** + * 店铺信息表 Service + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface ShopService extends IService { + + /** + * 创建店铺 + * + * @param shopDTO 店铺DTO + * @return 店铺ID + */ + Long createShop(ShopDTO shopDTO); + + /** + * 更新店铺 + * + * @param id 店铺ID + * @param shopDTO 店铺DTO + * @return 是否更新成功 + */ + boolean updateShop(Long id, ShopDTO shopDTO); + + /** + * 删除店铺 + * + * @param id 店铺ID + * @return 是否删除成功 + */ + boolean deleteShop(Long id); + + /** + * 根据ID查询店铺 + * + * @param id 店铺ID + * @return 店铺VO + */ + ShopVO getShopById(Long id); + + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals. + * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. + * + * @param id shop id to inspect + * @return public trust profile or null when the shop cannot be viewed + */ + ShopTrustProfileVO getShopTrustProfile(Long id); + + /** + * 查询所有店铺 + * + * @return 店铺VO列表 + */ + List listAllShops(); + + /** + * 查询后台全部店铺(含停用,不含删除) + * + * @return 店铺列表 + */ + List listAllShopsForAdmin(); + + /** + * 根据店铺名称查询店铺 + * + * @param shopName 店铺名称 + * @return 店铺VO列表 + */ + List listShopsByShopName(String shopName); + + /** + * 分页查询店铺 + * + * @param page 页码 + * @param size 每页大小 + * @param keyword 搜索关键词 + * @return 分页结果 + */ + PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId); + + /** + * 更新店铺状态 + * + * @param id 店铺ID + * @param status 状态:1-启用,0-停用 + * @return 是否成功 + */ + boolean updateShopStatus(Long id, Integer status); + + /** + * 店铺是否已超过授权有效期。 + */ + boolean isAuthorizationExpired(Long shopId); + + /** + * 前台可用:未删除、启用、且授权未到期。 + */ + boolean isFrontendAvailable(Long shopId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ContactInfoServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ContactInfoServiceImpl.java new file mode 100644 index 00000000..6a032536 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ContactInfoServiceImpl.java @@ -0,0 +1,217 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderItemDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ContactInfoService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.xiaowang.fingertipdesigner.core.common.Result; +@Service +@RequiredArgsConstructor +/** + * ContactInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoServiceImpl implements ContactInfoService { + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderItemMapper orderItemMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `objectStorageUrlSupport`: converts stored QR image URLs into frontend-safe signed URLs. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getShopManagerContact(Long userId, Long shopId) { + if (shopId == null || shopId <= 0) throw new RuntimeException("店铺ID不能为空"); + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureUserCanSeeShop(userId, shopId); + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 2) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param manager parameter `manager` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(manager, "店长"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId) { + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) throw new RuntimeException("作品不存在"); + if (artistId == null || artistId <= 0) throw new RuntimeException("请选择美甲师"); + ensureArtistAllowed(product.getBookableArtists(), artistId); + return toContact(userMapper.selectById(artistId), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || !userId.equals(order.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在或无权查看"); + } + OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getOrderId, orderId) + .eq(OrderItemDO::getIsDelete, 0) + .eq(artistId != null && artistId > 0, OrderItemDO::getArtistId, artistId) + .isNotNull(OrderItemDO::getArtistId) + .last("LIMIT 1")) + .stream() + .findFirst() + .orElseThrow(() -> new RuntimeException("订单暂无可联系美甲师")); + return toContact(userMapper.selectById(item.getArtistId()), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getPlatformContact() { + UserDO admin = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 4) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .isNotNull(UserDO::getPhone) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param admin parameter `admin` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(admin, "平台客服"); + } + + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureUserCanSeeShop(Long userId, Long shopId) { + if (userId == null) return; + UserDO user = userMapper.selectById(userId); + if (user != null && shopId.equals(user.getShopId())) return; + if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { + // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 + } + } + + /** + * Run business method `ensureArtistAllowed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureArtistAllowed(String rawBookableArtists, Long artistId) { + if (!StringUtils.hasText(rawBookableArtists)) return; + boolean allowed = java.util.Arrays.stream(rawBookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .anyMatch(id -> id.equals(String.valueOf(artistId))); + if (!allowed) throw new RuntimeException("该美甲师不可预约当前作品"); + } + + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param roleLabel parameter `roleLabel` supplied by the caller + * @return private ContactInfoVO result consumed by the caller or returned to the frontend + */ + private ContactInfoVO toContact(UserDO user, String roleLabel) { + ContactInfoVO vo = new ContactInfoVO(); + vo.setPlatformContactAvailable(false); + vo.setPlatformContactText("平台联系暂未接入"); + vo.setRoleLabel(roleLabel); + if (user == null) { + vo.setContactName(roleLabel); + vo.setPhoneAvailable(false); + return vo; + } + vo.setContactUserId(user.getId()); + vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); + vo.setPhone(contactPhone); + vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); + vo.setWechatId(user.getWechatId()); + vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); + vo.setWechatQrCode(StringUtils.hasText(user.getWechatQrCode()) + ? objectStorageUrlSupport.toAccessibleUrl(user.getWechatQrCode()) + : null); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ShopServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ShopServiceImpl.java new file mode 100644 index 00000000..5162afec --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/service/impl/ShopServiceImpl.java @@ -0,0 +1,900 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.ShopDTO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.CouponDO; +import com.xiaowang.fingertipdesigner.core.modules.content.entity.CommentDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.ProductDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.product.entity.TagDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.UserCouponDO; +import com.xiaowang.fingertipdesigner.core.modules.content.mapper.CommentMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.ProductMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.product.mapper.TagMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.CouponService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.MapService; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.ShopThemeSupport; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.support.cache.MultiLevelCacheService; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopTrustProfileVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 店铺信息表 Service 实现 + * 对应数据库表 t_shop + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class ShopServiceImpl extends ServiceImpl implements ShopService { + /** + * Purpose: SHOP_DETAIL_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop detail cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:"; + /** + * Purpose: SHOP_LIST_CACHE_PREFIX supports ShopServiceImpl.java by holding or executing the shop list cache prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:"; + /** + * Purpose: SHOP_DELETE_DISABLED_MESSAGE supports ShopServiceImpl.java by holding or executing the shop delete disabled message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SHOP_DELETE_DISABLED_MESSAGE = "店铺删除已停用,请使用停用封存"; + /** + * Purpose: DISABLED_SHOP_ARCHIVED_MESSAGE supports ShopServiceImpl.java by holding or executing the disabled shop archived message business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DISABLED_SHOP_ARCHIVED_MESSAGE = "停用店铺已封存,仅允许重新启用"; + private static final Set FEATURED_PRODUCT_TAG_NAMES = Set.of("特色作品", "热门"); + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponService couponService; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CouponMapper couponMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TagMapper tagMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final CommentMapper commentMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserCouponMapper userCouponMapper; + /** + * Variable `orderArtistReviewMapper`: Spring-injected collaborator used by this class to aggregate public shop review trust signals. + */ + private final OrderArtistReviewMapper orderArtistReviewMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to resolve public image URLs for trust cards. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageUrlSupport`: converts stored object URLs into frontend-accessible signed URLs. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + private final NailArtistInfoService nailArtistInfoService; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AppCacheProperties appCacheProperties; + /** + * Purpose: mapService supports ShopServiceImpl.java by holding or executing the map service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final MapService mapService; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createShop(ShopDTO shopDTO) { + ShopDO shopDO = new ShopDO(); + shopDO.setShopName(shopDTO.getShopName()); + shopDO.setDescription(shopDTO.getDescription()); + shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); + shopDO.setBusinessHours(shopDTO.getBusinessHours()); + shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); + shopDO.setImageFileIds(shopDTO.getImageFileIds()); + applyTheme(shopDO, shopDTO); + applyAuthorization(shopDO, shopDTO); + shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); + shopDO.setIsDelete(0); + shopMapper.insert(shopDO); + couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); + evictShopCaches(shopDO.getId()); + return shopDO.getId(); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateShop(Long id, ShopDTO shopDTO) { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null) { + return false; + } + if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { + throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); + } + shopDO.setShopName(shopDTO.getShopName()); + shopDO.setDescription(shopDTO.getDescription()); + shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); + shopDO.setBusinessHours(shopDTO.getBusinessHours()); + shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); + shopDO.setImageFileIds(shopDTO.getImageFileIds()); + applyTheme(shopDO, shopDTO); + applyAuthorization(shopDO, shopDTO); + if (shopDTO.getStatus() != null) { + shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); + } + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictShopCaches(id); + } + return updated; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteShop(Long id) { + throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateShopStatus(Long id, Integer status) { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { + return false; + } + shopDO.setStatus(normalizeStatus(status)); + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + evictShopCaches(id); + } + return updated; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ShopVO result consumed by the caller or returned to the frontend + */ + public ShopVO getShopById(Long id) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(shopDO); + } + ); + } + + @Override + /** + * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. + * Usage: pass a valid shop id; the returned profile never exposes contact phone data. + */ + public ShopTrustProfileVO getShopTrustProfile(Long id) { + if (id == null || id <= 0) { + return null; + } + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + return null; + } + + long productCount = countActiveProducts(id); + long artistCount = countShopArtists(id); + List featuredProducts = listFeaturedProducts(id); + List recentReviews = listSubmittedReviews(id, 3); + BigDecimal averageRating = calculateAverageRating(id); + long reviewCount = countSubmittedReviews(id); + + Set fileIds = new LinkedHashSet<>(); + fileIds.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + fileIds.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + featuredProducts.forEach(product -> fileIds.addAll(parseLongIds(product.getImageFileIds(), ","))); + recentReviews.forEach(review -> fileIds.addAll(parseLongIds(review.getImageFileIds(), ","))); + Map fileMap = objectStorageFileService.getObjectStorageFileMapByIds(fileIds); + + ShopTrustProfileVO profile = new ShopTrustProfileVO(); + profile.setShopId(shopDO.getId()); + profile.setShopName(shopDO.getShopName()); + profile.setBusinessHoursText(StringUtils.hasText(shopDO.getBusinessHours()) ? shopDO.getBusinessHours() : "营业时间待补充"); + profile.setBusinessStatusText(Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) ? "正常营业" : "暂不可预约"); + boolean locationAvailable = shopDO.getLatitude() != null && shopDO.getLongitude() != null; + profile.setLocationAvailable(locationAvailable); + profile.setNavigationAvailable(locationAvailable); + profile.setDistanceCapabilityText(locationAvailable ? "开启定位后可查看距离" : "门店暂未设置地图位置"); + profile.setEnvironmentImages(resolveImageUrls(fileIdsForShop(shopDO), fileMap)); + + ShopTrustProfileVO.Stats stats = new ShopTrustProfileVO.Stats(); + stats.setProductCount(productCount); + stats.setArtistCount(artistCount); + stats.setReviewCount(reviewCount); + stats.setAverageRating(averageRating); + stats.setRecentReviewCount(recentReviews.size()); + profile.setStats(stats); + + profile.setFeaturedProducts(featuredProducts.stream() + .map(product -> buildFeaturedProduct(product, fileMap)) + .collect(Collectors.toList())); + profile.setRecentReviews(recentReviews.stream() + .map(review -> buildRecentReview(review, featuredProducts, fileMap)) + .collect(Collectors.toList())); + profile.setAvailabilitySummary(buildAvailabilitySummary(shopDO, productCount)); + profile.setContactSummary(buildContactSummary()); + return profile; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllShops() { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "active", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .orderByDesc(ShopDO::getCreateTime) + ).stream() + .filter(this::isAuthorizationValid) + .map(this::convertToVO) + .collect(Collectors.toList()) + ); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List listAllShopsForAdmin() { + List shopDOs = shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .orderByDesc(ShopDO::getCreateTime) + ); + return shopDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listShopsByShopName(String shopName) { + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : ""; + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "name:" + normalizedShopName, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List shopDOs = shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .like(ShopDO::getShopName, normalizedShopName) + ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); + return shopDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + ); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ShopDO.class); + wrapper.eq(ShopDO::getIsDelete, 0); + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(ShopDO::getShopName, keyword) + .or().like(ShopDO::getDescription, keyword) + .or().like(ShopDO::getAddress, keyword)); + } + if (shopId != null && shopId > 0) { + wrapper.eq(ShopDO::getId, shopId); + } + wrapper.orderByDesc(ShopDO::getCreateTime); + + Page shopPage = shopMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(shopPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setTotal(shopPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + /** + * Purpose: countActiveProducts counts products that can contribute to a public shop trust profile. + * Usage: call it with a valid shop id before rendering product trust metrics. + */ + private long countActiveProducts(Long shopId) { + Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + private long countShopArtists(Long shopId) { + return nailArtistInfoService.getByShopId(shopId).size(); + } + + /** + * Purpose: listFeaturedProducts returns representative active products for shop detail trust cards. + * Usage: render at most three products and navigate to product detail when tapped. + */ + private List listFeaturedProducts(Long shopId) { + Set featuredTagTokens = findFeaturedProductTagTokens(shopId); + if (featuredTagTokens.isEmpty()) { + return Collections.emptyList(); + } + return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getShopId, shopId) + .eq(ProductDO::getIsDelete, 0) + .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) + .orderByDesc(ProductDO::getCollectCount) + .orderByDesc(ProductDO::getLikeCount) + .orderByDesc(ProductDO::getCreateTime) + .last("LIMIT 3")) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private Set findFeaturedProductTagTokens(Long shopId) { + Set tokens = new LinkedHashSet<>(FEATURED_PRODUCT_TAG_NAMES); + List tags = tagMapper.selectList(Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .and(wrapper -> wrapper.eq(TagDO::getShopId, shopId) + .or() + .isNull(TagDO::getShopId) + .or() + .eq(TagDO::getShopId, 0L)) + .and(wrapper -> wrapper.in(TagDO::getTagName, FEATURED_PRODUCT_TAG_NAMES) + .or() + .in(TagDO::getDisplayName, FEATURED_PRODUCT_TAG_NAMES))); + tags.stream() + .map(TagDO::getId) + .filter(Objects::nonNull) + .map(String::valueOf) + .forEach(tokens::add); + return tokens.stream() + .filter(StringUtils::hasText) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + private void applyProductTagTokenConditions(LambdaQueryWrapper wrapper, Set tagTokens) { + boolean appended = false; + for (String tagToken : tagTokens) { + if (!StringUtils.hasText(tagToken)) { + continue; + } + if (appended) { + wrapper.or(); + } + wrapper.apply("FIND_IN_SET({0}, REPLACE(tags, ';', ','))", tagToken); + appended = true; + } + if (!appended) { + wrapper.apply("1 = 0"); + } + } + + /** + * Purpose: listSubmittedReviews loads privacy-safe submitted review rows for the shop. + * Usage: only status=1 reviews should feed public trust display. + */ + private List listSubmittedReviews(Long shopId, int limit) { + return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .orderByDesc(OrderArtistReviewDO::getSubmittedAt) + .orderByDesc(OrderArtistReviewDO::getCreateTime) + .last("LIMIT " + Math.max(1, limit))) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: countSubmittedReviews counts reviews that are visible in public shop trust sections. + * Usage: render it beside average rating so customers can judge sample size. + */ + private long countSubmittedReviews(Long shopId) { + Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0)); + return count == null ? 0L : count; + } + + /** + * Purpose: calculateAverageRating derives the public average rating for a shop. + * Usage: use submitted reviews only and return zero when no rating exists. + */ + private BigDecimal calculateAverageRating(Long shopId) { + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + .eq(OrderArtistReviewDO::getShopId, shopId) + .eq(OrderArtistReviewDO::getStatus, 1) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .isNotNull(OrderArtistReviewDO::getRatingScore)); + if (reviews == null || reviews.isEmpty()) { + return BigDecimal.ZERO; + } + BigDecimal total = reviews.stream() + .map(OrderArtistReviewDO::getRatingScore) + .filter(Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + long count = reviews.stream().map(OrderArtistReviewDO::getRatingScore).filter(Objects::nonNull).count(); + if (count == 0) { + return BigDecimal.ZERO; + } + return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); + } + + /** + * Purpose: buildFeaturedProduct converts a product row into a compact trust card. + * Usage: keep this card small and do not include unpublished product internals. + */ + private ShopTrustProfileVO.FeaturedProduct buildFeaturedProduct(ProductDO product, Map fileMap) { + ShopTrustProfileVO.FeaturedProduct featured = new ShopTrustProfileVO.FeaturedProduct(); + featured.setId(product.getId()); + featured.setTitle(product.getTitle()); + featured.setPrice(product.getPrice()); + featured.setLikeCount(product.getLikeCount() == null ? 0 : product.getLikeCount()); + featured.setCollectCount(product.getCollectCount() == null ? 0 : product.getCollectCount()); + int artistCount = countBookableArtists(product.getBookableArtists()); + featured.setAvailableBookableArtistCount(artistCount); + featured.setBookingHint(artistCount > 0 ? artistCount + " 位美甲师可预约" : "到店后由门店安排美甲师"); + featured.setImageUrl(resolveFirstImageUrl(product.getImageFileIds(), fileMap)); + featured.setImageFileIds(product.getImageFileIds()); + return featured; + } + + /** + * Purpose: buildRecentReview converts a submitted review row into a privacy-safe card. + * Usage: never include customer phone, account, or full order identifiers here. + */ + private ShopTrustProfileVO.RecentReview buildRecentReview(OrderArtistReviewDO review, + List featuredProducts, + Map fileMap) { + ShopTrustProfileVO.RecentReview item = new ShopTrustProfileVO.RecentReview(); + item.setId(review.getId()); + item.setProductId(review.getProductId()); + item.setProductTitle(resolveProductTitle(review.getProductId(), featuredProducts)); + item.setRatingScore(review.getRatingScore()); + item.setContent(review.getContent()); + item.setSubmittedAt(review.getSubmittedAt() == null ? review.getCreateTime() : review.getSubmittedAt()); + item.setImageUrls(resolveImageUrls(parseLongIds(review.getImageFileIds(), ","), fileMap)); + return item; + } + + /** + * Purpose: buildAvailabilitySummary gives a coarse booking-readiness summary for the public page. + * Usage: clients must still rely on order creation for final schedule validation. + */ + private ShopTrustProfileVO.AvailabilitySummary buildAvailabilitySummary(ShopDO shopDO, long productCount) { + ShopTrustProfileVO.AvailabilitySummary summary = new ShopTrustProfileVO.AvailabilitySummary(); + boolean active = Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) && productCount > 0; + summary.setAvailable(active); + if (!Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus()))) { + summary.setSummaryText("门店暂不可预约"); + } else if (productCount <= 0) { + summary.setSummaryText("暂无可预约作品"); + } else { + summary.setSummaryText("当前有 " + productCount + " 个作品可预约,提交订单前会再次校验档期"); + summary.setNextSlots(buildCoarseSlotHints(shopDO.getBusinessHours())); + } + return summary; + } + + /** + * Purpose: buildContactSummary documents the explicit contact flow without public phone leakage. + * Usage: tests assert phoneExposed is false for the public trust endpoint. + */ + private ShopTrustProfileVO.ContactSummary buildContactSummary() { + ShopTrustProfileVO.ContactSummary contact = new ShopTrustProfileVO.ContactSummary(); + contact.setActionText("点击联系店长后获取联系方式"); + contact.setPhoneExposed(false); + contact.setPhone(null); + return contact; + } + + /** + * Purpose: buildCoarseSlotHints creates simple near-term booking hints from business hours. + * Usage: render these as guidance only, not as guaranteed appointment slots. + */ + private List buildCoarseSlotHints(String businessHours) { + String hours = StringUtils.hasText(businessHours) ? businessHours.trim() : "营业时间内"; + List hints = new ArrayList<>(); + hints.add("今天 " + hours); + hints.add("明天 " + hours); + hints.add("后天 " + hours); + return hints; + } + + /** + * Purpose: fileIdsForShop returns cover and environment image ids in display order. + * Usage: resolve these ids into environment image URLs for shop detail pages. + */ + private List fileIdsForShop(ShopDO shopDO) { + List ids = new ArrayList<>(); + ids.addAll(parseLongIds(shopDO.getCoverImageFileId(), ",")); + ids.addAll(parseLongIds(shopDO.getImageFileIds(), ",")); + return ids; + } + + /** + * Purpose: resolveFirstImageUrl returns the first available image URL from a delimited file id string. + * Usage: use it for compact product cards where only one thumbnail is needed. + */ + private String resolveFirstImageUrl(String fileIds, Map fileMap) { + return resolveImageUrls(parseLongIds(fileIds, ","), fileMap).stream().findFirst().orElse(null); + } + + /** + * Purpose: resolveImageUrls maps file ids to public URLs while preserving order. + * Usage: call it for shop environment, product thumbnails, and review thumbnails. + */ + private List resolveImageUrls(List fileIds, Map fileMap) { + if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) { + return Collections.emptyList(); + } + List urls = new ArrayList<>(); + for (Long fileId : fileIds) { + ObjectStorageFileVO file = fileMap.get(fileId); + if (file != null && StringUtils.hasText(file.getFileUrl())) { + urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); + } + } + return urls; + } + + /** + * Purpose: resolveProductTitle returns the title for a reviewed product. + * Usage: prefer already-loaded featured products and fall back to one product lookup. + */ + private String resolveProductTitle(Long productId, List featuredProducts) { + if (productId == null) { + return null; + } + for (ProductDO product : featuredProducts) { + if (product != null && productId.equals(product.getId())) { + return product.getTitle(); + } + } + ProductDO product = productMapper.selectById(productId); + return product == null || Integer.valueOf(1).equals(product.getIsDelete()) ? null : product.getTitle(); + } + + /** + * Purpose: parseLongIds parses comma or semicolon separated numeric ids. + * Usage: feed image/product/tag id strings into batch lookup helpers. + */ + private List parseLongIds(String value, String delimiter) { + if (!StringUtils.hasText(value)) { + return Collections.emptyList(); + } + List ids = new ArrayList<>(); + String regex = ",".equals(delimiter) ? "[,;]" : delimiter; + for (String part : value.split(regex)) { + if (!StringUtils.hasText(part)) { + continue; + } + try { + ids.add(Long.parseLong(part.trim())); + } catch (NumberFormatException ignored) { + // Ignore dirty historical file id fragments instead of failing the public shop page. + } + } + return ids; + } + + /** + * Purpose: countBookableArtists counts the configured artist ids for a product. + * Usage: render a compact availability hint without validating live schedules. + */ + private int countBookableArtists(String bookableArtists) { + if (!StringUtils.hasText(bookableArtists)) { + return 0; + } + return (int) parseLongIds(bookableArtists, ",").stream().distinct().count(); + } + + /** + * 将 DO 转换为 VO + * + * @param shopDO 店铺DO + * @return 店铺VO + */ + private ShopVO convertToVO(ShopDO shopDO) { + ShopVO shopVO = new ShopVO(); + shopVO.setId(shopDO.getId()); + shopVO.setShopName(shopDO.getShopName()); + shopVO.setDescription(shopDO.getDescription()); + shopVO.setAddress(shopDO.getAddress()); + shopVO.setMapProvider(mapService.normalizeProvider(shopDO.getMapProvider())); + shopVO.setLongitude(shopDO.getLongitude()); + shopVO.setLatitude(shopDO.getLatitude()); + shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); + shopVO.setBusinessHours(shopDO.getBusinessHours()); + shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); + shopVO.setCoverImageUrls(new java.util.ArrayList<>()); + shopVO.setImageFileIds(shopDO.getImageFileIds()); + shopVO.setImageUrls(new java.util.ArrayList<>()); + shopVO.setThemePrimaryColor(shopDO.getThemePrimaryColor()); + shopVO.setThemeSecondaryColor(shopDO.getThemeSecondaryColor()); + shopVO.setThemeAccentColor(shopDO.getThemeAccentColor()); + shopVO.setThemePageBgColor(shopDO.getThemePageBgColor()); + shopVO.setThemeCardBgColor(shopDO.getThemeCardBgColor()); + shopVO.setThemeBackgroundImageFileId(shopDO.getThemeBackgroundImageFileId()); + shopVO.setStatus(normalizeStatus(shopDO.getStatus())); + shopVO.setAuthorizationStartDate(shopDO.getAuthorizationStartDate()); + shopVO.setAuthorizationDays(shopDO.getAuthorizationDays()); + shopVO.setAuthorizationExpireTime(shopDO.getAuthorizationExpireTime()); + boolean expired = isAuthorizationExpired(shopDO); + shopVO.setAuthorizationExpired(expired); + shopVO.setAuthorizationStatusText(expired ? "已到期" : "有效"); + shopVO.setCreateTime(shopDO.getCreateTime()); + shopVO.setUpdateTime(shopDO.getUpdateTime()); + return shopVO; + } + + @Override + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + return isAuthorizationExpired(shopMapper.selectById(shopId)); + } + + @Override + /** + * Run business method `isFrontendAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isFrontendAvailable(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) + && isAuthorizationValid(shopDO); + } + + /** + * Run business method `isAuthorizationValid`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationValid(ShopDO shopDO) { + return !isAuthorizationExpired(shopDO); + } + + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationExpired(ShopDO shopDO) { + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + + /** + * Run business method `normalizeStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ + private Integer normalizeStatus(Integer status) { + return Integer.valueOf(0).equals(status) ? 0 : 1; + } + + /** + * Purpose: applyAuthorization supports ShopServiceImpl.java by holding or executing the apply authorization business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void applyAuthorization(ShopDO shopDO, ShopDTO shopDTO) { + LocalDate startDate = shopDTO.getAuthorizationStartDate(); + Integer days = shopDTO.getAuthorizationDays(); + shopDO.setAuthorizationStartDate(startDate); + shopDO.setAuthorizationDays(days); + if (startDate != null && days != null && days > 0) { + shopDO.setAuthorizationExpireTime(startDate.plusDays(days - 1L).atTime(23, 59, 59)); + return; + } + shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime()); + } + + /** + * Purpose: applyTheme supports ShopServiceImpl.java by holding or executing the apply theme business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void applyTheme(ShopDO shopDO, ShopDTO shopDTO) { + shopDO.setThemePrimaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePrimaryColor(), "themePrimaryColor")); + shopDO.setThemeSecondaryColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeSecondaryColor(), "themeSecondaryColor")); + shopDO.setThemeAccentColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeAccentColor(), "themeAccentColor")); + shopDO.setThemePageBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemePageBgColor(), "themePageBgColor")); + shopDO.setThemeCardBgColor(ShopThemeSupport.normalizeColor(shopDTO.getThemeCardBgColor(), "themeCardBgColor")); + shopDO.setThemeBackgroundImageFileId(StringUtils.hasText(shopDTO.getThemeBackgroundImageFileId()) + ? shopDTO.getThemeBackgroundImageFileId().trim() + : null); + } + + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void evictShopCaches(Long shopId) { + if (shopId != null) { + multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId); + } + multiLevelCacheService.evictByPrefix(SHOP_LIST_CACHE_PREFIX); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/ShopThemeSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/ShopThemeSupport.java new file mode 100644 index 00000000..e6db7cba --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/ShopThemeSupport.java @@ -0,0 +1,32 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.support; + +import org.springframework.util.StringUtils; + +import java.util.Locale; +import java.util.regex.Pattern; + +/** + * Purpose: ShopThemeSupport supports ShopThemeSupport.java by holding or executing the shop theme support business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class ShopThemeSupport { + private static final Pattern HEX_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$"); + + private ShopThemeSupport() { + } + + /** + * Purpose: normalizeColor supports ShopThemeSupport.java by holding or executing the normalize color business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String normalizeColor(String color, String fieldName) { + if (!StringUtils.hasText(color)) { + return null; + } + String value = color.trim(); + if (!HEX_COLOR.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a #RRGGBB color"); + } + return value.toUpperCase(Locale.ROOT); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/UserShopBindingSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/UserShopBindingSupport.java new file mode 100644 index 00000000..5ad7c0b5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/support/UserShopBindingSupport.java @@ -0,0 +1,636 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.support; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * 用户-店铺绑定关系支撑类。 + */ +@Component +@RequiredArgsConstructor +public class UserShopBindingSupport { + + /** + * Purpose: userShopBindingMapper supports UserShopBindingSupport.java by holding or executing the user shop binding mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Purpose: shopMapper supports UserShopBindingSupport.java by holding or executing the shop mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ShopMapper shopMapper; + /** + * Purpose: userMapper supports UserShopBindingSupport.java by holding or executing the user mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserMapper userMapper; + + /** + * Purpose: listBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listBindingsByUserId(Long userId, boolean includeDeleted) { + if (userId == null) { + return List.of(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .orderByAsc(UserShopBindingDO::getCreateTime) + .orderByAsc(UserShopBindingDO::getId); + if (!includeDeleted) { + wrapper.eq(UserShopBindingDO::getIsDelete, 0); + } + return userShopBindingMapper.selectList(wrapper); + } + + /** + * Purpose: hasBindingHistory supports UserShopBindingSupport.java by holding or executing the has binding history business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasBindingHistory(Long userId) { + if (userId == null) { + return false; + } + return userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId)) > 0; + } + + /** + * Purpose: listActiveBindingsByUserId supports UserShopBindingSupport.java by holding or executing the list active bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveBindingsByUserId(Long userId) { + return listBindingsByUserId(userId, false).stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .filter(binding -> isShopActive(binding.getShopId())) + .sorted(Comparator.comparing(UserShopBindingDO::getCreateTime, Comparator.nullsLast(LocalDateTime::compareTo)) + .thenComparing(UserShopBindingDO::getId, Comparator.nullsLast(Long::compareTo))) + .collect(Collectors.toList()); + } + + /** + * Purpose: listActiveShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop ids by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveShopIdsByUserId(Long userId) { + return listShopIdsByUserId(userId, true, true); + } + + /** + * Purpose: listActiveShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list active shop options by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listActiveShopOptionsByUserId(Long userId) { + return listShopOptionsByUserId(userId, true, true); + } + + /** + * Purpose: listAllActiveShopOptions supports UserShopBindingSupport.java by holding or executing the list all active shop options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listAllActiveShopOptions() { + return toShopOptions(fetchAllShopMap(true)); + } + + /** + * Purpose: listShopIdsByUserId supports UserShopBindingSupport.java by holding or executing the list shop ids by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listShopIdsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { + return listShopOptionsByUserId(userId, onlyActiveBindings, onlyActiveShops).stream() + .map(ShopSimpleVO::getId) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + /** + * Purpose: listShopOptionsByUserId supports UserShopBindingSupport.java by holding or executing the list shop options by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listShopOptionsByUserId(Long userId, boolean onlyActiveBindings, boolean onlyActiveShops) { + return listShopOptionsByUserIds(List.of(userId), onlyActiveBindings, onlyActiveShops) + .getOrDefault(userId, List.of()); + } + + /** + * Purpose: hasActiveBinding supports UserShopBindingSupport.java by holding or executing the has active binding business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasActiveBinding(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + return listActiveBindingsByUserId(userId).stream() + .anyMatch(binding -> shopId.equals(binding.getShopId())); + } + + /** + * Purpose: hasBindingInShop supports UserShopBindingSupport.java by holding or executing the has binding in shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean hasBindingInShop(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + return userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)) > 0; + } + + /** + * Purpose: isShopActive supports UserShopBindingSupport.java by holding or executing the is shop active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopActive(Long shopId) { + return isShopEnabledIgnoringAuthorization(shopId) && !isShopAuthorizationExpired(shopId); + } + + /** + * Purpose: isShopEnabledIgnoringAuthorization supports UserShopBindingSupport.java by holding or executing the is shop enabled ignoring authorization business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopEnabledIgnoringAuthorization(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus())); + } + + /** + * Purpose: isShopAuthorizationExpired supports UserShopBindingSupport.java by holding or executing the is shop authorization expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isShopAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + + /** + * Purpose: pickPrimaryShopId supports UserShopBindingSupport.java by holding or executing the pick primary shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long pickPrimaryShopId(Long userId) { + return listActiveBindingsByUserId(userId).stream() + .map(UserShopBindingDO::getShopId) + .findFirst() + .orElse(null); + } + + /** + * Purpose: listActiveShopOptionsByUserIds supports UserShopBindingSupport.java by holding or executing the list active shop options by user ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Map> listActiveShopOptionsByUserIds(Collection userIds) { + return listShopOptionsByUserIds(userIds, true, true); + } + + public Map> listShopOptionsByUserIds( + Collection userIds, + boolean onlyActiveBindings, + boolean onlyActiveShops + ) { + if (userIds == null || userIds.isEmpty()) { + return Collections.emptyMap(); + } + List normalizedUserIds = userIds.stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (normalizedUserIds.isEmpty()) { + return Collections.emptyMap(); + } + + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .in(UserShopBindingDO::getUserId, normalizedUserIds) + .eq(UserShopBindingDO::getIsDelete, 0) + .orderByAsc(UserShopBindingDO::getCreateTime) + .orderByAsc(UserShopBindingDO::getId)); + if (bindings.isEmpty()) { + return Collections.emptyMap(); + } + + if (onlyActiveBindings) { + bindings = bindings.stream() + .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) + .collect(Collectors.toList()); + if (bindings.isEmpty()) { + return Collections.emptyMap(); + } + } + + Map shopMap = fetchShopMap(bindings.stream() + .map(UserShopBindingDO::getShopId) + .collect(Collectors.toSet()), onlyActiveShops); + Map> result = new LinkedHashMap<>(); + for (UserShopBindingDO binding : bindings) { + ShopDO shopDO = shopMap.get(binding.getShopId()); + if (shopDO == null) { + continue; + } + result.computeIfAbsent(binding.getUserId(), key -> new java.util.ArrayList<>()) + .add(new ShopSimpleVO(shopDO.getId(), shopDO.getShopName())); + } + return result; + } + + /** + * Purpose: listUserIdsByShopId supports UserShopBindingSupport.java by holding or executing the list user ids by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listUserIdsByShopId(Long shopId, boolean onlyActiveBindings) { + if (shopId == null || shopId <= 0) { + return List.of(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0); + if (onlyActiveBindings) { + wrapper.eq(UserShopBindingDO::getStatus, 1); + } + return userShopBindingMapper.selectList(wrapper).stream() + .map(UserShopBindingDO::getUserId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Purpose: countUsersByShopId supports UserShopBindingSupport.java by holding or executing the count users by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public long countUsersByShopId(Long shopId, boolean onlyActiveBindings) { + return listUserIdsByShopId(shopId, onlyActiveBindings).size(); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: ensureUserBoundToShop supports UserShopBindingSupport.java by holding or executing the ensure user bound to shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void ensureUserBoundToShop(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + throw new RuntimeException("店铺绑定信息不完整"); + } + if (!isShopActive(shopId)) { + throw new RuntimeException("所选店铺不存在或已停用"); + } + + UserShopBindingDO existing = userShopBindingMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .last("limit 1")); + if (existing == null) { + UserShopBindingDO binding = new UserShopBindingDO(); + binding.setUserId(userId); + binding.setShopId(shopId); + binding.setStatus(1); + binding.setIsDelete(0); + userShopBindingMapper.insert(binding); + refreshLegacyPrimaryShop(userId); + return; + } + + existing.setStatus(1); + existing.setIsDelete(0); + existing.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(existing); + refreshLegacyPrimaryShop(userId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: syncUserShopBindings supports UserShopBindingSupport.java by holding or executing the sync user shop bindings business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void syncUserShopBindings(Long userId, Collection shopIds) { + if (userId == null) { + return; + } + + Set desiredShopIds = normalizeActiveShopIds(shopIds); + List existingBindings = listBindingsByUserId(userId, true); + Map bindingMap = existingBindings.stream() + .filter(binding -> binding.getShopId() != null) + .collect(Collectors.toMap(UserShopBindingDO::getShopId, binding -> binding, (left, right) -> right, LinkedHashMap::new)); + + for (Long shopId : desiredShopIds) { + UserShopBindingDO existing = bindingMap.remove(shopId); + if (existing == null) { + UserShopBindingDO binding = new UserShopBindingDO(); + binding.setUserId(userId); + binding.setShopId(shopId); + binding.setStatus(1); + binding.setIsDelete(0); + userShopBindingMapper.insert(binding); + continue; + } + existing.setStatus(1); + existing.setIsDelete(0); + existing.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(existing); + } + + for (UserShopBindingDO staleBinding : bindingMap.values()) { + staleBinding.setIsDelete(1); + staleBinding.setUpdateTime(LocalDateTime.now()); + userShopBindingMapper.updateById(staleBinding); + } + + refreshLegacyPrimaryShop(userId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: updateBindingStatus supports UserShopBindingSupport.java by holding or executing the update binding status business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean updateBindingStatus(Long userId, Long shopId, Integer status) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindingCount <= 0) { + return false; + } + Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; + LocalDateTime now = LocalDateTime.now(); + int updated = userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getStatus, normalizedStatus) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + return updated > 0; + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBinding supports UserShopBindingSupport.java by holding or executing the delete binding business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean deleteBinding(Long userId, Long shopId) { + if (userId == null || shopId == null || shopId <= 0) { + return false; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindingCount <= 0) { + return false; + } + LocalDateTime now = LocalDateTime.now(); + int updated = userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + return updated > 0; + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBindingsByShopId supports UserShopBindingSupport.java by holding or executing the delete bindings by shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void deleteBindingsByShopId(Long shopId) { + if (shopId == null || shopId <= 0) { + return; + } + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0)); + if (bindings.isEmpty()) { + return; + } + Set affectedUserIds = new LinkedHashSet<>(); + for (UserShopBindingDO binding : bindings) { + affectedUserIds.add(binding.getUserId()); + } + LocalDateTime now = LocalDateTime.now(); + userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getShopId, shopId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + affectedUserIds.forEach(this::refreshLegacyPrimaryShop); + } + + /** + * Purpose: canUserAccessShop supports UserShopBindingSupport.java by holding or executing the can user access shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean canUserAccessShop(Long userId, Long shopId, boolean adminLogin, Integer userType) { + if (Integer.valueOf(4).equals(userType)) { + if (shopId == null || shopId <= 0) { + return Boolean.TRUE.equals(adminLogin); + } + return isShopSelectableForPlatformAdmin(shopId); + } + if (shopId == null || shopId <= 0) { + return false; + } + if (Boolean.TRUE.equals(adminLogin)) { + if (!isShopEnabledIgnoringAuthorization(shopId)) { + return false; + } + } else if (!isShopActive(shopId)) { + return false; + } + return hasActiveBinding(userId, shopId); + } + + /** + * Purpose: isShopSelectableForPlatformAdmin supports UserShopBindingSupport.java by holding or executing the is shop selectable for platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isShopSelectableForPlatformAdmin(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && (shopDO.getAuthorizationExpireTime() == null + || !shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now())); + } + + /** + * Purpose: isUserAccessibleInShop supports UserShopBindingSupport.java by holding or executing the is user accessible in shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isUserAccessibleInShop(Long userId, Long shopId) { + return hasActiveBinding(userId, shopId); + } + + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: deleteBindingsByUserId supports UserShopBindingSupport.java by holding or executing the delete bindings by user id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void deleteBindingsByUserId(Long userId) { + if (userId == null) { + return; + } + LocalDateTime now = LocalDateTime.now(); + userShopBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getIsDelete, 0) + .set(UserShopBindingDO::getIsDelete, 1) + .set(UserShopBindingDO::getUpdateTime, now) + ); + refreshLegacyPrimaryShop(userId); + } + + /** + * Purpose: normalizeActiveShopIds supports UserShopBindingSupport.java by holding or executing the normalize active shop ids business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set normalizeActiveShopIds(Collection shopIds) { + if (shopIds == null || shopIds.isEmpty()) { + return Collections.emptySet(); + } + Set normalizedShopIds = new LinkedHashSet<>(); + for (Long shopId : shopIds) { + if (shopId == null || shopId <= 0) { + continue; + } + if (!isShopActive(shopId)) { + throw new RuntimeException("所选店铺不存在或已停用"); + } + normalizedShopIds.add(shopId); + } + return normalizedShopIds; + } + + /** + * Purpose: refreshLegacyPrimaryShop supports UserShopBindingSupport.java by holding or executing the refresh legacy primary shop business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void refreshLegacyPrimaryShop(Long userId) { + if (userId == null) { + return; + } + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return; + } + Long primaryShopId = pickPrimaryShopId(userId); + if (Objects.equals(userDO.getShopId(), primaryShopId)) { + return; + } + LocalDateTime now = LocalDateTime.now(); + userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, userId) + .set(UserDO::getShopId, primaryShopId) + .set(UserDO::getUpdateTime, now) + ); + } + + /** + * Purpose: fetchAllShopMap supports UserShopBindingSupport.java by holding or executing the fetch all shop map business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map fetchAllShopMap(boolean onlyActiveShops) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(ShopDO::getIsDelete, 0); + if (onlyActiveShops) { + wrapper.eq(ShopDO::getStatus, 1); + } + return shopMapper.selectList(wrapper).stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) + .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Purpose: fetchShopMap supports UserShopBindingSupport.java by holding or executing the fetch shop map business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map fetchShopMap(Collection shopIds, boolean onlyActiveShops) { + if (shopIds == null || shopIds.isEmpty()) { + return Collections.emptyMap(); + } + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .in(ShopDO::getId, shopIds) + .eq(ShopDO::getIsDelete, 0); + if (onlyActiveShops) { + wrapper.eq(ShopDO::getStatus, 1); + } + return shopMapper.selectList(wrapper) + .stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) + .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); + } + + /** + * Purpose: toShopOptions supports UserShopBindingSupport.java by holding or executing the to shop options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List toShopOptions(Map shopMap) { + return shopMap.values().stream() + .sorted(Comparator.comparing(ShopDO::getShopName, Comparator.nullsLast(String::compareTo)) + .thenComparing(ShopDO::getId, Comparator.nullsLast(Long::compareTo))) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * Purpose: normalizeShopStatus supports UserShopBindingSupport.java by holding or executing the normalize shop status business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer normalizeShopStatus(Integer status) { + return status == null ? 1 : status; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ContactInfoVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ContactInfoVO.java new file mode 100644 index 00000000..1bc3cf33 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ContactInfoVO.java @@ -0,0 +1,51 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.vo; + +import lombok.Data; + +@Data +/** + * ContactInfoVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ContactInfoVO { + /** + * Field `contactUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long contactUserId; + /** + * Field `contactName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String contactName; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + /** + * Field `phoneAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean phoneAvailable; + /** + * Field `wechatId` (String): contact WeChat ID for quick copy/open actions. + */ + private String wechatId; + /** + * Field `wechatAvailable` (Boolean): whether the contact exposes a WeChat ID. + */ + private Boolean wechatAvailable; + /** + * Field `wechatQrCode` (String): accessible WeChat QR code image URL. + */ + private String wechatQrCode; + /** + * Field `platformContactAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean platformContactAvailable; + /** + * Field `platformContactText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platformContactText; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopSimpleVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopSimpleVO.java new file mode 100644 index 00000000..539ea6fa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopSimpleVO.java @@ -0,0 +1,27 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +/** + * ShopSimpleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopSimpleVO { + + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopTrustProfileVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopTrustProfileVO.java new file mode 100644 index 00000000..2240739d --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopTrustProfileVO.java @@ -0,0 +1,290 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page. + * Usage: return this VO from /shop/trust-profile/{shopId}; clients render it without exposing phone numbers. + */ +@Data +public class ShopTrustProfileVO { + /** + * Purpose: shopId identifies the shop whose trust profile is being rendered. + * Usage: clients use it to keep the profile matched to the visible shop. + */ + private Long shopId; + + /** + * Purpose: shopName gives the profile a stable display label. + * Usage: render it in accessibility labels or fallback section titles. + */ + private String shopName; + + /** + * Purpose: businessHoursText describes when the shop says it is open. + * Usage: show it near booking and navigation actions. + */ + private String businessHoursText; + + /** + * Purpose: businessStatusText summarizes whether the shop can currently be viewed and booked. + * Usage: display this short text in trust summary chips. + */ + private String businessStatusText; + + /** + * Purpose: locationAvailable reports whether map coordinates exist. + * Usage: hide navigation/distance affordances when false. + */ + private Boolean locationAvailable; + + /** + * Purpose: distanceCapabilityText explains whether distance can be calculated on the client. + * Usage: show this text until the client has user location permission. + */ + private String distanceCapabilityText; + + /** + * Purpose: navigationAvailable reports whether navigation URLs can be offered. + * Usage: clients use it to enable map buttons. + */ + private Boolean navigationAvailable; + + /** + * Purpose: stats contains public aggregate numbers for customer confidence. + * Usage: render as compact metrics on the shop detail page. + */ + private Stats stats = new Stats(); + + /** + * Purpose: environmentImages contains public shop environment image URLs. + * Usage: render thumbnails or a carousel; it must not include contact data. + */ + private List environmentImages = new ArrayList<>(); + + /** + * Purpose: featuredProducts lists representative products from this shop. + * Usage: render as quick inspection or booking entry cards. + */ + private List featuredProducts = new ArrayList<>(); + + /** + * Purpose: recentReviews lists recent submitted reviews only. + * Usage: show social proof while keeping customer identity private. + */ + private List recentReviews = new ArrayList<>(); + + /** + * Purpose: availabilitySummary gives a safe booking summary without reserving slots. + * Usage: render it near booking actions and keep final conflict checks in order creation. + */ + private AvailabilitySummary availabilitySummary = new AvailabilitySummary(); + + /** + * Purpose: contactSummary tells clients how to request contact details without exposing phone data. + * Usage: render the action hint and fetch phone only through the explicit contact endpoint. + */ + private ContactSummary contactSummary = new ContactSummary(); + + /** + * Purpose: Stats groups aggregate shop trust metrics. + * Usage: serialize inside ShopTrustProfileVO.stats for frontend summary cards. + */ + @Data + public static class Stats { + /** + * Purpose: averageRating is the submitted-review average for this shop. + * Usage: display with one decimal place when reviewCount is greater than zero. + */ + private BigDecimal averageRating = BigDecimal.ZERO; + + /** + * Purpose: reviewCount is the number of submitted, public reviews. + * Usage: render beside averageRating to avoid showing score without sample size. + */ + private Long reviewCount = 0L; + + /** + * Purpose: productCount is the number of active products in this shop. + * Usage: render as a confidence signal and empty-state condition. + */ + private Long productCount = 0L; + + /** + * Purpose: artistCount is the number of active nail artist users bound to this shop. + * Usage: render as the staff confidence signal on shop detail pages. + */ + private Long artistCount = 0L; + + /** + * Purpose: recentReviewCount is the number of review cards included in this response. + * Usage: clients use it for section labels and empty states. + */ + private Integer recentReviewCount = 0; + } + + /** + * Purpose: FeaturedProduct is a compact public product card for shop trust display. + * Usage: render these cards on shop detail pages without fetching full product detail first. + */ + @Data + public static class FeaturedProduct { + /** + * Purpose: id identifies the product for detail navigation. + * Usage: pass it to product detail routes when the customer taps the card. + */ + private Long id; + + /** + * Purpose: title names the featured product. + * Usage: render as the card title. + */ + private String title; + + /** + * Purpose: imageUrl provides the first public product image. + * Usage: render as a thumbnail and fall back gracefully when blank. + */ + private String imageUrl; + + /** + * Purpose: imageFileIds provides product image file ids for clients that need signed image URLs. + * Usage: clients may resolve the first id into a stable thumbnail URL. + */ + private String imageFileIds; + + /** + * Purpose: price carries the current product price. + * Usage: show it as a current quote, not as historical order price. + */ + private BigDecimal price; + + /** + * Purpose: likeCount is the current like count. + * Usage: render as a lightweight popularity signal. + */ + private Integer likeCount; + + /** + * Purpose: collectCount is the current wishlist count. + * Usage: render as a lightweight popularity signal. + */ + private Integer collectCount; + + /** + * Purpose: availableBookableArtistCount tells whether this product has available artists configured. + * Usage: show concise booking hints without exposing artist schedules. + */ + private Integer availableBookableArtistCount; + + /** + * Purpose: bookingHint is a customer-facing availability hint for this product. + * Usage: display below the product title. + */ + private String bookingHint; + } + + /** + * Purpose: RecentReview is a privacy-safe submitted review summary. + * Usage: render public review snippets without customer account or phone fields. + */ + @Data + public static class RecentReview { + /** + * Purpose: id identifies the review row. + * Usage: use it as a frontend list key. + */ + private Long id; + + /** + * Purpose: productId links the review to the reviewed product. + * Usage: optionally navigate to the product detail page. + */ + private Long productId; + + /** + * Purpose: productTitle names the product reviewed. + * Usage: display as context for the review. + */ + private String productTitle; + + /** + * Purpose: ratingScore is the submitted rating. + * Usage: render with one decimal place. + */ + private BigDecimal ratingScore; + + /** + * Purpose: content stores the submitted review text. + * Usage: display a short snippet and hide the section when blank if desired. + */ + private String content; + + /** + * Purpose: imageUrls contains public review image URLs. + * Usage: render thumbnails without exposing customer identity. + */ + private List imageUrls = new ArrayList<>(); + + /** + * Purpose: submittedAt records when the review was submitted. + * Usage: render relative or formatted review time. + */ + private LocalDateTime submittedAt; + } + + /** + * Purpose: AvailabilitySummary summarizes booking readiness for the shop. + * Usage: clients render it as guidance while final validation remains server-side on order creation. + */ + @Data + public static class AvailabilitySummary { + /** + * Purpose: available states whether the shop currently has active products to book. + * Usage: enable or soften booking entry copy. + */ + private Boolean available = false; + + /** + * Purpose: summaryText gives the customer a direct booking-readiness sentence. + * Usage: render as the availability card body. + */ + private String summaryText = "暂无可预约作品"; + + /** + * Purpose: nextSlots gives coarse upcoming booking hints when available. + * Usage: render as chips; clients must not treat these as reserved slots. + */ + private List nextSlots = new ArrayList<>(); + } + + /** + * Purpose: ContactSummary describes the explicit contact action without leaking phone data. + * Usage: render the action label and call contact-info only after the user taps contact. + */ + @Data + public static class ContactSummary { + /** + * Purpose: actionText is the label for the explicit contact action. + * Usage: render on the contact button or helper text. + */ + private String actionText = "点击联系店长后获取联系方式"; + + /** + * Purpose: phoneExposed records whether this public profile includes phone data. + * Usage: assert false in tests and use contact-info endpoint for phone data. + */ + private Boolean phoneExposed = false; + + /** + * Purpose: phone is intentionally null in this public profile. + * Usage: clients must ignore it and call the explicit contact endpoint instead. + */ + private String phone; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopVO.java new file mode 100644 index 00000000..2184325c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/shop/vo/ShopVO.java @@ -0,0 +1,170 @@ +package com.xiaowang.fingertipdesigner.core.modules.shop.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * 店铺信息表 VO + * 用于前端展示店铺信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class ShopVO { + + /** + * 店铺唯一主键ID + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 店铺描述 + */ + private String description; + + /** + * 店铺地址 + */ + private String address; + + /** + * Purpose: mapProvider supports ShopVO.java by holding or executing the map provider business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String mapProvider; + + /** + * Purpose: longitude supports ShopVO.java by holding or executing the longitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal longitude; + + /** + * Purpose: latitude supports ShopVO.java by holding or executing the latitude business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private BigDecimal latitude; + + /** + * Purpose: navigationUrls supports ShopVO.java by holding or executing the navigation urls business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map navigationUrls; + + /** + * 店铺营业时间 + */ + private String businessHours; + + /** + * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 + */ + private String coverImageFileId; + + /** + * 店铺封面图URL列表(Banner图) + */ + private List coverImageUrls; + + /** + * 店铺图片文件ID集合,多个ID以逗号分隔 + */ + private String imageFileIds; + + /** + * 店铺图片URL列表 + */ + private List imageUrls; + + /** + * Purpose: themePrimaryColor supports ShopVO.java by holding or executing the theme primary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePrimaryColor; + + /** + * Purpose: themeSecondaryColor supports ShopVO.java by holding or executing the theme secondary color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeSecondaryColor; + + /** + * Purpose: themeAccentColor supports ShopVO.java by holding or executing the theme accent color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeAccentColor; + + /** + * Purpose: themePageBgColor supports ShopVO.java by holding or executing the theme page bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themePageBgColor; + + /** + * Purpose: themeCardBgColor supports ShopVO.java by holding or executing the theme card bg color business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeCardBgColor; + + /** + * Purpose: themeBackgroundImageFileId supports ShopVO.java by holding or executing the theme background image file id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String themeBackgroundImageFileId; + + /** + * 店铺状态:1-启用,0-停用 + */ + private Integer status; + + /** + * Purpose: authorizationStartDate supports ShopVO.java by holding or executing the authorization start date business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDate authorizationStartDate; + + /** + * Purpose: authorizationDays supports ShopVO.java by holding or executing the authorization days business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer authorizationDays; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; + + /** + * 当前时间是否已超过授权有效期。 + */ + private Boolean authorizationExpired; + + /** + * 给前端直接展示的授权状态文案。 + */ + private String authorizationStatusText; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/admin/AdminLegalAgreementController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/admin/AdminLegalAgreementController.java new file mode 100644 index 00000000..11836847 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/admin/AdminLegalAgreementController.java @@ -0,0 +1,109 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.service.LegalAgreementService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.LegalAgreementVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/legal-agreement") +/** + * Purpose: AdminLegalAgreementController supports AdminLegalAgreementController.java by holding or executing the admin legal agreement controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class AdminLegalAgreementController { + + /** + * Purpose: legalAgreementService supports AdminLegalAgreementController.java by holding or executing the legal agreement service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementService legalAgreementService; + /** + * Purpose: adminScopeHelper supports AdminLegalAgreementController.java by holding or executing the admin scope helper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: securityAuditLogService supports AdminLegalAgreementController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + @GetMapping("/list") + @RequirePermission("legal_agreement:manage") + /** + * Purpose: list supports AdminLegalAgreementController.java by holding or executing the list business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> list(HttpServletRequest request) { + return Result.success(legalAgreementService.listAdminAgreements(adminScopeHelper.getCurrentUser(request))); + } + + @PostMapping("/create") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: create supports AdminLegalAgreementController.java by holding or executing the create business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long id = legalAgreementService.createAgreement(currentUser, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); + return Result.success(id); + } + + @PutMapping("/{id}") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: update supports AdminLegalAgreementController.java by holding or executing the update business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/{id}/publish") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") + /** + * Purpose: publish supports AdminLegalAgreementController.java by holding or executing the publish business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result publish(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.publishAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/{id}/disable") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") + /** + * Purpose: disable supports AdminLegalAgreementController.java by holding or executing the disable business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result disable(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.disableAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/HealthController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/HealthController.java new file mode 100644 index 00000000..aee333fa --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/HealthController.java @@ -0,0 +1,125 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.controller.front; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 健康检查控制器 + * + * @author xiaowang + * @date 2026-02-12 + */ +@RestController +@RequestMapping("/health") +@RequiredArgsConstructor +public class HealthController { + /** + * Variable `dataSource`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final DataSource dataSource; + /** + * Variable `stringRedisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Variable `discoveryClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final DiscoveryClient discoveryClient; + /** + * Variable `environment`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final Environment environment; + + /** + * 服务状态检查 + */ + @GetMapping("/check") + public Result check() { + return Result.success("JayuCloud-Salon-Core is running"); + } + + @GetMapping("/diagnostics") + /** + * Run business method `diagnostics`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> diagnostics() { + Map diagnostics = new LinkedHashMap<>(); + diagnostics.put("service", environment.getProperty("spring.application.name", "jayucloud-salon-core")); + diagnostics.put("port", environment.getProperty("server.port", "")); + diagnostics.put("database", checkDatabase()); + diagnostics.put("redis", checkRedis()); + diagnostics.put("discovery", checkDiscovery()); + return Result.success(diagnostics); + } + + /** + * Run business method `checkDatabase`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkDatabase() { + Map result = new LinkedHashMap<>(); + try (Connection connection = dataSource.getConnection()) { + result.put("ok", connection.isValid(2)); + result.put("catalog", connection.getCatalog()); + result.put("product", connection.getMetaData().getDatabaseProductName()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + /** + * Run business method `checkRedis`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkRedis() { + Map result = new LinkedHashMap<>(); + try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) { + String pong = connection.ping(); + result.put("ok", "PONG".equalsIgnoreCase(pong)); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + /** + * Run business method `checkDiscovery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map checkDiscovery() { + Map result = new LinkedHashMap<>(); + try { + String serviceName = environment.getProperty("spring.application.name", "jayucloud-salon-core"); + List instances = discoveryClient.getInstances(serviceName); + result.put("ok", !instances.isEmpty()); + result.put("service", serviceName); + result.put("instanceCount", instances.size()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/LegalAgreementController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/LegalAgreementController.java new file mode 100644 index 00000000..f6f7928a --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/LegalAgreementController.java @@ -0,0 +1,147 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.service.LegalAgreementService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/legal-agreement", "/api/legal-agreement"}) +/** + * Purpose: LegalAgreementController supports LegalAgreementController.java by holding or executing the legal agreement controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementController { + + /** + * Purpose: legalAgreementService supports LegalAgreementController.java by holding or executing the legal agreement service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementService legalAgreementService; + /** + * Purpose: adminScopeHelper supports LegalAgreementController.java by holding or executing the admin scope helper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Purpose: securityAuditLogService supports LegalAgreementController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + /** + * Purpose: requestThrottleService supports LegalAgreementController.java by holding or executing the request throttle service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestThrottleService requestThrottleService; + + @GetMapping("/current") + /** + * Purpose: listCurrent supports LegalAgreementController.java by holding or executing the list current business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listCurrent(HttpServletRequest request) { + requestThrottleService.checkAgreementRead(request, "ALL"); + return Result.success(legalAgreementService.listCurrentAgreements()); + } + + @GetMapping("/current/{type}") + /** + * Purpose: getCurrent supports LegalAgreementController.java by holding or executing the get current business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result getCurrent(HttpServletRequest request, @PathVariable String type) { + requestThrottleService.checkAgreementRead(request, type); + return Result.success(legalAgreementService.getCurrentAgreement(type)); + } + + @GetMapping("/admin/list") + @RequirePermission("legal_agreement:manage") + /** + * Purpose: listAdmin supports LegalAgreementController.java by holding or executing the list admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(legalAgreementService.listAdminAgreements(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: create supports LegalAgreementController.java by holding or executing the create business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long id = legalAgreementService.createAgreement(currentUser, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); + return Result.success(id); + } + + @PutMapping("/admin/{id}") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + /** + * Purpose: update supports LegalAgreementController.java by holding or executing the update business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/publish") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") + /** + * Purpose: publish supports LegalAgreementController.java by holding or executing the publish business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result publish(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.publishAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/disable") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") + /** + * Purpose: disable supports LegalAgreementController.java by holding or executing the disable business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result disable(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.disableAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @GetMapping("/user/agreement-consent/me") + /** + * Purpose: getMyConsent supports LegalAgreementController.java by holding or executing the get my consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result getMyConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/SystemParameterConfigController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/SystemParameterConfigController.java new file mode 100644 index 00000000..aa1bced2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/controller/front/SystemParameterConfigController.java @@ -0,0 +1,101 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-parameter-config", "/api/system-parameter-config", "/admin/system-parameter-config"}) +/** + * Purpose: SystemParameterConfigController supports SystemParameterConfigController.java by holding or executing the system parameter config controller business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigController { + + /** + * Purpose: configService supports SystemParameterConfigController.java by holding or executing the config service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SystemParameterConfigService configService; + /** + * Purpose: adminScopeHelper supports SystemParameterConfigController.java by holding or executing the admin scope helper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) String configGroup) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser, configGroup)); + } + + @PostMapping("/admin/save") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "system-parameter-config-save", ttlSeconds = 8, message = "系统参数保存处理中,请勿重复提交") + /** + * Purpose: save supports SystemParameterConfigController.java by holding or executing the save business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result save(HttpServletRequest request, @Valid @RequestBody SystemParameterConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.saveConfig(currentUser, dto)); + } + + @GetMapping("/admin/tencent-map") + /** + * Purpose: getTencentMapKey supports SystemParameterConfigController.java by holding or executing the get tencent map key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> getTencentMapKey(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); + return Result.success(result); + } + + @GetMapping("/admin/map-config") + /** + * Purpose: getMapConfig supports SystemParameterConfigController.java by holding or executing the get map config business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> getMapConfig(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + String provider = configService.getEnabledValue("MAP", "MAP_PROVIDER"); + result.put("provider", "AMAP".equalsIgnoreCase(provider) ? "AMAP" : "TENCENT"); + result.put("tencentWebKey", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); + result.put("amapWebKey", configService.getEnabledValue("MAP", "AMAP_WEB_KEY")); + result.put("amapMiniKey", configService.getEnabledValue("MAP", "AMAP_MINI_KEY")); + return Result.success(result); + } + + @GetMapping("/admin/user-default-password") + @RequirePermission("user:create") + public Result> getUserDefaultPassword(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + String configuredDefaultPassword = configService.getEnabledValue( + AdminDefaultPasswordSupport.CONFIG_GROUP, + AdminDefaultPasswordSupport.CONFIG_KEY + ); + result.put("password", AdminDefaultPasswordSupport.resolveDefaultPassword(configuredDefaultPassword)); + return Result.success(result); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/LegalAgreementDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/LegalAgreementDTO.java new file mode 100644 index 00000000..4f01cd35 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/LegalAgreementDTO.java @@ -0,0 +1,44 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * Purpose: LegalAgreementDTO supports LegalAgreementDTO.java by holding or executing the legal agreement dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementDTO { + + @NotBlank(message = "协议类型不能为空") + /** + * Purpose: agreementType supports LegalAgreementDTO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @NotBlank(message = "协议标题不能为空") + @Size(max = 100, message = "协议标题不能超过100个字符") + /** + * Purpose: title supports LegalAgreementDTO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + @NotBlank(message = "协议版本不能为空") + @Size(max = 40, message = "协议版本不能超过40个字符") + /** + * Purpose: version supports LegalAgreementDTO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @NotBlank(message = "协议内容不能为空") + /** + * Purpose: content supports LegalAgreementDTO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/SystemParameterConfigDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/SystemParameterConfigDTO.java new file mode 100644 index 00000000..e92d45bb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/dto/SystemParameterConfigDTO.java @@ -0,0 +1,58 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * Purpose: SystemParameterConfigDTO supports SystemParameterConfigDTO.java by holding or executing the system parameter config dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigDTO { + + @NotBlank(message = "配置分组不能为空") + @Size(max = 50, message = "配置分组不能超过50个字符") + /** + * Purpose: configGroup supports SystemParameterConfigDTO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + + @NotBlank(message = "配置键不能为空") + @Size(max = 100, message = "配置键不能超过100个字符") + /** + * Purpose: configKey supports SystemParameterConfigDTO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + + @NotBlank(message = "配置名称不能为空") + @Size(max = 100, message = "配置名称不能超过100个字符") + /** + * Purpose: configName supports SystemParameterConfigDTO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + + @Size(max = 1000, message = "配置值不能超过1000个字符") + /** + * Purpose: configValue supports SystemParameterConfigDTO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + + /** + * Purpose: enabled supports SystemParameterConfigDTO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + /** + * Purpose: remark supports SystemParameterConfigDTO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/LegalAgreementDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/LegalAgreementDO.java new file mode 100644 index 00000000..95df01cd --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/LegalAgreementDO.java @@ -0,0 +1,70 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_legal_agreement") +/** + * Purpose: LegalAgreementDO supports LegalAgreementDO.java by holding or executing the legal agreement do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementDO extends BaseEntity { + + @TableField("agreement_type") + /** + * Purpose: agreementType supports LegalAgreementDO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @TableField("title") + /** + * Purpose: title supports LegalAgreementDO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + @TableField("version") + /** + * Purpose: version supports LegalAgreementDO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @TableField("content") + /** + * Purpose: content supports LegalAgreementDO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + @TableField("status") + /** + * Purpose: status supports LegalAgreementDO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + @TableField("effective_time") + /** + * Purpose: effectiveTime supports LegalAgreementDO.java by holding or executing the effective time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime effectiveTime; + + @TableField("is_delete") + @TableLogic + /** + * Purpose: isDelete supports LegalAgreementDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/SystemParameterConfigDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/SystemParameterConfigDO.java new file mode 100644 index 00000000..d2fc3264 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/entity/SystemParameterConfigDO.java @@ -0,0 +1,68 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_system_parameter_config") +/** + * Purpose: SystemParameterConfigDO supports SystemParameterConfigDO.java by holding or executing the system parameter config do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigDO extends BaseEntity { + + @TableField("config_group") + /** + * Purpose: configGroup supports SystemParameterConfigDO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + + @TableField("config_key") + /** + * Purpose: configKey supports SystemParameterConfigDO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + + @TableField("config_name") + /** + * Purpose: configName supports SystemParameterConfigDO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + + @TableField("config_value") + /** + * Purpose: configValue supports SystemParameterConfigDO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + + @TableField("enabled") + /** + * Purpose: enabled supports SystemParameterConfigDO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled; + + @TableField("remark") + /** + * Purpose: remark supports SystemParameterConfigDO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; + + @TableField("is_delete") + @TableLogic + /** + * Purpose: isDelete supports SystemParameterConfigDO.java by holding or executing the is delete business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/LegalAgreementMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/LegalAgreementMapper.java new file mode 100644 index 00000000..90969e12 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/LegalAgreementMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.system.entity.LegalAgreementDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: LegalAgreementMapper supports LegalAgreementMapper.java by holding or executing the legal agreement mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface LegalAgreementMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/SystemParameterConfigMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/SystemParameterConfigMapper.java new file mode 100644 index 00000000..4b19d1ea --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/mapper/SystemParameterConfigMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.system.entity.SystemParameterConfigDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: SystemParameterConfigMapper supports SystemParameterConfigMapper.java by holding or executing the system parameter config mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SystemParameterConfigMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/LegalAgreementService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/LegalAgreementService.java new file mode 100644 index 00000000..1b8e054c --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/LegalAgreementService.java @@ -0,0 +1,37 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.service; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAgreementConsentVO; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * Purpose: LegalAgreementService supports LegalAgreementService.java by holding or executing the legal agreement service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface LegalAgreementService { + + List listAdminAgreements(UserDO currentUser); + + Long createAgreement(UserDO currentUser, LegalAgreementDTO dto); + + Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto); + + Boolean publishAgreement(UserDO currentUser, Long id); + + Boolean disableAgreement(UserDO currentUser, Long id); + + List listCurrentAgreements(); + + LegalAgreementVO getCurrentAgreement(String agreementType); + + UserAgreementConsentVO getMyConsent(Long userId); + + void requireAccepted(AgreementAwareRequest request); + + void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/SystemParameterConfigService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/SystemParameterConfigService.java new file mode 100644 index 00000000..e367147f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/SystemParameterConfigService.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.service; + +import com.xiaowang.fingertipdesigner.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.SystemParameterConfigVO; + +import java.util.List; + +/** + * Purpose: SystemParameterConfigService supports SystemParameterConfigService.java by holding or executing the system parameter config service business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface SystemParameterConfigService { + + List listConfigs(UserDO currentUser, String configGroup); + + Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto); + + String getEnabledValue(String configGroup, String configKey); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/LegalAgreementServiceImpl.java new file mode 100644 index 00000000..9d7596fb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/LegalAgreementServiceImpl.java @@ -0,0 +1,348 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.LegalAgreementDTO; +import com.xiaowang.fingertipdesigner.core.modules.system.entity.LegalAgreementDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.mapper.LegalAgreementMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserAgreementConsentMapper; +import com.xiaowang.fingertipdesigner.core.modules.system.service.LegalAgreementService; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.LegalAgreementVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * Purpose: LegalAgreementServiceImpl supports LegalAgreementServiceImpl.java by holding or executing the legal agreement service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementServiceImpl implements LegalAgreementService { + + /** + * Purpose: USER_TERMS supports LegalAgreementServiceImpl.java by holding or executing the user terms business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String USER_TERMS = "USER_TERMS"; + /** + * Purpose: PRIVACY_POLICY supports LegalAgreementServiceImpl.java by holding or executing the privacy policy business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String PRIVACY_POLICY = "PRIVACY_POLICY"; + + /** + * Purpose: agreementMapper supports LegalAgreementServiceImpl.java by holding or executing the agreement mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementMapper agreementMapper; + /** + * Purpose: consentMapper supports LegalAgreementServiceImpl.java by holding or executing the consent mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UserAgreementConsentMapper consentMapper; + + @Override + /** + * Purpose: listAdminAgreements supports LegalAgreementServiceImpl.java by holding or executing the list admin agreements business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listAdminAgreements(UserDO currentUser) { + ensurePlatformAdmin(currentUser); + return agreementMapper.selectList(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .orderByDesc(LegalAgreementDO::getCreateTime)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: createAgreement supports LegalAgreementServiceImpl.java by holding or executing the create agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long createAgreement(UserDO currentUser, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = new LegalAgreementDO(); + apply(agreement, dto); + agreement.setStatus(0); + agreement.setIsDelete(0); + agreementMapper.insert(agreement); + return agreement.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: updateAgreement supports LegalAgreementServiceImpl.java by holding or executing the update agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + apply(agreement, dto); + agreementMapper.updateById(agreement); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: publishAgreement supports LegalAgreementServiceImpl.java by holding or executing the publish agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean publishAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreementMapper.update(null, new LambdaUpdateWrapper() + .eq(LegalAgreementDO::getAgreementType, agreement.getAgreementType()) + .eq(LegalAgreementDO::getIsDelete, 0) + .set(LegalAgreementDO::getStatus, 0)); + agreement.setStatus(1); + agreement.setEffectiveTime(LocalDateTime.now()); + agreementMapper.updateById(agreement); + return true; + } + + @Override + /** + * Purpose: disableAgreement supports LegalAgreementServiceImpl.java by holding or executing the disable agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean disableAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreement.setStatus(0); + agreementMapper.updateById(agreement); + return true; + } + + @Override + /** + * Purpose: listCurrentAgreements supports LegalAgreementServiceImpl.java by holding or executing the list current agreements business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listCurrentAgreements() { + return List.of(USER_TERMS, PRIVACY_POLICY).stream() + .map(this::getCurrentAgreement) + .collect(Collectors.toList()); + } + + @Override + /** + * Purpose: getCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the get current agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public LegalAgreementVO getCurrentAgreement(String agreementType) { + LegalAgreementDO agreement = findCurrentAgreement(normalizeType(agreementType)); + if (agreement == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + return toVO(agreement); + } + + @Override + /** + * Purpose: getMyConsent supports LegalAgreementServiceImpl.java by holding or executing the get my consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public UserAgreementConsentVO getMyConsent(Long userId) { + Map versions = consentMapper.selectList(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId)) + .stream() + .collect(Collectors.toMap(UserAgreementConsentDO::getAgreementType, UserAgreementConsentDO::getVersion, (left, right) -> right, LinkedHashMap::new)); + return new UserAgreementConsentVO(versions); + } + + @Override + /** + * Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void requireAccepted(AgreementAwareRequest request) { + if (request == null || !Boolean.TRUE.equals(request.getAgreementAccepted())) { + throw new RuntimeException("请先阅读并同意用户协议和隐私政策"); + } + Map versions = request.getAgreementVersions(); + requireVersion(versions, USER_TERMS); + requireVersion(versions, PRIVACY_POLICY); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: recordConsent supports LegalAgreementServiceImpl.java by holding or executing the record consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest) { + if (userId == null || request == null || request.getAgreementVersions() == null) { + return; + } + String clientType = StringUtils.hasText(request.getClientType()) ? request.getClientType().trim().toUpperCase() : "WEB"; + request.getAgreementVersions().forEach((type, version) -> upsertConsent( + userId, + normalizeType(type), + version, + entry, + clientType, + resolveClientIp(httpRequest), + httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) + )); + } + + /** + * Purpose: requireVersion supports LegalAgreementServiceImpl.java by holding or executing the require version business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void requireVersion(Map versions, String type) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + String submittedVersion = versions == null ? null : versions.get(type); + if (!StringUtils.hasText(submittedVersion) || !current.getVersion().equals(submittedVersion.trim())) { + throw new RuntimeException("协议版本已更新,请重新阅读并同意"); + } + } + + /** + * Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { + if (!StringUtils.hasText(version)) { + return; + } + UserAgreementConsentDO existing = consentMapper.selectOne(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId) + .eq(UserAgreementConsentDO::getAgreementType, type) + .last("limit 1")); + UserAgreementConsentDO consent = existing == null ? new UserAgreementConsentDO() : existing; + consent.setUserId(userId); + consent.setAgreementType(type); + consent.setVersion(version.trim()); + consent.setEntry(entry); + consent.setClientType(clientType); + consent.setIpAddress(ip); + consent.setDeviceId(deviceId); + consent.setConsentTime(LocalDateTime.now()); + if (existing == null) { + consentMapper.insert(consent); + } else { + consentMapper.updateById(consent); + } + } + + /** + * Purpose: findCurrentAgreement supports LegalAgreementServiceImpl.java by holding or executing the find current agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementDO findCurrentAgreement(String type) { + return agreementMapper.selectOne(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getAgreementType, normalizeType(type)) + .eq(LegalAgreementDO::getStatus, 1) + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .last("limit 1")); + } + + /** + * Purpose: requireAgreement supports LegalAgreementServiceImpl.java by holding or executing the require agreement business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementDO requireAgreement(Long id) { + LegalAgreementDO agreement = agreementMapper.selectById(id); + if (agreement == null || Integer.valueOf(1).equals(agreement.getIsDelete())) { + throw new RuntimeException("协议不存在"); + } + return agreement; + } + + /** + * Purpose: apply supports LegalAgreementServiceImpl.java by holding or executing the apply business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void apply(LegalAgreementDO agreement, LegalAgreementDTO dto) { + agreement.setAgreementType(normalizeType(dto.getAgreementType())); + agreement.setTitle(dto.getTitle().trim()); + agreement.setVersion(dto.getVersion().trim()); + agreement.setContent(dto.getContent().trim()); + } + + /** + * Purpose: normalizeType supports LegalAgreementServiceImpl.java by holding or executing the normalize type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalizeType(String type) { + if (!StringUtils.hasText(type)) { + throw new RuntimeException("协议类型不能为空"); + } + String normalized = type.trim().toUpperCase(); + if (!USER_TERMS.equals(normalized) && !PRIVACY_POLICY.equals(normalized)) { + throw new RuntimeException("协议类型不正确"); + } + return normalized; + } + + /** + * Purpose: ensurePlatformAdmin supports LegalAgreementServiceImpl.java by holding or executing the ensure platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理协议"); + } + } + + /** + * Purpose: resolveClientIp supports LegalAgreementServiceImpl.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + /** + * Purpose: toVO supports LegalAgreementServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private LegalAgreementVO toVO(LegalAgreementDO agreement) { + LegalAgreementVO vo = new LegalAgreementVO(); + vo.setId(agreement.getId()); + vo.setAgreementType(agreement.getAgreementType()); + vo.setAgreementTypeName(USER_TERMS.equals(agreement.getAgreementType()) ? "用户协议" : "隐私政策"); + vo.setTitle(agreement.getTitle()); + vo.setVersion(agreement.getVersion()); + vo.setContent(agreement.getContent()); + vo.setStatus(agreement.getStatus()); + vo.setStatusText(Integer.valueOf(1).equals(agreement.getStatus()) ? "已发布" : "草稿/停用"); + vo.setEffectiveTime(agreement.getEffectiveTime()); + vo.setCreateTime(agreement.getCreateTime()); + vo.setUpdateTime(agreement.getUpdateTime()); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java new file mode 100644 index 00000000..67926512 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -0,0 +1,140 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.SystemParameterConfigDTO; +import com.xiaowang.fingertipdesigner.core.modules.system.entity.SystemParameterConfigDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.fingertipdesigner.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.fingertipdesigner.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.fingertipdesigner.core.modules.system.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * Purpose: SystemParameterConfigServiceImpl supports SystemParameterConfigServiceImpl.java by holding or executing the system parameter config service impl business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigServiceImpl implements SystemParameterConfigService { + + /** + * Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SystemParameterConfigMapper configMapper; + + @Override + /** + * Purpose: listConfigs supports SystemParameterConfigServiceImpl.java by holding or executing the list configs business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public List listConfigs(UserDO currentUser, String configGroup) { + ensurePlatformAdmin(currentUser); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getIsDelete, 0) + .orderByAsc(SystemParameterConfigDO::getConfigGroup) + .orderByAsc(SystemParameterConfigDO::getConfigKey); + if (StringUtils.hasText(configGroup)) { + wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); + } + return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: saveConfig supports SystemParameterConfigServiceImpl.java by holding or executing the save config business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto) { + ensurePlatformAdmin(currentUser); + String group = normalize(dto.getConfigGroup()); + String key = normalize(dto.getConfigKey()); + if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) { + AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue()); + } + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, group) + .eq(SystemParameterConfigDO::getConfigKey, key) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (config == null) { + config = new SystemParameterConfigDO(); + config.setConfigGroup(group); + config.setConfigKey(key); + config.setIsDelete(0); + } + config.setConfigName(dto.getConfigName().trim()); + config.setConfigValue(StringUtils.hasText(dto.getConfigValue()) ? dto.getConfigValue().trim() : ""); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + if (config.getId() == null) { + configMapper.insert(config); + } else { + configMapper.updateById(config); + } + return true; + } + + @Override + /** + * Purpose: getEnabledValue supports SystemParameterConfigServiceImpl.java by holding or executing the get enabled value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getEnabledValue(String configGroup, String configKey) { + if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { + return ""; + } + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) + .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) + .eq(SystemParameterConfigDO::getEnabled, 1) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + return config == null ? "" : config.getConfigValue(); + } + + /** + * Purpose: ensurePlatformAdmin supports SystemParameterConfigServiceImpl.java by holding or executing the ensure platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理系统参数"); + } + } + + /** + * Purpose: normalize supports SystemParameterConfigServiceImpl.java by holding or executing the normalize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalize(String value) { + return value.trim().toUpperCase(Locale.ROOT); + } + + /** + * Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SystemParameterConfigVO toVO(SystemParameterConfigDO config) { + SystemParameterConfigVO vo = new SystemParameterConfigVO(); + vo.setId(config.getId()); + vo.setConfigGroup(config.getConfigGroup()); + vo.setConfigKey(config.getConfigKey()); + vo.setConfigName(config.getConfigName()); + vo.setConfigValue(config.getConfigValue()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/support/AdminDefaultPasswordSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/support/AdminDefaultPasswordSupport.java new file mode 100644 index 00000000..821c2af3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/support/AdminDefaultPasswordSupport.java @@ -0,0 +1,70 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.support; + +import org.springframework.util.StringUtils; + +import java.util.Locale; + +public final class AdminDefaultPasswordSupport { + + public static final String CONFIG_GROUP = "USER"; + public static final String CONFIG_KEY = "DEFAULT_PASSWORD"; + public static final String FALLBACK_DEFAULT_PASSWORD = "Fingertip@123"; + + private AdminDefaultPasswordSupport() { + } + + public static String resolveCreatePassword(String requestedPassword, String configuredDefaultPassword) { + String resolvedPassword = StringUtils.hasText(requestedPassword) + ? requestedPassword.trim() + : resolveDefaultPassword(configuredDefaultPassword); + validatePasswordStrength(resolvedPassword); + return resolvedPassword; + } + + public static String resolveDefaultPassword(String configuredDefaultPassword) { + if (!StringUtils.hasText(configuredDefaultPassword)) { + return FALLBACK_DEFAULT_PASSWORD; + } + String defaultPassword = configuredDefaultPassword.trim(); + validateDefaultPassword(defaultPassword); + return defaultPassword; + } + + public static void validatePasswordStrength(String password) { + validatePasswordStrength(password, "密码"); + } + + public static void validateDefaultPassword(String password) { + validatePasswordStrength(password, "默认密码"); + } + + public static boolean isDefaultPasswordConfig(String configGroup, String configKey) { + return CONFIG_GROUP.equals(normalize(configGroup)) && CONFIG_KEY.equals(normalize(configKey)); + } + + private static void validatePasswordStrength(String password, String label) { + if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { + throw new RuntimeException(label + "长度需为 8-32 位"); + } + int count = 0; + if (password.matches(".*\\d.*")) { + count++; + } + if (password.matches(".*[a-z].*")) { + count++; + } + if (password.matches(".*[A-Z].*")) { + count++; + } + if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { + count++; + } + if (count < 3) { + throw new RuntimeException(label + "需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); + } + } + + private static String normalize(String value) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : ""; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/LegalAgreementVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/LegalAgreementVO.java new file mode 100644 index 00000000..5922c414 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/LegalAgreementVO.java @@ -0,0 +1,79 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * Purpose: LegalAgreementVO supports LegalAgreementVO.java by holding or executing the legal agreement vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class LegalAgreementVO { + + /** + * Purpose: id supports LegalAgreementVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + + /** + * Purpose: agreementType supports LegalAgreementVO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + /** + * Purpose: agreementTypeName supports LegalAgreementVO.java by holding or executing the agreement type name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementTypeName; + + /** + * Purpose: title supports LegalAgreementVO.java by holding or executing the title business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String title; + + /** + * Purpose: version supports LegalAgreementVO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + /** + * Purpose: content supports LegalAgreementVO.java by holding or executing the content business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String content; + + /** + * Purpose: status supports LegalAgreementVO.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + + /** + * Purpose: statusText supports LegalAgreementVO.java by holding or executing the status text business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String statusText; + + /** + * Purpose: effectiveTime supports LegalAgreementVO.java by holding or executing the effective time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime effectiveTime; + + /** + * Purpose: createTime supports LegalAgreementVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + + /** + * Purpose: updateTime supports LegalAgreementVO.java by holding or executing the update time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/SystemParameterConfigVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/SystemParameterConfigVO.java new file mode 100644 index 00000000..8aa382f0 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/system/vo/SystemParameterConfigVO.java @@ -0,0 +1,59 @@ +package com.xiaowang.fingertipdesigner.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * Purpose: SystemParameterConfigVO supports SystemParameterConfigVO.java by holding or executing the system parameter config vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class SystemParameterConfigVO { + + /** + * Purpose: id supports SystemParameterConfigVO.java by holding or executing the id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long id; + /** + * Purpose: configGroup supports SystemParameterConfigVO.java by holding or executing the config group business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configGroup; + /** + * Purpose: configKey supports SystemParameterConfigVO.java by holding or executing the config key business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configKey; + /** + * Purpose: configName supports SystemParameterConfigVO.java by holding or executing the config name business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configName; + /** + * Purpose: configValue supports SystemParameterConfigVO.java by holding or executing the config value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String configValue; + /** + * Purpose: enabled supports SystemParameterConfigVO.java by holding or executing the enabled business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer enabled; + /** + * Purpose: remark supports SystemParameterConfigVO.java by holding or executing the remark business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String remark; + /** + * Purpose: createTime supports SystemParameterConfigVO.java by holding or executing the create time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime createTime; + /** + * Purpose: updateTime supports SystemParameterConfigVO.java by holding or executing the update time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime updateTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/admin/AdminUserController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/admin/AdminUserController.java new file mode 100644 index 00000000..8ff69dc5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/admin/AdminUserController.java @@ -0,0 +1,519 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.controller.admin; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserBalanceChangeDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserVipOverrideDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserRelationUpdateDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserAssetService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.ShopRoleService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.artist.support.BookableArtistSupport; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.fingertipdesigner.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserStatisticsVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAssetVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/admin/user") +@RequiredArgsConstructor +/** + * AdminUserController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminUserController { + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserAssetService userAssetService; + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BookableArtistSupport bookableArtistSupport; + /** + * Purpose: securityAuditSupport supports AdminUserController.java by holding or executing the security audit support business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditSupport securityAuditSupport; + + @GetMapping("/list") + @RequirePermission("user:view") + public Result> listUsers( + HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Integer type, + @RequestParam(required = false) Long roleId, + @RequestParam(required = false) Long parentUserId, + @RequestParam(required = false) String sourceType, + @RequestParam(required = false) Integer status, + @RequestParam(required = false) String vipLevel, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo, + @RequestParam(required = false) Boolean hasPhone, + @RequestParam(required = false) Boolean hasOrder + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + PageResultVO result = userService.pageUsers(page, size, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder); + return Result.success(result); + } + + @GetMapping("/statistics") + @RequirePermission("user:view") + public Result statisticsUsers(HttpServletRequest request, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Integer type, + @RequestParam(required = false) Long roleId, + @RequestParam(required = false) Long parentUserId, + @RequestParam(required = false) String sourceType, + @RequestParam(required = false) Integer status, + @RequestParam(required = false) String vipLevel, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo, + @RequestParam(required = false) Boolean hasPhone, + @RequestParam(required = false) Boolean hasOrder) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return Result.success(userService.statisticsUsers(keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder)); + } + + @GetMapping("/relation/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyRelation(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.getCurrentUserRelation(userId)); + } + + @GetMapping("/relation/options") + @RequirePermission("user:relation:view") + /** + * Purpose: relationOptions supports AdminUserController.java by holding or executing the relation options business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result> relationOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listRelationOptions(currentUser, shopId)); + } + + @PutMapping("/{id}/relation") + @RequirePermission("user:relation:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateRelation(HttpServletRequest request, @PathVariable Long id, @RequestBody UserRelationUpdateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateUserRelation(currentUser, id, dto)); + } + + @PostMapping("/create") + @RequirePermission("user:create") + @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + userDTO.setShopId(managedShopId); + userDTO.setShopIds(List.of(managedShopId)); + } + Long id = userService.createUser(userDTO); + return Result.success(id); + } + + @PutMapping("/update/{id}") + @RequirePermission("user:edit") + @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = userService.getUserById(id); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureShopAccessible(currentUser, targetUser.getShopId(), "无权编辑其他店铺用户"); + if (userDTO.getType() != null) { + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + } + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + userDTO.setShopId(null); + userDTO.setShopIds(null); + } + boolean success = userService.updateUser(id, userDTO); + return Result.success(success); + } + + @PutMapping("/status/{id}") + @RequirePermission("user:disable") + @OperationGuard(action = "admin-user-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param httpRequest parameter `httpRequest` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateUserStatus(HttpServletRequest httpRequest, @PathVariable Long id, @RequestBody StatusRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(httpRequest); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以停用用户"); + UserVO targetUser = userService.getUserById(id); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权变更其他店铺用户状态"); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许停用"); + } + try { + boolean success = userService.updateUserStatus(id, request.getStatus()); + securityAuditSupport.success(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",status=" + request.getStatus()); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PostMapping("/reset-password/{userId}") + @RequirePermission("user:reset_password") + @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码"); + Long currentUserId = (Long) request.getAttribute("userId"); + try { + boolean success = userService.resetPassword(userId, currentUserId); + securityAuditSupport.success(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @DeleteMapping("/delete/{id}") + @RequirePermission("user:delete") + @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); + UserVO targetUser = userService.getUserById(id); + if (targetUser == null) { + return Result.success(false); + } + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许删除"); + } + try { + boolean success = userService.deleteUser(id); + securityAuditSupport.success(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PutMapping("/unbind/{id}") + @RequirePermission("user:unbind") + @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Run business method `unbindUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = userService.getUserById(id); + if (targetUser == null) { + return Result.success(false); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权解绑其他店铺用户"); + adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许解绑"); + } + try { + boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); + securityAuditSupport.success(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",result=" + success); + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/{id}/asset") + @RequirePermission("user:balance:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getUserAsset(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产"); + UserAssetVO assetVO = userAssetService.getUserAsset(targetUser.getId()); + return Result.success(assetVO); + } + + @GetMapping("/{id}/balance/history") + @RequirePermission("user:balance:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水"); + List history = userAssetService.listBalanceHistory(targetUser.getId()); + return Result.success(history); + } + + @PostMapping("/{id}/balance/change") + @RequirePermission("user:balance:manage") + @OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result changeUserBalance( + HttpServletRequest request, + @PathVariable Long id, + @RequestBody AdminUserBalanceChangeDTO balanceChangeDTO + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额"); + try { + UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO); + securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id); + return Result.success(assetVO); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PostMapping("/{id}/vip/override") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + public Result overrideUserVip( + HttpServletRequest request, + @PathVariable Long id, + @RequestBody AdminUserVipOverrideDTO vipOverrideDTO + ) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP"); + try { + UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO); + securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id); + return Result.success(assetVO); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @PostMapping("/{id}/vip/recalculate") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Run business method `recalculateUserVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); + try { + UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId()); + securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id); + return Result.success(assetVO); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage()); + throw exception; + } + } + + @GetMapping("/info") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getUserInfo(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + UserVO userVO = userService.getUserById(userId); + return Result.success(userVO); + } + + /** + * 获取所有用户 + * @return 用户列表 + */ + @GetMapping("/list/all") + @RequirePermission("user:view") + public Result> listAllUsers(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List users = adminScopeHelper.isPlatformAdmin(currentUser) + ? userService.listAllUsers() + : userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser)); + return Result.success(users); + } + + /** + * 获取美甲师列表 + * @param shopId 店铺ID(可选) + * @return 美甲师列表 + */ + @GetMapping("/list/artists") + @RequirePermission("user:view") + public Result> listArtists(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + final Long resolvedScopeShopId = shopId; + List artists = userService.listAllUsers().stream() + .filter(user -> Integer.valueOf(2).equals(user.getType()) || Integer.valueOf(3).equals(user.getType())) + .filter(user -> bookableArtistSupport.isValidBookableArtist(resolvedScopeShopId, user.getId())) + .collect(Collectors.toList()); + // 用户类型 3 表示美甲师 + // 如果指定了店铺ID,则过滤该店铺的美甲师 + if (shopId != null) { + final Long resolvedShopId = shopId; + artists = artists.stream() + .filter(artist -> artist.getShopIds() != null && artist.getShopIds().contains(resolvedShopId)) + .collect(Collectors.toList()); + } + return Result.success(artists); + } + + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ + private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); + return targetUser; + } + + @Data + /** + * Purpose: StatusRequest supports AdminUserController.java by holding or executing the status request business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class StatusRequest { + /** + * Purpose: status supports AdminUserController.java by holding or executing the status business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer status; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/front/UserController.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/front/UserController.java new file mode 100644 index 00000000..4aad58b7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/controller/front/UserController.java @@ -0,0 +1,1069 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.controller.front; + +import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission; +import com.xiaowang.fingertipdesigner.core.annotation.OperationGuard; +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.common.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.content.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.file.service.ChunkUploadService; +import com.xiaowang.fingertipdesigner.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.fingertipdesigner.core.modules.file.vo.ChunkUploadSessionVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAssetVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.InviteCodeVO; +import com.xiaowang.fingertipdesigner.core.modules.integration.vo.WechatMiniLoginResultVO; +import com.xiaowang.fingertipdesigner.core.modules.file.service.PrimaryObjectStorageService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserAssetService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.ShopRoleService; +import com.xiaowang.fingertipdesigner.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.fingertipdesigner.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.fingertipdesigner.core.modules.system.service.LegalAgreementService; +import com.xiaowang.fingertipdesigner.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.support.security.RequestThrottleService; +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import com.xiaowang.fingertipdesigner.core.support.security.OperationGuardStrategy; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import org.springframework.web.multipart.MultipartFile; +import javax.validation.Valid; +import javax.servlet.http.HttpServletRequest; +import java.io.FileInputStream; +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RefreshTokenRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.SendVerificationCodeRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.SwitchShopRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadCompleteRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.ChunkUploadInitRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAgreementConsentVO; +/** + * 系统用户信息表 Controller + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@RestController +@RequestMapping("/user") +@RequiredArgsConstructor +public class UserController { + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserService userService; + /** + * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserAssetService userAssetService; + /** + * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PrimaryObjectStorageService primaryObjectStorageService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ChunkUploadService chunkUploadService; + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VerificationCodeService verificationCodeService; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniAuthService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniAuthService wechatMiniAuthService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final RequestThrottleService requestThrottleService; + /** + * Purpose: legalAgreementService supports UserController.java by holding or executing the legal agreement service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LegalAgreementService legalAgreementService; + /** + * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final SecurityAuditLogService securityAuditLogService; + + /** + * 创建用户 + * + * @param userDTO 用户DTO + * @return 用户ID + */ + @PostMapping("/create") + @RequirePermission("user:create") + @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + userDTO.setShopId(managedShopId); + userDTO.setShopIds(List.of(managedShopId)); + } + Long id = userService.createUser(userDTO); + return Result.success(id); + } + + /** + * 更新用户 + * + * @param id 用户ID + * @param userDTO 用户DTO + * @return 是否更新成功 + */ + @PutMapping("/update/{id}") + @RequirePermission("user:edit") + @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权编辑其他店铺用户"); + if (userDTO.getType() != null) { + adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); + } + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + userDTO.setShopId(null); + userDTO.setShopIds(null); + } + boolean success = userService.updateUser(id, userDTO); + return Result.success(success); + } + + /** + * 删除用户 + * + * @param id 用户ID + * @return 是否删除成功 + */ + @DeleteMapping("/delete/{id}") + @RequirePermission("user:delete") + @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权删除其他店铺用户"); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许删除"); + } + boolean success = userService.deleteUser(id); + return Result.success(success); + } + + @PutMapping("/unbind/{id}") + @RequirePermission("user:unbind") + @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + /** + * Run business method `unbindUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户"); + adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); + if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员账号不允许解绑"); + } + boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); + return Result.success(success); + } + + @GetMapping("/asset/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyAsset(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.getUserAsset(userId)); + } + + @GetMapping("/balance/history/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getMyBalanceHistory(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.listBalanceHistory(userId)); + } + + /** + * 根据ID查询用户 + * + * @param id 用户ID + * @return 用户VO + */ + @GetMapping("/get/{id}") + @RequirePermission("user:view") + public Result getUserById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO userVO = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户"); + return Result.success(userVO); + } + + /** + * 查询所有用户 + * + * @return 用户VO列表 + */ + @GetMapping("/list/all") + @RequirePermission("user:view") + public Result> listAllUsers(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List userVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? userService.listAllUsers() + : userService.listUsersByShopId(adminScopeHelper.getManagedShopId(currentUser)); + return Result.success(userVOs); + } + + /** + * 根据店铺ID查询用户 + * + * @param shopId 店铺ID + * @return 用户VO列表 + */ + @GetMapping("/list/shop/{shopId}") + @RequirePermission("user:view") + public Result> listUsersByShopId(HttpServletRequest request, @PathVariable Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List userVOs = userService.listUsersByShopId(shopId); + return Result.success(userVOs); + } + + /** + * 根据用户类型查询用户 + * + * @param type 用户类型 + * @return 用户VO列表 + */ + @GetMapping("/list/type/{type}") + public Result> listUsersByType(@PathVariable Integer type) { + if (!Integer.valueOf(3).equals(type)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅支持查询可预约的美甲师列表"); + } + List userVOs = userService.listUsersByType(type).stream() + .filter(user -> Integer.valueOf(1).equals(user.getStatus())) + .map(this::sanitizePublicArtist) + .collect(Collectors.toList()); + return Result.success(userVOs); + } + + /** + * 根据账号查询用户 + * + * @param account 账号 + * @return 用户VO + */ + @GetMapping("/get/account/{account}") + @RequirePermission("user:view") + public Result getUserByAccount(HttpServletRequest request, @PathVariable String account) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + UserVO userVO = userService.getUserByAccount(AccountValidationUtils.requireValidAccount(account)); + if (userVO != null) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "无权查看其他店铺用户"); + } + return Result.success(userVO); + } + + @GetMapping("/check/account/{account}") + /** + * Run business method `checkAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkAccountAvailability(@PathVariable String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); + String message = available ? "账号可用" : "账号已被注册"; + return Result.success(new AvailabilityVO(available, message)); + } + + @GetMapping("/check/login-account/{account}") + /** + * Run business method `checkLoginAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkLoginAccountAvailability(@PathVariable String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + boolean exists = userDO != null; + String nickname = exists ? userDO.getNickname() : null; + String message = exists + ? (nickname != null && !nickname.isEmpty() ? "该账号已注册,昵称:" + nickname : "该账号已注册,可继续登录") + : "该账号不存在"; + return Result.success(new LoginAccountAvailabilityVO(exists, nickname, message)); + } + + @GetMapping("/check/login-shops/account/{account}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getLoginShopsByAccount(@PathVariable String account) { + return Result.success(userService.getLoginShopSelectionByAccount(AccountValidationUtils.requireValidAccount(account))); + } + + @GetMapping("/check/login-shops/phone/{phone}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getLoginShopsByPhone(@PathVariable String phone) { + return Result.success(userService.getLoginShopSelectionByPhone(phone)); + } + + @GetMapping("/check/phone/{phone}") + /** + * Run business method `checkPhoneAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result checkPhoneAvailability(@PathVariable String phone) { + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + ); + boolean available = userDO == null; + String message = available ? "手机号可用" : "该手机号已被注册"; + return Result.success(new AvailabilityVO(available, message)); + } + + /** + * 用户登录 + * + * @param loginRequestDTO 登录请求DTO + * @return 登录响应VO + */ + @PostMapping("/login") + @OperationGuard(action = "user-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { + requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); + legalAgreementService.requireAccepted(loginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.login(loginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), loginRequestDTO, "USER_PASSWORD_LOGIN", request); + requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "USER_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(null, loginRequestDTO.getAccount(), "USER_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + /** + * 手机号验证码登录 + * + * @param phoneLoginRequestDTO 手机号验证码登录请求DTO + * @return 登录响应VO + */ + @PostMapping("/phone-login") + @OperationGuard(action = "user-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result phoneLogin(HttpServletRequest request, @RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) { + requestThrottleService.checkLogin(request, phoneLoginRequestDTO.getPhone()); + legalAgreementService.requireAccepted(phoneLoginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO, "USER_PHONE_LOGIN", request); + requestThrottleService.clearLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(null, phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @PostMapping("/wechat-mini/auto-login") + @OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `wechatMiniAutoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); + } + + @PostMapping("/wechat-mini/phone-login") + @OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `wechatMiniPhoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result wechatMiniPhoneLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, "wechat-mini-phone"); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.phoneLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_PHONE_LOGIN", request); + return Result.success(result); + } + + @PostMapping("/wechat-mini/confirm-login") + @OperationGuard(action = "wechat-mini-confirm-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `confirmWechatMiniLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result confirmWechatMiniLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, requestDTO.getTicket()); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.confirmLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_CONFIRM_LOGIN", request); + return Result.success(result); + } + + @PostMapping("/switch-shop") + @OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); + } + + /** + * 用户注册 + * + * @param registerRequestDTO 注册请求DTO + * @return 是否注册成功 + */ + @PostMapping("/register") + @OperationGuard(action = "user-register", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result register(HttpServletRequest request, @Valid @RequestBody RegisterRequestDTO registerRequestDTO) { + requestThrottleService.checkRegister(request, registerRequestDTO.getAccount()); + legalAgreementService.requireAccepted(registerRequestDTO); + try { + boolean success = userService.register(registerRequestDTO); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO != null) { + legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); + securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); + } + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditLogService.record(null, registerRequestDTO.getAccount(), "USER_REGISTER", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @GetMapping("/relation/me") + /** + * Run business method `relationMe`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result relationMe(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.getCurrentUserRelation(userId)); + } + + @GetMapping("/invite-code/resolve") + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resolveInviteCode(@RequestParam String code) { + return Result.success(shopRoleService.resolveInviteCode(code)); + } + + /** + * 发送验证码 + * + * @param sendVerificationCodeRequestDTO 发送验证码请求DTO + * @return 是否发送成功 + */ + @PostMapping("/send-verification-code") + @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") + public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { + requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); + if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 1 parameter `1` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); + } + verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); + return Result.success(true); + } + + /** + * 通过手机号验证码重置密码 + * + * @param resetPasswordRequestDTO 重置密码请求DTO + * @return 是否重置成功 + */ + @PostMapping("/reset-password-by-phone") + @OperationGuard(action = "reset-password-by-phone", ttlSeconds = 8, message = "操作进行中,请勿重复点击") + public Result resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { + requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone()); + boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO); + securityAuditLogService.record(null, resetPasswordRequestDTO.getPhone(), "RESET_PASSWORD_BY_PHONE", success ? "SUCCESS" : "FAIL", null, request); + return Result.success(success); + } + + /** + * 刷新Token + * + * @param refreshTokenRequestDTO 刷新Token请求DTO + * @return 新的Token + */ + @PostMapping("/refresh-token") + public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { + LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); + return Result.success(loginResponseVO); + } + + /** + * 用户登出 + * + * @return 是否登出成功 + */ + @PostMapping("/logout") + @OperationGuard(action = "user-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + public Result logout(HttpServletRequest request) { + boolean success = userService.logout((String) request.getAttribute("sessionId")); + return Result.success(success); + } + + @GetMapping("/agreement-consent/me") + public Result getMyAgreementConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } + + private void recordWechatConsentIfLoggedIn(WechatMiniLoginResultVO result, + com.xiaowang.fingertipdesigner.core.common.dto.AgreementAwareRequest dto, + String entry, + HttpServletRequest request) { + if (result != null && result.getUserInfo() != null) { + legalAgreementService.recordConsent(result.getUserInfo().getId(), dto, entry, request); + securityAuditLogService.record(result.getUserInfo().getId(), null, entry, "SUCCESS", null, request); + } + } + + /** + * 获取当前用户信息 + * + * @return 用户VO + */ + @GetMapping("/info") + public Result getCurrentUserInfo(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + UserVO userVO = userService.getUserById(userId); + return Result.success(userVO); + } + + /** + * 更新当前用户信息 + * + * @param userDTO 用户DTO + * @return 是否更新成功 + */ + @PutMapping({"/update", "/info"}) + @OperationGuard(action = "user-update-info", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateCurrentUserInfo(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updateCurrentUserInfo(userId, userDTO); + return Result.success(success); + } + + /** + * 绑定手机号 + * + * @param bindPhoneRequestDTO 绑定手机号请求DTO + * @return 是否绑定成功 + */ + @PostMapping("/bind-phone") + @OperationGuard(action = "user-bind-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result bindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO bindPhoneRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.bindPhone(userId, bindPhoneRequestDTO); + return Result.success(success); + } + + /** + * 绑定邮箱 + * + * @param bindEmailRequestDTO 绑定邮箱请求DTO + * @return 是否绑定成功 + */ + @PostMapping("/bind-email") + @OperationGuard(action = "user-bind-email", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result bindEmail(HttpServletRequest request, @RequestBody BindEmailRequestDTO bindEmailRequestDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.bindEmail(userId, bindEmailRequestDTO); + return Result.success(success); + } + + /** + * 上传头像 + * + * @param file 头像文件 + * @return 头像URL + */ + @PostMapping("/upload-avatar/init") + @OperationGuard(action = "user-avatar-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO)); + } + + @PostMapping("/upload-avatar/chunk") + @OperationGuard(action = "user-avatar-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadAvatarChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.uploadUserAvatarChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-avatar/complete") + @OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + + String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + userService.updateUserAvatar(userId, avatarUrl); + chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("头像上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-avatar/{uploadId}") + @OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearUserAvatarUpload(userId, uploadId); + return Result.success(true); + } + + @PostMapping("/upload-avatar") + @OperationGuard(action = "user-avatar-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Purpose: uploadAvatar supports UserController.java by holding or executing the upload avatar business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Result uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + try { + Long userId = (Long) request.getAttribute("userId"); + String originalFilename = file.getOriginalFilename(); + String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + + String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName); + userService.updateUserAvatar(userId, avatarUrl); + + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("头像上传失败: " + e.getMessage()); + } + } + + /** + * 重置用户密码为88888888 + * + * @param userId 目标用户ID + * @return 是否重置成功 + */ + /** + * 上传个人资料图片,不直接修改头像或资料字段。 + */ + @PostMapping("/upload-profile-image/init") + @OperationGuard(action = "user-profile-image-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(chunkUploadService.initUserProfileImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-profile-image/chunk") + @OperationGuard(action = "user-profile-image-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadProfileImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.uploadUserProfileImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-profile-image/complete") + @OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = ""; + if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { + fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + } + String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("资料图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-profile-image/{uploadId}") + @OperationGuard(action = "user-profile-image-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result cancelProfileImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearUserProfileImageUpload(userId, uploadId); + return Result.success(true); + } + + @PostMapping("/upload-profile-image") + @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + try { + if (file == null || file.isEmpty()) { + return Result.error("请选择要上传的图片"); + } + Long userId = (Long) request.getAttribute("userId"); + String originalFilename = file.getOriginalFilename(); + String fileExtension = ""; + if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { + fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + } + String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + String imageUrl = primaryObjectStorageService.uploadFile(file, objectName); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("资料图片上传失败: " + e.getMessage()); + } + } + + /** + * 重置用户密码。 + */ + @PostMapping("/reset-password/{userId}") + @RequirePermission("user:reset_password") + @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码"); + Long currentUserId = (Long) request.getAttribute("userId"); + boolean success = userService.resetPassword(userId, currentUserId); + return Result.success(success); + } + + /** + * 更新用户密码 + * + * @param request 请求对象 + * @param passwordDTO 密码DTO + * @return 是否更新成功 + */ + @PutMapping("/password") + @OperationGuard(action = "user-update-password", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updatePassword(HttpServletRequest request, @RequestBody PasswordDTO passwordDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updatePassword(userId, passwordDTO.getPassword(), passwordDTO.getVerificationCode()); + return Result.success(success); + } + + /** + * 修改手机号 + * + * @param request 请求对象 + * @param updatePhoneDTO 修改手机号DTO + * @return 是否修改成功 + */ + @PutMapping("/phone") + @OperationGuard(action = "user-update-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updatePhone(HttpServletRequest request, @RequestBody UpdatePhoneRequestDTO updatePhoneDTO) { + Long userId = (Long) request.getAttribute("userId"); + boolean success = userService.updatePhone(userId, updatePhoneDTO); + return Result.success(success); + } + + /** + * 注销账号 + * + * @param request 请求对象 + * @return 是否注销成功 + */ + @DeleteMapping("/deactivate") + @OperationGuard(action = "user-deactivate", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + public Result deactivateAccount(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + + // 获取用户信息 + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + return Result.error("用户不存在"); + } + + // 管理员账号无法注销 + if (userDO.getType() == 4) { + return Result.error("管理员账号无法注销"); + } + + boolean success = userService.deleteUser(userId); + return Result.success(success); + } + + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ + private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { + UserVO targetUser = userService.getUserById(userId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); + return targetUser; + } + + /** + * Run business method `sanitizePublicArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ + private UserVO sanitizePublicArtist(UserVO userVO) { + UserVO sanitized = new UserVO(); + sanitized.setId(userVO.getId()); + sanitized.setShopId(userVO.getShopId()); + sanitized.setShopName(userVO.getShopName()); + sanitized.setShopIds(userVO.getShopIds()); + sanitized.setShopNames(userVO.getShopNames()); + sanitized.setNickname(userVO.getNickname()); + sanitized.setAvatar(userVO.getAvatar()); + sanitized.setType(userVO.getType()); + sanitized.setStatus(userVO.getStatus()); + sanitized.setCreateTime(userVO.getCreateTime()); + sanitized.setUpdateTime(userVO.getUpdateTime()); + return sanitized; + } + + @Data + /** + * Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class PasswordDTO { + /** + * Purpose: password supports UserController.java by holding or executing the password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String password; + /** + * Purpose: verificationCode supports UserController.java by holding or executing the verification code business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String verificationCode; + } + + @Data + /** + * Purpose: AvailabilityVO supports UserController.java by holding or executing the availability vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class AvailabilityVO { + /** + * Variable `available`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final boolean available; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String message; + } + + @Data + /** + * Purpose: LoginAccountAvailabilityVO supports UserController.java by holding or executing the login account availability vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class LoginAccountAvailabilityVO { + /** + * Variable `exists`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final boolean exists; + /** + * Variable `nickname`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String nickname; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final String message; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserBalanceChangeDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserBalanceChangeDTO.java new file mode 100644 index 00000000..e3be6d54 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserBalanceChangeDTO.java @@ -0,0 +1,38 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +/** + * AdminUserBalanceChangeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AdminUserBalanceChangeDTO { + + /** + * Field `amount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal amount; + + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String changeScene; + + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long relatedOrderId; + + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String externalOrderNo; + + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserVipOverrideDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserVipOverrideDTO.java new file mode 100644 index 00000000..e5f5dbae --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/AdminUserVipOverrideDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.dto; + +import lombok.Data; + +@Data +/** + * AdminUserVipOverrideDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AdminUserVipOverrideDTO { + + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/InviteCodeDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/InviteCodeDTO.java new file mode 100644 index 00000000..6ed4e8da --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/InviteCodeDTO.java @@ -0,0 +1,41 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @NotBlank(message = "邀请码不能为空") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserDTO.java new file mode 100644 index 00000000..05acd9a3 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserDTO.java @@ -0,0 +1,95 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.dto; + +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import lombok.Data; + +import javax.validation.constraints.Pattern; +import java.time.LocalDate; +import java.util.List; + +/** + * 系统用户信息表 DTO + * 用于用户信息的传输 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class UserDTO { + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + private Long shopId; + + /** + * 绑定店铺ID列表 + */ + private List shopIds; + + /** + * 用户昵称 + */ + private String nickname; + + /** + * 用户账号(登录用) + */ + @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + private String account; + + /** + * 用户密码(加密存储) + */ + private String password; + + /** + * 用户头像URL + */ + private String avatar; + + /** + * 用户签名 + */ + private String signature; + + /** + * 用户等级 + */ + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + private Integer type; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + private Long vipId; + + /** + * 手机号 + */ + private String phone; + + /** + * 联系电话 + */ + private String contactPhone; + + /** + * 生日 + */ + private LocalDate birthday; + + /** + * 微信号 + */ + private String wechatId; + + /** + * 微信二维码 + */ + private String wechatQrCode; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserRelationUpdateDTO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserRelationUpdateDTO.java new file mode 100644 index 00000000..b5e2a8bb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/dto/UserRelationUpdateDTO.java @@ -0,0 +1,27 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.dto; + +import lombok.Data; + +@Data +/** + * UserRelationUpdateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationUpdateDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserAgreementConsentDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserAgreementConsentDO.java new file mode 100644 index 00000000..89a0f643 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserAgreementConsentDO.java @@ -0,0 +1,75 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Getter +@Setter +@TableName("t_user_agreement_consent") +/** + * Purpose: UserAgreementConsentDO supports UserAgreementConsentDO.java by holding or executing the user agreement consent do business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UserAgreementConsentDO extends BaseEntity { + + @TableField("user_id") + /** + * Purpose: userId supports UserAgreementConsentDO.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + + @TableField("agreement_type") + /** + * Purpose: agreementType supports UserAgreementConsentDO.java by holding or executing the agreement type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String agreementType; + + @TableField("version") + /** + * Purpose: version supports UserAgreementConsentDO.java by holding or executing the version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String version; + + @TableField("entry") + /** + * Purpose: entry supports UserAgreementConsentDO.java by holding or executing the entry business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String entry; + + @TableField("client_type") + /** + * Purpose: clientType supports UserAgreementConsentDO.java by holding or executing the client type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String clientType; + + @TableField("ip_address") + /** + * Purpose: ipAddress supports UserAgreementConsentDO.java by holding or executing the ip address business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String ipAddress; + + @TableField("device_id") + /** + * Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String deviceId; + + @TableField("consent_time") + /** + * Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private LocalDateTime consentTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserDO.java new file mode 100644 index 00000000..e1d2fd33 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserDO.java @@ -0,0 +1,148 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; +import lombok.EqualsAndHashCode; + +import java.time.LocalDate; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +/** + * 系统用户信息表 DO + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = true) +@TableName("t_user") +public class UserDO extends BaseEntity { + + /** + * 用户唯一主键ID(雪花ID) + */ + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + @TableField("shop_id") + private Long shopId; + + /** + * 用户昵称 + */ + @TableField("nickname") + private String nickname; + + /** + * 用户账号(登录用) + */ + @TableField("account") + private String account; + + /** + * 手机号 + */ + @TableField("phone") + private String phone; + + /** + * 联系电话 + */ + @TableField("contact_phone") + private String contactPhone; + + /** + * 生日 + */ + @TableField("birthday") + private LocalDate birthday; + + /** + * 微信号 + */ + @TableField("wechat_id") + private String wechatId; + + /** + * 微信二维码 + */ + @TableField("wechat_qr_code") + private String wechatQrCode; + + /** + * 邮箱 + */ + @TableField("email") + private String email; + + /** + * 手机号是否已验证:0-未验证,1-已验证 + */ + @TableField("phone_verified") + private Integer phoneVerified; + + /** + * 邮箱是否已验证:0-未验证,1-已验证 + */ + @TableField("email_verified") + private Integer emailVerified; + + /** + * 用户密码(加密存储) + */ + @TableField("password") + private String password; + + /** + * 用户头像URL + */ + @TableField("avatar") + private String avatar; + + /** + * 用户签名 + */ + @TableField("signature") + private String signature; + + /** + * 用户等级 + */ + @TableField("level") + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + @TableField("type") + private Integer type; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + @TableField("vip_id") + private Long vipId; + + /** + * 逻辑删除:0-未删,1-已删 + */ + @TableField("is_delete") + @TableLogic + private Integer isDelete; + + /** + * 用户状态:1-正常,0-禁用 + */ + @TableField("status") + private Integer status; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserGrowthRecordDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserGrowthRecordDO.java new file mode 100644 index 00000000..793b77b9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserGrowthRecordDO.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_growth_record") +public class UserGrowthRecordDO extends BaseEntity { + @TableField("user_id") + private Long userId; + @TableField("source_type") + private String sourceType; + @TableField("source_id") + private Long sourceId; + @TableField("growth_value") + private Integer growthValue; + @TableField("remark") + private String remark; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserInviteCodeDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserInviteCodeDO.java new file mode 100644 index 00000000..78cbccee --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserInviteCodeDO.java @@ -0,0 +1,63 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_invite_code") +/** + * UserInviteCodeDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserInviteCodeDO extends BaseEntity { + + @TableField("invite_code") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + @TableField("owner_user_id") + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("use_count") + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + + @TableField("expire_time") + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserRelationDO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserRelationDO.java new file mode 100644 index 00000000..000347a7 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/entity/UserRelationDO.java @@ -0,0 +1,61 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity; +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_relation") +/** + * UserRelationDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("parent_user_id") + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + + @TableField("parent_role_type") + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + + @TableField("source_type") + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserAgreementConsentMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserAgreementConsentMapper.java new file mode 100644 index 00000000..7872447b --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserAgreementConsentMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserAgreementConsentDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * Purpose: UserAgreementConsentMapper supports UserAgreementConsentMapper.java by holding or executing the user agreement consent mapper business role. + * Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state. + */ +public interface UserAgreementConsentMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserGrowthRecordMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserGrowthRecordMapper.java new file mode 100644 index 00000000..1c9c34bb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserGrowthRecordMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserGrowthRecordDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserGrowthRecordMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserInviteCodeMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserInviteCodeMapper.java new file mode 100644 index 00000000..7624d9a8 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserInviteCodeMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserInviteCodeDO; + +/** + * UserInviteCodeMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserInviteCodeMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserMapper.java new file mode 100644 index 00000000..2d2a3270 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserMapper.java @@ -0,0 +1,14 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; + +/** + * 系统用户信息表 Mapper + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +public interface UserMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserRelationMapper.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserRelationMapper.java new file mode 100644 index 00000000..b467d225 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/mapper/UserRelationMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserRelationDO; + +/** + * UserRelationMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserRelationMapper extends BaseMapper { +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserAssetService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserAssetService.java new file mode 100644 index 00000000..c885d513 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserAssetService.java @@ -0,0 +1,60 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.service; + +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserBalanceChangeDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserVipOverrideDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAssetVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * UserAssetService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface UserAssetService { + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO getUserAsset(Long userId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listBalanceHistory(Long userId); + + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request); + + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request); + + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + UserAssetVO recalculateVip(Long operatorId, Long userId); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserService.java new file mode 100644 index 00000000..2c733c9e --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/UserService.java @@ -0,0 +1,397 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningManagerRegisterDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserStatisticsVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; + +import java.util.List; +import com.xiaowang.fingertipdesigner.core.common.Result; +/** + * UserService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface UserService extends IService { + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDTO parameter `userDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createUser(UserDTO userDTO); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUser(Long id, UserDTO userDTO); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteUser(Long id); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getUserById(Long id); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + List listAllUsers(); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listUsersByShopId(Long shopId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listUsersByType(Integer type); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getUserByAccount(String account); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO login(LoginRequestDTO loginRequestDTO); + + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO loginByVerifiedPhone(String phone, Long shopId); + + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO loginByUserId(Long userId, Long shopId); + + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getLoginShopSelectionByAccount(String account); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getLoginShopSelectionByPhone(String phone); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + LoginShopSelectionVO getAdminLoginShopSelection(String account); + + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId); + + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId); + + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + void syncManagedPermissions(Long userId); + + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean register(RegisterRequestDTO registerRequestDTO); + + LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO); + + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + LoginResponseVO refreshToken(String refreshToken); + + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean logout(String sessionId); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ + UserVO getCurrentUserInfo(); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateCurrentUserInfo(Long userId, UserDTO userDTO); + + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); + + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO); + + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean resetPassword(Long targetUserId, Long currentUserId); + + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + UserRelationVO getCurrentUserRelation(Long userId); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserStatus(Long id, Integer status); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserStatusInShop(Long id, Integer status, Long shopId); + + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean deleteUserInShop(Long id, Long shopId); + + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean unbindUserInShop(Long id, Long shopId); + + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updateUserAvatar(Long userId, String avatarUrl); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updatePassword(Long userId, String password, String verificationCode); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserAssetServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserAssetServiceImpl.java new file mode 100644 index 00000000..e1388c93 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserAssetServiceImpl.java @@ -0,0 +1,631 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserBalanceChangeDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.AdminUserVipOverrideDTO; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceChangeDetailDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.entity.BalanceDO; +import com.xiaowang.fingertipdesigner.core.modules.order.entity.OrderDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipBenefitDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipInfoDO; +import com.xiaowang.fingertipdesigner.core.modules.marketing.entity.VipRechargePlanDO; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.BalanceChangeDetailMapper; +import com.xiaowang.fingertipdesigner.core.modules.payment.mapper.BalanceMapper; +import com.xiaowang.fingertipdesigner.core.modules.order.mapper.OrderMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipBenefitMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipInfoMapper; +import com.xiaowang.fingertipdesigner.core.modules.marketing.mapper.VipRechargePlanMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserAssetService; +import com.xiaowang.fingertipdesigner.core.modules.payment.vo.BalanceChangeDetailVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserAssetVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.marketing.service.impl.VipRechargePlanServiceImpl; +@Service +@RequiredArgsConstructor +/** + * UserAssetServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class UserAssetServiceImpl implements UserAssetService { + + /** + * Purpose: VIP_LEVEL_NORMAL supports UserAssetServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Purpose: SCENE_RECHARGE supports UserAssetServiceImpl.java by holding or executing the scene recharge business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_RECHARGE = "RECHARGE"; + /** + * Purpose: SCENE_MANUAL_ADD supports UserAssetServiceImpl.java by holding or executing the scene manual add business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_MANUAL_ADD = "MANUAL_ADD"; + /** + * Purpose: SCENE_MANUAL_DEDUCT supports UserAssetServiceImpl.java by holding or executing the scene manual deduct business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_MANUAL_DEDUCT = "MANUAL_DEDUCT"; + /** + * Purpose: SCENE_ORDER_CONSUME supports UserAssetServiceImpl.java by holding or executing the scene order consume business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_ORDER_CONSUME = "ORDER_CONSUME"; + /** + * Purpose: SCENE_ORDER_REFUND supports UserAssetServiceImpl.java by holding or executing the scene order refund business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SCENE_ORDER_REFUND = "ORDER_REFUND"; + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceMapper balanceMapper; + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BalanceChangeDetailMapper balanceChangeDetailMapper; + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipInfoMapper vipInfoMapper; + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipBenefitMapper vipBenefitMapper; + /** + * Purpose: vipRechargePlanMapper supports UserAssetServiceImpl.java by holding or executing the vip recharge plan mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final VipRechargePlanMapper vipRechargePlanMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO getUserAsset(Long userId) { + UserDO user = getAvailableUser(userId); + BalanceDO balance = ensureBalance(userId); + VipInfoDO vipInfo = getVipInfo(userId); + VipBenefitDO benefit = vipInfo != null && vipInfo.getBenefitId() != null + ? vipBenefitMapper.selectById(vipInfo.getBenefitId()) + : null; + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toAssetVO(user, balance, vipInfo, benefit); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listBalanceHistory(Long userId) { + UserDO user = getAvailableUser(userId); + return balanceChangeDetailMapper.selectList( + Wrappers.lambdaQuery(BalanceChangeDetailDO.class) + .eq(BalanceChangeDetailDO::getUserId, userId) + .orderByDesc(BalanceChangeDetailDO::getChangeTime) + .orderByDesc(BalanceChangeDetailDO::getId)) + .stream() + .map(detail -> toBalanceHistoryVO(detail, user.getNickname())) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request) { + if (request == null || request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("变动金额必须大于 0"); + } + if (!StringUtils.hasText(request.getChangeScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("变动场景不能为空"); + } + + UserDO user = getAvailableUser(userId); + BalanceDO balance = ensureBalance(userId); + LocalDateTime now = LocalDateTime.now(); + + BigDecimal beforeBalance = defaultDecimal(balance.getAmount()); + BigDecimal delta = normalizeDelta(request.getAmount(), request.getChangeScene()); + BigDecimal afterBalance = beforeBalance.add(delta); + if (afterBalance.compareTo(BigDecimal.ZERO) < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("余额不足,无法执行扣减"); + } + + OrderDO relatedOrder = null; + String relatedOrderNo = null; + if (request.getRelatedOrderId() != null) { + relatedOrder = orderMapper.selectById(request.getRelatedOrderId()); + if (relatedOrder == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("关联系统订单不存在"); + } + if (!userId.equals(relatedOrder.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("所选订单不属于当前用户"); + } + relatedOrderNo = relatedOrder.getOrderNo(); + } + + if (isDeductScene(request.getChangeScene()) + && relatedOrder == null + && !StringUtils.hasText(request.getExternalOrderNo())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("扣减余额时必须关联系统订单或填写外部订单号"); + } + + balance.setAmount(afterBalance); + balance.setLastUpdateTime(now); + if (SCENE_RECHARGE.equals(request.getChangeScene())) { + balance.setTotalRechargeAmount(defaultDecimal(balance.getTotalRechargeAmount()).add(request.getAmount())); + balance.setLastRechargeTime(now); + } + balanceMapper.updateById(balance); + + BalanceChangeDetailDO detail = new BalanceChangeDetailDO(); + detail.setUserId(userId); + detail.setAmount(delta); + detail.setType(request.getChangeScene()); + detail.setCurrentBalance(afterBalance); + detail.setBeforeBalance(beforeBalance); + detail.setAfterBalance(afterBalance); + detail.setChangeScene(request.getChangeScene()); + detail.setRelatedOrderId(relatedOrder != null ? relatedOrder.getId() : null); + detail.setRelatedOrderNo(relatedOrderNo); + detail.setExternalOrderNo(StringUtils.hasText(request.getExternalOrderNo()) ? request.getExternalOrderNo().trim() : null); + detail.setOperatorId(operatorId); + detail.setRemark(StringUtils.hasText(request.getRemark()) ? request.getRemark().trim() : null); + detail.setChangeTime(now); + balanceChangeDetailMapper.insert(detail); + + if (SCENE_RECHARGE.equals(request.getChangeScene())) { + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + recalculateVipInternal(user, false); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return getUserAsset(userId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request) { + if (request == null || !StringUtils.hasText(request.getVipLevel())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("VIP 等级不能为空"); + } + + UserDO user = getAvailableUser(userId); + String targetLevel = request.getVipLevel().trim(); + VipInfoDO vipInfo = getOrCreateVipInfo(userId); + vipInfo.setActivationMethod("MANUAL_OVERRIDE"); + vipInfo.setManualOverride(1); + vipInfo.setStartTime(LocalDateTime.now()); + + VipBenefitDO benefit = null; + if (!VIP_LEVEL_NORMAL.equals(targetLevel)) { + benefit = vipBenefitMapper.selectOne( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getRequiredVipLevel, targetLevel) + .eq(VipBenefitDO::getStatus, 1) + .last("limit 1")); + if (benefit == null && !isVipLevelAvailable(targetLevel)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标 VIP 等级未配置有效规则"); + } + vipInfo.setBenefitId(benefit != null ? benefit.getId() : null); + } else { + vipInfo.setBenefitId(null); + } + vipInfo.setVipLevel(targetLevel); + vipInfoMapper.updateById(vipInfo); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, vipInfo, targetLevel); + return toAssetVO(userMapper.selectById(userId), ensureBalance(userId), vipInfo, benefit); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ + public UserAssetVO recalculateVip(Long operatorId, Long userId) { + UserDO user = getAvailableUser(userId); + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param true parameter `true` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + recalculateVipInternal(user, true); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return getUserAsset(userId); + } + + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param clearManualOverride parameter `clearManualOverride` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void recalculateVipInternal(UserDO user, boolean clearManualOverride) { + BalanceDO balance = ensureBalance(user.getId()); + VipBenefitDO matchedBenefit = vipBenefitMapper.selectList( + Wrappers.lambdaQuery(VipBenefitDO.class) + .eq(VipBenefitDO::getStatus, 1) + .orderByAsc(VipBenefitDO::getLevelRank) + .orderByAsc(VipBenefitDO::getRechargeThreshold)) + .stream() + .filter(benefit -> defaultDecimal(balance.getTotalRechargeAmount()) + .compareTo(defaultDecimal(benefit.getRechargeThreshold())) >= 0) + .max(Comparator.comparing(VipBenefitDO::getLevelRank, Comparator.nullsLast(Integer::compareTo)) + .thenComparing(VipBenefitDO::getRechargeThreshold, Comparator.nullsLast(BigDecimal::compareTo))) + .orElse(null); + + VipInfoDO vipInfo = getVipInfo(user.getId()); + if (vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride()) && !clearManualOverride) { + return; + } + if (vipInfo == null && matchedBenefit == null) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param VIP_LEVEL_NORMAL parameter `VIP_LEVEL_NORMAL` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, null, VIP_LEVEL_NORMAL); + return; + } + + vipInfo = vipInfo == null ? getOrCreateVipInfo(user.getId()) : vipInfo; + vipInfo.setActivationMethod("AUTO_RECALCULATE"); + vipInfo.setManualOverride(clearManualOverride ? 0 : vipInfo.getManualOverride()); + vipInfo.setStartTime(LocalDateTime.now()); + + String targetLevel = matchedBenefit != null ? matchedBenefit.getRequiredVipLevel() : VIP_LEVEL_NORMAL; + vipInfo.setVipLevel(targetLevel); + vipInfo.setBenefitId(matchedBenefit != null ? matchedBenefit.getId() : null); + vipInfoMapper.updateById(vipInfo); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + updateUserVipFields(user, vipInfo, targetLevel); + } + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void updateUserVipFields(UserDO user, VipInfoDO vipInfo, String vipLevel) { + user.setLevel(StringUtils.hasText(vipLevel) ? vipLevel : VIP_LEVEL_NORMAL); + user.setVipId(VIP_LEVEL_NORMAL.equals(user.getLevel()) || vipInfo == null ? 0L : vipInfo.getId()); + user.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(user); + } + + /** + * Run business method `normalizeDelta`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param amount parameter `amount` supplied by the caller + * @param changeScene parameter `changeScene` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal normalizeDelta(BigDecimal amount, String changeScene) { + if (isDeductScene(changeScene)) { + return amount.negate(); + } + if (SCENE_RECHARGE.equals(changeScene) || SCENE_MANUAL_ADD.equals(changeScene) || SCENE_ORDER_REFUND.equals(changeScene)) { + return amount; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("不支持的余额变动场景"); + } + + /** + * Run business method `isDeductScene`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param changeScene parameter `changeScene` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isDeductScene(String changeScene) { + return SCENE_MANUAL_DEDUCT.equals(changeScene) || SCENE_ORDER_CONSUME.equals(changeScene); + } + + /** + * Run business method `ensureBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private BalanceDO result consumed by the caller or returned to the frontend + */ + private BalanceDO ensureBalance(Long userId) { + BalanceDO balance = balanceMapper.selectOne( + Wrappers.lambdaQuery(BalanceDO.class) + .eq(BalanceDO::getUserId, userId) + .last("limit 1")); + if (balance != null) { + if (balance.getAmount() == null) { + balance.setAmount(BigDecimal.ZERO); + } + if (balance.getTotalRechargeAmount() == null) { + balance.setTotalRechargeAmount(BigDecimal.ZERO); + } + return balance; + } + + balance = new BalanceDO(); + balance.setUserId(userId); + balance.setAmount(BigDecimal.ZERO); + balance.setTotalRechargeAmount(BigDecimal.ZERO); + balance.setLastUpdateTime(LocalDateTime.now()); + balanceMapper.insert(balance); + return balance; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ + private VipInfoDO getVipInfo(Long userId) { + return vipInfoMapper.selectOne( + Wrappers.lambdaQuery(VipInfoDO.class) + .eq(VipInfoDO::getUserId, userId) + .last("limit 1")); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ + private VipInfoDO getOrCreateVipInfo(Long userId) { + VipInfoDO vipInfo = getVipInfo(userId); + if (vipInfo != null) { + return vipInfo; + } + vipInfo = new VipInfoDO(); + vipInfo.setUserId(userId); + vipInfo.setVipLevel(VIP_LEVEL_NORMAL); + vipInfo.setManualOverride(0); + vipInfo.setActivationMethod("INIT"); + vipInfo.setStartTime(LocalDateTime.now()); + vipInfoMapper.insert(vipInfo); + return vipInfo; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO getAvailableUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + return user; + } + + /** + * Purpose: isVipLevelAvailable supports UserAssetServiceImpl.java by holding or executing the is vip level available business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isVipLevelAvailable(String vipLevel) { + if (!StringUtils.hasText(vipLevel)) { + return false; + } + if (VipRechargePlanServiceImpl.DEFAULT_VIP_LEVELS.contains(vipLevel.trim())) { + return true; + } + Long count = vipRechargePlanMapper.selectCount( + Wrappers.lambdaQuery(VipRechargePlanDO.class) + .eq(VipRechargePlanDO::getVipLevel, vipLevel.trim()) + .eq(VipRechargePlanDO::getStatus, 1) + .eq(VipRechargePlanDO::getIsDelete, 0)); + return count != null && count > 0; + } + + /** + * Run business method `defaultDecimal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ + private BigDecimal defaultDecimal(BigDecimal value) { + return value == null ? BigDecimal.ZERO : value; + } + + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return private UserAssetVO result consumed by the caller or returned to the frontend + */ + private UserAssetVO toAssetVO(UserDO user, BalanceDO balance, VipInfoDO vipInfo, VipBenefitDO benefit) { + UserAssetVO vo = new UserAssetVO(); + vo.setUserId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setBalance(defaultDecimal(balance != null ? balance.getAmount() : null)); + vo.setTotalRechargeAmount(defaultDecimal(balance != null ? balance.getTotalRechargeAmount() : null)); + vo.setLastRechargeTime(balance != null ? balance.getLastRechargeTime() : null); + vo.setVipInfoId(vipInfo != null ? vipInfo.getId() : null); + vo.setVipLevel(StringUtils.hasText(user.getLevel()) ? user.getLevel() : VIP_LEVEL_NORMAL); + vo.setBenefitId(vipInfo != null ? vipInfo.getBenefitId() : null); + vo.setBenefitInfo(benefit != null ? benefit.getBenefitInfo() : null); + vo.setManualOverride(vipInfo != null && Integer.valueOf(1).equals(vipInfo.getManualOverride())); + vo.setVipStartTime(vipInfo != null ? vipInfo.getStartTime() : null); + vo.setVipExpireTime(vipInfo != null ? vipInfo.getExpireTime() : null); + return vo; + } + + /** + * Run business method `toBalanceHistoryVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param detail parameter `detail` supplied by the caller + * @param nickname parameter `nickname` supplied by the caller + * @return private BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ + private BalanceChangeDetailVO toBalanceHistoryVO(BalanceChangeDetailDO detail, String nickname) { + BalanceChangeDetailVO vo = new BalanceChangeDetailVO(); + vo.setId(detail.getId()); + vo.setUserId(detail.getUserId()); + vo.setUserNickname(nickname); + vo.setAmount(detail.getAmount()); + vo.setType(detail.getType()); + vo.setCurrentBalance(detail.getCurrentBalance()); + vo.setBeforeBalance(detail.getBeforeBalance()); + vo.setAfterBalance(detail.getAfterBalance()); + vo.setChangeScene(detail.getChangeScene()); + vo.setRelatedOrderId(detail.getRelatedOrderId()); + vo.setRelatedOrderNo(detail.getRelatedOrderNo()); + vo.setExternalOrderNo(detail.getExternalOrderNo()); + vo.setOperatorId(detail.getOperatorId()); + vo.setRemark(detail.getRemark()); + vo.setChangeTime(detail.getChangeTime()); + return vo; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserServiceImpl.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserServiceImpl.java new file mode 100644 index 00000000..ecd22431 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/service/impl/UserServiceImpl.java @@ -0,0 +1,3260 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.fingertipdesigner.core.config.BrandProperties; +import com.xiaowang.fingertipdesigner.core.common.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.content.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.file.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.integration.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.inventory.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.marketing.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.message.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.order.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.payment.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.product.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.security.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.shop.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.system.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.*; +import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserPermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.PermissionDO; +import com.xiaowang.fingertipdesigner.core.modules.shop.entity.ShopDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserRelationDO; +import com.xiaowang.fingertipdesigner.core.modules.user.entity.UserInviteCodeDO; +import com.xiaowang.fingertipdesigner.core.modules.security.entity.UserShopRoleDO; +import com.xiaowang.fingertipdesigner.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserMapper; +import com.xiaowang.fingertipdesigner.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserPermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.PermissionMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserRelationMapper; +import com.xiaowang.fingertipdesigner.core.modules.user.mapper.UserInviteCodeMapper; +import com.xiaowang.fingertipdesigner.core.modules.security.mapper.UserShopRoleMapper; +import com.xiaowang.fingertipdesigner.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.fingertipdesigner.core.modules.shop.service.ShopService; +import com.xiaowang.fingertipdesigner.core.modules.system.service.SystemParameterConfigService; +import com.xiaowang.fingertipdesigner.core.modules.user.service.UserService; +import com.xiaowang.fingertipdesigner.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.fingertipdesigner.core.modules.system.support.AdminDefaultPasswordSupport; +import com.xiaowang.fingertipdesigner.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionCatalog; +import com.xiaowang.fingertipdesigner.core.support.security.UserSessionService; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.fingertipdesigner.core.modules.security.support.PermissionPolicy; +import com.xiaowang.fingertipdesigner.core.support.RequestShopContext; +import com.xiaowang.fingertipdesigner.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.fingertipdesigner.core.modules.user.support.UserProfileFieldSupport; +import com.xiaowang.fingertipdesigner.core.utils.AccountValidationUtils; +import com.xiaowang.fingertipdesigner.core.utils.JwtUtil; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginShopSelectionVO; +import com.xiaowang.fingertipdesigner.core.modules.auth.vo.LoginResponseVO; +import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopSimpleVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserVO; +import com.xiaowang.fingertipdesigner.core.modules.shop.vo.ShopVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserRelationVO; +import com.xiaowang.fingertipdesigner.core.modules.user.vo.UserStatisticsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import com.xiaowang.fingertipdesigner.core.common.Result; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindEmailRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.BindPhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.LoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.PhoneLoginRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.RegisterRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.ResetPasswordRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.auth.dto.UpdatePhoneRequestDTO; +import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningManagerRegisterDTO; +import com.xiaowang.fingertipdesigner.core.modules.user.dto.UserDTO; +/** + * 系统用户信息表 Service 实现 + * 对应数据库表 t_user + * + * @author xiaowang + * @date 2026-02-13 + */ +@Service +@RequiredArgsConstructor +public class UserServiceImpl extends ServiceImpl implements UserService { + /** + * Purpose: VIP_LEVEL_NORMAL supports UserServiceImpl.java by holding or executing the vip level normal business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String VIP_LEVEL_NORMAL = "普通"; + /** + * Purpose: PHONE_REGEX supports UserServiceImpl.java by holding or executing the phone regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; + /** + * Purpose: DEFAULT_AVATAR_URL supports UserServiceImpl.java by holding or executing the default avatar url business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; + private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); + /** + * Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String DELETED_PHONE_MARKER = "_deleted_"; + /** + * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:"; + /** + * Purpose: MAX_LOGIN_FAILURES supports UserServiceImpl.java by holding or executing the max login failures business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final int MAX_LOGIN_FAILURES = 5; + private static final Duration LOGIN_FAIL_EXPIRE = Duration.ofDays(7); + /** + * Purpose: SYSTEM_PERMISSION_ASSIGNER_ID supports UserServiceImpl.java by holding or executing the system permission assigner id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L; + private static final Set MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes(); + private static final Map DEFAULT_PERMISSION_SEEDS = PermissionCatalog.getDefinitionsByCode(); + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + private final ShopMapper shopMapper; + /** + * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final JwtUtil jwtUtil; + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopService shopService; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserPermissionMapper userPermissionMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + private final BrandProperties brandProperties; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final NailArtistInfoService nailArtistInfoService; + private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VerificationCodeService verificationCodeService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final StringRedisTemplate redisTemplate; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userSessionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserSessionService userSessionService; + private final SystemParameterConfigService systemParameterConfigService; + + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void synchronizeManagedDefaultPermissions(Long userId, Integer userType) { + List desiredPermissionCodes = getDefaultPermissionCodes(userType); + List managedPermissions = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getIsDelete, 0) + .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) + ); + + if (managedPermissions.isEmpty()) { + return; + } + + Map permissionIdByCode = managedPermissions.stream() + .collect(Collectors.toMap(PermissionDO::getPermissionCode, PermissionDO::getId, (left, right) -> left)); + List managedPermissionIds = managedPermissions.stream() + .map(PermissionDO::getId) + .collect(Collectors.toList()); + Set desiredPermissionIds = desiredPermissionCodes.stream() + .map(permissionIdByCode::get) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + List currentPermissions = userPermissionMapper.selectList( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + .in(UserPermissionDO::getPermissionId, managedPermissionIds) + ); + + Set currentPermissionIds = currentPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .collect(Collectors.toSet()); + List stalePermissionIds = currentPermissions.stream() + .map(UserPermissionDO::getPermissionId) + .filter(permissionId -> !desiredPermissionIds.contains(permissionId)) + .distinct() + .collect(Collectors.toList()); + + if (!stalePermissionIds.isEmpty()) { + userPermissionMapper.delete( + Wrappers.lambdaQuery(UserPermissionDO.class) + .eq(UserPermissionDO::getUserId, userId) + .in(UserPermissionDO::getPermissionId, stalePermissionIds) + ); + } + + for (Long permissionId : desiredPermissionIds) { + if (currentPermissionIds.contains(permissionId)) { + continue; + } + UserPermissionDO userPermissionDO = new UserPermissionDO(); + userPermissionDO.setUserId(userId); + userPermissionDO.setPermissionId(permissionId); + userPermissionDO.setCreateBy(SYSTEM_PERMISSION_ASSIGNER_ID); + userPermissionMapper.insert(userPermissionDO); + } + } + + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePermissionDefinitions() { + List existingPermissions = permissionMapper.selectList( + Wrappers.lambdaQuery(PermissionDO.class) + .in(PermissionDO::getPermissionCode, MANAGED_DEFAULT_PERMISSION_CODES) + ); + + Map existingByCode = existingPermissions.stream() + .collect(Collectors.toMap(PermissionDO::getPermissionCode, permission -> permission, (left, right) -> left)); + + for (String permissionCode : MANAGED_DEFAULT_PERMISSION_CODES) { + PermissionCatalog.PermissionDefinition permissionSeed = DEFAULT_PERMISSION_SEEDS.get(permissionCode); + if (permissionSeed == null) { + continue; + } + + PermissionDO permissionDO = existingByCode.get(permissionCode); + if (permissionDO == null) { + permissionDO = new PermissionDO(); + permissionDO.setPermissionCode(permissionCode); + permissionDO.setPermissionName(permissionSeed.permissionName()); + permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); + permissionDO.setDescription(permissionSeed.description()); + permissionDO.setIsDelete(0); + permissionDO.setUpdateTime(LocalDateTime.now()); + permissionMapper.insert(permissionDO); + continue; + } + + if (isPermissionDefinitionCurrent(permissionDO, permissionSeed)) { + continue; + } + + permissionDO.setPermissionName(permissionSeed.permissionName()); + permissionDO.setPermissionGroup(permissionSeed.permissionGroup()); + permissionDO.setDescription(permissionSeed.description()); + permissionDO.setIsDelete(0); + permissionDO.setUpdateTime(LocalDateTime.now()); + permissionMapper.updateById(permissionDO); + } + } + + private boolean isPermissionDefinitionCurrent(PermissionDO permissionDO, PermissionCatalog.PermissionDefinition permissionSeed) { + return Objects.equals(permissionDO.getPermissionName(), permissionSeed.permissionName()) + && Objects.equals(permissionDO.getPermissionGroup(), permissionSeed.permissionGroup()) + && Objects.equals(permissionDO.getDescription(), permissionSeed.description()) + && Objects.equals(permissionDO.getIsDelete(), 0); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List getDefaultPermissionCodes(Integer userType) { + return PermissionPolicy.getDefaultPermissionCodes(userType); + } + + /** + * Run business method `assignDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assignDefaultPermissions(Long userId, Integer userType) { + if (getDefaultPermissionCodes(userType).isEmpty()) { + return; + } + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncDefaultPermissions(userId, userType); + } + + /** + * 创建新用户 + * @param userDTO 用户数据传输对象 + * @return 新创建用户的ID + */ + @Override + @Transactional(rollbackFor = Exception.class) + public Long createUser(UserDTO userDTO) { + String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount()); + // 检查账号是否已存在 + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } + + List validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); + Long validatedShopId = pickPrimaryShopId(validatedShopIds); + String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); + Integer userType = userDTO.getType(); + String validatedWechatId = UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()); + UserProfileFieldSupport.requireWechatIdForServiceUser(userType, validatedWechatId); + + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopBindingRequirement(userType, validatedShopIds); + + // 创建用户实体并设置属性 + UserDO userDO = new UserDO(); + userDO.setShopId(validatedShopId); + userDO.setNickname(userDTO.getNickname()); + userDO.setAccount(validatedAccount); + String resolvedPassword = AdminDefaultPasswordSupport.resolveCreatePassword( + userDTO.getPassword(), + getConfiguredAdminDefaultPassword() + ); + validatePasswordStrength(resolvedPassword); + userDO.setPassword(passwordEncoder.encode(resolvedPassword)); + userDO.setPhone(validatedPhone); + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + userDO.setBirthday(userDTO.getBirthday()); + userDO.setWechatId(validatedWechatId); + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + userDO.setSignature(userDTO.getSignature()); + userDO.setLevel(userDTO.getLevel()); + userDO.setType(userType); + userDO.setVipId(userDTO.getVipId()); + userDO.setIsDelete(0); + userDO.setStatus(1); + if (StringUtils.hasText(userDTO.getAvatar())) { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } else { + userDO.setAvatar(DEFAULT_AVATAR_URL); + } + + if (Integer.valueOf(0).equals(userDO.getType())) { + if (!StringUtils.hasText(userDO.getLevel())) { + userDO.setLevel(VIP_LEVEL_NORMAL); + } + if (userDO.getVipId() == null) { + userDO.setVipId(0L); + } + } + + try { + // 插入用户数据 + userMapper.insert(userDO); + } catch (Exception e) { + // 捕获重复账号异常 + if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被使用"); + } + throw e; + } + + // 分配默认权限 + assignDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); + + // 如果是美甲师,创建对应的美甲师信息记录 + if (userDO.getType() == 3) { + NailArtistInfoDTO nailArtistInfoDTO = new NailArtistInfoDTO(); + nailArtistInfoDTO.setUserId(userDO.getId()); + nailArtistInfoDTO.setIdentity(""); // 默认身份为空 + nailArtistInfoDTO.setExperience(0); // 默认经验为0 + nailArtistInfoDTO.setSkills(""); // 默认技能为空 + nailArtistInfoDTO.setRating(DEFAULT_NAIL_ARTIST_RATING); // 默认评分为4.5 + nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 + nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 + nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + } + + return userDO.getId(); + } + + /** + * 分配默认权限 + * @param userId 用户ID + * @param userType 用户类型 + */ + private void syncDefaultPermissions(Long userId, Integer userType) { + if (userId == null) { + return; + } + + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ + ensurePermissionDefinitions(); + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + synchronizeManagedDefaultPermissions(userId, userType); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ + public void syncManagedPermissions(Long userId) { + if (userId == null) { + return; + } + UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return; + } + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + + /** + * 更新用户信息 + * @param id 用户ID + * @param userDTO 用户数据传输对象 + * @return 更新是否成功 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateUser(Long id, UserDTO userDTO) { + // 查询用户是否存在 + UserDO userDO = userMapper.selectById(id); + if (userDO == null) { + return false; + } + + // 更新账号(如果提供且变更) + String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); + if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } + userDO.setAccount(normalizedAccount); + } + + // 更新其他字段(如果提供) + if (userDTO.getShopId() != null) { + userDO.setShopId(validateAndNormalizeShopId(userDTO.getShopId())); + } + if (userDTO.getNickname() != null) { + userDO.setNickname(userDTO.getNickname()); + } + if (userDTO.getPassword() != null) { + validatePasswordStrength(userDTO.getPassword()); + userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); + } + if (userDTO.getPhone() != null) { + userDO.setPhone(validateUserPhone(userDTO.getPhone(), id, true)); + } + if (userDTO.getContactPhone() != null) { + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + } + if (userDTO.getBirthday() != null) { + userDO.setBirthday(userDTO.getBirthday()); + } + if (userDTO.getWechatId() != null) { + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + } + if (userDTO.getWechatQrCode() != null) { + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + } + if (userDTO.getAvatar() != null) { + if (userDTO.getAvatar().isEmpty()) { + userDO.setAvatar(null); + } else { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } + } + if (userDTO.getSignature() != null) { + userDO.setSignature(userDTO.getSignature()); + } + if (userDTO.getLevel() != null) { + userDO.setLevel(userDTO.getLevel()); + } + if (userDTO.getType() != null) { + userDO.setType(userDTO.getType()); + } + if (userDTO.getVipId() != null) { + userDO.setVipId(userDTO.getVipId()); + } + Integer targetUserType = userDO.getType(); + UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); + List validatedShopIds = null; + boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; + if (shopBindingChanged) { + validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserType parameter `targetUserType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopBindingRequirement(targetUserType, validatedShopIds); + userDO.setShopId(pickPrimaryShopId(validatedShopIds)); + } + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + if (shopBindingChanged) { + userShopBindingSupport.syncUserShopBindings(id, validatedShopIds); + } + if (userDTO.getPassword() != null) { + userSessionService.revokeAllUserSessions(id); + } + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param targetUserType parameter `targetUserType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncDefaultPermissions(id, targetUserType); + } + return updated; + } + + /** + * 删除用户 + * @param id 用户ID + * @return 删除是否成功 + */ + @Override + public boolean deleteUser(Long id) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + + clearLoginFailureCount(userDO.getAccount()); + userSessionService.revokeAllUserSessions(id); + userShopBindingSupport.deleteBindingsByUserId(id); + wechatMiniBindingMapper.update( + null, + new LambdaUpdateWrapper() + .eq(WechatMiniBindingDO::getUserId, id) + .set(WechatMiniBindingDO::getStatus, 0) + .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) + ); + LocalDateTime now = LocalDateTime.now(); + return userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getAccount, buildDeletedAccount(userDO)) + .set(UserDO::getPhone, buildDeletedPhone(userDO)) + .set(UserDO::getStatus, 0) + .set(UserDO::getIsDelete, 1) + .set(UserDO::getUpdateTime, now) + ) > 0; + } + + /** + * 根据ID获取用户信息 + * @param id 用户ID + * @return 用户视图对象 + */ + @Override + public UserVO getUserById(Long id) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(userDO); + } + + /** + * 获取所有用户列表 + * @return 用户视图对象列表 + */ + @Override + public List listAllUsers() { + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据店铺ID获取用户列表 + * @param shopId 店铺ID + * @return 用户视图对象列表 + */ + @Override + public List listUsersByShopId(Long shopId) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (userIds.isEmpty()) { + return List.of(); + } + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .in(UserDO::getId, userIds) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据用户类型获取用户列表 + * @param type 用户类型 + * @return 用户视图对象列表 + */ + @Override + public List listUsersByType(Integer type) { + List userDOs = userMapper.selectList( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getType, type) + ); + return userDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + /** + * 根据账号获取用户信息 + * @param account 用户账号 + * @return 用户视图对象 + */ + @Override + public UserVO getUserByAccount(String account) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(account); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + ); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return null; + } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToVO(userDO); + } + + /** + * 将 DO 转换为 VO + * @param userDO 用户DO + * @param userDO 用户DO + * @return 用户VO + */ + private UserVO convertToVO(UserDO userDO) { + UserVO userVO = new UserVO(); + userVO.setId(userDO.getId()); + List shopOptions = resolveShopOptions(userDO, true, false); + Long scopedShopId = RequestShopContext.getCurrentShopId(); + if (scopedShopId != null) { + shopOptions.stream() + .filter(shop -> Objects.equals(shop.getId(), scopedShopId)) + .findFirst() + .ifPresent(shop -> { + shopOptions.remove(shop); + shopOptions.add(0, shop); + }); + } + Long primaryShopId = !shopOptions.isEmpty() ? shopOptions.get(0).getId() : normalizeShopId(userDO.getShopId()); + String primaryShopName = !shopOptions.isEmpty() ? shopOptions.get(0).getShopName() : null; + userVO.setShopId(primaryShopId); + userVO.setShopName(primaryShopName); + userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); + userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); + userVO.setNickname(userDO.getNickname()); + userVO.setAccount(userDO.getAccount()); + userVO.setPhone(userDO.getPhone()); + userVO.setContactPhone(userDO.getContactPhone()); + userVO.setBirthday(userDO.getBirthday()); + userVO.setWechatId(userDO.getWechatId()); + userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); + userVO.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); + userVO.setSignature(userDO.getSignature()); + userVO.setLevel(userDO.getLevel()); + userVO.setType(userDO.getType()); + userVO.setTypeName(resolveUserTypeName(userDO.getType())); + userVO.setVipId(userDO.getVipId()); + userVO.setCreateTime(userDO.getCreateTime()); + userVO.setUpdateTime(userDO.getUpdateTime()); + userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1); + userVO.setEmail(userDO.getEmail()); + userVO.setMaskedPhone(maskPhone(userDO.getPhone())); + userVO.setMaskedEmail(maskEmail(userDO.getEmail())); + applyRelationInfo(userVO, userDO.getId()); + return userVO; + } + + /** + * Run business method `resolveAccessibleAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveAccessibleAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return DEFAULT_AVATAR_URL; + } + return objectStorageUrlSupport.toAccessibleUrl(avatarUrl); + } + + /** + * Run business method `normalizeStoredAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeStoredAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return avatarUrl; + } + return objectStorageUrlSupport.toStoredUrl(avatarUrl); + } + + private String resolveAccessibleProfileImage(String imageUrl) { + if (!StringUtils.hasText(imageUrl)) { + return imageUrl; + } + return objectStorageUrlSupport.toAccessibleUrl(imageUrl); + } + + private String normalizeStoredProfileImage(String imageUrl) { + if (!StringUtils.hasText(imageUrl)) { + return null; + } + return objectStorageUrlSupport.toStoredUrl(imageUrl); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) { + String normalizedAccount = account == null ? "" : account.trim(); + if (!StringUtils.hasText(normalizedAccount)) { + return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); + } + AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection(List.of(), false, "该账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无店铺,可直接登录" + : "平台管理员可选择任意店铺作为本次登录店铺"; + return buildLoginShopSelection(shops, true, message); + } + + List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "该账号首次登录,请先选择店铺" + ); + } + + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) { + String normalizedPhone = phone == null ? "" : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺"); + } + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, normalizedPhone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "新手机号首次登录需要选择店铺" + ); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无店铺,可直接登录" + : "平台管理员可选择任意店铺作为本次登录店铺"; + return buildLoginShopSelection(shops, true, message); + } + + List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return buildLoginShopSelection( + userShopBindingSupport.listAllActiveShopOptions(), + false, + "该手机号账号首次登录,请先选择店铺" + ); + } + + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系门店处理"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + public LoginShopSelectionVO getAdminLoginShopSelection(String account) { + String normalizedAccount = account == null ? "" : account.trim(); + if (!StringUtils.hasText(normalizedAccount)) { + return buildLoginShopSelection(List.of(), false, "请输入账号后再选择店铺"); + } + AccountValidationUtils.ensureValidAccountFormat(normalizedAccount); + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO == null) { + return buildLoginShopSelection(List.of(), false, "该账号不存在"); + } + if (userDO.getType() == null || userDO.getType() < 2) { + return buildLoginShopSelection(List.of(), false, "该账号不是后台管理账号"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + return buildLoginShopSelection(List.of(), false, "该账号已被禁用"); + } + + if (Integer.valueOf(4).equals(userDO.getType())) { + List shops = listSelectableShopOptionsForPlatformAdmin(); + String message = shops.isEmpty() + ? "当前暂无可选店铺,可直接进入平台总览模式" + : "平台管理员可直接进入平台总览,也可选择任意店铺作为本次登录店铺"; + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginShopSelection(shops, true, message); + } + + List shops = listEnabledShopOptionsForUser(userDO.getId()); + if (!shops.isEmpty()) { + return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); + } + return buildLoginShopSelection(List.of(), false, "当前账号没有可登录的店铺,请联系平台管理员"); + } + + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertLoginAccountAvailable(userDO); + + // 检查是否为未设置密码的账号 + if (ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请使用手机号验证码登录,并在个人中心设置密码"); + } + + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + handleLoginPasswordFailure(userDO); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId()); + clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + } + + @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO) { + if (!verificationCodeService.verifyCode(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) + .eq(UserDO::getIsDelete, 0) + ); + + if (userDO == null) { + if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId()); + } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId()); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe())); + } + + // 未设置密码的特殊标识 + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + + if (userDO == null) { + if (shopId == null || shopId == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + userDO = registerByPhone(phone, shopId); + } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + } + + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + } + + @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO loginByUserId(Long userId, Long shopId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + clearLoginFailureCount(userDO.getAccount()); + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + } + + /** + * Purpose: UNSET_PASSWORD_MARKER supports UserServiceImpl.java by holding or executing the unset password marker business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__"; + /** + * Purpose: ENCODED_UNSET_PASSWORD supports UserServiceImpl.java by holding or executing the encoded unset password business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识 + + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO registerByPhone(String phone, Long shopId) { + Long validatedShopId = validateAndNormalizeShopId(shopId); + if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("首次登录需要选择店铺"); + } + UserDO userDO = new UserDO(); + userDO.setAccount(phone); + userDO.setPhone(phone); + userDO.setPhoneVerified(1); + userDO.setNickname("用户" + phone.substring(7)); + userDO.setType(0); + userDO.setLevel(VIP_LEVEL_NORMAL); + userDO.setVipId(0L); + userDO.setShopId(validatedShopId); + userDO.setIsDelete(0); + userDO.setStatus(1); + userDO.setCreateTime(LocalDateTime.now()); + userDO.setUpdateTime(LocalDateTime.now()); + userDO.setPassword(ENCODED_UNSET_PASSWORD); + + userMapper.insert(userDO); + syncDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); + return userDO; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { + String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); + UserDO userDO = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, normalizedAccount) + ); + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertLoginAccountAvailable(userDO); + + if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + handleLoginPasswordFailure(userDO); + } + + Integer userType = userDO.getType(); + if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号不是后台管理账号"); + } + + Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); + clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, Boolean.TRUE.equals(loginRequestDTO.getRememberMe())); + } + + @Override + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + Integer userType = userDO.getType(); + if (userType != null && userType >= 2 && !Integer.valueOf(4).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号请使用后台切换店铺"); + } + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), previousSessionId); + } + + @Override + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + Integer userType = userDO.getType(); + if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("您没有后台管理权限"); + } + Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId); + } + + /** + * Run business method `resolveAdminLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) { + Long normalizedRequestedShopId = normalizeShopId(requestedShopId); + if (Integer.valueOf(4).equals(userDO.getType())) { + if (normalizedRequestedShopId == null) { + return null; + } + boolean canSelectShop = listSelectableShopOptionsForPlatformAdmin().stream() + .map(ShopSimpleVO::getId) + .anyMatch(shopId -> Objects.equals(shopId, normalizedRequestedShopId)); + if (!canSelectShop) { + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + + List activeShopIds = listEnabledShopOptionsForUser(userDO.getId()).stream() + .map(ShopSimpleVO::getId) + .collect(Collectors.toList()); + if (activeShopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员"); + } + if (normalizedRequestedShopId != null) { + if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + if (activeShopIds.size() == 1) { + return activeShopIds.get(0); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择登录店铺"); + } + + /** + * Run business method `hasAnyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean hasAnyShop() { + return !listEnabledShopOptionsForAdmin().isEmpty(); + } + + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long normalizeShopId(Long shopId) { + return shopId != null && shopId > 0 ? shopId : null; + } + + @Override + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean register(RegisterRequestDTO registerRequestDTO) { + String validatedAccount = AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()); + if (!verificationCodeService.verifyCode(registerRequestDTO.getPhone(), registerRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, validatedAccount) + ); + + if (existingUser != null) { + if (existingUser.getIsDelete() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已存在"); + } else { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号已被注销,请使用手机号验证码登录"); + } + } + + UserDO existingPhoneUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, registerRequestDTO.getPhone()) + .eq(UserDO::getIsDelete, 0) + ); + + if (existingPhoneUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该手机号已被注册"); + } + + Long validatedShopId = resolveRegisterShopId(registerRequestDTO.getShopId(), registerRequestDTO.getInviteCode()); + if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + UserDO userDO = new UserDO(); + userDO.setShopId(validatedShopId); + userDO.setAccount(validatedAccount); + validatePasswordStrength(registerRequestDTO.getPassword()); + userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword())); + userDO.setNickname(registerRequestDTO.getNickname()); + userDO.setPhone(registerRequestDTO.getPhone()); + userDO.setPhoneVerified(1); + userDO.setType(Integer.valueOf(0)); + userDO.setLevel(VIP_LEVEL_NORMAL); + userDO.setVipId(0L); + userDO.setIsDelete(Integer.valueOf(0)); + userDO.setCreateTime(LocalDateTime.now()); + userDO.setUpdateTime(LocalDateTime.now()); + + userMapper.insert(userDO); + assignDefaultPermissions(userDO.getId(), userDO.getType()); + userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); + createRelationForRegister(userDO.getId(), validatedShopId, registerRequestDTO.getInviteCode()); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public LoginResponseVO registerPlanningManager(PlanningManagerRegisterDTO registerDTO) { + if (registerDTO == null) { + throw new RuntimeException("注册信息不能为空"); + } + String phone = validateUserPhone(registerDTO.getPhone(), null, true); + if (!verificationCodeService.verifyCode(phone, registerDTO.getCode())) { + throw new RuntimeException("验证码错误或已过期"); + } + String password = registerDTO.getPassword(); + if (!StringUtils.hasText(password)) { + throw new RuntimeException("密码不能为空"); + } + if (!Objects.equals(password, registerDTO.getConfirmPassword())) { + throw new RuntimeException("两次密码不一致"); + } + validatePasswordStrength(password); + String shopName = registerDTO.getShopName() == null ? null : registerDTO.getShopName().trim(); + if (!StringUtils.hasText(shopName)) { + throw new RuntimeException("店铺名称不能为空"); + } + + UserDO existingUser = userMapper.selectOne( + Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, phone) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (existingUser != null) { + throw new RuntimeException("该手机号已注册"); + } + + ShopDO shop = new ShopDO(); + shop.setShopName(shopName); + shop.setDescription(brandProperties.getManagerRegisterShopDescription()); + shop.setBusinessHours("10:00-22:00"); + shop.setStatus(1); + shop.setAuthorizationStartDate(LocalDateTime.now().minusDays(1).toLocalDate()); + shop.setAuthorizationDays(0); + shop.setAuthorizationExpireTime(LocalDateTime.now().minusSeconds(1)); + shop.setIsDelete(0); + shopMapper.insert(shop); + + UserDO manager = new UserDO(); + manager.setShopId(shop.getId()); + manager.setNickname(shopName + "店长"); + manager.setAccount(phone); + manager.setPassword(passwordEncoder.encode(password)); + manager.setPhone(phone); + manager.setContactPhone(phone); + manager.setPhoneVerified(1); + manager.setEmailVerified(0); + manager.setType(2); + manager.setStatus(1); + manager.setIsDelete(0); + manager.setAvatar(DEFAULT_AVATAR_URL); + userMapper.insert(manager); + + syncDefaultPermissions(manager.getId(), manager.getType()); + userShopBindingSupport.syncUserShopBindings(manager.getId(), List.of(shop.getId())); + createRelationForRegister(manager.getId(), shop.getId(), null); + clearLoginFailureCount(manager.getAccount()); + return buildLoginResponse(manager, shop.getId(), false); + } + + @Override + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ + public LoginResponseVO refreshToken(String refreshToken) { + if (!jwtUtil.validateToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("刷新Token无效或已过期"); + } + + if (!jwtUtil.isRefreshToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("Token类型错误"); + } + + Long userId = jwtUtil.getUserIdFromToken(refreshToken); + String account = jwtUtil.getAccountFromToken(refreshToken); + Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); + String refreshJti = jwtUtil.getJtiFromToken(refreshToken); + if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("登录态已失效,请重新登录"); + } + + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前登录店铺已失效,请重新登录"); + } + + return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), sessionId); + } + + @Override + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean logout(String sessionId) { + userSessionService.revokeSession(sessionId); + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ + public UserVO getCurrentUserInfo() { + org.springframework.web.context.request.ServletRequestAttributes attributes = + (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); + Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); + return userId == null ? null : getUserById(userId); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateCurrentUserInfo(Long userId, UserDTO userDTO) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + + if (userDTO.getNickname() != null) { + userDO.setNickname(userDTO.getNickname()); + } + if (userDTO.getAvatar() != null) { + if (userDTO.getAvatar().isEmpty()) { + userDO.setAvatar(null); + } else { + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); + } + } + if (userDTO.getSignature() != null) { + userDO.setSignature(userDTO.getSignature()); + } + if (userDTO.getContactPhone() != null) { + userDO.setContactPhone(UserProfileFieldSupport.normalizeOptionalText(userDTO.getContactPhone())); + } + if (userDTO.getBirthday() != null) { + userDO.setBirthday(userDTO.getBirthday()); + } + if (userDTO.getWechatId() != null) { + userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); + } + if (userDTO.getWechatQrCode() != null) { + userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); + } + UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); + + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + return updated; + } + + @Override + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + validateVerificationCode(bindPhoneRequestDTO.getPhone(), bindPhoneRequestDTO.getVerificationCode()); + ensurePhoneNotUsed(bindPhoneRequestDTO.getPhone(), userId); + + userDO.setPhone(bindPhoneRequestDTO.getPhone()); + userDO.setPhoneVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO) { + UserDO userDO = userMapper.selectById(userId); + if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + + userDO.setEmail(bindEmailRequestDTO.getEmail()); + userDO.setEmailVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean resetPassword(Long targetUserId, Long currentUserId) { + UserDO targetUser = userMapper.selectById(targetUserId); + if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("目标用户不存在"); + } + + UserDO currentUser = userMapper.selectById(currentUserId); + if (currentUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前用户不存在"); + } + + Integer currentUserType = currentUser.getType(); + Integer targetUserType = targetUser.getType(); + + if (currentUserType == null || targetUserType == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户类型错误"); + } + + if (currentUserType <= targetUserType) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("权限不足,只能重置比自己级别低的用户密码"); + } + + targetUser.setPassword(passwordEncoder.encode(resolveAdminDefaultPassword())); + targetUser.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(targetUser) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(targetUserId); + } + return updated; + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type) { + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return pageUsers(page, size, keyword, shopId, type, null, null, null, null, null, null, null, null, null); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); + wrapper.eq(UserDO::getIsDelete, 0); + // 不再过滤普通用户,由前端根据用户角色进行过滤 + if (StringUtils.hasText(keyword)) { + wrapper.and(w -> w.like(UserDO::getAccount, keyword) + .or().like(UserDO::getNickname, keyword) + .or().like(UserDO::getPhone, keyword) + .or().like(UserDO::getContactPhone, keyword)); + } + if (shopId != null && shopId > 0) { + List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (userIds.isEmpty()) { + PageResultVO emptyResult = new PageResultVO<>(); + emptyResult.setList(List.of()); + emptyResult.setTotal(0L); + emptyResult.setPage(page); + emptyResult.setSize(size); + return emptyResult; + } + wrapper.in(UserDO::getId, userIds); + } + Set relationFilteredIds = resolveRelationFilteredUserIds(roleId, parentUserId, sourceType); + if (relationFilteredIds != null) { + if (relationFilteredIds.isEmpty()) { + PageResultVO emptyResult = new PageResultVO<>(); + emptyResult.setList(List.of()); + emptyResult.setTotal(0L); + emptyResult.setPage(page); + emptyResult.setSize(size); + return emptyResult; + } + wrapper.in(UserDO::getId, relationFilteredIds); + } + if (type != null) { + wrapper.eq(UserDO::getType, type); + } + if (status != null) { + wrapper.eq(UserDO::getStatus, status); + } + if (StringUtils.hasText(vipLevel)) { + wrapper.eq(UserDO::getLevel, vipLevel); + } + if (StringUtils.hasText(createdFrom)) { + wrapper.ge(UserDO::getCreateTime, LocalDateTime.parse(createdFrom)); + } + if (StringUtils.hasText(createdTo)) { + wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); + } + if (Boolean.TRUE.equals(hasPhone)) { + wrapper.isNotNull(UserDO::getPhone); + } + if (Boolean.FALSE.equals(hasPhone)) { + wrapper.isNull(UserDO::getPhone); + } + wrapper.orderByDesc(UserDO::getCreateTime); + + Page userPage = userMapper.selectPage(pageParam, wrapper); + + PageResultVO result = new PageResultVO<>(); + result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setTotal(userPage.getTotal()); + result.setPage(page); + result.setSize(size); + + return result; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserStatus(Long id, Integer status) { + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + Integer normalizedStatus = Integer.valueOf(1).equals(status) ? 1 : 0; + boolean updated = userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getStatus, normalizedStatus) + .set(UserDO::getUpdateTime, LocalDateTime.now()) + ) > 0; + if (updated && normalizedStatus == 1) { + UserDO latestUser = userMapper.selectById(id); + if (latestUser != null) { + clearLoginFailureCount(latestUser.getAccount()); + } + } else if (updated) { + userSessionService.revokeAllUserSessions(id); + } + return updated; + } + + @Override + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + public UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { + List users = pageUsers(1, Integer.MAX_VALUE, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder).getList(); + UserStatisticsVO vo = new UserStatisticsVO(); + vo.setTotalUserCount(users.size()); + vo.setNormalUserCount(users.stream().filter(u -> Integer.valueOf(0).equals(u.getType())).count()); + vo.setEmployeeCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType()) || Integer.valueOf(3).equals(u.getType())).count()); + vo.setManagerCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType())).count()); + vo.setArtistCount(users.stream().filter(u -> Integer.valueOf(3).equals(u.getType())).count()); + vo.setVipUserCount(users.stream().filter(u -> StringUtils.hasText(u.getLevel()) && !"普通".equals(u.getLevel())).count()); + vo.setNewUserCount(users.stream().filter(u -> u.getCreateTime() != null && u.getCreateTime().isAfter(LocalDateTime.now().minusDays(7))).count()); + vo.setByShop(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopId()), Collectors.counting()))); + vo.setByRole(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopRoleName()), Collectors.counting()))); + vo.setByParent(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getParentUserName()), Collectors.counting()))); + return vo; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + public UserRelationVO getCurrentUserRelation(Long userId) { + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildRelationVO(userId); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return updateUserStatus(id, status); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean deleteUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return unbindUserInShop(id, shopId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean unbindUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return unbindUserInShopWithOperator(id, shopId, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType) { + Long normalizedShopId = normalizeShopId(shopId); + if (normalizedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前操作缺少店铺上下文"); + } + UserDO userDO = userMapper.selectById(id); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return false; + } + + boolean success = userShopBindingSupport.updateBindingStatus(id, normalizedShopId, 0); + if (!success) { + return false; + } + + if (Integer.valueOf(2).equals(operatorType) && Integer.valueOf(3).equals(userDO.getType())) { + userDO.setType(0); + userDO.setUpdateTime(LocalDateTime.now()); + userMapper.updateById(userDO); + syncDefaultPermissions(userDO.getId(), userDO.getType()); + } + return true; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updateUserAvatar(Long userId, String avatarUrl) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + userDO.setAvatar(avatarUrl); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePassword(Long userId, String password, String verificationCode) { + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先绑定手机号"); + } + validateVerificationCode(userDO.getPhone(), verificationCode); + validatePasswordStrength(password); + userDO.setPassword(passwordEncoder.encode(password)); + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userId); + } + return updated; + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { + String oldPhone = updatePhoneDTO.getOldPhone(); + String newPhone = updatePhoneDTO.getNewPhone(); + String verificationCode = updatePhoneDTO.getVerificationCode(); + + UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号未绑定手机号"); + } + if (!userDO.getPhone().equals(oldPhone)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("原手机号不匹配"); + } + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateVerificationCode(newPhone, verificationCode); + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePhoneNotUsed(newPhone, userId); + + userDO.setPhone(newPhone); + userDO.setPhoneVerified(1); + userDO.setUpdateTime(LocalDateTime.now()); + return userMapper.updateById(userDO) > 0; + } + + @Override + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO) { + String phone = resetPasswordRequestDTO.getPhone(); + String verificationCode = resetPasswordRequestDTO.getVerificationCode(); + String newPassword = resetPasswordRequestDTO.getNewPassword(); + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + validateVerificationCode(phone, verificationCode); + + // 根据手机号查找用户 + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); + wrapper.eq(UserDO::getPhone, phone); + wrapper.eq(UserDO::getIsDelete, 0); + UserDO userDO = userMapper.selectOne(wrapper); + + if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("未绑定手机号,请联系店员"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被禁用"); + } + + // 更新密码 + validatePasswordStrength(newPassword); + userDO.setPassword(passwordEncoder.encode(newPassword)); + userDO.setUpdateTime(LocalDateTime.now()); + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userDO.getId()); + } + return updated; + } + + /** + * Run business method `buildDeletedAccount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDeletedAccount(UserDO userDO) { + String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); + String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + } + + /** + * Run business method `buildDeletedPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildDeletedPhone(UserDO userDO) { + String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); + String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + } + + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param maxLength parameter `maxLength` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String trimDeletedPlaceholder(String value, int maxLength) { + if (!StringUtils.hasText(value) || value.length() <= maxLength) { + return value; + } + return value.substring(value.length() - maxLength); + } + + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUserAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("账号已被禁用"); + } + } + + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertLoginAccountAvailable(UserDO userDO) { + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号不存在"); + } + if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该账号已被禁用"); + } + } + + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void handleLoginPasswordFailure(UserDO userDO) { + if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误"); + } + String failKey = buildLoginFailKey(userDO.getAccount()); + Long failCount = redisTemplate.opsForValue().increment(failKey); + redisTemplate.expire(failKey, LOGIN_FAIL_EXPIRE); + long safeFailCount = failCount == null ? 1L : failCount; + if (safeFailCount >= MAX_LOGIN_FAILURES) { + disableUserByFailedPassword(userDO.getId()); + redisTemplate.delete(failKey); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误次数过多,账号已被禁用"); + } + long remainingAttempts = MAX_LOGIN_FAILURES - safeFailCount; + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("密码错误,还可尝试" + remainingAttempts + "次"); + } + + /** + * Run business method `disableUserByFailedPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void disableUserByFailedPassword(Long userId) { + if (userId == null) { + return; + } + userMapper.update( + null, + new LambdaUpdateWrapper() + .eq(UserDO::getId, userId) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getStatus, 0) + .set(UserDO::getUpdateTime, LocalDateTime.now()) + ); + userSessionService.revokeAllUserSessions(userId); + } + + /** + * Run business method `clearLoginFailureCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void clearLoginFailureCount(String account) { + if (!StringUtils.hasText(account)) { + return; + } + redisTemplate.delete(buildLoginFailKey(account)); + } + + /** + * Run business method `buildLoginFailKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildLoginFailKey(String account) { + return LOGIN_FAIL_KEY_PREFIX + account.trim(); + } + + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void validateVerificationCode(String phone, String verificationCode) { + if (!StringUtils.hasText(phone) || !StringUtils.hasText(verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码不能为空"); + } + if (!verificationCodeService.verifyCode(phone, verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("验证码错误或已过期"); + } + } + + /** + * Purpose: validatePasswordStrength supports UserServiceImpl.java by holding or executing the validate password strength business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validatePasswordStrength(String password) { + if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { + throw new RuntimeException("密码长度需为 8-32 位"); + } + int count = 0; + if (password.matches(".*\\d.*")) { + count++; + } + if (password.matches(".*[a-z].*")) { + count++; + } + if (password.matches(".*[A-Z].*")) { + count++; + } + if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { + count++; + } + if (count < 3) { + throw new RuntimeException("密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); + } + } + + private String resolveAdminDefaultPassword() { + return AdminDefaultPasswordSupport.resolveDefaultPassword(getConfiguredAdminDefaultPassword()); + } + + private String getConfiguredAdminDefaultPassword() { + return systemParameterConfigService.getEnabledValue( + AdminDefaultPasswordSupport.CONFIG_GROUP, + AdminDefaultPasswordSupport.CONFIG_KEY + ); + } + + /** + * Run business method `resolveValidatedShopIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @param fallbackShopId parameter `fallbackShopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveValidatedShopIds(List shopIds, Long fallbackShopId) { + LinkedHashSet resolvedShopIds = new LinkedHashSet<>(); + if (shopIds != null) { + for (Long shopId : shopIds) { + Long validatedShopId = validateAndNormalizeShopId(shopId); + if (validatedShopId != null) { + resolvedShopIds.add(validatedShopId); + } + } + } + Long validatedFallbackShopId = validateAndNormalizeShopId(fallbackShopId); + if (validatedFallbackShopId != null) { + resolvedShopIds.add(validatedFallbackShopId); + } + return new ArrayList<>(resolvedShopIds); + } + + /** + * Run business method `pickPrimaryShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long pickPrimaryShopId(List shopIds) { + return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0); + } + + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureShopBindingRequirement(Integer userType, List shopIds) { + if (Integer.valueOf(4).equals(userType)) { + return; + } + if (shopIds == null || shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请至少选择一个所属店铺"); + } + } + + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ + private LoginShopSelectionVO buildLoginShopSelection(List shops, boolean allowShoplessLogin, String message) { + LoginShopSelectionVO selectionVO = new LoginShopSelectionVO(); + selectionVO.setAllowShoplessLogin(allowShoplessLogin); + selectionVO.setMessage(message); + selectionVO.setShops(shops == null ? new ArrayList<>() : new ArrayList<>(shops)); + return selectionVO; + } + + /** + * Run business method `buildLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildLoginShopMessage(List shops) { + if (shops == null || shops.isEmpty()) { + return "当前暂无可登录店铺"; + } + if (shops.size() == 1) { + return "已匹配到 1 家可登录店铺,已为您默认选中"; + } + return "该账号已绑定多家店铺,请选择本次登录店铺"; + } + + /** + * Run business method `buildAdminLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String buildAdminLoginShopMessage(List shops) { + if (shops == null || shops.isEmpty()) { + return "当前暂无启用店铺,可直接进入平台总览模式"; + } + if (shops.size() == 1) { + return "平台管理员将进入平台总览模式,店铺业务默认仅可查看"; + } + return "当前已有 " + shops.size() + " 家启用店铺;平台管理员将进入平台总览模式"; + } + + /** + * Run business method `resolveUserLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) { + if (Integer.valueOf(4).equals(userDO.getType())) { + return resolveAdminLoginShopId(userDO, requestedShopId); + } + Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId); + List activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()); + if (!activeShopIds.isEmpty()) { + if (normalizedRequestedShopId != null) { + if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号无权登录所选店铺"); + } + return normalizedRequestedShopId; + } + if (activeShopIds.size() == 1) { + return activeShopIds.get(0); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择登录店铺"); + } + + if (!userShopBindingSupport.hasBindingHistory(userDO.getId())) { + if (normalizedRequestedShopId != null) { + userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), normalizedRequestedShopId); + return normalizedRequestedShopId; + } + + Long legacyShopId = normalizeShopId(userDO.getShopId()); + if (legacyShopId != null && userShopBindingSupport.isShopActive(legacyShopId)) { + userShopBindingSupport.ensureUserBoundToShop(userDO.getId(), legacyShopId); + return legacyShopId; + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理"); + } + + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) { + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildLoginResponse(userDO, currentShopId, needSetPassword, null); + } + + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, boolean rememberMe) { + return buildLoginResponse(userDO, currentShopId, needSetPassword, null, rememberMe); + } + + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId) { + return buildLoginResponse(userDO, currentShopId, needSetPassword, previousSessionId, false); + } + + private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId, boolean rememberMe) { + UserSessionService.SessionIssueResult sessionIssueResult = StringUtils.hasText(previousSessionId) + ? userSessionService.rotateSession(previousSessionId, userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()) + : userSessionService.issueSession(userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()); + String accessToken = jwtUtil.generateAccessToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.accessJti(), + jwtUtil.resolveAccessTokenExpirationSeconds(rememberMe) + ); + String refreshToken = jwtUtil.generateRefreshToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.refreshJti() + ); + + LoginResponseVO responseVO = new LoginResponseVO(); + responseVO.setAccessToken(accessToken); + responseVO.setRefreshToken(refreshToken); + responseVO.setNeedSetPassword(needSetPassword); + responseVO.setUserInfo(buildLoginUserInfo(userDO, currentShopId)); + return responseVO; + } + + /** + * Run business method `buildLoginUserInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @return private LoginResponseVO.UserInfo result consumed by the caller or returned to the frontend + */ + private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) { + boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + List activeShopOptions = resolveShopOptions(userDO, true, !adminLogin); + Long normalizedCurrentShopId = normalizeShopId(currentShopId); + String currentShopName = activeShopOptions.stream() + .filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId)) + .map(ShopSimpleVO::getShopName) + .findFirst() + .orElseGet(() -> { + if (normalizedCurrentShopId == null) { + return null; + } + ShopVO shopVO = shopService.getShopById(normalizedCurrentShopId); + return shopVO == null ? null : shopVO.getShopName(); + }); + + LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo(); + userInfo.setId(userDO.getId()); + userInfo.setAccount(userDO.getAccount()); + userInfo.setNickname(userDO.getNickname()); + userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); + userInfo.setType(userDO.getType()); + userInfo.setShopId(normalizedCurrentShopId); + userInfo.setShopName(currentShopName); + ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); + userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); + userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); + userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); + userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); + userInfo.setCreateTime(userDO.getCreateTime()); + return userInfo; + } + + /** + * Run business method `resolveShopOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param onlyActiveBindings parameter `onlyActiveBindings` supplied by the caller + * @param onlyActiveShops parameter `onlyActiveShops` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) { + if (userDO == null) { + return new ArrayList<>(); + } + + List shopOptions; + if (Integer.valueOf(4).equals(userDO.getType())) { + shopOptions = new ArrayList<>(onlyActiveShops + ? userShopBindingSupport.listAllActiveShopOptions() + : listSelectableShopOptionsForPlatformAdmin()); + } else { + shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId( + userDO.getId(), + onlyActiveBindings, + onlyActiveShops + )); + } + + if (!shopOptions.isEmpty()) { + return shopOptions; + } + + if (userShopBindingSupport.hasBindingHistory(userDO.getId())) { + return shopOptions; + } + + Long legacyShopId = normalizeShopId(userDO.getShopId()); + if (legacyShopId != null) { + ShopVO legacyShop = shopService.getShopById(legacyShopId); + if (legacyShop != null && (!onlyActiveShops || Integer.valueOf(1).equals(legacyShop.getStatus()))) { + shopOptions.add(new ShopSimpleVO(legacyShop.getId(), legacyShop.getShopName())); + } + } + return shopOptions; + } + + /** + * Run business method `validateAndNormalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long validateAndNormalizeShopId(Long shopId) { + Long normalizedShopId = normalizeShopId(shopId); + if (normalizedShopId == null) { + return null; + } + if (!userShopBindingSupport.isShopActive(normalizedShopId)) { + if (userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedShopId) + && userShopBindingSupport.isShopAuthorizationExpired(normalizedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺已被冻结"); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("所属店铺不存在或已失效"); + } + return normalizedShopId; + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForAdmin() { + return shopService.listAllShopsForAdmin().stream() + .filter(shop -> Integer.valueOf(1).equals(shop.getStatus())) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * Purpose: listSelectableShopOptionsForPlatformAdmin supports UserServiceImpl.java by holding or executing the list selectable shop options for platform admin business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private List listSelectableShopOptionsForPlatformAdmin() { + return shopService.listAllShopsForAdmin().stream() + .filter(shop -> !Boolean.TRUE.equals(shop.getAuthorizationExpired())) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForUser(Long userId) { + return userShopBindingSupport.listShopOptionsByUserId(userId, true, false).stream() + .filter(shop -> userShopBindingSupport.isShopEnabledIgnoringAuthorization(shop.getId())) + .collect(Collectors.toList()); + } + + /** + * Run business method `validateUserPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param required parameter `required` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String validateUserPhone(String phone, Long currentUserId, boolean required) { + String normalizedPhone = phone == null ? null : phone.trim(); + if (!StringUtils.hasText(normalizedPhone)) { + if (required) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号不能为空"); + } + return null; + } + if (isDeletedPlaceholderPhone(normalizedPhone)) { + return normalizedPhone; + } + if (!normalizedPhone.matches(PHONE_REGEX)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号格式不正确"); + } + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param normalizedPhone parameter `normalizedPhone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePhoneNotUsed(normalizedPhone, currentUserId); + return normalizedPhone; + } + + /** + * Run business method `isDeletedPlaceholderPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isDeletedPlaceholderPhone(String phone) { + return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); + } + + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePhoneNotUsed(String phone, Long currentUserId) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getPhone, phone) + .eq(UserDO::getIsDelete, 0); + if (currentUserId != null) { + wrapper.ne(UserDO::getId, currentUserId); + } + if (userMapper.selectOne(wrapper) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("手机号已被使用"); + } + } + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserRelationVO result consumed by the caller or returned to the frontend + */ + private UserRelationVO buildRelationVO(Long userId) { + if (userId == null) { + return null; + } + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + return null; + } + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(userId); + vo.setShopId(relation.getShopId()); + vo.setShopName(relation.getShopId() == null ? null : Optional.ofNullable(shopService.getShopById(relation.getShopId())).map(ShopVO::getShopName).orElse(null)); + vo.setParentUserId(relation.getParentUserId()); + vo.setParentUserName(relation.getParentUserId() == null ? null : Optional.ofNullable(userMapper.selectById(relation.getParentUserId())).map(UserDO::getNickname).orElse(null)); + vo.setParentRoleType(relation.getParentRoleType()); + vo.setParentRoleTypeName(resolveUserTypeName(relation.getParentRoleType())); + vo.setSourceType(relation.getSourceType()); + vo.setSourceTypeName(resolveSourceTypeName(relation.getSourceType())); + return vo; + } + + /** + * Run business method `applyRelationInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyRelationInfo(UserVO userVO, Long userId) { + UserRelationVO relation = buildRelationVO(userId); + if (relation != null) { + userVO.setParentUserId(relation.getParentUserId()); + userVO.setParentUserName(relation.getParentUserName()); + userVO.setParentUserTypeName(relation.getParentRoleTypeName()); + userVO.setRelationSourceType(relation.getSourceTypeName()); + } + UserShopRoleDO roleBinding = userShopRoleMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, userId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1) + .last("limit 1")); + if (roleBinding != null) { + userVO.setShopRoleId(roleBinding.getRoleId()); + } + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } + + /** + * Run business method `resolveSourceTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveSourceTypeName(String sourceType) { + if (!StringUtils.hasText(sourceType)) { + return "-"; + } + return switch (sourceType) { + case "INVITE" -> "邀请码"; + case "DEFAULT_MANAGER" -> "默认店长"; + case "MANUAL" -> "手动"; + default -> sourceType; + }; + } + + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone) || phone.length() < 7) { + return phone; + } + return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); + } + + /** + * Run business method `maskEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param email parameter `email` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskEmail(String email) { + if (!StringUtils.hasText(email) || !email.contains("@")) { + return email; + } + int at = email.indexOf('@'); + return (at <= 1 ? "***" : email.substring(0, 1) + "***") + email.substring(at); + } + + /** + * Run business method `resolveRegisterShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveRegisterShopId(Long requestedShopId, String inviteCode) { + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(UserInviteCodeDO::getStatus, 1) + .last("limit 1")); + if (code != null) { + return code.getShopId(); + } + } + Long normalized = validateAndNormalizeShopId(requestedShopId); + if (normalized != null) { + return normalized; + } + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (currentShopId != null) { + return currentShopId; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void createRelationForRegister(Long userId, Long shopId, String inviteCode) { + UserRelationDO relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setShopId(shopId); + relation.setCreatorId(userId); + relation.setSourceType(StringUtils.hasText(inviteCode) ? "INVITE" : "DEFAULT_MANAGER"); + relation.setIsDelete(0); + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + if (code != null) { + relation.setParentUserId(code.getOwnerUserId()); + UserDO parent = userMapper.selectById(code.getOwnerUserId()); + relation.setParentRoleType(parent == null ? null : parent.getType()); + code.setUseCount((code.getUseCount() == null ? 0 : code.getUseCount()) + 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + } + } else if (shopId != null) { + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getType, 2) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("limit 1")); + relation.setParentUserId(manager == null ? null : manager.getId()); + relation.setParentRoleType(manager == null ? null : manager.getType()); + } + userRelationMapper.insert(relation); + } + + /** + * Run business method `resolveRelationFilteredUserIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set resolveRelationFilteredUserIds(Long roleId, Long parentUserId, String sourceType) { + if (roleId == null && parentUserId == null && !StringUtils.hasText(sourceType)) { + return null; + } + List relations = userRelationMapper.selectList(new LambdaQueryWrapper() + .eq(UserRelationDO::getIsDelete, 0)); + if (roleId != null) { + Set roleUserIds = userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, roleId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)) + .stream().map(UserShopRoleDO::getUserId).filter(Objects::nonNull).collect(Collectors.toSet()); + relations = relations.stream() + .filter(r -> roleUserIds.contains(r.getParentUserId())) + .collect(Collectors.toList()); + } + if (parentUserId != null) { + relations = relations.stream() + .filter(r -> Objects.equals(parentUserId, r.getParentUserId())) + .collect(Collectors.toList()); + } + if (StringUtils.hasText(sourceType)) { + relations = relations.stream() + .filter(r -> sourceType.equals(r.getSourceType())) + .collect(Collectors.toList()); + } + return relations.stream() + .map(UserRelationDO::getUserId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/support/UserProfileFieldSupport.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/support/UserProfileFieldSupport.java new file mode 100644 index 00000000..b78ebd93 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/support/UserProfileFieldSupport.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.support; + +import org.springframework.util.StringUtils; + +public final class UserProfileFieldSupport { + + private UserProfileFieldSupport() { + } + + public static String normalizeOptionalText(String value) { + if (!StringUtils.hasText(value)) { + return null; + } + return value.trim(); + } + + public static void requireWechatIdForServiceUser(Integer userType, String wechatId) { + if ((Integer.valueOf(2).equals(userType) || Integer.valueOf(3).equals(userType)) + && !StringUtils.hasText(wechatId)) { + throw new IllegalArgumentException("店长和美甲师的微信号不能为空"); + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/InviteCodeVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/InviteCodeVO.java new file mode 100644 index 00000000..7f571cd2 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/InviteCodeVO.java @@ -0,0 +1,58 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + /** + * Field `ownerUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ownerUserName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAgreementConsentVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAgreementConsentVO.java new file mode 100644 index 00000000..1503e238 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAgreementConsentVO.java @@ -0,0 +1,23 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@NoArgsConstructor +@AllArgsConstructor +/** + * Purpose: UserAgreementConsentVO supports UserAgreementConsentVO.java by holding or executing the user agreement consent vo business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UserAgreementConsentVO { + + /** + * Purpose: consentVersions supports UserAgreementConsentVO.java by holding or executing the consent versions business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Map consentVersions; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAssetVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAssetVO.java new file mode 100644 index 00000000..8a7b6685 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserAssetVO.java @@ -0,0 +1,74 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * UserAssetVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserAssetVO { + + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + + /** + * Field `balance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal balance; + + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalRechargeAmount; + + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime lastRechargeTime; + + /** + * Field `vipInfoId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long vipInfoId; + + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + /** + * Field `benefitId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long benefitId; + + /** + * Field `benefitInfo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String benefitInfo; + + /** + * Field `manualOverride` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean manualOverride; + + /** + * Field `vipStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime vipStartTime; + + /** + * Field `vipExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime vipExpireTime; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserRelationVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserRelationVO.java new file mode 100644 index 00000000..55be4638 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserRelationVO.java @@ -0,0 +1,52 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +@Data +/** + * UserRelationVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `parentRoleTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentRoleTypeName; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + /** + * Field `sourceTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceTypeName; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserStatisticsVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserStatisticsVO.java new file mode 100644 index 00000000..1fb40b97 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserStatisticsVO.java @@ -0,0 +1,53 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import lombok.Data; + +import java.util.Map; + +@Data +/** + * UserStatisticsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserStatisticsVO { + /** + * Field `totalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long totalUserCount; + /** + * Field `normalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long normalUserCount; + /** + * Field `employeeCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long employeeCount; + /** + * Field `managerCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long managerCount; + /** + * Field `artistCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long artistCount; + /** + * Field `vipUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long vipUserCount; + /** + * Field `newUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long newUserCount; + /** + * Field `byShop` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byShop; + /** + * Field `byRole` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byRole; + /** + * Field `byParent` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byParent; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserVO.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserVO.java new file mode 100644 index 00000000..b3781157 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/modules/user/vo/UserVO.java @@ -0,0 +1,168 @@ +package com.xiaowang.fingertipdesigner.core.modules.user.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +/** + * 系统用户信息表 VO + * 用于前端展示用户信息 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Data +public class UserVO { + + /** + * 用户唯一主键ID(雪花ID) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + + /** + * 所属店铺ID,关联店铺表主键(0表示无所属店铺) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long shopId; + + /** + * 店铺名称 + */ + private String shopName; + + /** + * 绑定店铺ID列表 + */ + @JsonSerialize(contentUsing = ToStringSerializer.class) + private List shopIds; + + /** + * 绑定店铺名称列表 + */ + private List shopNames; + + /** + * 用户昵称 + */ + private String nickname; + + /** + * 用户账号(登录用) + */ + private String account; + + /** + * 用户头像URL + */ + private String avatar; + + /** + * 用户签名 + */ + private String signature; + + /** + * 用户等级 + */ + private String level; + + /** + * 用户类型,(0-用户,2-店长,3-美甲师,4-管理员) + */ + private Integer type; + + /** + * 用户类型名称 + */ + private String typeName; + + /** + * 关联VIP信息表主键(0表示非VIP) + */ + @JsonSerialize(using = ToStringSerializer.class) + private Long vipId; + + /** + * VIP等级 + */ + private String vipLevel; + + /** + * 创建时间 + */ + private LocalDateTime createTime; + + /** + * 更新时间 + */ + private LocalDateTime updateTime; + + /** + * 用户状态:1-正常,0-禁用 + */ + private Integer status; + + /** + * 手机号 + */ + private String phone; + /** + * 联系电话 + */ + private String contactPhone; + /** + * 生日 + */ + private LocalDate birthday; + /** + * 微信号 + */ + private String wechatId; + /** + * 微信二维码 + */ + private String wechatQrCode; + /** + * Field `email` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String email; + /** + * Field `maskedPhone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedPhone; + /** + * Field `maskedEmail` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedEmail; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopRoleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopRoleId; + /** + * Field `shopRoleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopRoleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentUserTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserTypeName; + /** + * Field `relationSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relationSourceType; +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/RequestShopContext.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/RequestShopContext.java new file mode 100644 index 00000000..29d73688 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/RequestShopContext.java @@ -0,0 +1,67 @@ +package com.xiaowang.fingertipdesigner.core.support; + +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +/** + * 当前请求中的店铺上下文。 + */ +public final class RequestShopContext { + + /** + * Purpose: CURRENT_SHOP_ID_ATTRIBUTE supports RequestShopContext.java by holding or executing the current shop id attribute business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String CURRENT_SHOP_ID_ATTRIBUTE = "currentShopId"; + + private RequestShopContext() { + } + + /** + * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Long getCurrentShopId() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return null; + } + return parseShopId(attributes.getRequest().getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); + } + + /** + * Purpose: getCurrentShopId supports RequestShopContext.java by holding or executing the get current shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static Long getCurrentShopId(HttpServletRequest request) { + if (request == null) { + return null; + } + return parseShopId(request.getAttribute(CURRENT_SHOP_ID_ATTRIBUTE)); + } + + /** + * Purpose: parseShopId supports RequestShopContext.java by holding or executing the parse shop id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private static Long parseShopId(Object value) { + if (value == null) { + return null; + } + if (value instanceof Number number) { + long shopId = number.longValue(); + return shopId > 0 ? shopId : null; + } + if (value instanceof String text) { + try { + long shopId = Long.parseLong(text.trim()); + return shopId > 0 ? shopId : null; + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/cache/MultiLevelCacheService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/cache/MultiLevelCacheService.java new file mode 100644 index 00000000..7f837d6f --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/cache/MultiLevelCacheService.java @@ -0,0 +1,325 @@ +package com.xiaowang.fingertipdesigner.core.support.cache; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.xiaowang.fingertipdesigner.core.config.AppCacheProperties; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.ScanOptions; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashSet; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * 本地 + Redis 多级缓存。 + */ +@Component +@RequiredArgsConstructor +@Slf4j +public class MultiLevelCacheService { + + /** + * Purpose: NULL_SENTINEL supports MultiLevelCacheService.java by holding or executing the null sentinel business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String NULL_SENTINEL = "__CACHE_NULL__"; + + /** + * Purpose: stringRedisTemplate supports MultiLevelCacheService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports MultiLevelCacheService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + /** + * Purpose: cacheProperties supports MultiLevelCacheService.java by holding or executing the cache properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final AppCacheProperties cacheProperties; + + /** + * Purpose: localCache supports MultiLevelCacheService.java by holding or executing the local cache business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Cache localCache; + + /** + * Purpose: getLocalCache supports MultiLevelCacheService.java by holding or executing the get local cache business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Cache getLocalCache() { + if (localCache == null) { + localCache = Caffeine.newBuilder() + .maximumSize(Math.max(128, cacheProperties.getLocalMaxSize())) + .build(); + } + return localCache; + } + + public T getOrLoad(String key, + Duration localTtl, + Duration redisTtl, + TypeReference typeReference, + Supplier loader) { + CacheLookup lookup = get(key, localTtl, typeReference); + if (lookup.isHit()) { + return lookup.getValue(); + } + + T loaded = loader.get(); + put(key, loaded, localTtl, redisTtl); + return loaded; + } + + /** + * Purpose: get supports MultiLevelCacheService.java by holding or executing the get business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public CacheLookup get(String key, Duration localTtl, TypeReference typeReference) { + if (!StringUtils.hasText(key)) { + return CacheLookup.miss(); + } + + LocalCacheEntry localEntry = getLocalCache().getIfPresent(key); + if (localEntry != null) { + if (!localEntry.isExpired()) { + return CacheLookup.hit(readValue(localEntry.getJson(), typeReference)); + } + getLocalCache().invalidate(key); + } + + String json = readRedisValue(key); + if (!StringUtils.hasText(json)) { + return CacheLookup.miss(); + } + + putLocal(key, json, localTtl); + return CacheLookup.hit(readValue(json, typeReference)); + } + + /** + * Purpose: put supports MultiLevelCacheService.java by holding or executing the put business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void put(String key, Object value, Duration localTtl, Duration redisTtl) { + if (!StringUtils.hasText(key)) { + return; + } + String json = writeValue(value); + putLocal(key, json, localTtl); + writeRedisValue(key, json, redisTtl); + } + + /** + * Purpose: evict supports MultiLevelCacheService.java by holding or executing the evict business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void evict(String... keys) { + if (keys == null || keys.length == 0) { + return; + } + for (String key : keys) { + getLocalCache().invalidate(key); + } + deleteRedisKeys(Set.of(keys)); + } + + /** + * Purpose: evictByPrefix supports MultiLevelCacheService.java by holding or executing the evict by prefix business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void evictByPrefix(String prefix) { + if (!StringUtils.hasText(prefix)) { + return; + } + getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix)); + Set redisKeys = scanRedisKeys(prefix + "*"); + if (!CollectionUtils.isEmpty(redisKeys)) { + deleteRedisKeys(redisKeys); + } + } + + /** + * Purpose: readRedisValue supports MultiLevelCacheService.java by holding or executing the read redis value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String readRedisValue(String key) { + try { + return stringRedisTemplate.opsForValue().get(key); + } catch (Exception exception) { + log.warn("Redis cache read failed, key={}", key, exception); + return null; + } + } + + /** + * Purpose: writeRedisValue supports MultiLevelCacheService.java by holding or executing the write redis value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void writeRedisValue(String key, String json, Duration redisTtl) { + try { + stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); + } catch (Exception exception) { + log.warn("Redis cache write failed, key={}", key, exception); + } + } + + /** + * Purpose: deleteRedisKeys supports MultiLevelCacheService.java by holding or executing the delete redis keys business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void deleteRedisKeys(Set keys) { + if (CollectionUtils.isEmpty(keys)) { + return; + } + try { + stringRedisTemplate.delete(keys); + } catch (Exception exception) { + log.warn("Redis cache delete failed, size={}", keys.size(), exception); + } + } + + /** + * Purpose: scanRedisKeys supports MultiLevelCacheService.java by holding or executing the scan redis keys business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Set scanRedisKeys(String pattern) { + Set keys = new LinkedHashSet<>(); + try { + return stringRedisTemplate.execute((RedisConnection connection) -> { + Set matchedKeys = new LinkedHashSet<>(); + try (Cursor cursor = connection.scan(ScanOptions.scanOptions() + .match(pattern) + .count(500) + .build())) { + while (cursor.hasNext()) { + matchedKeys.add(new String(cursor.next(), StandardCharsets.UTF_8)); + } + } + return matchedKeys; + }); + } catch (Exception exception) { + log.warn("Redis cache scan failed, pattern={}", pattern, exception); + return keys; + } + } + + /** + * Purpose: putLocal supports MultiLevelCacheService.java by holding or executing the put local business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void putLocal(String key, String json, Duration localTtl) { + getLocalCache().put(key, new LocalCacheEntry(json, System.currentTimeMillis() + Math.max(1L, localTtl.toMillis()))); + } + + /** + * Purpose: writeValue supports MultiLevelCacheService.java by holding or executing the write value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String writeValue(Object value) { + try { + return value == null ? NULL_SENTINEL : objectMapper.writeValueAsString(value); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存序列化失败", exception); + } + } + + /** + * Purpose: readValue supports MultiLevelCacheService.java by holding or executing the read value business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private T readValue(String json, TypeReference typeReference) { + if (NULL_SENTINEL.equals(json)) { + return null; + } + try { + return objectMapper.readValue(json, typeReference); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存反序列化失败", exception); + } + } + + @Getter + /** + * Purpose: CacheLookup supports MultiLevelCacheService.java by holding or executing the cache lookup business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final class CacheLookup { + /** + * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final boolean hit; + /** + * Purpose: value supports MultiLevelCacheService.java by holding or executing the value business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final T value; + + private CacheLookup(boolean hit, T value) { + this.hit = hit; + this.value = value; + } + + /** + * Purpose: hit supports MultiLevelCacheService.java by holding or executing the hit business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static CacheLookup hit(T value) { + return new CacheLookup<>(true, value); + } + + /** + * Purpose: miss supports MultiLevelCacheService.java by holding or executing the miss business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static CacheLookup miss() { + return new CacheLookup<>(false, null); + } + } + + @Getter + @RequiredArgsConstructor + /** + * Purpose: LocalCacheEntry supports MultiLevelCacheService.java by holding or executing the local cache entry business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final class LocalCacheEntry { + /** + * Purpose: json supports MultiLevelCacheService.java by holding or executing the json business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final String json; + /** + * Purpose: expireAt supports MultiLevelCacheService.java by holding or executing the expire at business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long expireAt; + + /** + * Purpose: isExpired supports MultiLevelCacheService.java by holding or executing the is expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isExpired() { + return System.currentTimeMillis() >= expireAt; + } + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/id/TimeOrderedSnowflakeIdGenerator.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/id/TimeOrderedSnowflakeIdGenerator.java new file mode 100644 index 00000000..85e346cb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/id/TimeOrderedSnowflakeIdGenerator.java @@ -0,0 +1,275 @@ +package com.xiaowang.fingertipdesigner.core.support.id; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.lang.management.ManagementFactory; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.nio.charset.StandardCharsets; +import java.util.Enumeration; +import java.util.Locale; + +/** + * 时间高位雪花 ID 生成器。 + * 统一为数据库主键和业务有序标识提供趋势递增的唯一 ID。 + */ +@Slf4j +@Component +public class TimeOrderedSnowflakeIdGenerator { + + /** + * Purpose: DEFAULT_EPOCH supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the default epoch business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DEFAULT_EPOCH = 1704067200000L; + /** + * Purpose: WORKER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long WORKER_ID_BITS = 5L; + /** + * Purpose: DATACENTER_ID_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DATACENTER_ID_BITS = 5L; + /** + * Purpose: SEQUENCE_BITS supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence bits business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long SEQUENCE_BITS = 12L; + private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); + private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); + private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); + /** + * Purpose: WORKER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; + /** + * Purpose: DATACENTER_ID_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; + /** + * Purpose: TIMESTAMP_LEFT_SHIFT supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the timestamp left shift business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; + + /** + * Purpose: epoch supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the epoch business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long epoch; + /** + * Purpose: workerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the worker id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long workerId; + /** + * Purpose: datacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the datacenter id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final long datacenterId; + + /** + * Purpose: sequence supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the sequence business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long sequence = 0L; + /** + * Purpose: lastTimestamp supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the last timestamp business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private long lastTimestamp = -1L; + + public TimeOrderedSnowflakeIdGenerator( + @Value("${snowflake.epoch:" + DEFAULT_EPOCH + "}") long configuredEpoch, + @Value("${snowflake.worker-id:-1}") long configuredWorkerId, + @Value("${snowflake.datacenter-id:-1}") long configuredDatacenterId, + @Value("${spring.application.name:jayucloud-salon-core}") String applicationName + ) { + this.epoch = configuredEpoch > 0 ? configuredEpoch : DEFAULT_EPOCH; + this.datacenterId = resolveNodeId(configuredDatacenterId, MAX_DATACENTER_ID, resolveDatacenterId()); + this.workerId = resolveNodeId(configuredWorkerId, MAX_WORKER_ID, resolveWorkerId(applicationName)); + log.info("Snowflake generator ready: app={}, epoch={}, datacenterId={}, workerId={}", + applicationName, this.epoch, this.datacenterId, this.workerId); + } + + /** + * Purpose: nextId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public synchronized long nextId() { + long timestamp = currentTimeMillis(); + if (timestamp < lastTimestamp) { + timestamp = waitUntil(lastTimestamp); + } + + if (timestamp == lastTimestamp) { + sequence = (sequence + 1) & SEQUENCE_MASK; + if (sequence == 0L) { + timestamp = waitUntilNextMillis(lastTimestamp); + } + } else { + sequence = 0L; + } + + lastTimestamp = timestamp; + return ((timestamp - epoch) << TIMESTAMP_LEFT_SHIFT) + | (datacenterId << DATACENTER_ID_SHIFT) + | (workerId << WORKER_ID_SHIFT) + | sequence; + } + + /** + * Purpose: nextIdString supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next id string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextIdString() { + return Long.toUnsignedString(nextId()); + } + + /** + * Purpose: nextBase36String supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the next base36 string business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String nextBase36String(int width) { + String raw = Long.toUnsignedString(nextId(), 36).toUpperCase(Locale.ROOT); + if (raw.length() >= width) { + return raw.substring(raw.length() - width); + } + return "0".repeat(width - raw.length()) + raw; + } + + /** + * Purpose: currentTimeMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the current time millis business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long currentTimeMillis() { + return System.currentTimeMillis(); + } + + /** + * Purpose: waitUntil supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long waitUntil(long targetTimestamp) { + long timestamp = currentTimeMillis(); + while (timestamp < targetTimestamp) { + Thread.yield(); + timestamp = currentTimeMillis(); + } + return timestamp; + } + + /** + * Purpose: waitUntilNextMillis supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the wait until next millis business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long waitUntilNextMillis(long currentTimestamp) { + long timestamp = currentTimeMillis(); + while (timestamp <= currentTimestamp) { + Thread.yield(); + timestamp = currentTimeMillis(); + } + return timestamp; + } + + /** + * Purpose: resolveNodeId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve node id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveNodeId(long configuredValue, long maxValue, long fallbackValue) { + long candidate = configuredValue >= 0 ? configuredValue : fallbackValue; + return Math.floorMod(candidate, maxValue + 1); + } + + /** + * Purpose: resolveDatacenterId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve datacenter id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveDatacenterId() { + return stableHash(resolveMachineFingerprint()); + } + + /** + * Purpose: resolveWorkerId supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve worker id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long resolveWorkerId(String applicationName) { + return stableHash(applicationName + ":" + resolveProcessFingerprint()); + } + + /** + * Purpose: resolveMachineFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve machine fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveMachineFingerprint() { + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces != null && interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + if (networkInterface == null || networkInterface.isLoopback() || networkInterface.isVirtual()) { + continue; + } + byte[] hardwareAddress = networkInterface.getHardwareAddress(); + if (hardwareAddress != null && hardwareAddress.length > 0) { + return bytesToHex(hardwareAddress); + } + } + } catch (Exception exception) { + log.warn("Unable to resolve hardware address for snowflake datacenter id", exception); + } + + try { + return InetAddress.getLocalHost().getHostAddress(); + } catch (Exception exception) { + log.warn("Unable to resolve host address for snowflake datacenter id", exception); + return "fallback-host"; + } + } + + /** + * Purpose: resolveProcessFingerprint supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the resolve process fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveProcessFingerprint() { + try { + return ManagementFactory.getRuntimeMXBean().getName(); + } catch (Exception exception) { + return "pid-unknown"; + } + } + + /** + * Purpose: stableHash supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the stable hash business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private long stableHash(String value) { + if (value == null || value.isEmpty()) { + return 0L; + } + long hash = 1469598103934665603L; + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + for (byte currentByte : bytes) { + hash ^= currentByte; + hash *= 1099511628211L; + } + return hash & Long.MAX_VALUE; + } + + /** + * Purpose: bytesToHex supports TimeOrderedSnowflakeIdGenerator.java by holding or executing the bytes to hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String bytesToHex(byte[] source) { + StringBuilder builder = new StringBuilder(source.length * 2); + for (byte currentByte : source) { + builder.append(String.format("%02X", currentByte)); + } + return builder.toString(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/CachedBodyHttpServletRequest.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/CachedBodyHttpServletRequest.java new file mode 100644 index 00000000..ddc7ba78 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/CachedBodyHttpServletRequest.java @@ -0,0 +1,87 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 可重复读取 body 的请求包装。 + */ +public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper { + + /** + * Purpose: cachedBody supports CachedBodyHttpServletRequest.java by holding or executing the cached body business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final byte[] cachedBody; + + public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] cachedBody) { + super(request); + this.cachedBody = cachedBody == null ? new byte[0] : cachedBody; + } + + @Override + /** + * Purpose: getInputStream supports CachedBodyHttpServletRequest.java by holding or executing the get input stream business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public ServletInputStream getInputStream() { + ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody); + return new ServletInputStream() { + @Override + /** + * Purpose: isFinished supports CachedBodyHttpServletRequest.java by holding or executing the is finished business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isFinished() { + return inputStream.available() == 0; + } + + @Override + /** + * Purpose: isReady supports CachedBodyHttpServletRequest.java by holding or executing the is ready business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isReady() { + return true; + } + + @Override + /** + * Purpose: setReadListener supports CachedBodyHttpServletRequest.java by holding or executing the set read listener business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void setReadListener(ReadListener readListener) { + // no-op + } + + @Override + /** + * Purpose: read supports CachedBodyHttpServletRequest.java by holding or executing the read business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public int read() { + return inputStream.read(); + } + }; + } + + @Override + /** + * Purpose: getReader supports CachedBodyHttpServletRequest.java by holding or executing the get reader business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public BufferedReader getReader() throws IOException { + Charset charset = getCharacterEncoding() == null + ? StandardCharsets.UTF_8 + : Charset.forName(getCharacterEncoding()); + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardService.java new file mode 100644 index 00000000..4cab17cb --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardService.java @@ -0,0 +1,384 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.fingertipdesigner.core.support.RequestShopContext; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static com.xiaowang.fingertipdesigner.core.support.security.RequestSignatureService.REQUEST_BODY_ATTRIBUTE; + +@Component +@RequiredArgsConstructor +/** + * Purpose: OperationGuardService supports OperationGuardService.java by holding or executing the operation guard service business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class OperationGuardService { + + private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); + + static { + RELEASE_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else return 0 end" + ); + RELEASE_LOCK_SCRIPT.setResultType(Long.class); + } + + private static final TypeReference> MAP_TYPE = new TypeReference<>() { + }; + + /** + * Purpose: stringRedisTemplate supports OperationGuardService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports OperationGuardService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + + /** + * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public GuardHandle tryAcquire(HttpServletRequest request, String action, Duration ttl) { + String key = buildKey(request, action); + String token = UUID.randomUUID().toString(); + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + key, + token, + Math.max(1L, ttl == null ? 10L : ttl.getSeconds()), + TimeUnit.SECONDS + ); + return new GuardHandle(key, token, Boolean.TRUE.equals(success)); + } + + /** + * Purpose: release supports OperationGuardService.java by holding or executing the release business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void release(GuardHandle handle) { + if (handle == null || !handle.acquired()) { + return; + } + stringRedisTemplate.execute( + RELEASE_LOCK_SCRIPT, + Collections.singletonList(handle.key()), + handle.token() + ); + } + + /** + * Purpose: buildKey supports OperationGuardService.java by holding or executing the build key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String buildKey(HttpServletRequest request, String action) { + String safeAction = sanitize(action); + String path = request == null ? "-" : sanitize(request.getRequestURI()); + Long userId = request == null ? null : parseLong(request.getAttribute("userId")); + Integer userType = request == null ? null : parseInteger(request.getAttribute("userType")); + Long shopId = request == null ? null : RequestShopContext.getCurrentShopId(request); + + if (isUploadPath(path)) { + return buildUploadKey(request, safeAction, userId); + } + + String fingerprint = buildRequestFingerprint(request, path); + if (userId != null) { + if (isAdminRequest(path, userType)) { + return String.join(":", + "op", + "admin", + String.valueOf(userId), + safeAction, + sanitize(shopId), + fingerprint + ); + } + return String.join(":", + "op", + "user", + String.valueOf(userId), + safeAction, + fingerprint + ); + } + + String subject = resolvePublicSubject(request); + return String.join(":", + "op", + "public", + safeAction, + subject, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)) + ); + } + + /** + * Purpose: buildUploadKey supports OperationGuardService.java by holding or executing the build upload key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUploadKey(HttpServletRequest request, String action, Long userId) { + String uploadId = firstNonBlank( + request == null ? null : request.getParameter("uploadId"), + readBodyField(request, "uploadId") + ); + String chunkIndex = firstNonBlank( + request == null ? null : request.getParameter("chunkIndex"), + readBodyField(request, "chunkIndex") + ); + String suffix = StringUtils.hasText(chunkIndex) + ? sanitize(chunkIndex) + : buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + return String.join(":", + "op", + "upload", + sanitize(userId), + action, + sanitize(uploadId), + suffix + ); + } + + /** + * Purpose: buildRequestFingerprint supports OperationGuardService.java by holding or executing the build request fingerprint business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildRequestFingerprint(HttpServletRequest request, String path) { + String canonicalParams = buildCanonicalParams(request == null ? null : request.getParameterMap()); + String bodyHash = buildBodyHash(request); + String raw = String.join("|", + sanitize(path), + sanitize(canonicalParams), + sanitize(bodyHash) + ); + return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: resolvePublicSubject supports OperationGuardService.java by holding or executing the resolve public subject business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolvePublicSubject(HttpServletRequest request) { + for (String key : new String[]{"account", "phone", "shopId", "productId", "couponId", "userId", "uploadId", "ticket"}) { + String value = firstNonBlank( + request == null ? null : request.getParameter(key), + readBodyField(request, key) + ); + if (StringUtils.hasText(value)) { + return sanitize(value); + } + } + return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + } + + /** + * Purpose: buildBodyHash supports OperationGuardService.java by holding or executing the build body hash business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildBodyHash(HttpServletRequest request) { + if (request == null) { + return "-"; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return DigestUtils.md5DigestAsHex(bytes); + } + return DigestUtils.md5DigestAsHex( + buildCanonicalParams(request.getParameterMap()).getBytes(StandardCharsets.UTF_8) + ); + } + + /** + * Purpose: readBodyField supports OperationGuardService.java by holding or executing the read body field business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String readBodyField(HttpServletRequest request, String fieldName) { + if (request == null || !StringUtils.hasText(fieldName)) { + return null; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (!(cachedBody instanceof byte[] bytes) || bytes.length == 0) { + return null; + } + try { + Map payload = objectMapper.readValue(bytes, MAP_TYPE); + Object value = payload.get(fieldName); + return value == null ? null : String.valueOf(value); + } catch (Exception ignored) { + return null; + } + } + + /** + * Purpose: buildCanonicalParams supports OperationGuardService.java by holding or executing the build canonical params business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + Map sorted = new LinkedHashMap<>(); + parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach(entry -> sorted.put(entry.getKey(), entry.getValue())); + StringBuilder builder = new StringBuilder(); + sorted.forEach((key, values) -> { + if (builder.length() > 0) { + builder.append('&'); + } + builder.append(key) + .append('=') + .append(String.join(",", sortValues(values))); + }); + return builder.toString(); + } + + /** + * Purpose: sortValues supports OperationGuardService.java by holding or executing the sort values business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String[] sortValues(String[] values) { + String[] copy = values == null ? new String[0] : values.clone(); + Arrays.sort(copy, Comparator.nullsLast(String::compareTo)); + return copy; + } + + /** + * Purpose: isUploadPath supports OperationGuardService.java by holding or executing the is upload path business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isUploadPath(String path) { + return StringUtils.hasText(path) && path.contains("/upload/"); + } + + /** + * Purpose: isAdminRequest supports OperationGuardService.java by holding or executing the is admin request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAdminRequest(String path, Integer userType) { + return (StringUtils.hasText(path) && (path.startsWith("/admin/") || path.startsWith("/order/admin/"))) + || (userType != null && userType >= 2); + } + + /** + * Purpose: resolveClientIp supports OperationGuardService.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return "-"; + } + 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(); + } + + /** + * Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveDeviceId(HttpServletRequest request) { + if (request == null) { + return "-"; + } + return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); + } + + /** + * Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(Object value) { + if (value == null) { + return "-"; + } + String text = String.valueOf(value).trim(); + return text.isEmpty() ? "-" : text.replace(":", "_"); + } + + /** + * Purpose: firstNonBlank supports OperationGuardService.java by holding or executing the first non blank business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String firstNonBlank(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value.trim(); + } + } + return null; + } + + /** + * Purpose: parseLong supports OperationGuardService.java by holding or executing the parse long business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long parseLong(Object value) { + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Long.parseLong(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: parseInteger supports OperationGuardService.java by holding or executing the parse integer business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer parseInteger(Object value) { + if (value instanceof Number number) { + return number.intValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Integer.parseInt(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: GuardHandle supports OperationGuardService.java by holding or executing the guard handle business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record GuardHandle(String key, String token, boolean acquired) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardStrategy.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardStrategy.java new file mode 100644 index 00000000..4f242199 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/OperationGuardStrategy.java @@ -0,0 +1,10 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +/** + * Purpose: OperationGuardStrategy supports OperationGuardStrategy.java by holding or executing the operation guard strategy business role. + * Usage: reference this enum from the owning layer and pass validated inputs before reading or updating related state. + */ +public enum OperationGuardStrategy { + REJECT_IF_RUNNING, + NOOP_IF_DUPLICATE +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestSignatureService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestSignatureService.java new file mode 100644 index 00000000..95a99dc9 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestSignatureService.java @@ -0,0 +1,238 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import com.xiaowang.fingertipdesigner.core.config.RequestSignatureProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * 已登录写接口签名校验。 + */ +@Component +@RequiredArgsConstructor +public class RequestSignatureService { + + /** + * Purpose: REQUEST_BODY_ATTRIBUTE supports RequestSignatureService.java by holding or executing the request body attribute business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String REQUEST_BODY_ATTRIBUTE = "cachedRequestBody"; + /** + * Purpose: HEADER_TIMESTAMP supports RequestSignatureService.java by holding or executing the header timestamp business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_TIMESTAMP = "X-Timestamp"; + /** + * Purpose: HEADER_NONCE supports RequestSignatureService.java by holding or executing the header nonce business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_NONCE = "X-Nonce"; + /** + * Purpose: HEADER_SIGNATURE supports RequestSignatureService.java by holding or executing the header signature business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_SIGNATURE = "X-Signature"; + /** + * Purpose: HEADER_SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the header signature version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String HEADER_SIGNATURE_VERSION = "X-Sign-Version"; + + /** + * Purpose: SIGNATURE_VERSION supports RequestSignatureService.java by holding or executing the signature version business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SIGNATURE_VERSION = "v1"; + /** + * Purpose: HMAC_ALGORITHM supports RequestSignatureService.java by holding or executing the hmac algorithm business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + /** + * Purpose: properties supports RequestSignatureService.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RequestSignatureProperties properties; + /** + * Purpose: stringRedisTemplate supports RequestSignatureService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + + /** + * Purpose: validateRequest supports RequestSignatureService.java by holding or executing the validate request business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateRequest(HttpServletRequest request, String accessToken, Long userId) { + if (!properties.isEnabled() || isSafeMethod(request.getMethod())) { + return; + } + if (!StringUtils.hasText(accessToken)) { + throw new RuntimeException("请求签名缺少登录态"); + } + + String version = request.getHeader(HEADER_SIGNATURE_VERSION); + String timestamp = request.getHeader(HEADER_TIMESTAMP); + String nonce = request.getHeader(HEADER_NONCE); + String signature = request.getHeader(HEADER_SIGNATURE); + + if (!SIGNATURE_VERSION.equals(version)) { + throw new RuntimeException("请求签名版本不正确"); + } + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) { + throw new RuntimeException("请求签名缺失"); + } + + validateTimestamp(timestamp); + registerNonce(userId, nonce); + + String bodyHash = sha256Hex(resolvePayloadBytes(request)); + String canonical = request.getMethod().toUpperCase() + + "\n" + request.getRequestURI() + + "\n" + timestamp + + "\n" + nonce + + "\n" + bodyHash; + String expected = hmacSha256Hex(accessToken, canonical); + if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) { + throw new RuntimeException("请求签名无效"); + } + } + + /** + * Purpose: validateTimestamp supports RequestSignatureService.java by holding or executing the validate timestamp business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void validateTimestamp(String timestamp) { + long requestTimestamp; + try { + requestTimestamp = Long.parseLong(timestamp); + } catch (NumberFormatException exception) { + throw new RuntimeException("请求时间戳不合法"); + } + long now = Instant.now().toEpochMilli(); + long delta = Math.abs(now - requestTimestamp); + if (delta > properties.getWindowSeconds() * 1000L) { + throw new RuntimeException("请求已过期,请重试"); + } + } + + /** + * Purpose: registerNonce supports RequestSignatureService.java by holding or executing the register nonce business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void registerNonce(Long userId, String nonce) { + String nonceKey = "request:nonce:" + (userId == null ? "anon" : userId) + ":" + nonce; + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + nonceKey, + "1", + properties.getNonceRetentionSeconds(), + TimeUnit.SECONDS + ); + if (Boolean.FALSE.equals(success)) { + throw new RuntimeException("请求已失效,请勿重复提交"); + } + } + + /** + * Purpose: isSafeMethod supports RequestSignatureService.java by holding or executing the is safe method business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isSafeMethod(String method) { + if (!StringUtils.hasText(method)) { + return true; + } + String normalized = method.toUpperCase(); + return "GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized); + } + + /** + * Purpose: resolvePayloadBytes supports RequestSignatureService.java by holding or executing the resolve payload bytes business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private byte[] resolvePayloadBytes(HttpServletRequest request) { + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return bytes; + } + String canonicalParams = buildCanonicalParams(request.getParameterMap()); + return canonicalParams.getBytes(StandardCharsets.UTF_8); + } + + /** + * Purpose: buildCanonicalParams supports RequestSignatureService.java by holding or executing the build canonical params business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + return parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + String.join(",", sorted(entry.getValue()))) + .reduce((left, right) -> left + "&" + right) + .orElse(""); + } + + /** + * Purpose: sorted supports RequestSignatureService.java by holding or executing the sorted business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String[] sorted(String[] values) { + String[] result = values == null ? new String[0] : values.clone(); + Arrays.sort(result, Comparator.nullsLast(String::compareTo)); + return result; + } + + /** + * Purpose: sha256Hex supports RequestSignatureService.java by holding or executing the sha256 hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sha256Hex(byte[] payload) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(payload == null ? new byte[0] : payload); + return toHex(bytes); + } catch (Exception exception) { + throw new RuntimeException("计算请求摘要失败", exception); + } + } + + /** + * Purpose: hmacSha256Hex supports RequestSignatureService.java by holding or executing the hmac sha256 hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String hmacSha256Hex(String secret, String text) { + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); + return toHex(mac.doFinal(text.getBytes(StandardCharsets.UTF_8))); + } catch (Exception exception) { + throw new RuntimeException("计算请求签名失败", exception); + } + } + + /** + * Purpose: toHex supports RequestSignatureService.java by holding or executing the to hex business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String toHex(byte[] bytes) { + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte value : bytes) { + builder.append(String.format("%02x", value)); + } + return builder.toString(); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestThrottleService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestThrottleService.java new file mode 100644 index 00000000..8b33d468 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/RequestThrottleService.java @@ -0,0 +1,230 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import com.xiaowang.fingertipdesigner.core.config.LoginLockProperties; +import com.xiaowang.fingertipdesigner.core.config.RateLimitProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +@Component +@RequiredArgsConstructor +/** + * Purpose: RequestThrottleService supports RequestThrottleService.java by holding or executing the request throttle service business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class RequestThrottleService { + + /** + * Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String DEVICE_ID_HEADER = "X-Device-Id"; + + /** + * Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: rateLimitProperties supports RequestThrottleService.java by holding or executing the rate limit properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final RateLimitProperties rateLimitProperties; + /** + * Purpose: loginLockProperties supports RequestThrottleService.java by holding or executing the login lock properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final LoginLockProperties loginLockProperties; + + /** + * Purpose: checkLogin supports RequestThrottleService.java by holding or executing the check login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkLogin(HttpServletRequest request, String account) { + assertLoginNotLocked(request, account); + assertAllowed("login", request, sanitize(account), rateLimitProperties.getLogin(), "登录过于频繁,请稍后再试"); + } + + /** + * Purpose: checkRegister supports RequestThrottleService.java by holding or executing the check register business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkRegister(HttpServletRequest request, String account) { + assertAllowed("register", request, sanitize(account), rateLimitProperties.getRegister(), "注册过于频繁,请稍后再试"); + } + + /** + * Purpose: checkSendCode supports RequestThrottleService.java by holding or executing the check send code business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkSendCode(HttpServletRequest request, String phone) { + assertAllowed("send-code", request, sanitize(phone), rateLimitProperties.getSendCode(), "验证码发送过于频繁,请稍后再试"); + } + + /** + * Purpose: checkResetPassword supports RequestThrottleService.java by holding or executing the check reset password business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkResetPassword(HttpServletRequest request, String phone) { + assertAllowed("reset-password", request, sanitize(phone), rateLimitProperties.getResetPassword(), "密码重置请求过于频繁,请稍后再试"); + } + + /** + * Purpose: checkWechatMiniLogin supports RequestThrottleService.java by holding or executing the check wechat mini login business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkWechatMiniLogin(HttpServletRequest request, String subject) { + assertAllowed("wechat-mini-login", request, sanitize(subject), rateLimitProperties.getWechatMiniLogin(), "微信登录过于频繁,请稍后再试"); + } + + /** + * Purpose: checkAgreementRead supports RequestThrottleService.java by holding or executing the check agreement read business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkAgreementRead(HttpServletRequest request, String agreementType) { + assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); + } + + /** + * Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) { + String path = request.getRequestURI(); + RateLimitProperties.LimitRule rule = rateLimitProperties.getAuthenticatedWrite(); + String message = "操作过于频繁,请稍后再试"; + String category = "write:" + path; + if ("/order/create".equals(path)) { + rule = rateLimitProperties.getOrderCreate(); + message = "下单过于频繁,请稍后再试"; + } + assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); + } + + /** + * Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void recordLoginFailure(HttpServletRequest request, String account) { + if (loginLockProperties.getMaxFailures() <= 0 || loginLockProperties.getWindowSeconds() <= 0) { + return; + } + String key = buildLoginFailureKey(request, account); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, loginLockProperties.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count >= loginLockProperties.getMaxFailures()) { + stringRedisTemplate.opsForValue().set(buildLoginLockKey(request, account), "1", loginLockProperties.getLockSeconds(), TimeUnit.SECONDS); + } + } + + /** + * Purpose: clearLoginFailure supports RequestThrottleService.java by holding or executing the clear login failure business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void clearLoginFailure(HttpServletRequest request, String account) { + stringRedisTemplate.delete(buildLoginFailureKey(request, account)); + stringRedisTemplate.delete(buildLoginLockKey(request, account)); + } + + private void assertAllowed(String category, + HttpServletRequest request, + String subject, + RateLimitProperties.LimitRule rule, + String message) { + if (rule == null || rule.getLimit() <= 0 || rule.getWindowSeconds() <= 0) { + return; + } + String raw = String.join("|", + category, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)), + sanitize(subject) + ); + String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, rule.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count > rule.getLimit()) { + throw new RuntimeException(message); + } + } + + /** + * Purpose: assertLoginNotLocked supports RequestThrottleService.java by holding or executing the assert login not locked business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void assertLoginNotLocked(HttpServletRequest request, String account) { + Boolean locked = stringRedisTemplate.hasKey(buildLoginLockKey(request, account)); + if (Boolean.TRUE.equals(locked)) { + throw new RuntimeException("登录失败次数过多,请稍后再试"); + } + } + + /** + * Purpose: buildLoginFailureKey supports RequestThrottleService.java by holding or executing the build login failure key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginFailureKey(HttpServletRequest request, String account) { + return "login:fail:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: buildLoginLockKey supports RequestThrottleService.java by holding or executing the build login lock key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginLockKey(HttpServletRequest request, String account) { + return "login:lock:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: buildLoginLockRaw supports RequestThrottleService.java by holding or executing the build login lock raw business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildLoginLockRaw(HttpServletRequest request, String account) { + return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); + } + + /** + * Purpose: resolveClientIp supports RequestThrottleService.java by holding or executing the resolve client ip business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return "-"; + } + 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(); + } + + /** + * Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveDeviceId(HttpServletRequest request) { + return request == null ? null : request.getHeader(DEVICE_ID_HEADER); + } + + /** + * Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sanitize(String value) { + return StringUtils.hasText(value) ? value.trim() : "-"; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UploadSecurityValidator.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UploadSecurityValidator.java new file mode 100644 index 00000000..9c26fcea --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UploadSecurityValidator.java @@ -0,0 +1,146 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import com.xiaowang.fingertipdesigner.core.config.UploadSecurityProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Locale; +import java.util.Set; + +@Component +@RequiredArgsConstructor +/** + * Purpose: UploadSecurityValidator supports UploadSecurityValidator.java by holding or executing the upload security validator business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class UploadSecurityValidator { + + private static final Set BLOCKED_EXTENSIONS = Set.of( + ".jsp", ".jspx", ".php", ".asp", ".aspx", ".js", ".html", ".htm", ".exe", ".bat", ".cmd", ".sh", ".jar" + ); + + private static final Set IMAGE_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp", ".gif"); + + private static final Set COMPATIBLE_IMAGE_MIME_TYPES = Set.of( + "image/jpeg", + "image/jpg", + "image/pjpeg", + "image/png", + "image/webp", + "image/gif" + ); + + /** + * Purpose: properties supports UploadSecurityValidator.java by holding or executing the properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final UploadSecurityProperties properties; + + /** + * Purpose: validate supports UploadSecurityValidator.java by holding or executing the validate business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validate(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new RuntimeException("上传文件不能为空"); + } + if (file.getSize() > properties.getMaxSize()) { + throw new RuntimeException("上传文件过大"); + } + String filename = file.getOriginalFilename(); + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String contentType = normalizeContentType(file.getContentType()); + if (!contentType.isEmpty() && !isAllowedMimeType(contentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + if (isLikelyImage(extension, contentType) && !IMAGE_EXTENSIONS.contains(extension)) { + throw new RuntimeException("图片文件扩展名不匹配"); + } + } + + /** + * Purpose: validateMetadata supports UploadSecurityValidator.java by holding or executing the validate metadata business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateMetadata(String filename, String contentType, Long fileSize) { + if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxTotalSize()) { + throw new RuntimeException("上传文件大小不合法"); + } + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String normalizedContentType = normalizeContentType(contentType); + if (!normalizedContentType.isEmpty() && !isAllowedMimeType(normalizedContentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + } + + /** + * Purpose: validateChunk supports UploadSecurityValidator.java by holding or executing the validate chunk business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void validateChunk(MultipartFile chunkFile) { + if (chunkFile == null || chunkFile.isEmpty()) { + throw new RuntimeException("上传分片不能为空"); + } + if (chunkFile.getSize() > properties.getMaxSize()) { + throw new RuntimeException("上传文件过大"); + } + String filename = chunkFile.getOriginalFilename(); + String extension = resolveExtension(filename); + if (StringUtils.hasText(extension) && BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + } + + /** + * Purpose: isAllowedMimeType supports UploadSecurityValidator.java by holding or executing the is allowed mime type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isAllowedMimeType(String contentType) { + return properties.getAllowedMimeTypes().contains(contentType) || COMPATIBLE_IMAGE_MIME_TYPES.contains(contentType); + } + + /** + * Purpose: isLikelyImage supports UploadSecurityValidator.java by holding or executing the is likely image business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean isLikelyImage(String extension, String contentType) { + return IMAGE_EXTENSIONS.contains(extension) || contentType.startsWith("image/"); + } + + /** + * Purpose: normalizeContentType supports UploadSecurityValidator.java by holding or executing the normalize content type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String normalizeContentType(String contentType) { + return StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT).trim() : ""; + } + + /** + * Purpose: resolveExtension supports UploadSecurityValidator.java by holding or executing the resolve extension business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String resolveExtension(String filename) { + if (!StringUtils.hasText(filename) || !filename.contains(".")) { + return ""; + } + String normalized = filename.trim(); + int queryIndex = normalized.indexOf('?'); + if (queryIndex >= 0) { + normalized = normalized.substring(0, queryIndex); + } + int fragmentIndex = normalized.indexOf('#'); + if (fragmentIndex >= 0) { + normalized = normalized.substring(0, fragmentIndex); + } + int dotIndex = normalized.lastIndexOf("."); + return dotIndex >= 0 ? normalized.substring(dotIndex).toLowerCase(Locale.ROOT) : ""; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UserSessionService.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UserSessionService.java new file mode 100644 index 00000000..418d7338 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/support/security/UserSessionService.java @@ -0,0 +1,254 @@ +package com.xiaowang.fingertipdesigner.core.support.security; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.fingertipdesigner.core.config.JwtProperties; +import com.xiaowang.fingertipdesigner.core.support.id.TimeOrderedSnowflakeIdGenerator; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * 基于 Redis 的登录会话状态。 + */ +@Component +@RequiredArgsConstructor +public class UserSessionService { + + /** + * Purpose: SESSION_KEY_PREFIX supports UserSessionService.java by holding or executing the session key prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String SESSION_KEY_PREFIX = "auth:session:"; + /** + * Purpose: USER_SESSION_SET_PREFIX supports UserSessionService.java by holding or executing the user session set prefix business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:"; + + /** + * Purpose: stringRedisTemplate supports UserSessionService.java by holding or executing the string redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final StringRedisTemplate stringRedisTemplate; + /** + * Purpose: objectMapper supports UserSessionService.java by holding or executing the object mapper business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final ObjectMapper objectMapper; + /** + * Purpose: jwtProperties supports UserSessionService.java by holding or executing the jwt properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtProperties jwtProperties; + /** + * Purpose: idGenerator supports UserSessionService.java by holding or executing the id generator business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final TimeOrderedSnowflakeIdGenerator idGenerator; + + /** + * Purpose: issueSession supports UserSessionService.java by holding or executing the issue session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public SessionIssueResult issueSession(Long userId, String account, Long shopId, Integer userType) { + String sessionId = idGenerator.nextIdString(); + String accessJti = idGenerator.nextIdString(); + String refreshJti = idGenerator.nextIdString(); + SessionState state = SessionState.builder() + .sessionId(sessionId) + .userId(userId) + .account(account) + .shopId(shopId) + .userType(userType) + .accessJti(accessJti) + .refreshJti(refreshJti) + .build(); + save(state); + return new SessionIssueResult(sessionId, accessJti, refreshJti); + } + + /** + * Purpose: rotateSession supports UserSessionService.java by holding or executing the rotate session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public SessionIssueResult rotateSession(String previousSessionId, Long userId, String account, Long shopId, Integer userType) { + revokeSession(previousSessionId); + return issueSession(userId, account, shopId, userType); + } + + /** + * Purpose: isAccessSessionActive supports UserSessionService.java by holding or executing the is access session active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isAccessSessionActive(Long userId, String sessionId, String accessJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(accessJti) && accessJti.equals(state.getAccessJti()); + } + + /** + * Purpose: isRefreshSessionActive supports UserSessionService.java by holding or executing the is refresh session active business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isRefreshSessionActive(Long userId, String sessionId, String refreshJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(refreshJti) && refreshJti.equals(state.getRefreshJti()); + } + + /** + * Purpose: revokeSession supports UserSessionService.java by holding or executing the revoke session business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void revokeSession(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return; + } + SessionState state = getSessionState(sessionId); + stringRedisTemplate.delete(buildSessionKey(sessionId)); + if (state != null && state.getUserId() != null) { + stringRedisTemplate.opsForSet().remove(buildUserSessionSetKey(state.getUserId()), sessionId); + } + } + + /** + * Purpose: revokeAllUserSessions supports UserSessionService.java by holding or executing the revoke all user sessions business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public void revokeAllUserSessions(Long userId) { + if (userId == null) { + return; + } + String setKey = buildUserSessionSetKey(userId); + Set sessionIds = stringRedisTemplate.opsForSet().members(setKey); + if (sessionIds != null) { + for (String sessionId : sessionIds) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + } + } + stringRedisTemplate.delete(setKey); + } + + /** + * Purpose: matches supports UserSessionService.java by holding or executing the matches business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private boolean matches(SessionState state, Long userId) { + return state != null && state.getUserId() != null && state.getUserId().equals(userId); + } + + /** + * Purpose: save supports UserSessionService.java by holding or executing the save business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private void save(SessionState state) { + try { + String sessionKey = buildSessionKey(state.getSessionId()); + String setKey = buildUserSessionSetKey(state.getUserId()); + Duration ttl = Duration.ofSeconds(jwtProperties.getRefreshTokenExpirationSeconds()); + String json = objectMapper.writeValueAsString(state); + stringRedisTemplate.opsForValue().set(sessionKey, json, ttl.getSeconds(), TimeUnit.SECONDS); + stringRedisTemplate.opsForSet().add(setKey, state.getSessionId()); + stringRedisTemplate.expire(setKey, ttl.getSeconds(), TimeUnit.SECONDS); + } catch (JsonProcessingException exception) { + throw new RuntimeException("写入登录会话失败", exception); + } + } + + /** + * Purpose: getSessionState supports UserSessionService.java by holding or executing the get session state business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SessionState getSessionState(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return null; + } + String json = stringRedisTemplate.opsForValue().get(buildSessionKey(sessionId)); + if (!StringUtils.hasText(json)) { + return null; + } + try { + return objectMapper.readValue(json, SessionState.class); + } catch (JsonProcessingException exception) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + return null; + } + } + + /** + * Purpose: buildSessionKey supports UserSessionService.java by holding or executing the build session key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildSessionKey(String sessionId) { + return SESSION_KEY_PREFIX + sessionId; + } + + /** + * Purpose: buildUserSessionSetKey supports UserSessionService.java by holding or executing the build user session set key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String buildUserSessionSetKey(Long userId) { + return USER_SESSION_SET_PREFIX + userId; + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + /** + * Purpose: SessionState supports UserSessionService.java by holding or executing the session state business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ + public static class SessionState { + /** + * Purpose: sessionId supports UserSessionService.java by holding or executing the session id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String sessionId; + /** + * Purpose: userId supports UserSessionService.java by holding or executing the user id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long userId; + /** + * Purpose: account supports UserSessionService.java by holding or executing the account business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String account; + /** + * Purpose: shopId supports UserSessionService.java by holding or executing the shop id business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Long shopId; + /** + * Purpose: userType supports UserSessionService.java by holding or executing the user type business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private Integer userType; + /** + * Purpose: accessJti supports UserSessionService.java by holding or executing the access jti business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String accessJti; + /** + * Purpose: refreshJti supports UserSessionService.java by holding or executing the refresh jti business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private String refreshJti; + } + + /** + * Purpose: SessionIssueResult supports UserSessionService.java by holding or executing the session issue result business role. + * Usage: reference this record from the owning layer and pass validated inputs before reading or updating related state. + */ + public record SessionIssueResult(String sessionId, String accessJti, String refreshJti) { + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/AccountValidationUtils.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/AccountValidationUtils.java new file mode 100644 index 00000000..2fb14504 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/AccountValidationUtils.java @@ -0,0 +1,66 @@ +package com.xiaowang.fingertipdesigner.core.utils; + +import org.springframework.util.StringUtils; + +import java.util.regex.Pattern; + +/** + * Purpose: AccountValidationUtils supports AccountValidationUtils.java by holding or executing the account validation utils business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public final class AccountValidationUtils { + + /** + * Purpose: ACCOUNT_REGEX supports AccountValidationUtils.java by holding or executing the account regex business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + public static final String ACCOUNT_REGEX = "^[A-Za-z0-9]+$"; + private static final Pattern ACCOUNT_PATTERN = Pattern.compile(ACCOUNT_REGEX); + + private AccountValidationUtils() { + } + + /** + * Purpose: normalizeAccount supports AccountValidationUtils.java by holding or executing the normalize account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String normalizeAccount(String account) { + return account == null ? "" : account.trim(); + } + + /** + * Purpose: ensureValidAccountFormat supports AccountValidationUtils.java by holding or executing the ensure valid account format business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static void ensureValidAccountFormat(String account) { + if (!StringUtils.hasText(account)) { + throw new RuntimeException("账号不能为空"); + } + if (!ACCOUNT_PATTERN.matcher(account).matches()) { + throw new RuntimeException("账号只能包含字母和数字"); + } + } + + /** + * Purpose: requireValidAccount supports AccountValidationUtils.java by holding or executing the require valid account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String requireValidAccount(String account) { + String normalized = normalizeAccount(account); + ensureValidAccountFormat(normalized); + return normalized; + } + + /** + * Purpose: validateOptionalAccount supports AccountValidationUtils.java by holding or executing the validate optional account business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public static String validateOptionalAccount(String account) { + if (account == null) { + return null; + } + String normalized = normalizeAccount(account); + ensureValidAccountFormat(normalized); + return normalized; + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/JwtUtil.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/JwtUtil.java new file mode 100644 index 00000000..7ab043e5 --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/JwtUtil.java @@ -0,0 +1,236 @@ +package com.xiaowang.fingertipdesigner.core.utils; + +import com.xiaowang.fingertipdesigner.core.config.JwtProperties; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +@Component +@RequiredArgsConstructor +/** + * Purpose: JwtUtil supports JwtUtil.java by holding or executing the jwt util business role. + * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. + */ +public class JwtUtil { + + /** + * Purpose: jwtProperties supports JwtUtil.java by holding or executing the jwt properties business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private final JwtProperties jwtProperties; + + /** + * Purpose: getKey supports JwtUtil.java by holding or executing the get key business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private SecretKey getKey() { + return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); + } + + /** + * Purpose: generateAccessToken supports JwtUtil.java by holding or executing the generate access token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { + return generateAccessToken(userId, account, currentShopId, sessionId, jti, jwtProperties.getAccessTokenExpirationSeconds()); + } + + public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti, long expirationSeconds) { + Map claims = new HashMap<>(); + claims.put("userId", userId); + claims.put("account", account); + claims.put("type", "access"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); + if (currentShopId != null && currentShopId > 0) { + claims.put("shopId", currentShopId); + } + return createToken(claims, userId.toString(), expirationSeconds * 1000); + } + + public long resolveAccessTokenExpirationSeconds(boolean rememberMe) { + return rememberMe + ? jwtProperties.getRememberMeAccessTokenExpirationSeconds() + : jwtProperties.getAccessTokenExpirationSeconds(); + } + + /** + * Purpose: generateRefreshToken supports JwtUtil.java by holding or executing the generate refresh token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String generateRefreshToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { + Map claims = new HashMap<>(); + claims.put("userId", userId); + claims.put("account", account); + claims.put("type", "refresh"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); + if (currentShopId != null && currentShopId > 0) { + claims.put("shopId", currentShopId); + } + return createToken(claims, userId.toString(), jwtProperties.getRefreshTokenExpirationSeconds() * 1000); + } + + /** + * Purpose: createToken supports JwtUtil.java by holding or executing the create token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + private String createToken(Map claims, String subject, long expiration) { + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + expiration); + + return Jwts.builder() + .setClaims(claims) + .setSubject(subject) + .setIssuer(jwtProperties.getIssuer()) + .setIssuedAt(now) + .setExpiration(expiryDate) + .signWith(getKey(), SignatureAlgorithm.HS512) + .compact(); + } + + /** + * Purpose: parseToken supports JwtUtil.java by holding or executing the parse token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Claims parseToken(String token) { + return Jwts.parserBuilder() + .setSigningKey(getKey()) + .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) + .requireIssuer(jwtProperties.getIssuer()) + .build() + .parseClaimsJws(token) + .getBody(); + } + + /** + * Purpose: getUserIdFromToken supports JwtUtil.java by holding or executing the get user id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getUserIdFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("userId", Long.class); + } + + /** + * Purpose: getAccountFromToken supports JwtUtil.java by holding or executing the get account from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getAccountFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("account", String.class); + } + + /** + * Purpose: getTokenType supports JwtUtil.java by holding or executing the get token type business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getTokenType(String token) { + Claims claims = parseToken(token); + return claims.get("type", String.class); + } + + /** + * Purpose: getSessionIdFromToken supports JwtUtil.java by holding or executing the get session id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getSessionIdFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("sessionId", String.class); + } + + /** + * Purpose: getJtiFromToken supports JwtUtil.java by holding or executing the get jti from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getJtiFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("jti", String.class); + } + + /** + * Purpose: getIssuerFromToken supports JwtUtil.java by holding or executing the get issuer from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public String getIssuerFromToken(String token) { + Claims claims = parseToken(token); + return claims.getIssuer(); + } + + /** + * Purpose: getShopIdFromToken supports JwtUtil.java by holding or executing the get shop id from token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public Long getShopIdFromToken(String token) { + Claims claims = parseToken(token); + Object value = claims.get("shopId"); + if (value == null) { + return null; + } + if (value instanceof Integer integer) { + return integer.longValue(); + } + if (value instanceof Long longValue) { + return longValue; + } + if (value instanceof String text) { + try { + return Long.parseLong(text); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + /** + * Purpose: isTokenExpired supports JwtUtil.java by holding or executing the is token expired business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isTokenExpired(String token) { + try { + Claims claims = parseToken(token); + return claims.getExpiration().before(new Date()); + } catch (Exception e) { + return true; + } + } + + /** + * Purpose: validateToken supports JwtUtil.java by holding or executing the validate token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean validateToken(String token) { + try { + parseToken(token); + return !isTokenExpired(token); + } catch (Exception e) { + return false; + } + } + + /** + * Purpose: isAccessToken supports JwtUtil.java by holding or executing the is access token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isAccessToken(String token) { + return "access".equals(getTokenType(token)); + } + + /** + * Purpose: isRefreshToken supports JwtUtil.java by holding or executing the is refresh token business role. + * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. + */ + public boolean isRefreshToken(String token) { + return "refresh".equals(getTokenType(token)); + } +} diff --git a/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/RedisUtils.java b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/RedisUtils.java new file mode 100644 index 00000000..fd5dd9cf --- /dev/null +++ b/FM-Core/src/main/java/com/xiaowang/fingertipdesigner/core/utils/RedisUtils.java @@ -0,0 +1,253 @@ +package com.xiaowang.fingertipdesigner.core.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Component +public class RedisUtils { + + @Autowired + /** + * Purpose: redisTemplate supports RedisUtils.java by holding or executing the redis template business role. + * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. + */ + private RedisTemplate redisTemplate; + + /** + * 指定缓存失效时间 + * @param key 键 + * @param time 时间(秒) + * @return + */ + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 根据key 获取过期时间 + * @param key 键 不能为null + * @return 时间(秒) 返回0代表为永久有效 + */ + public long getExpire(String key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + /** + * 判断key是否存在 + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除缓存 + * @param key 可以传一个值 或多个 + */ + @SuppressWarnings("unchecked") + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete((Collection) CollectionUtils.arrayToList(key)); + } + } + } + + // ============================String============================= + /** + * 普通缓存获取 + * @param key 键 + * @return 值 + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 普通缓存放入 + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + // ================================Hash================================= + /** + * HashGet + * @param key 键 不能为null + * @param item 项 不能为null + * @return 值 + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * @param key 键 + * @param item 项 + * @param value 值 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * @param key 键 + * @param item 项 + * @param value 值 + * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 获取hashKey对应的所有键值 + * @param key 键 + * @return 对应的多个键值 + */ + public Map hmget(String key) { + return redisTemplate.opsForHash().entries(key); + } + + // ============================set============================= + /** + * 根据key获取Set中的所有值 + * @param key 键 + * @return + */ + public Set sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将数据放入set缓存 + * @param key 键 + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + // ===============================list================================= + /** + * 获取list缓存的内容 + * @param key 键 + * @param start 开始 + * @param end 结束 0 到 -1代表所有值 + * @return + */ + public List lGet(String key, long start, long end) { + try { + return redisTemplate.opsForList().range(key, start, end); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 将list放入缓存 + * @param key 键 + * @param value 值 + * @return + */ + public boolean lSet(String key, Object value) { + try { + redisTemplate.opsForList().rightPush(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/FM-Core/src/main/resources/application.yaml b/FM-Core/src/main/resources/application.yaml new file mode 100644 index 00000000..e0a1f54c --- /dev/null +++ b/FM-Core/src/main/resources/application.yaml @@ -0,0 +1,138 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3306/jayucloud_salon?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + servlet: + multipart: + max-file-size: 5MB + max-request-size: 10MB + jackson: + time-zone: Asia/Shanghai + date-format: yyyy-MM-dd HH:mm:ss + +logging: + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" + +server: + servlet: + encoding: + charset: UTF-8 + force: true + enabled: true + timezone: Asia/Shanghai + +mybatis: + configuration: + map-underscore-to-camel-case: true + +fingertip-designer: + brand: + message-template-name: ${PLATFORM_MESSAGE_TEMPLATE_NAME:FingertipDesigner} + manager-register-shop-description: ${PLATFORM_MANAGER_REGISTER_SHOP_DESCRIPTION:甲屿店务注册店铺} + security: + jwt: + issuer: fingertip-designer + access-token-expiration-seconds: 7200 + remember-me-access-token-expiration-seconds: 604800 + refresh-token-expiration-seconds: 604800 + clock-skew-seconds: 30 + signature: + enabled: true + window-seconds: 300 + nonce-retention-seconds: 600 + rate-limit: + login: + limit: 10 + window-seconds: 60 + send-code: + limit: 5 + window-seconds: 60 + reset-password: + limit: 5 + window-seconds: 600 + authenticated-write: + limit: 80 + window-seconds: 60 + order-create: + limit: 10 + window-seconds: 60 + cache: + local-max-size: 2048 + product-detail: + local-ttl-seconds: 120 + redis-ttl-seconds: 900 + product-list: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + product-search: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + shop: + local-ttl-seconds: 180 + redis-ttl-seconds: 900 + tag: + local-ttl-seconds: 300 + redis-ttl-seconds: 1200 + object-storage-file: + local-ttl-seconds: 300 + redis-ttl-seconds: 1800 + dashboard: + local-ttl-seconds: 30 + redis-ttl-seconds: 90 + 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 + +object-storage: + provider-order: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + replica-required-providers: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + primary-provider: MINIO + backup-provider: QINIU_KODO,ALIYUN_OSS + signed-url-expire-minutes: 60 + backup-queue-name: fingertip-designer.file.object-storage.backup.queue + backup-exchange-name: fingertip-designer.file.object-storage.backup.exchange + backup-routing-key: fingertip-designer.file.object-storage.backup + backup-retry-batch-limit: 500 + backup-retry-cron: "0 0 2 * * ?" + +qiniu: + kodo: + access-key: ${QINIU_KODO_ACCESS_KEY:} + secret-key: ${QINIU_KODO_SECRET_KEY:} + bucket-name: ${QINIU_KODO_BUCKET_NAME:} + domain: ${QINIU_KODO_DOMAIN:} + zone: ${QINIU_KODO_ZONE:z2} + private-bucket: ${QINIU_KODO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${QINIU_KODO_SIGNED_URL_EXPIRE_MINUTES:60} + +minio: + enabled: ${MINIO_ENABLED:false} + endpoint: ${MINIO_ENDPOINT:} + bucket-name: ${MINIO_BUCKET_NAME:} + access-key: ${MINIO_ACCESS_KEY:} + secret-key: ${MINIO_SECRET_KEY:} + private-bucket: ${MINIO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${MINIO_SIGNED_URL_EXPIRE_MINUTES:60} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:false} + endpoint: ${ALIYUN_OSS_ENDPOINT:} + region: ${ALIYUN_OSS_REGION:} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID:} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET:} + signed-url-expire-minutes: ${ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES:60} diff --git a/FM-Core/src/main/resources/bootstrap.yaml b/FM-Core/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..e5441606 --- /dev/null +++ b/FM-Core/src/main/resources/bootstrap.yaml @@ -0,0 +1,51 @@ +spring: + application: + name: jayucloud-salon-core + + cloud: + nacos: + discovery: + # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} + # Nacos 命名空间,默认指向开发环境。 + namespace: ${NACOS_NAMESPACE:jayucloud-salon} + # 服务注册分组。 + group: DEFAULT_GROUP + # 注册到 Nacos 的服务名。 + service: ${spring.application.name} + # 是否启用服务发现。 + enabled: true + # 是否将当前服务注册到 Nacos。 + register-enabled: true + # Nacos 认证用户名。 + username: ${NACOS_USERNAME} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD} + config: + # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} + # Nacos 配置中心命名空间,默认指向开发环境。 + namespace: ${NACOS_NAMESPACE:jayucloud-salon} + # 配置分组。 + group: ${NACOS_GROUP:DEFAULT_GROUP} + # Core 服务独有配置文件。 + name: core + # 所有 Nacos 配置均使用 YAML。 + file-extension: yaml + # 是否启用配置中心。 + enabled: true + # Nacos 认证用户名。 + username: ${NACOS_USERNAME} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD} + # Core 与 Gateway 共享的公共配置文件。 + shared-configs: + - data-id: infra.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true + - data-id: secret.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true + - data-id: logging.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true diff --git a/FM-Core/src/main/resources/log4j2.xml b/FM-Core/src/main/resources/log4j2.xml new file mode 100644 index 00000000..fc63d3ad --- /dev/null +++ b/FM-Core/src/main/resources/log4j2.xml @@ -0,0 +1,82 @@ + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + E:/code/xiaowang/JayuCloud-Salon-Core/logs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FM-Frontend/.env.development b/FM-Frontend/.env.development new file mode 100644 index 00000000..0d2962f0 --- /dev/null +++ b/FM-Frontend/.env.development @@ -0,0 +1,8 @@ +VITE_API_BASE_URL=/api +VITE_ADMIN_API_BASE_URL=/admin/api +VITE_DEV_PROXY_TARGET=http://127.0.0.1:80 +VITE_APP_NAME=指尖设计师 +VITE_APP_NAME_EN=Fingertip Designer +VITE_APP_TITLE=Fingertip Designer 指尖设计师 +VITE_ADMIN_APP_NAME=指尖设计师管理台 +VITE_APP_SHORT_NAME=YN diff --git a/FM-Frontend/.env.production b/FM-Frontend/.env.production new file mode 100644 index 00000000..ddefe686 --- /dev/null +++ b/FM-Frontend/.env.production @@ -0,0 +1,7 @@ +VITE_API_BASE_URL=https://yunail.art/api +VITE_ADMIN_API_BASE_URL=https://yunail.art/admin/api +VITE_APP_NAME=指尖设计师 +VITE_APP_NAME_EN=Fingertip Designer +VITE_APP_TITLE=Fingertip Designer 指尖设计师 +VITE_ADMIN_APP_NAME=指尖设计师管理台 +VITE_APP_SHORT_NAME=YN diff --git a/FM-Frontend/.playwright-cli/page-2026-05-29T02-58-21-174Z.yml b/FM-Frontend/.playwright-cli/page-2026-05-29T02-58-21-174Z.yml new file mode 100644 index 00000000..95bba7a7 --- /dev/null +++ b/FM-Frontend/.playwright-cli/page-2026-05-29T02-58-21-174Z.yml @@ -0,0 +1,82 @@ +- generic [ref=e4]: + - main [ref=e6]: + - button "home 首页" [ref=e7] [cursor=pointer]: + - img "home" [ref=e10]: + - img [ref=e11] + - generic [ref=e13]: 首页 + - button "shopping 作品" [ref=e14] [cursor=pointer]: + - img "shopping" [ref=e17]: + - img [ref=e18] + - generic [ref=e20]: 作品 + - button "shopping-cart 购物车" [ref=e21] [cursor=pointer]: + - img "shopping-cart" [ref=e24]: + - img [ref=e25] + - generic [ref=e27]: 购物车 + - button "user 我的" [ref=e28] [cursor=pointer]: + - generic [ref=e29]: + - img "user" [ref=e31]: + - img [ref=e32] + - superscript [ref=e34] + - generic [ref=e35]: 我的 + - generic [ref=e37]: + - banner [ref=e38]: + - button "打开菜单" [ref=e39] [cursor=pointer]: + - img "menu" [ref=e40]: + - img [ref=e41] + - strong [ref=e43]: YumiNail + - button "查看购物车" [ref=e44] [cursor=pointer]: + - img "shopping" [ref=e45]: + - img [ref=e46] + - generic [ref=e48]: + - generic [ref=e49]: + - paragraph [ref=e50]: 游客模式 + - heading "早上好,先看看门店和作品" [level=1] [ref=e51] + - paragraph [ref=e52]: 先看看门店和作品,喜欢了再登录也可以。 + - button [ref=e53] [cursor=pointer]: + - img [ref=e55] + - generic [ref=e56]: + - img "search" [ref=e57]: + - img [ref=e58] + - searchbox "搜索美甲风格或美甲师..." [ref=e60] + - button "搜索" [ref=e61] [cursor=pointer] + - generic [ref=e62] [cursor=pointer]: + - img "春日柔彩系列" [ref=e63] + - generic [ref=e65]: + - generic [ref=e66]: 新品上线 + - heading "春日柔彩系列" [level=2] [ref=e67] + - paragraph [ref=e68]: 轻盈裸粉、微闪珠光与日常通勤都刚好。 + - navigation "快捷入口" [ref=e69]: + - button "calendar 约时间" [ref=e70] [cursor=pointer]: + - img "calendar" [ref=e72]: + - img [ref=e73] + - generic [ref=e75]: 约时间 + - button "shop 找门店" [ref=e76] [cursor=pointer]: + - img "shop" [ref=e78]: + - img [ref=e79] + - generic [ref=e81]: 找门店 + - button "shopping 购物车" [ref=e82] [cursor=pointer]: + - img "shopping" [ref=e84]: + - img [ref=e85] + - generic [ref=e87]: 购物车 + - button "heart 我的收藏" [ref=e88] [cursor=pointer]: + - img "heart" [ref=e90]: + - img [ref=e91] + - generic [ref=e93]: 我的收藏 + - generic [ref=e95]: + - generic [ref=e96]: + - generic [ref=e97]: Curated + - heading "精选作品" [level=3] [ref=e98] + - button "查看全部 right" [ref=e99] [cursor=pointer]: + - text: 查看全部 + - img "right" [ref=e100]: + - img [ref=e101] + - generic [ref=e103]: + - generic [ref=e104]: + - generic [ref=e105]: + - generic [ref=e106]: Trending + - heading "热门作品" [level=3] [ref=e107] + - button "查看全部 right" [ref=e108] [cursor=pointer]: + - text: 查看全部 + - img "right" [ref=e109]: + - img [ref=e110] + - generic [ref=e119]: 加载中... diff --git a/FM-Frontend/.vscode/extensions.json b/FM-Frontend/.vscode/extensions.json new file mode 100644 index 00000000..a7cea0b0 --- /dev/null +++ b/FM-Frontend/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["Vue.volar"] +} diff --git a/FM-Frontend/index.html b/FM-Frontend/index.html new file mode 100644 index 00000000..c3913ed9 --- /dev/null +++ b/FM-Frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + %VITE_APP_TITLE% + + +
+ + + diff --git a/FM-Frontend/package-lock.json b/FM-Frontend/package-lock.json new file mode 100644 index 00000000..6a0431d6 --- /dev/null +++ b/FM-Frontend/package-lock.json @@ -0,0 +1,4349 @@ +{ + "name": "jayucloud-salon-frontend", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "jayucloud-salon-frontend", + "version": "0.0.1", + "dependencies": { + "@element-plus/icons-vue": "^2.3.2", + "@iconify/vue": "^5.0.0", + "ant-design-vue": "^4.2.6", + "axios": "^1.13.5", + "element-plus": "^2.13.2", + "pinia": "^3.0.4", + "vue": "^3.5.25", + "vue-router": "^4.6.4" + }, + "devDependencies": { + "@types/node": "^24.10.13", + "@vitejs/plugin-vue": "^6.0.2", + "@vue/tsconfig": "^0.8.1", + "jsdom": "^26.1.0", + "less": "^4.5.1", + "sass": "^1.97.3", + "typescript": "~5.9.3", + "unplugin-auto-import": "^21.0.0", + "unplugin-vue-components": "^31.0.0", + "vite": "^7.3.1", + "vitest": "^3.2.4", + "vue-tsc": "^3.1.5" + } + }, + "node_modules/@ant-design/colors": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@ant-design/colors/-/colors-6.0.0.tgz", + "integrity": "sha512-qAZRvPzfdWHtfameEGP2Qvuf838NhergR35o+EuVyB5XvSA98xod5r4utvi4TJ3ywmevm290g9nsCG5MryrdWQ==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^3.4.0" + } + }, + "node_modules/@ant-design/icons-svg": { + "version": "4.4.2", + "resolved": "https://registry.npmmirror.com/@ant-design/icons-svg/-/icons-svg-4.4.2.tgz", + "integrity": "sha512-vHbT+zJEVzllwP+CM+ul7reTEfBR0vgxFe7+lREAsAA7YGsYpboiq2sQNeQeRvh09GfQgs/GyFEvZpJ9cLXpXA==", + "license": "MIT" + }, + "node_modules/@ant-design/icons-vue": { + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/@ant-design/icons-vue/-/icons-vue-7.0.1.tgz", + "integrity": "sha512-eCqY2unfZK6Fe02AwFlDHLfoyEFreP6rBwAZMIJ1LugmfMiVgwWDYlp1YsRugaPtICYOabV1iWxXdP12u9U43Q==", + "license": "MIT", + "dependencies": { + "@ant-design/colors": "^6.0.0", + "@ant-design/icons-svg": "^4.2.1" + }, + "peerDependencies": { + "vue": ">=3.0.3" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.0", + "resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.29.0.tgz", + "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.28.6", + "resolved": "https://registry.npmmirror.com/@babel/runtime/-/runtime-7.28.6.tgz", + "integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmmirror.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@ctrl/tinycolor": { + "version": "3.6.1", + "resolved": "https://registry.npmmirror.com/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz", + "integrity": "sha512-SITSV6aIXsuVNV3f3O0f2n/cgyEDWoSqtZMYiAmcsYHydcKrOz3gUxB/iXd/Qf08+IZX4KpgNbvUdMBmWz+kcA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/@element-plus/icons-vue": { + "version": "2.3.2", + "resolved": "https://registry.npmmirror.com/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz", + "integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==", + "license": "MIT", + "peerDependencies": { + "vue": "^3.2.0" + } + }, + "node_modules/@emotion/hash": { + "version": "0.9.2", + "resolved": "https://registry.npmmirror.com/@emotion/hash/-/hash-0.9.2.tgz", + "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==", + "license": "MIT" + }, + "node_modules/@emotion/unitless": { + "version": "0.8.1", + "resolved": "https://registry.npmmirror.com/@emotion/unitless/-/unitless-0.8.1.tgz", + "integrity": "sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ==", + "license": "MIT" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", + "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.27.3.tgz", + "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz", + "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/android-x64/-/android-x64-0.27.3.tgz", + "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz", + "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz", + "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz", + "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz", + "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz", + "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", + "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz", + "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz", + "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz", + "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz", + "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz", + "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz", + "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz", + "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz", + "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz", + "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz", + "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz", + "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz", + "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz", + "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz", + "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz", + "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz", + "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@floating-ui/core": { + "version": "1.7.4", + "resolved": "https://registry.npmmirror.com/@floating-ui/core/-/core-1.7.4.tgz", + "integrity": "sha512-C3HlIdsBxszvm5McXlB8PeOEWfBhcGBTZGkGlWc2U0KFY5IwG5OQEuQ8rq52DZmcHDlPLd+YFBK+cZcytwIFWg==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.10" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.7.5", + "resolved": "https://registry.npmmirror.com/@floating-ui/dom/-/dom-1.7.5.tgz", + "integrity": "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.7.4", + "@floating-ui/utils": "^0.2.10" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.10", + "resolved": "https://registry.npmmirror.com/@floating-ui/utils/-/utils-0.2.10.tgz", + "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==", + "license": "MIT" + }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "license": "MIT" + }, + "node_modules/@iconify/vue": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/@iconify/vue/-/vue-5.0.0.tgz", + "integrity": "sha512-C+KuEWIF5nSBrobFJhT//JS87OZ++QDORB6f2q2Wm6fl2mueSTpFBeBsveK0KW9hWiZ4mNiPjsh6Zs4jjdROSg==", + "license": "MIT", + "dependencies": { + "@iconify/types": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/cyberalien" + }, + "peerDependencies": { + "vue": ">=3" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher/-/watcher-2.5.6.tgz", + "integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.5.6", + "@parcel/watcher-darwin-arm64": "2.5.6", + "@parcel/watcher-darwin-x64": "2.5.6", + "@parcel/watcher-freebsd-x64": "2.5.6", + "@parcel/watcher-linux-arm-glibc": "2.5.6", + "@parcel/watcher-linux-arm-musl": "2.5.6", + "@parcel/watcher-linux-arm64-glibc": "2.5.6", + "@parcel/watcher-linux-arm64-musl": "2.5.6", + "@parcel/watcher-linux-x64-glibc": "2.5.6", + "@parcel/watcher-linux-x64-musl": "2.5.6", + "@parcel/watcher-win32-arm64": "2.5.6", + "@parcel/watcher-win32-ia32": "2.5.6", + "@parcel/watcher-win32-x64": "2.5.6" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.6.tgz", + "integrity": "sha512-YQxSS34tPF/6ZG7r/Ih9xy+kP/WwediEUsqmtf0cuCV5TPPKw/PQHRhueUo6JdeFJaqV3pyjm0GdYjZotbRt/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.6.tgz", + "integrity": "sha512-Z2ZdrnwyXvvvdtRHLmM4knydIdU9adO3D4n/0cVipF3rRiwP+3/sfzpAwA/qKFL6i1ModaabkU7IbpeMBgiVEA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.6.tgz", + "integrity": "sha512-HgvOf3W9dhithcwOWX9uDZyn1lW9R+7tPZ4sug+NGrGIo4Rk1hAXLEbcH1TQSqxts0NYXXlOWqVpvS1SFS4fRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.6.tgz", + "integrity": "sha512-vJVi8yd/qzJxEKHkeemh7w3YAn6RJCtYlE4HPMoVnCpIXEzSrxErBW5SJBgKLbXU3WdIpkjBTeUNtyBVn8TRng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.6.tgz", + "integrity": "sha512-9JiYfB6h6BgV50CCfasfLf/uvOcJskMSwcdH1PHH9rvS1IrNy8zad6IUVPVUfmXr+u+Km9IxcfMLzgdOudz9EQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.6.tgz", + "integrity": "sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.6.tgz", + "integrity": "sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.6.tgz", + "integrity": "sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.5.6.tgz", + "integrity": "sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.5.6.tgz", + "integrity": "sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.6.tgz", + "integrity": "sha512-3ukyebjc6eGlw9yRt678DxVF7rjXatWiHvTXqphZLvo7aC5NdEgFufVwjFfY51ijYEWpXbqF5jtrK275z52D4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-ia32": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.6.tgz", + "integrity": "sha512-k35yLp1ZMwwee3Ez/pxBi5cf4AoBKYXj00CZ80jUz5h8prpiaQsiRPKQMxoLstNuqe2vR4RNPEAEcjEFzhEz/g==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.5.6", + "resolved": "https://registry.npmmirror.com/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.6.tgz", + "integrity": "sha512-hbQlYcCq5dlAX9Qx+kFb0FHue6vbjlf0FrNzSKdYK2APUf7tGfGxQCk2ihEREmbR6ZMc0MVAD5RIX/41gpUzTw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@popperjs/core": { + "name": "@sxzz/popperjs-es", + "version": "2.11.8", + "resolved": "https://registry.npmmirror.com/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz", + "integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.2", + "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz", + "integrity": "sha512-izyXV/v+cHiRfozX62W9htOAvwMo4/bXKDrQ+vom1L1qRuexPock/7VZDAhnpHCLNejd3NJ6hiab+tO0D44Rgw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", + "integrity": "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.1.tgz", + "integrity": "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.1.tgz", + "integrity": "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.1.tgz", + "integrity": "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.1.tgz", + "integrity": "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.1.tgz", + "integrity": "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.1.tgz", + "integrity": "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.1.tgz", + "integrity": "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", + "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", + "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.1.tgz", + "integrity": "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.1.tgz", + "integrity": "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.1.tgz", + "integrity": "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.1.tgz", + "integrity": "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.1.tgz", + "integrity": "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.1.tgz", + "integrity": "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.1.tgz", + "integrity": "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz", + "integrity": "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz", + "integrity": "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.1.tgz", + "integrity": "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.1.tgz", + "integrity": "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.1.tgz", + "integrity": "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.1.tgz", + "integrity": "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.1.tgz", + "integrity": "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.1.tgz", + "integrity": "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@simonwep/pickr": { + "version": "1.8.2", + "resolved": "https://registry.npmmirror.com/@simonwep/pickr/-/pickr-1.8.2.tgz", + "integrity": "sha512-/l5w8BIkrpP6n1xsetx9MWPWlU6OblN5YgZZphxan0Tq4BByTCETL6lyIeY8lagalS2Nbt4F2W034KHLIiunKA==", + "license": "MIT", + "dependencies": { + "core-js": "^3.15.1", + "nanopop": "^2.1.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmmirror.com/@types/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmmirror.com/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/node": { + "version": "24.10.13", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-24.10.13.tgz", + "integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/web-bluetooth": { + "version": "0.0.20", + "resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.20.tgz", + "integrity": "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "6.0.4", + "resolved": "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-6.0.4.tgz", + "integrity": "sha512-uM5iXipgYIn13UUQCZNdWkYk+sysBeA97d5mHsAoAt1u/wpN3+zxOmsVJWosuzX+IMGRzeYUNytztrYznboIkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "1.0.0-rc.2" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0", + "vue": "^3.2.25" + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.27", + "resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.27.tgz", + "integrity": "sha512-DjmjBWZ4tJKxfNC1F6HyYERNHPYS7L7OPFyCrestykNdUZMFYzI9WTyvwPcaNaHlrEUwESHYsfEw3isInncZxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.27" + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.27", + "resolved": "https://registry.npmmirror.com/@volar/source-map/-/source-map-2.4.27.tgz", + "integrity": "sha512-ynlcBReMgOZj2i6po+qVswtDUeeBRCTgDurjMGShbm8WYZgJ0PA4RmtebBJ0BCYol1qPv3GQF6jK7C9qoVc7lg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.27", + "resolved": "https://registry.npmmirror.com/@volar/typescript/-/typescript-2.4.27.tgz", + "integrity": "sha512-eWaYCcl/uAPInSK2Lze6IqVWaBu/itVqR5InXcHXFyles4zO++Mglt3oxdgj75BDcv1Knr9Y93nowS8U3wqhxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.27", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/compiler-core/-/compiler-core-3.5.28.tgz", + "integrity": "sha512-kviccYxTgoE8n6OCw96BNdYlBg2GOWfBuOW4Vqwrt7mSKWKwFVvI8egdTltqRgITGPsTFYtKYfxIG8ptX2PJHQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@vue/shared": "3.5.28", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/compiler-dom/-/compiler-dom-3.5.28.tgz", + "integrity": "sha512-/1ZepxAb159jKR1btkefDP+J2xuWL5V3WtleRmxaT+K2Aqiek/Ab/+Ebrw2pPj0sdHO8ViAyyJWfhXXOP/+LQA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.28", + "@vue/shared": "3.5.28" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/compiler-sfc/-/compiler-sfc-3.5.28.tgz", + "integrity": "sha512-6TnKMiNkd6u6VeVDhZn/07KhEZuBSn43Wd2No5zaP5s3xm8IqFTHBj84HJah4UepSUJTro5SoqqlOY22FKY96g==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@vue/compiler-core": "3.5.28", + "@vue/compiler-dom": "3.5.28", + "@vue/compiler-ssr": "3.5.28", + "@vue/shared": "3.5.28", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.6", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/compiler-ssr/-/compiler-ssr-3.5.28.tgz", + "integrity": "sha512-JCq//9w1qmC6UGLWJX7RXzrGpKkroubey/ZFqTpvEIDJEKGgntuDMqkuWiZvzTzTA5h2qZvFBFHY7fAAa9475g==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.28", + "@vue/shared": "3.5.28" + } + }, + "node_modules/@vue/devtools-api": { + "version": "7.7.9", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-7.7.9.tgz", + "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==", + "license": "MIT", + "dependencies": { + "@vue/devtools-kit": "^7.7.9" + } + }, + "node_modules/@vue/devtools-kit": { + "version": "7.7.9", + "resolved": "https://registry.npmmirror.com/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz", + "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==", + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^7.7.9", + "birpc": "^2.3.0", + "hookable": "^5.5.3", + "mitt": "^3.0.1", + "perfect-debounce": "^1.0.0", + "speakingurl": "^14.0.1", + "superjson": "^2.2.2" + } + }, + "node_modules/@vue/devtools-shared": { + "version": "7.7.9", + "resolved": "https://registry.npmmirror.com/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz", + "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==", + "license": "MIT", + "dependencies": { + "rfdc": "^1.4.1" + } + }, + "node_modules/@vue/language-core": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vue/language-core/-/language-core-3.2.4.tgz", + "integrity": "sha512-bqBGuSG4KZM45KKTXzGtoCl9cWju5jsaBKaJJe3h5hRAAWpZUuj5G+L+eI01sPIkm4H6setKRlw7E85wLdDNew==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.27", + "@vue/compiler-dom": "^3.5.0", + "@vue/shared": "^3.5.0", + "alien-signals": "^3.0.0", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1", + "picomatch": "^4.0.2" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.28.tgz", + "integrity": "sha512-gr5hEsxvn+RNyu9/9o1WtdYdwDjg5FgjUSBEkZWqgTKlo/fvwZ2+8W6AfKsc9YN2k/+iHYdS9vZYAhpi10kNaw==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.28" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/runtime-core/-/runtime-core-3.5.28.tgz", + "integrity": "sha512-POVHTdbgnrBBIpnbYU4y7pOMNlPn2QVxVzkvEA2pEgvzbelQq4ZOUxbp2oiyo+BOtiYlm8Q44wShHJoBvDPAjQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.28", + "@vue/shared": "3.5.28" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/runtime-dom/-/runtime-dom-3.5.28.tgz", + "integrity": "sha512-4SXxSF8SXYMuhAIkT+eBRqOkWEfPu6nhccrzrkioA6l0boiq7sp18HCOov9qWJA5HML61kW8p/cB4MmBiG9dSA==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.28", + "@vue/runtime-core": "3.5.28", + "@vue/shared": "3.5.28", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/server-renderer/-/server-renderer-3.5.28.tgz", + "integrity": "sha512-pf+5ECKGj8fX95bNincbzJ6yp6nyzuLDhYZCeFxUNp8EBrQpPpQaLX3nNCp49+UbgbPun3CeVE+5CXVV1Xydfg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.28", + "@vue/shared": "3.5.28" + }, + "peerDependencies": { + "vue": "3.5.28" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.28.tgz", + "integrity": "sha512-cfWa1fCGBxrvaHRhvV3Is0MgmrbSCxYTXCSCau2I0a1Xw1N1pHAvkWCiXPRAqjvToILvguNyEwjevUqAuBQWvQ==", + "license": "MIT" + }, + "node_modules/@vue/tsconfig": { + "version": "0.8.1", + "resolved": "https://registry.npmmirror.com/@vue/tsconfig/-/tsconfig-0.8.1.tgz", + "integrity": "sha512-aK7feIWPXFSUhsCP9PFqPyFOcz4ENkb8hZ2pneL6m2UjCkccvaOhC/5KCKluuBufvp2KzkbdA2W2pk20vLzu3g==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "typescript": "5.x", + "vue": "^3.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "vue": { + "optional": true + } + } + }, + "node_modules/@vueuse/core": { + "version": "10.11.1", + "resolved": "https://registry.npmmirror.com/@vueuse/core/-/core-10.11.1.tgz", + "integrity": "sha512-guoy26JQktXPcz+0n3GukWIy/JDNKti9v6VEMu6kV2sYBsWuGiTU8OWdg+ADfUbHg3/3DlqySDe7JmdHrktiww==", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.20", + "@vueuse/metadata": "10.11.1", + "@vueuse/shared": "10.11.1", + "vue-demi": ">=0.14.8" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/core/node_modules/vue-demi": { + "version": "0.14.10", + "resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.14.10.tgz", + "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/@vueuse/metadata": { + "version": "10.11.1", + "resolved": "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-10.11.1.tgz", + "integrity": "sha512-IGa5FXd003Ug1qAZmyE8wF3sJ81xGLSqTqtQ6jaVfkeZ4i5kS2mwQF61yhVqojRnenVew5PldLyRgvdl4YYuSw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared": { + "version": "10.11.1", + "resolved": "https://registry.npmmirror.com/@vueuse/shared/-/shared-10.11.1.tgz", + "integrity": "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA==", + "license": "MIT", + "dependencies": { + "vue-demi": ">=0.14.8" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@vueuse/shared/node_modules/vue-demi": { + "version": "0.14.10", + "resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.14.10.tgz", + "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "vue-demi-fix": "bin/vue-demi-fix.js", + "vue-demi-switch": "bin/vue-demi-switch.js" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@vue/composition-api": "^1.0.0-rc.1", + "vue": "^3.0.0-0 || ^2.6.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/alien-signals": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/alien-signals/-/alien-signals-3.1.2.tgz", + "integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/ant-design-vue": { + "version": "4.2.6", + "resolved": "https://registry.npmmirror.com/ant-design-vue/-/ant-design-vue-4.2.6.tgz", + "integrity": "sha512-t7eX13Yj3i9+i5g9lqFyYneoIb3OzTvQjq9Tts1i+eiOd3Eva/6GagxBSXM1fOCjqemIu0FYVE1ByZ/38epR3Q==", + "license": "MIT", + "dependencies": { + "@ant-design/colors": "^6.0.0", + "@ant-design/icons-vue": "^7.0.0", + "@babel/runtime": "^7.10.5", + "@ctrl/tinycolor": "^3.5.0", + "@emotion/hash": "^0.9.0", + "@emotion/unitless": "^0.8.0", + "@simonwep/pickr": "~1.8.0", + "array-tree-filter": "^2.1.0", + "async-validator": "^4.0.0", + "csstype": "^3.1.1", + "dayjs": "^1.10.5", + "dom-align": "^1.12.1", + "dom-scroll-into-view": "^2.0.0", + "lodash": "^4.17.21", + "lodash-es": "^4.17.15", + "resize-observer-polyfill": "^1.5.1", + "scroll-into-view-if-needed": "^2.2.25", + "shallow-equal": "^1.0.0", + "stylis": "^4.1.3", + "throttle-debounce": "^5.0.0", + "vue-types": "^3.0.0", + "warning": "^4.0.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ant-design-vue" + }, + "peerDependencies": { + "vue": ">=3.2.0" + } + }, + "node_modules/array-tree-filter": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/array-tree-filter/-/array-tree-filter-2.1.0.tgz", + "integrity": "sha512-4ROwICNlNw/Hqa9v+rk5h22KjmzB1JGTMVKP2AKJBOCgb0yL0ASf0+YvCcLNNwquOHNX48jkeZIJ3a+oOQqKcw==", + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/async-validator": { + "version": "4.2.5", + "resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz", + "integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==", + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmmirror.com/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.13.5", + "resolved": "https://registry.npmmirror.com/axios/-/axios-1.13.5.tgz", + "integrity": "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.11", + "form-data": "^4.0.5", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/birpc": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/birpc/-/birpc-2.9.0.tgz", + "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmmirror.com/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmmirror.com/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/compute-scroll-into-view": { + "version": "1.0.20", + "resolved": "https://registry.npmmirror.com/compute-scroll-into-view/-/compute-scroll-into-view-1.0.20.tgz", + "integrity": "sha512-UCB0ioiyj8CRjtrvaceBLqqhZCVP+1B8+NWQhmdsm0VXOJtobBCf1dBQmebCCo34qZmUwZfIH2MZLqNHazrfjg==", + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmmirror.com/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/copy-anything": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/copy-anything/-/copy-anything-4.0.5.tgz", + "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==", + "license": "MIT", + "dependencies": { + "is-what": "^5.2.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/core-js": { + "version": "3.48.0", + "resolved": "https://registry.npmmirror.com/core-js/-/core-js-3.48.0.tgz", + "integrity": "sha512-zpEHTy1fjTMZCKLHUZoVeylt9XrzaIN2rbPXEt0k+q7JE5CkCZdo6bNq55bn24a69CH7ErAVLKijxJja4fw+UQ==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/dayjs": { + "version": "1.11.19", + "resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.19.tgz", + "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmmirror.com/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-align": { + "version": "1.12.4", + "resolved": "https://registry.npmmirror.com/dom-align/-/dom-align-1.12.4.tgz", + "integrity": "sha512-R8LUSEay/68zE5c8/3BDxiTEvgb4xZTF0RKmAHfiEVN3klfIpXfi2/QCoiWPccVQ0J/ZGdz9OjzL4uJEP/MRAw==", + "license": "MIT" + }, + "node_modules/dom-scroll-into-view": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/dom-scroll-into-view/-/dom-scroll-into-view-2.0.1.tgz", + "integrity": "sha512-bvVTQe1lfaUr1oFzZX80ce9KLDlZ3iU+XGNE/bz9HnGdklTieqsbmsLHe+rT2XWqopvL0PckkYqN7ksmm5pe3w==", + "license": "MIT" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/element-plus": { + "version": "2.13.2", + "resolved": "https://registry.npmmirror.com/element-plus/-/element-plus-2.13.2.tgz", + "integrity": "sha512-Zjzm1NnFXGhV4LYZ6Ze9skPlYi2B4KAmN18FL63A3PZcjhDfroHwhtM6RE8BonlOPHXUnPQynH0BgaoEfvhrGw==", + "license": "MIT", + "dependencies": { + "@ctrl/tinycolor": "^3.4.1", + "@element-plus/icons-vue": "^2.3.2", + "@floating-ui/dom": "^1.0.1", + "@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.7", + "@types/lodash": "^4.17.20", + "@types/lodash-es": "^4.17.12", + "@vueuse/core": "^10.11.0", + "async-validator": "^4.2.5", + "dayjs": "^1.11.19", + "lodash": "^4.17.23", + "lodash-es": "^4.17.23", + "lodash-unified": "^1.0.3", + "memoize-one": "^6.0.0", + "normalize-wheel-es": "^1.2.0" + }, + "peerDependencies": { + "vue": "^3.3.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/errno": { + "version": "0.1.8", + "resolved": "https://registry.npmmirror.com/errno/-/errno-0.1.8.tgz", + "integrity": "sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "prr": "~1.0.1" + }, + "bin": { + "errno": "cli.js" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.3", + "resolved": "https://registry.npmmirror.com/esbuild/-/esbuild-0.27.3.tgz", + "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.3", + "@esbuild/android-arm": "0.27.3", + "@esbuild/android-arm64": "0.27.3", + "@esbuild/android-x64": "0.27.3", + "@esbuild/darwin-arm64": "0.27.3", + "@esbuild/darwin-x64": "0.27.3", + "@esbuild/freebsd-arm64": "0.27.3", + "@esbuild/freebsd-x64": "0.27.3", + "@esbuild/linux-arm": "0.27.3", + "@esbuild/linux-arm64": "0.27.3", + "@esbuild/linux-ia32": "0.27.3", + "@esbuild/linux-loong64": "0.27.3", + "@esbuild/linux-mips64el": "0.27.3", + "@esbuild/linux-ppc64": "0.27.3", + "@esbuild/linux-riscv64": "0.27.3", + "@esbuild/linux-s390x": "0.27.3", + "@esbuild/linux-x64": "0.27.3", + "@esbuild/netbsd-arm64": "0.27.3", + "@esbuild/netbsd-x64": "0.27.3", + "@esbuild/openbsd-arm64": "0.27.3", + "@esbuild/openbsd-x64": "0.27.3", + "@esbuild/openharmony-arm64": "0.27.3", + "@esbuild/sunos-x64": "0.27.3", + "@esbuild/win32-arm64": "0.27.3", + "@esbuild/win32-ia32": "0.27.3", + "@esbuild/win32-x64": "0.27.3" + } + }, + "node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/exsolve": { + "version": "1.0.8", + "resolved": "https://registry.npmmirror.com/exsolve/-/exsolve-1.0.8.tgz", + "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hookable": { + "version": "5.5.3", + "resolved": "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", + "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", + "license": "MIT" + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/image-size": { + "version": "0.5.5", + "resolved": "https://registry.npmmirror.com/image-size/-/image-size-0.5.5.tgz", + "integrity": "sha512-6TDAlDPZxUFCv+fuOkIoXT/V/f3Qbq8e37p+YOiYrUv3v9cc3/6x78VdfPgFVaB9dZYeLUfKgHRebpkm/oP2VQ==", + "dev": true, + "license": "MIT", + "optional": true, + "bin": { + "image-size": "bin/image-size.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/immutable": { + "version": "5.1.4", + "resolved": "https://registry.npmmirror.com/immutable/-/immutable-5.1.4.tgz", + "integrity": "sha512-p6u1bG3YSnINT5RQmx/yRZBpenIl30kVxkTLDyHLIMk0gict704Q9n+thfDI7lTRm9vXdDYutVzXhzcThxTnXA==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-plain-object": { + "version": "3.0.1", + "resolved": "https://registry.npmmirror.com/is-plain-object/-/is-plain-object-3.0.1.tgz", + "integrity": "sha512-Xnpx182SBMrr/aBik8y+GuR4U1L9FqMSojwDQwPMmxyC6bvEqly9UBCxhauBF5vNh2gwWJNX6oDV7O+OM4z34g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-what": { + "version": "5.5.0", + "resolved": "https://registry.npmmirror.com/is-what/-/is-what-5.5.0.tgz", + "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/less": { + "version": "4.5.1", + "resolved": "https://registry.npmmirror.com/less/-/less-4.5.1.tgz", + "integrity": "sha512-UKgI3/KON4u6ngSsnDADsUERqhZknsVZbnuzlRZXLQCmfC/MDld42fTydUE9B+Mla1AL6SJ/Pp6SlEFi/AVGfw==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "copy-anything": "^2.0.1", + "parse-node-version": "^1.0.1", + "tslib": "^2.3.0" + }, + "bin": { + "lessc": "bin/lessc" + }, + "engines": { + "node": ">=14" + }, + "optionalDependencies": { + "errno": "^0.1.1", + "graceful-fs": "^4.1.2", + "image-size": "~0.5.0", + "make-dir": "^2.1.0", + "mime": "^1.4.1", + "needle": "^3.1.0", + "source-map": "~0.6.0" + } + }, + "node_modules/less/node_modules/copy-anything": { + "version": "2.0.6", + "resolved": "https://registry.npmmirror.com/copy-anything/-/copy-anything-2.0.6.tgz", + "integrity": "sha512-1j20GZTsvKNkc4BY3NpMOM8tt///wY3FpIzozTOFO2ffuZcV61nojHXVKIy3WM+7ADCy5FVhdZYHYDdgTU0yJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-what": "^3.14.1" + }, + "funding": { + "url": "https://github.com/sponsors/mesqueeb" + } + }, + "node_modules/less/node_modules/is-what": { + "version": "3.14.1", + "resolved": "https://registry.npmmirror.com/is-what/-/is-what-3.14.1.tgz", + "integrity": "sha512-sNxgpk9793nzSs7bA6JQJGeIuRBQhAaNGG77kzYQgMkrID+lS6SlK07K5LaptscDlSaIgH+GPFzf+d75FVxozA==", + "dev": true, + "license": "MIT" + }, + "node_modules/local-pkg": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/local-pkg/-/local-pkg-1.1.2.tgz", + "integrity": "sha512-arhlxbFRmoQHl33a0Zkle/YWlmNwoyt6QNZEIJcqNbdrsix5Lvc4HyyI3EnwxTYlZYc32EbYrQ8SzEZ7dqgg9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "license": "MIT" + }, + "node_modules/lodash-es": { + "version": "4.17.23", + "resolved": "https://registry.npmmirror.com/lodash-es/-/lodash-es-4.17.23.tgz", + "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==", + "license": "MIT" + }, + "node_modules/lodash-unified": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/lodash-unified/-/lodash-unified-1.0.3.tgz", + "integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==", + "license": "MIT", + "peerDependencies": { + "@types/lodash-es": "*", + "lodash": "*", + "lodash-es": "*" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/loose-envify/node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/make-dir": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/make-dir/-/make-dir-2.1.0.tgz", + "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "pify": "^4.0.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/memoize-one": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/memoize-one/-/memoize-one-6.0.0.tgz", + "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", + "license": "MIT" + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmmirror.com/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "license": "MIT", + "optional": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmmirror.com/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "license": "MIT" + }, + "node_modules/mlly": { + "version": "1.8.0", + "resolved": "https://registry.npmmirror.com/mlly/-/mlly-1.8.0.tgz", + "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.1" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmmirror.com/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmmirror.com/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nanopop": { + "version": "2.4.2", + "resolved": "https://registry.npmmirror.com/nanopop/-/nanopop-2.4.2.tgz", + "integrity": "sha512-NzOgmMQ+elxxHeIha+OG/Pv3Oc3p4RU2aBhwWwAqDpXrdTbtRylbRLQztLy8dMMwfl6pclznBdfUhccEn9ZIzw==", + "license": "MIT" + }, + "node_modules/needle": { + "version": "3.3.1", + "resolved": "https://registry.npmmirror.com/needle/-/needle-3.3.1.tgz", + "integrity": "sha512-6k0YULvhpw+RoLNiQCRKOl09Rv1dPLr8hHnVjHqdolKwDrdNyk+Hmrthi4lIGPPz3r39dLx0hsF5s40sZ3Us4Q==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.3", + "sax": "^1.2.4" + }, + "bin": { + "needle": "bin/needle" + }, + "engines": { + "node": ">= 4.4.x" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmmirror.com/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/normalize-wheel-es": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz", + "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", + "license": "BSD-3-Clause" + }, + "node_modules/nwsapi": { + "version": "2.2.23", + "resolved": "https://registry.npmmirror.com/nwsapi/-/nwsapi-2.2.23.tgz", + "integrity": "sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmmirror.com/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/parse-node-version": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/parse-node-version/-/parse-node-version-1.0.1.tgz", + "integrity": "sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmmirror.com/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/pinia": { + "version": "3.0.4", + "resolved": "https://registry.npmmirror.com/pinia/-/pinia-3.0.4.tgz", + "integrity": "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^7.7.7" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "typescript": ">=4.5.0", + "vue": "^3.5.11" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/pkg-types": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/pkg-types/-/pkg-types-2.3.0.tgz", + "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, + "node_modules/prr": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/prr/-/prr-1.0.1.tgz", + "integrity": "sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmmirror.com/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resize-observer-polyfill": { + "version": "1.5.1", + "resolved": "https://registry.npmmirror.com/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz", + "integrity": "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==", + "license": "MIT" + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmmirror.com/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/rollup": { + "version": "4.57.1", + "resolved": "https://registry.npmmirror.com/rollup/-/rollup-4.57.1.tgz", + "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.57.1", + "@rollup/rollup-android-arm64": "4.57.1", + "@rollup/rollup-darwin-arm64": "4.57.1", + "@rollup/rollup-darwin-x64": "4.57.1", + "@rollup/rollup-freebsd-arm64": "4.57.1", + "@rollup/rollup-freebsd-x64": "4.57.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", + "@rollup/rollup-linux-arm-musleabihf": "4.57.1", + "@rollup/rollup-linux-arm64-gnu": "4.57.1", + "@rollup/rollup-linux-arm64-musl": "4.57.1", + "@rollup/rollup-linux-loong64-gnu": "4.57.1", + "@rollup/rollup-linux-loong64-musl": "4.57.1", + "@rollup/rollup-linux-ppc64-gnu": "4.57.1", + "@rollup/rollup-linux-ppc64-musl": "4.57.1", + "@rollup/rollup-linux-riscv64-gnu": "4.57.1", + "@rollup/rollup-linux-riscv64-musl": "4.57.1", + "@rollup/rollup-linux-s390x-gnu": "4.57.1", + "@rollup/rollup-linux-x64-gnu": "4.57.1", + "@rollup/rollup-linux-x64-musl": "4.57.1", + "@rollup/rollup-openbsd-x64": "4.57.1", + "@rollup/rollup-openharmony-arm64": "4.57.1", + "@rollup/rollup-win32-arm64-msvc": "4.57.1", + "@rollup/rollup-win32-ia32-msvc": "4.57.1", + "@rollup/rollup-win32-x64-gnu": "4.57.1", + "@rollup/rollup-win32-x64-msvc": "4.57.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmmirror.com/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/sass": { + "version": "1.97.3", + "resolved": "https://registry.npmmirror.com/sass/-/sass-1.97.3.tgz", + "integrity": "sha512-fDz1zJpd5GycprAbu4Q2PV/RprsRtKC/0z82z0JLgdytmcq0+ujJbJ/09bPGDxCLkKY3Np5cRAOcWiVkLXJURg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^4.0.0", + "immutable": "^5.0.2", + "source-map-js": ">=0.6.2 <2.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=14.0.0" + }, + "optionalDependencies": { + "@parcel/watcher": "^2.4.1" + } + }, + "node_modules/sax": { + "version": "1.5.0", + "resolved": "https://registry.npmmirror.com/sax/-/sax-1.5.0.tgz", + "integrity": "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA==", + "dev": true, + "license": "BlueOak-1.0.0", + "optional": true, + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scroll-into-view-if-needed": { + "version": "2.2.31", + "resolved": "https://registry.npmmirror.com/scroll-into-view-if-needed/-/scroll-into-view-if-needed-2.2.31.tgz", + "integrity": "sha512-dGCXy99wZQivjmjIqihaBQNjryrz5rueJY7eHfTdyWEiR4ttYpsajb14rn9s5d4DY4EcY6+4+U/maARBXJedkA==", + "license": "MIT", + "dependencies": { + "compute-scroll-into-view": "^1.0.20" + } + }, + "node_modules/scule": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/scule/-/scule-1.3.0.tgz", + "integrity": "sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmmirror.com/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "dev": true, + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/shallow-equal": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/shallow-equal/-/shallow-equal-1.2.1.tgz", + "integrity": "sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA==", + "license": "MIT" + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/speakingurl": { + "version": "14.0.1", + "resolved": "https://registry.npmmirror.com/speakingurl/-/speakingurl-14.0.1.tgz", + "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/stylis": { + "version": "4.3.6", + "resolved": "https://registry.npmmirror.com/stylis/-/stylis-4.3.6.tgz", + "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==", + "license": "MIT" + }, + "node_modules/superjson": { + "version": "2.2.6", + "resolved": "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", + "integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==", + "license": "MIT", + "dependencies": { + "copy-anything": "^4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/throttle-debounce": { + "version": "5.0.2", + "resolved": "https://registry.npmmirror.com/throttle-debounce/-/throttle-debounce-5.0.2.tgz", + "integrity": "sha512-B71/4oyj61iNH0KeCamLuE2rmKuTO5byTOSVwECM5FA7TiAiAW+UqTKZ9ERueC4qvgSttUhdmq1mXC3kJqGX7A==", + "license": "MIT", + "engines": { + "node": ">=12.22" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.4", + "resolved": "https://registry.npmmirror.com/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmmirror.com/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.3", + "resolved": "https://registry.npmmirror.com/ufo/-/ufo-1.6.3.tgz", + "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/unimport": { + "version": "5.6.0", + "resolved": "https://registry.npmmirror.com/unimport/-/unimport-5.6.0.tgz", + "integrity": "sha512-8rqAmtJV8o60x46kBAJKtHpJDJWkA2xcBqWKPI14MgUb05o1pnpnCnXSxedUXyeq7p8fR5g3pTo2BaswZ9lD9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "escape-string-regexp": "^5.0.0", + "estree-walker": "^3.0.3", + "local-pkg": "^1.1.2", + "magic-string": "^0.30.21", + "mlly": "^1.8.0", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "pkg-types": "^2.3.0", + "scule": "^1.3.0", + "strip-literal": "^3.1.0", + "tinyglobby": "^0.2.15", + "unplugin": "^2.3.11", + "unplugin-utils": "^0.3.1" + }, + "engines": { + "node": ">=18.12.0" + } + }, + "node_modules/unimport/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/unplugin": { + "version": "2.3.11", + "resolved": "https://registry.npmmirror.com/unplugin/-/unplugin-2.3.11.tgz", + "integrity": "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "acorn": "^8.15.0", + "picomatch": "^4.0.3", + "webpack-virtual-modules": "^0.6.2" + }, + "engines": { + "node": ">=18.12.0" + } + }, + "node_modules/unplugin-auto-import": { + "version": "21.0.0", + "resolved": "https://registry.npmmirror.com/unplugin-auto-import/-/unplugin-auto-import-21.0.0.tgz", + "integrity": "sha512-vWuC8SwqJmxZFYwPojhOhOXDb5xFhNNcEVb9K/RFkyk/3VnfaOjzitWN7v+8DEKpMjSsY2AEGXNgt6I0yQrhRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "local-pkg": "^1.1.2", + "magic-string": "^0.30.21", + "picomatch": "^4.0.3", + "unimport": "^5.6.0", + "unplugin": "^2.3.11", + "unplugin-utils": "^0.3.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@nuxt/kit": "^4.0.0", + "@vueuse/core": "*" + }, + "peerDependenciesMeta": { + "@nuxt/kit": { + "optional": true + }, + "@vueuse/core": { + "optional": true + } + } + }, + "node_modules/unplugin-utils": { + "version": "0.3.1", + "resolved": "https://registry.npmmirror.com/unplugin-utils/-/unplugin-utils-0.3.1.tgz", + "integrity": "sha512-5lWVjgi6vuHhJ526bI4nlCOmkCIF3nnfXkCMDeMJrtdvxTs6ZFCM8oNufGTsDbKv/tJ/xj8RpvXjRuPBZJuJog==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/unplugin-vue-components": { + "version": "31.0.0", + "resolved": "https://registry.npmmirror.com/unplugin-vue-components/-/unplugin-vue-components-31.0.0.tgz", + "integrity": "sha512-4ULwfTZTLuWJ7+S9P7TrcStYLsSRkk6vy2jt/WTfgUEUb0nW9//xxmrfhyHUEVpZ2UKRRwfRb8Yy15PDbVZf+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "local-pkg": "^1.1.2", + "magic-string": "^0.30.21", + "mlly": "^1.8.0", + "obug": "^2.1.1", + "picomatch": "^4.0.3", + "tinyglobby": "^0.2.15", + "unplugin": "^2.3.11", + "unplugin-utils": "^0.3.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@nuxt/kit": "^3.2.2 || ^4.0.0", + "vue": "^3.0.0" + }, + "peerDependenciesMeta": { + "@nuxt/kit": { + "optional": true + } + } + }, + "node_modules/unplugin-vue-components/node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/unplugin-vue-components/node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/vite": { + "version": "7.3.1", + "resolved": "https://registry.npmmirror.com/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.28", + "resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.28.tgz", + "integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.28", + "@vue/compiler-sfc": "3.5.28", + "@vue/runtime-dom": "3.5.28", + "@vue/server-renderer": "3.5.28", + "@vue/shared": "3.5.28" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "4.6.4", + "resolved": "https://registry.npmmirror.com/vue-router/-/vue-router-4.6.4.tgz", + "integrity": "sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==", + "license": "MIT", + "dependencies": { + "@vue/devtools-api": "^6.6.4" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/vue-router/node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/vue-tsc": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-3.2.4.tgz", + "integrity": "sha512-xj3YCvSLNDKt1iF9OcImWHhmYcihVu9p4b9s4PGR/qp6yhW+tZJaypGxHScRyOrdnHvaOeF+YkZOdKwbgGvp5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.27", + "@vue/language-core": "3.2.4" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/vue-types": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/vue-types/-/vue-types-3.0.2.tgz", + "integrity": "sha512-IwUC0Aq2zwaXqy74h4WCvFCUtoV0iSWr0snWnE9TnU18S66GAQyqQbRf2qfJtUuiFsBf6qp0MEwdonlwznlcrw==", + "license": "MIT", + "dependencies": { + "is-plain-object": "3.0.1" + }, + "engines": { + "node": ">=10.15.0" + }, + "peerDependencies": { + "vue": "^3.0.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/warning": { + "version": "4.0.3", + "resolved": "https://registry.npmmirror.com/warning/-/warning-4.0.3.tgz", + "integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/webpack-virtual-modules": { + "version": "0.6.2", + "resolved": "https://registry.npmmirror.com/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.20.1", + "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.1.tgz", + "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/FM-Frontend/package.json b/FM-Frontend/package.json new file mode 100644 index 00000000..f3fae2f4 --- /dev/null +++ b/FM-Frontend/package.json @@ -0,0 +1,36 @@ +{ + "name": "jayucloud-salon-frontend", + "private": true, + "version": "0.0.1", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc -b && vite build", + "preview": "vite preview", + "test:unit": "vitest run" + }, + "dependencies": { + "@element-plus/icons-vue": "^2.3.2", + "@iconify/vue": "^5.0.0", + "ant-design-vue": "^4.2.6", + "axios": "^1.13.5", + "element-plus": "^2.13.2", + "pinia": "^3.0.4", + "vue": "^3.5.25", + "vue-router": "^4.6.4" + }, + "devDependencies": { + "@types/node": "^24.10.13", + "@vitejs/plugin-vue": "^6.0.2", + "@vue/tsconfig": "^0.8.1", + "jsdom": "^26.1.0", + "less": "^4.5.1", + "sass": "^1.97.3", + "typescript": "~5.9.3", + "unplugin-auto-import": "^21.0.0", + "unplugin-vue-components": "^31.0.0", + "vite": "^7.3.1", + "vitest": "^3.2.4", + "vue-tsc": "^3.1.5" + } +} diff --git a/FM-Frontend/public/assets/images/default-product.png b/FM-Frontend/public/assets/images/default-product.png new file mode 100644 index 00000000..84c1b545 Binary files /dev/null and b/FM-Frontend/public/assets/images/default-product.png differ diff --git a/FM-Frontend/public/assets/images/default-shop.png b/FM-Frontend/public/assets/images/default-shop.png new file mode 100644 index 00000000..bbcce9f4 Binary files /dev/null and b/FM-Frontend/public/assets/images/default-shop.png differ diff --git a/FM-Frontend/public/fingertip-designer-icon.svg b/FM-Frontend/public/fingertip-designer-icon.svg new file mode 100644 index 00000000..aebebf3e --- /dev/null +++ b/FM-Frontend/public/fingertip-designer-icon.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FM-Frontend/public/jiayu-designer-icon.png b/FM-Frontend/public/jiayu-designer-icon.png new file mode 100644 index 00000000..4e373e9a Binary files /dev/null and b/FM-Frontend/public/jiayu-designer-icon.png differ diff --git a/FM-Frontend/public/vite.svg b/FM-Frontend/public/vite.svg new file mode 100644 index 00000000..e7b8dfb1 --- /dev/null +++ b/FM-Frontend/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/FM-Frontend/src/App.vue b/FM-Frontend/src/App.vue new file mode 100644 index 00000000..d06c0597 --- /dev/null +++ b/FM-Frontend/src/App.vue @@ -0,0 +1,462 @@ + + + + + diff --git a/FM-Frontend/src/api/admin.ts b/FM-Frontend/src/api/admin.ts new file mode 100644 index 00000000..700d9423 --- /dev/null +++ b/FM-Frontend/src/api/admin.ts @@ -0,0 +1,1976 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import axios, { AxiosError, type AxiosProgressEvent } from 'axios' +import { message } from 'ant-design-vue' +import { ADMIN_API_BASE_URL } from '../config/api' +import type { IdType } from '@/utils/id' +import { clearAdminSessionStorage } from '@/utils/admin-session' +import { attachRequestSignature } from '@/utils/request-signature' +import { isAdminApiAuthFreePath } from './auth-free-paths' + +/** + * Purpose: lastErrorTime supports admin.ts by holding or executing the last error time page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let lastErrorTime = 0 +/** + * Purpose: lastErrorMessage supports admin.ts by holding or executing the last error message page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let lastErrorMessage = '' +/** + * Purpose: ERROR_DEBOUNCE_TIME supports admin.ts by holding or executing the error debounce time page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const ERROR_DEBOUNCE_TIME = 1000 + +/** + * Purpose: adminApi supports admin.ts by holding or executing the admin api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const adminApi = axios.create({ + baseURL: ADMIN_API_BASE_URL, + timeout: 60000, + headers: { + 'Content-Type': 'application/json' + } +}) + +/** + * Purpose: isRefreshing supports admin.ts by holding or executing the is refreshing page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let isRefreshing = false +let failedQueue: Array<{ + resolve: (value?: any) => void + reject: (reason?: any) => void +}> = [] + +/** + * Purpose: processQueue supports admin.ts by holding or executing the process queue page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const processQueue = (error: any, token: string | null = null) => { + failedQueue.forEach(prom => { + if (error) { + prom.reject(error) + } else { + prom.resolve(token) + } + }) + failedQueue = [] +} + +/** + * Purpose: getStoredAdminAccessToken supports admin.ts by holding or executing the get stored admin access token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getStoredAdminAccessToken = () => { + return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken') +} + +/** + * Purpose: getRequestToken supports admin.ts by holding or executing the get request token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getRequestToken = (request: any) => { + if (request?._authToken) { + return request._authToken as string + } + const authHeader = request?.headers?.Authorization || request?.headers?.authorization + if (typeof authHeader !== 'string') { + return null + } + return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null +} + +/** + * Purpose: isCurrentStoredAdminToken supports admin.ts by holding or executing the is current stored admin token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isCurrentStoredAdminToken = (token: string | null) => { + return Boolean(token && token === getStoredAdminAccessToken()) +} + +/** + * Purpose: showError supports admin.ts by holding or executing the show error page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const showError = (msg: string) => { + const now = Date.now() + if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { + lastErrorTime = now + lastErrorMessage = msg + message.error(msg) + } +} + +/** + * Purpose: isAuthFreePath supports admin.ts by holding or executing the is auth free path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isAuthFreePath = (url?: string) => { + return isAdminApiAuthFreePath(url) +} + +/** + * Purpose: handleAdminTokenExpired supports admin.ts by holding or executing the handle admin token expired page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const handleAdminTokenExpired = (failedToken: string | null = null) => { + if (!isCurrentStoredAdminToken(failedToken)) { + return + } + + clearAdminSessionStorage() + + if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') { + showError('登录已过期,请重新登录') + } + + setTimeout(() => { + window.location.href = '/admin/login' + }, 300) +} + +adminApi.interceptors.request.use( + async config => { + let token: string | null = null + if (!isAuthFreePath(config.url)) { + token = getStoredAdminAccessToken() + if (token) { + config.headers.Authorization = `Bearer ${token}` + } + } + ;(config as any)._authToken = token || null + return attachRequestSignature(config, token, { + authFree: isAuthFreePath(config.url) + }) + }, + error => Promise.reject(error) +) + +adminApi.interceptors.response.use( + response => { + const res = response.data + if (res.code !== 200) { + const errorMsg = res.message || '请求失败' + if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) { + showError(errorMsg) + } else { + console.error('权限不足:', errorMsg) + } + return Promise.reject(new Error(errorMsg)) + } + return res.data as any + }, + async (error: AxiosError) => { + const originalRequest = error.config as any + + if (error.response?.status === 401) { + const requestToken = getRequestToken(originalRequest) + + if (!isCurrentStoredAdminToken(requestToken)) { + return Promise.reject(error) + } + + if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) { + if (isRefreshing) { + return new Promise((resolve, reject) => { + failedQueue.push({ resolve, reject }) + }).then(token => { + if (token) { + originalRequest.headers.Authorization = `Bearer ${token}` + } + return adminApi(originalRequest) + }) + } + + originalRequest._retry = true + isRefreshing = true + + try { + let refreshToken = localStorage.getItem('adminRefreshToken') + if (!refreshToken) { + refreshToken = sessionStorage.getItem('adminRefreshToken') + } + if (!refreshToken) { + throw new Error('No refresh token available') + } + + const response = await adminAuthApi.refreshToken(refreshToken) + const newToken = (response as any).accessToken + const newRefreshToken = (response as any).refreshToken + + localStorage.setItem('adminAccessToken', newToken) + localStorage.setItem('adminRefreshToken', newRefreshToken) + sessionStorage.setItem('adminAccessToken', newToken) + sessionStorage.setItem('adminRefreshToken', newRefreshToken) + + processQueue(null, newToken) + originalRequest.headers.Authorization = `Bearer ${newToken}` + return adminApi(originalRequest) + } catch (refreshError) { + processQueue(refreshError, null) + handleAdminTokenExpired(requestToken) + return Promise.reject(refreshError) + } finally { + isRefreshing = false + } + } + + handleAdminTokenExpired(requestToken) + } else if (error.response?.status !== 403) { + const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败' + showError(errorMsg) + } else { + console.error('权限不足:', error) + } + + if (error.response?.status === 403) { + const errorMsg = (error.response?.data as any)?.message || '权限不足' + console.error('Admin API Permission Error:', errorMsg) + return Promise.reject(new Error(errorMsg)) + } + + console.error('Admin API Error:', error) + return Promise.reject(error) + } +) + +/** + * Purpose: AdminLoginRequest supports admin.ts by holding or executing the admin login request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminLoginRequest { + account: string + password: string + shopId?: IdType +} + +/** + * Purpose: AdminLoginResponse supports admin.ts by holding or executing the admin login response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminLoginResponse { + accessToken: string + refreshToken: string + userInfo: any +} + +/** + * Purpose: LoginShopSelectionResponse supports admin.ts by holding or executing the login shop selection response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LoginShopSelectionResponse { + allowShoplessLogin: boolean + message: string + shops: Array<{ + id: IdType + shopName: string + }> +} + +/** + * Purpose: LegalAgreementAdminVO supports admin.ts by holding or executing the legal agreement admin vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LegalAgreementAdminVO { + id: IdType + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + agreementTypeName?: string + title: string + version: string + content: string + status: number + statusText?: string + effectiveTime?: string + createTime?: string + updateTime?: string +} + +/** + * Purpose: LegalAgreementAdminRequest supports admin.ts by holding or executing the legal agreement admin request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LegalAgreementAdminRequest { + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + title: string + version: string + content: string +} + +/** + * adminAuthApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminAuthApi = { + /** + * `login` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: AdminLoginRequest caller-supplied value for `data: AdminLoginRequest` + */ + login: (data: AdminLoginRequest) => { + return adminApi.post('/auth/login', data) + }, + /** + * `getLoginShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param account: string caller-supplied value for `account: string` + */ + getLoginShops: (account: string) => { + return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) + }, + /** + * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + logout: () => { + return adminApi.post('/auth/logout') + }, + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + switchShop: (shopId?: IdType) => { + return adminApi.post('/auth/switch-shop', { shopId }) + }, + /** + * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param refreshToken: string caller-supplied value for `refreshToken: string` + */ + refreshToken: (refreshToken: string) => { + return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) + } +} + +/** + * Purpose: adminLegalAgreementApi supports admin.ts by holding or executing the admin legal agreement api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const adminLegalAgreementApi = { + list: () => adminApi.get('/legal-agreement/list'), + create: (data: LegalAgreementAdminRequest) => adminApi.post('/legal-agreement/create', data), + update: (id: IdType, data: LegalAgreementAdminRequest) => adminApi.put(`/legal-agreement/${id}`, data), + publish: (id: IdType) => adminApi.put(`/legal-agreement/${id}/publish`), + disable: (id: IdType) => adminApi.put(`/legal-agreement/${id}/disable`) +} + +/** + * Purpose: ObjectStorageFileVO supports admin.ts by holding or executing the object storage file vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ObjectStorageFileVO { + id: IdType + fileName: string + fileUrl?: string + objectName?: string + primaryProvider?: string + primaryUrl?: string + backupProvider?: string + backupUrl?: string + fileSize: number + contentType: string + primaryUploadStatus?: number + backupUploadStatus?: number + backupRetryCount?: number + backupLastError?: string + backupUploadedAt?: string + backupLastRetryTime?: string + createTime: string +} + +/** + * Purpose: ChunkUploadInitRequest supports admin.ts by holding or executing the chunk upload init request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ChunkUploadInitRequest { + fileName: string + fileSize: number + contentType: string + fileFingerprint: string + scene: string +} + +/** + * Purpose: ChunkUploadSessionVO supports admin.ts by holding or executing the chunk upload session vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ChunkUploadSessionVO { + uploadId: string + chunkSize: number + totalChunks: number + uploadedChunks: number[] +} + +/** + * adminFileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminFileApi = { + /** + * `uploadFile` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param file: File caller-supplied value for `file: File` + */ + uploadFile: (file: File) => { + const formData = new FormData() + formData.append('file', file) + return adminApi.post('/object-storage-file/upload', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + } + }) as unknown as Promise + }, + /** + * `initChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest` + */ + initChunkUpload: (data: ChunkUploadInitRequest) => { + return adminApi.post('/object-storage-file/upload/init', data) as unknown as Promise + }, + uploadChunk: ( + /** + * Purpose: data supports admin.ts by holding or executing the data page or API role. + * Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow. + */ + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return adminApi.post('/object-storage-file/upload/chunk', formData, { + /** + * Purpose: headers supports admin.ts by holding or executing the headers page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + headers: { + 'Content-Type': 'multipart/form-data' + }, + /** + * Purpose: signal supports admin.ts by holding or executing the signal page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + signal: config?.signal, + /** + * Purpose: onUploadProgress supports admin.ts by holding or executing the on upload progress page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + onUploadProgress: config?.onUploadProgress + }) + }, + /** + * `completeChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ + completeChunkUpload: (uploadId: string) => { + return adminApi.post('/object-storage-file/upload/complete', { uploadId }) as unknown as Promise + }, + /** + * `cancelChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ + cancelChunkUpload: (uploadId: string) => { + return adminApi.delete(`/object-storage-file/upload/${uploadId}`) + }, + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + getSignedUrl: (id: IdType) => { + return adminApi.get(`/object-storage-file/get-signed-url/${id}`) as unknown as Promise + } +} + +/** + * Purpose: Tag supports admin.ts by holding or executing the tag page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Tag { + id: IdType + tagName: string + textColor?: string + bgColor?: string + borderColor?: string + sceneGroup?: string + displayName?: string + sortOrder?: number + frontVisible?: number + shopId?: IdType + shopName?: string + type?: number + typeName?: string + createTime: string + updateTime: string +} + +/** + * adminTagApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminTagApi = { + /** + * `listAllTags` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAllTags: () => { + return adminApi.get('/tag/list/all') as unknown as Promise + }, + /** + * `listTagsByShopId` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId: IdType caller-supplied value for `shopId: IdType` + */ + listTagsByShopId: (shopId: IdType) => { + return adminApi.get(`/tag/list/by-shop/${shopId}`) as unknown as Promise + }, + /** + * `createTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType } caller-supplied value for `data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }` + */ + createTag: (data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; sceneGroup?: string; displayName?: string; sortOrder?: number; frontVisible?: number; shopId?: IdType }) => { + return adminApi.post('/tag/create', data) + }, + /** + * `updateTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType } caller-supplied value for `data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }` + */ + updateTag: (id: IdType, data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; sceneGroup?: string; displayName?: string; sortOrder?: number; frontVisible?: number; shopId?: IdType }) => { + return adminApi.put(`/tag/update/${id}`, data) + }, + /** + * `deleteTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteTag: (id: IdType) => { + return adminApi.delete(`/tag/delete/${id}`) + } +} + +/** + * Purpose: Artist supports admin.ts by holding or executing the artist page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Artist { + id: IdType + nickname: string + account: string + avatar?: string + shopId?: IdType + shopName?: string + createTime: string + updateTime: string +} + +/** + * adminArtistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminArtistApi = { + /** + * `listArtists` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + listArtists: (shopId?: IdType) => { + const params: any = {} + if (shopId) { + params.shopId = shopId + } + return adminApi.get('/user/list/artists', { params }) + } +} + +/** + * Purpose: Coupon supports admin.ts by holding or executing the coupon page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Coupon { + id: IdType + couponCode?: string + couponName: string + couponType: number + couponTypeName?: string + discountValue?: string + minAmount?: number + reduceAmount?: string + totalCount?: number + usedCount?: number + remainingCount?: number + startTime: string + endTime: string + status?: number + statusName?: string + shopId?: IdType + shopName?: string + couponScene?: string + requiredVipLevel?: string + autoMatch?: number + availableTags?: Tag[] + unavailableTags?: Tag[] + createTime: string + updateTime: string +} + +/** + * adminCouponApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminCouponApi = { + /** + * `listAllCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + listAllCoupons: (shopId?: IdType) => { + const params = shopId ? { shopId } : {} + return adminApi.get('/coupon/list/all', { params }) as unknown as Promise + }, + /** + * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ + createCoupon: (data: any) => { + return adminApi.post('/coupon/create', data) + }, + /** + * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ + updateCoupon: (id: IdType, data: any) => { + return adminApi.put(`/coupon/update/${id}`, data) + }, + /** + * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteCoupon: (id: IdType) => { + return adminApi.delete(`/coupon/delete/${id}`) + }, + /** + * `distributeCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ + distributeCoupon: (data: any) => { + return adminApi.post('/coupon/distribute', null, { params: data }) + } +} + +/** + * Purpose: AdminCommentVO supports admin.ts by holding or executing the admin comment vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminCommentVO { + id: IdType + userId: IdType + userNickname?: string + shopId?: IdType + shopName?: string + productId?: IdType + productTitle?: string + commentContent: string + parentCommentId?: IdType + parentCommentContent?: string + createTime?: string +} + +/** + * adminCommentApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminCommentApi = { + /** + * `listComments` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string } caller-supplied value for `params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string }` + */ + listComments: (params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string }) => { + return adminApi.get('/comment/list', { params }) as unknown as Promise + }, + /** + * `deleteComment` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteComment: (id: IdType) => { + return adminApi.delete(`/comment/delete/${id}`) as unknown as Promise + } +} + +/** + * Purpose: Product supports admin.ts by holding or executing the product page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Product { + id: IdType + shopId: IdType + shopName?: string + title: string + description: string + targetAudience?: string + precautions?: string + price: number + approximateDuration?: string + tags?: string + tagList?: string[] + tagInfos?: any[] + imageFileIds?: string + imageUrls?: string[] + bookableArtists?: string + availableCoupons?: string + frontVisible?: number + sourceType?: string + likeCount?: number + collectCount?: number + createTime: string + updateTime: string +} + +/** + * adminProductApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminProductApi = { + /** + * `listProducts` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; shopId?: IdType }` + */ + listProducts: (params: { page: number; size: number; keyword?: string; shopId?: IdType; tagId?: IdType; minPrice?: number; maxPrice?: number; createdFrom?: string; createdTo?: string }) => { + return adminApi.get<{ list: Product[]; total: number; page: number; size: number }>('/product/list', { params }) + }, + /** + * `listAllProducts` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAllProducts: () => { + return adminApi.get('/product/list/all') + }, + /** + * `createProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ + createProduct: (data: any) => { + return adminApi.post('/product/create', data) + }, + /** + * `updateProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ + updateProduct: (id: IdType, data: any) => { + return adminApi.put(`/product/update/${id}`, data) + }, + /** + * `deleteProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteProduct: (id: IdType) => { + return adminApi.delete(`/product/delete/${id}`) + } +} + +/** + * Purpose: Shop supports admin.ts by holding or executing the shop page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Shop { + id: IdType + shopName: string + description: string + address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string + businessHours: string + status?: number + coverImageFileId?: string + coverImageUrls?: string[] + imageFileIds?: string + imageUrls?: string[] + themePrimaryColor?: string + themeSecondaryColor?: string + themeAccentColor?: string + themePageBgColor?: string + themeCardBgColor?: string + themeBackgroundImageFileId?: string + authorizationStartDate?: string + authorizationDays?: number + authorizationExpireTime?: string + authorizationExpired?: boolean + authorizationStatusText?: string + createTime: string + updateTime: string +} + +/** + * Purpose: ShopListResponse supports admin.ts by holding or executing the shop list response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ShopListResponse { + list: Shop[] + total: number + page: number + size: number +} + +/** + * Purpose: CreateShopRequest supports admin.ts by holding or executing the create shop request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateShopRequest { + shopName: string + description: string + address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string + businessHours: string + coverImageFileId?: string + imageFileIds?: string + themePrimaryColor?: string + themeSecondaryColor?: string + themeAccentColor?: string + themePageBgColor?: string + themeCardBgColor?: string + themeBackgroundImageFileId?: string + status?: number + authorizationStartDate?: string + authorizationDays?: number + authorizationExpireTime?: string +} + +/** + * adminShopApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminShopApi = { + /** + * `listShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; shopId?: IdType }` + */ + listShops: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => { + return adminApi.get('/shops/list', { params }) as unknown as Promise + }, + /** + * `listAllShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAllShops: () => { + return adminApi.get('/shops/list/all') as unknown as Promise + }, + /** + * `createShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateShopRequest caller-supplied value for `data: CreateShopRequest` + */ + createShop: (data: CreateShopRequest) => { + return adminApi.post('/shops/create', data) + }, + /** + * `updateShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: CreateShopRequest caller-supplied value for `data: CreateShopRequest` + */ + updateShop: (id: IdType, data: CreateShopRequest) => { + return adminApi.put(`/shops/update/${id}`, data) + }, + /** + * `updateShopStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ + updateShopStatus: (id: IdType, status: number) => { + return adminApi.put(`/shops/status/${id}`, { status }) + } +} + +/** + * Purpose: UserVO supports admin.ts by holding or executing the user vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserVO { + id: IdType + shopId?: IdType + shopName?: string + shopAuthorizationExpireTime?: string + shopAuthorizationExpired?: boolean + shopIds?: IdType[] + shopNames?: string[] + nickname: string + account: string + avatar: string + phone?: string + contactPhone?: string + birthday?: string + wechatId?: string + wechatQrCode?: string + signature?: string + level?: string + type: number + vipId?: IdType + createTime: string + updateTime: string + status?: number +} + +/** + * Purpose: UserRelationVO supports admin.ts by holding or executing the user relation vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserRelationVO { + userId: IdType + shopId?: IdType + shopName?: string + parentUserId?: IdType + parentUserName?: string + parentRoleType?: number + parentRoleTypeName?: string + sourceType?: string + sourceTypeName?: string +} + +/** + * Purpose: UserStatisticsVO supports admin.ts by holding or executing the user statistics vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserStatisticsVO { + totalUserCount: number + normalUserCount: number + employeeCount: number + managerCount: number + artistCount: number + vipUserCount: number + newUserCount: number + byShop?: Record + byRole?: Record + byParent?: Record +} + +/** + * Purpose: PageResult supports admin.ts by holding or executing the page result page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface PageResult { + list: T[] + total: number + page: number + size: number +} + +export interface ArtistScheduleVO { + id: IdType + shopId?: IdType + artistId: IdType + workDate: string + startTime: string + endTime: string + slotMinutes?: number + capacity?: number + status?: number + remark?: string + createTime?: string +} + +export interface ArtistScheduleRequest { + shopId?: IdType + artistId?: IdType + workDate?: string + startTime?: string + endTime?: string + slotMinutes?: number + capacity?: number + status?: number + remark?: string +} + +export interface ArtistScheduleQuery { + artistId?: IdType + startDate?: string + endDate?: string +} + +export interface PaymentOrderVO { + id: IdType + payNo?: string + orderId: IdType + orderNo?: string + userId?: IdType + shopId?: IdType + channel?: string + status?: string + payAmount?: number + paidAmount?: number + payTime?: string + expireTime?: string + remark?: string +} + +export interface AfterSaleVO { + id: IdType + afterSaleNo?: string + orderId: IdType + orderItemId?: IdType + userId?: IdType + shopId?: IdType + type?: string + reason?: string + refundAmount?: number + status?: string + auditUserId?: IdType + auditReason?: string + auditTime?: string + refundOrderId?: IdType + createTime?: string +} + +export interface AfterSaleAuditRequest { + auditReason?: string +} + +export interface AfterSaleQuery { + status?: string + page: number + size: number +} + +export interface InventoryItemVO { + id: IdType + shopId?: IdType + category?: string + itemName: string + unit?: string + stockQuantity?: number + warningThreshold?: number + warning?: boolean + status?: number +} + +export interface InventoryItemRequest { + shopId?: IdType + category?: string + itemName?: string + unit?: string + stockQuantity?: number + warningThreshold?: number + status?: number +} + +export interface InventoryAdjustRequest { + changeType?: string + changeQuantity?: number + remark?: string +} + +export interface CampaignVO { + id: IdType + shopId?: IdType + title: string + description?: string + scene?: string + productIds?: string + couponIds?: string + status?: number + startTime?: string + endTime?: string + sortOrder?: number +} + +export interface CampaignRequest { + shopId?: IdType + title?: string + description?: string + scene?: string + productIds?: string + couponIds?: string + status?: number + startTime?: string + endTime?: string + sortOrder?: number +} + +export interface OperationsAnalyticsVO { + viewCount?: number + favoriteCount?: number + cartCount?: number + orderCount?: number + paidOrderCount?: number + completedOrderCount?: number + reviewCount?: number + rebookCount?: number + totalAmount?: number +} + +export const adminArtistScheduleApi = { + listSchedules: (params: ArtistScheduleQuery = {}) => { + return adminApi.get('/artist-schedule/list', { params }) as unknown as Promise + }, + saveSchedule: (data: ArtistScheduleRequest) => { + return adminApi.post('/artist-schedule/save', data) as unknown as Promise + } +} + +export const adminPaymentApi = { + manualConfirmOrder: (orderId: IdType, remark?: string) => { + return adminApi.post(`/payment/order/${orderId}/manual-confirm`, undefined, { + params: { remark } + }) as unknown as Promise + } +} + +export const adminAfterSaleApi = { + listAfterSales: (params: AfterSaleQuery) => { + return adminApi.get>('/after-sale/list', { params }) as unknown as Promise> + }, + approveAfterSale: (id: IdType, data?: AfterSaleAuditRequest) => { + return adminApi.put(`/after-sale/${id}/approve`, data || {}) as unknown as Promise + }, + rejectAfterSale: (id: IdType, data?: AfterSaleAuditRequest) => { + return adminApi.put(`/after-sale/${id}/reject`, data || {}) as unknown as Promise + } +} + +export const adminInventoryApi = { + listItems: (params: { page: number; size: number }) => { + return adminApi.get>('/inventory/list', { params }) as unknown as Promise> + }, + saveItem: (data: InventoryItemRequest) => { + return adminApi.post('/inventory/save', data) as unknown as Promise + }, + adjustStock: (id: IdType, data: InventoryAdjustRequest) => { + return adminApi.post(`/inventory/${id}/adjust`, data) as unknown as Promise + } +} + +export const adminCampaignApi = { + listCampaigns: (params: { status?: number; page: number; size: number }) => { + return adminApi.get>('/campaign/list', { params }) as unknown as Promise> + }, + saveCampaign: (data: CampaignRequest) => { + return adminApi.post('/campaign/save', data) as unknown as Promise + } +} + +/** + * adminUserApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminUserApi = { + // 后台用户列表支持多维筛选;页面侧应优先展示 maskedPhone/maskedEmail, + // 避免在列表中直接暴露完整手机号或邮箱。 + /** + * `listUsers` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean } caller-supplied value for `params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }` + */ + listUsers: (params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }) => { + return adminApi.get>('/user/list', { params }) as unknown as Promise> + }, + /** + * `getUserStatistics` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean } caller-supplied value for `params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }` + */ + getUserStatistics: (params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }) => { + return adminApi.get('/user/statistics', { params }) as unknown as Promise + }, + /** + * `listAllUsers` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAllUsers: () => { + return adminApi.get('/user/list/all') as unknown as Promise + }, + /** + * `createUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ + createUser: (data: any) => { + return adminApi.post('/user/create', data) + }, + /** + * `updateUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ + updateUser: (id: IdType, data: any) => { + return adminApi.put(`/user/update/${id}`, data) + }, + /** + * `deleteUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteUser: (id: IdType) => { + return adminApi.delete(`/user/delete/${id}`) + }, + /** + * `unbindUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + unbindUser: (id: IdType) => { + return adminApi.put(`/user/unbind/${id}`, {}) + }, + /** + * `updateUserStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ + updateUserStatus: (id: IdType, status: number) => { + return adminApi.put(`/user/status/${id}`, { status }) + }, + /** + * `getRelationOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + getRelationOptions: (shopId?: IdType) => { + return adminApi.get(`/user/relation/options`, { params: { shopId } }) as unknown as Promise + }, + /** + * `updateUserRelation` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string } caller-supplied value for `data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string }` + */ + updateUserRelation: (id: IdType, data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string }) => { + return adminApi.put(`/user/${id}/relation`, data) as unknown as Promise + }, + /** + * `resetPassword` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + resetPassword: (id: IdType) => { + return adminApi.post(`/user/reset-password/${id}`) + }, + /** + * `getUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getUserInfo: () => { + return adminApi.get('/user/info') as unknown as Promise + }, + /** + * `getUserAsset` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + getUserAsset: (id: IdType) => { + return adminApi.get(`/user/${id}/asset`) as unknown as Promise + }, + /** + * `getUserBalanceHistory` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + getUserBalanceHistory: (id: IdType) => { + return adminApi.get(`/user/${id}/balance/history`) as unknown as Promise + }, + /** + * `changeUserBalance` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: AdminUserBalanceChangeRequest caller-supplied value for `data: AdminUserBalanceChangeRequest` + */ + changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => { + return adminApi.post(`/user/${id}/balance/change`, data) as unknown as Promise + }, + /** + * `overrideUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: AdminUserVipOverrideRequest caller-supplied value for `data: AdminUserVipOverrideRequest` + */ + overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => { + return adminApi.post(`/user/${id}/vip/override`, data) as unknown as Promise + }, + /** + * `recalculateUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + recalculateUserVip: (id: IdType) => { + return adminApi.post(`/user/${id}/vip/recalculate`) as unknown as Promise + } +} + +/** + * Purpose: UserAssetVO supports admin.ts by holding or executing the user asset vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserAssetVO { + userId: IdType + nickname: string + balance: number + totalRechargeAmount: number + lastRechargeTime?: string + vipInfoId?: IdType + vipLevel: string + benefitId?: IdType + benefitInfo?: string + manualOverride: boolean + vipStartTime?: string + vipExpireTime?: string +} + +/** + * Purpose: UserBalanceHistoryItem supports admin.ts by holding or executing the user balance history item page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserBalanceHistoryItem { + id: IdType + userId: IdType + userNickname?: string + amount: number + type?: string + currentBalance?: number + beforeBalance?: number + afterBalance?: number + changeScene?: string + relatedOrderId?: IdType + relatedOrderNo?: string + externalOrderNo?: string + operatorId?: IdType + remark?: string + changeTime: string +} + +/** + * Purpose: AdminUserBalanceChangeRequest supports admin.ts by holding or executing the admin user balance change request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminUserBalanceChangeRequest { + amount: number + changeScene: string + relatedOrderId?: IdType + externalOrderNo?: string + remark?: string +} + +/** + * Purpose: AdminUserVipOverrideRequest supports admin.ts by holding or executing the admin user vip override request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminUserVipOverrideRequest { + vipLevel: string + remark?: string +} + +/** + * Purpose: userApi supports admin.ts by holding or executing the user api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const userApi = adminUserApi + +/** + * Purpose: OrderVO supports admin.ts by holding or executing the order vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderVO { + id: IdType + orderNo: string + userId: IdType + userNickname?: string + shopId: IdType + shopName?: string + artistId?: IdType + artistName?: string + totalAmount: number + actualAmount?: number + discountAmount: number + payAmount: number + paidAmount?: number + paymentStatus?: string + paymentMethod?: string + paymentOrderNo?: string + payTime?: string + refundStatus?: string + customerRemark?: string + quoteStatus?: string + quoteStatusText?: string + quoteUserConfirmed?: boolean + quoteShopConfirmed?: boolean + quoteExpireTime?: string + quoteConfirmedTime?: string + quoteMessages?: any[] + couponName?: string + customerName?: string + customerPhone?: string + customerNickname?: string + customerPhoneMasked?: string + items?: Array<{ + id: IdType + productId: IdType + productTitle?: string + artistId?: IdType + artistName?: string + appointmentTime?: string + price: number + referencePrice?: number + quotedPrice?: number + confirmedPrice?: number + quantity: number + }> + status: number + statusText?: string + remark?: string + createTime: string + updateTime: string +} + +/** + * adminOrderApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminOrderApi = { + /** + * `listOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }` + */ + listOrders: (params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }) => { + return adminApi.get>('/order/list', { params }) + }, + /** + * `updateOrderStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ + updateOrderStatus: (id: IdType, status: number) => { + return adminApi.put(`/order/update-status/${id}`, {}, { params: { status } }) + }, + manualConfirmPayment: (id: IdType, remark?: string) => { + return adminPaymentApi.manualConfirmOrder(id, remark) + }, + submitQuote: (id: IdType, data: { remark?: string; items: Array<{ orderItemId: IdType; quotedPrice: number }> }) => { + return adminApi.post(`/order/${id}/quote`, data) + }, + confirmQuote: (id: IdType) => { + return adminApi.put(`/order/${id}/quote/confirm`) + } +} + +/** + * Purpose: HotProductVO supports admin.ts by holding or executing the hot product vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface HotProductVO { + id: IdType + title: string + price: number + likeCount: number + collectCount: number +} + +/** + * Purpose: RecentActivityVO supports admin.ts by holding or executing the recent activity vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface RecentActivityVO { + id: IdType + type: string + title?: string + description: string + time: string + color?: string +} + +/** + * Purpose: DashboardStats supports admin.ts by holding or executing the dashboard stats page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface DashboardStats { + totalUsers: number + totalProducts: number + totalShops: number + todayOrders: number + totalOrderAmount?: number + todayOrderAmount?: number + weekOrderAmount?: number + totalCustomers?: number + totalArtists?: number + newCustomersToday?: number + newCustomers7Days?: number + newOrders7Days?: number + pendingOrders?: number + completedOrders?: number + hotProducts: HotProductVO[] + recentActivities: RecentActivityVO[] +} + +/** + * adminDashboardApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminDashboardApi = { + /** + * `getStats` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getStats: () => { + return adminApi.get('/dashboard/stats') + }, + getAnalytics: () => { + return adminApi.get('/dashboard/analytics') as unknown as Promise + } +} + +/** + * Purpose: NailArtistInfoVO supports admin.ts by holding or executing the nail artist info vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface NailArtistInfoVO { + id: IdType + userId: IdType + identity: string + experience: number + skills: string + rating: number + status: number + portfolio: string + nickname: string + shopId: IdType + shopName: string + userType?: number + userTypeName?: string + participateProduction?: number + workStartTime?: string + workEndTime?: string +} + +/** + * adminNailArtistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminNailArtistApi = { + /** + * `listNailArtists` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listNailArtists: () => { + return adminApi.get('/nail-artist/list') as unknown as Promise + }, + /** + * `getNailArtistInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + */ + getNailArtistInfo: (userId: IdType) => { + return adminApi.get(`/nail-artist/get/${userId}`) + }, + /** + * `saveNailArtistInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ + saveNailArtistInfo: (data: any) => { + return adminApi.post('/nail-artist/save', data) + } +} + +/** + * Purpose: SystemMessageVO supports admin.ts by holding or executing the system message vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SystemMessageVO { + id: IdType + title: string + content: string + imageFileId?: IdType + imageUrl?: string + publisherId: IdType + publisherName?: string + publisherType: number + targetType: string + targetTypeName?: string + targetIds?: IdType[] + popupEnabled: number + status: number + publishTime?: string + createTime?: string + popupShown?: number + readStatus?: number +} + +/** + * Purpose: MessageTargetOptionsVO supports admin.ts by holding or executing the message target options vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface MessageTargetOptionsVO { + shops: Array<{ id: IdType; shopName: string }> + users: Array<{ id: IdType; nickname: string; account: string; shopId?: IdType; shopName?: string; type?: number }> +} + +/** + * Purpose: SystemMessageCreateRequest supports admin.ts by holding or executing the system message create request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SystemMessageCreateRequest { + title: string + content: string + imageFileId?: IdType + targetType: string + shopIds?: IdType[] + userIds?: IdType[] + popupEnabled?: number +} + +/** + * adminSystemMessageApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminSystemMessageApi = { + // 消息通知会进入用户“消息通知”列表;如果 popupEnabled=1, + // 前端展示弹窗后必须调用 mark popup-shown,保证每人每条只弹一次。 + /** + * `listMessages` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listMessages: () => { + return adminApi.get('/system-message/admin/list') as unknown as Promise + }, + /** + * `createMessage` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SystemMessageCreateRequest caller-supplied value for `data: SystemMessageCreateRequest` + */ + createMessage: (data: SystemMessageCreateRequest) => { + return adminApi.post('/system-message/admin/create', data) + }, + /** + * `revokeMessage` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + revokeMessage: (id: IdType) => { + return adminApi.put(`/system-message/admin/${id}/revoke`) + }, + /** + * `getTargetOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getTargetOptions: () => { + return adminApi.get('/system-message/admin/target-options') as unknown as Promise + } +} + +/** + * Purpose: AnnouncementVO supports admin.ts by holding or executing the announcement vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AnnouncementVO { + id: IdType + title: string + content: string + publisherId?: IdType + publisherName?: string + publisherType?: number + targetType: string + targetTypeName?: string + targetIds?: IdType[] + status: number + sortOrder?: number + publishTime?: string + createTime?: string +} + +/** + * Purpose: AnnouncementCreateRequest supports admin.ts by holding or executing the announcement create request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AnnouncementCreateRequest { + title: string + content: string + targetType: string + shopIds?: IdType[] + userIds?: IdType[] + sortOrder?: number +} + +/** + * adminAnnouncementApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminAnnouncementApi = { + // 公告只在首页顶部滚动显示,不写入消息已读/未读状态。 + /** + * `listAnnouncements` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAnnouncements: () => { + return adminApi.get('/announcement/admin/list') as unknown as Promise + }, + /** + * `createAnnouncement` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: AnnouncementCreateRequest caller-supplied value for `data: AnnouncementCreateRequest` + */ + createAnnouncement: (data: AnnouncementCreateRequest) => { + return adminApi.post('/announcement/admin/create', data) + }, + /** + * `revokeAnnouncement` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + revokeAnnouncement: (id: IdType) => { + return adminApi.put(`/announcement/admin/${id}/revoke`) + }, + /** + * `getTargetOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getTargetOptions: () => { + return adminApi.get('/announcement/admin/target-options') as unknown as Promise + } +} + +/** + * Purpose: VipRechargePlanVO supports admin.ts by holding or executing the vip recharge plan vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface VipRechargePlanVO { + id: IdType + shopId: IdType + shopName?: string + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status: number + createTime?: string + updateTime?: string +} + +/** + * Purpose: VipRechargePlanRequest supports admin.ts by holding or executing the vip recharge plan request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface VipRechargePlanRequest { + shopId?: IdType + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status?: number +} + +/** + * adminVipRechargePlanApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminVipRechargePlanApi = { + /** + * `listPlans` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + listPlans: (shopId?: IdType) => { + const params = shopId ? { shopId } : {} + return adminApi.get('/vip-recharge-plan/admin/list', { params }) as unknown as Promise + }, + /** + * `createPlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` + */ + createPlan: (data: VipRechargePlanRequest) => { + return adminApi.post('/vip-recharge-plan/admin/create', data) + }, + /** + * `updatePlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` + */ + updatePlan: (id: IdType, data: VipRechargePlanRequest) => { + return adminApi.put(`/vip-recharge-plan/admin/${id}`, data) + }, + /** + * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ + updateStatus: (id: IdType, status: number) => { + return adminApi.put(`/vip-recharge-plan/admin/${id}/status`, null, { params: { status } }) + }, + /** + * `listVipLevelOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + listVipLevelOptions: (shopId?: IdType) => { + const params = shopId ? { shopId } : {} + return adminApi.get('/vip-recharge-plan/admin/vip-level-options', { params }) as unknown as Promise + } +} + +/** + * Purpose: MessageHubPushConfigVO supports admin.ts by holding or executing the message hub push config vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface MessageHubPushConfigVO { + id: IdType + sceneCode: string + sceneName: string + platform: string + msgType: string + queueName: string + sourceSystem: string + templateCode: string + channelId?: IdType + sendMethod?: string + enabled: number + remark?: string + createTime?: string + updateTime?: string +} + +/** + * Purpose: MessageHubPushConfigRequest supports admin.ts by holding or executing the message hub push config request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface MessageHubPushConfigRequest { + sceneCode: string + sceneName: string + platform: string + msgType: string + queueName: string + sourceSystem: string + templateCode: string + channelId?: IdType + sendMethod?: string + enabled?: number + remark?: string +} + +/** + * adminMessageHubPushConfigApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminMessageHubPushConfigApi = { + /** + * `listConfigs` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listConfigs: () => { + return adminApi.get('/messagehub-push-config/admin/list') as unknown as Promise + }, + /** + * `createConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: MessageHubPushConfigRequest caller-supplied value for `data: MessageHubPushConfigRequest` + */ + createConfig: (data: MessageHubPushConfigRequest) => { + return adminApi.post('/messagehub-push-config/admin/create', data) + }, + /** + * `updateConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: MessageHubPushConfigRequest caller-supplied value for `data: MessageHubPushConfigRequest` + */ + updateConfig: (id: IdType, data: MessageHubPushConfigRequest) => { + return adminApi.put(`/messagehub-push-config/admin/${id}`, data) + }, + /** + * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param enabled: number caller-supplied value for `enabled: number` + */ + updateStatus: (id: IdType, enabled: number) => { + return adminApi.put(`/messagehub-push-config/admin/${id}/status`, null, { params: { enabled } }) + }, + /** + * `testConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param phone: string caller-supplied value for `phone: string` + */ + testConfig: (id: IdType, phone: string) => { + return adminApi.post(`/messagehub-push-config/admin/${id}/test`, { phone }) + } +} + +/** + * Purpose: SystemParameterConfigVO supports admin.ts by holding or executing the system parameter config vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SystemParameterConfigVO { + id?: IdType + configGroup: string + configKey: string + configName: string + configValue: string + enabled: number + remark?: string + createTime?: string + updateTime?: string +} + +export interface AdminDefaultPasswordResponse { + password: string +} + +/** + * Purpose: adminSystemParameterConfigApi supports admin.ts by holding or executing the admin system parameter config api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const adminSystemParameterConfigApi = { + listConfigs: (configGroup?: string) => { + return adminApi.get('/system-parameter-config/admin/list', { params: { configGroup } }) as unknown as Promise + }, + saveConfig: (data: SystemParameterConfigVO) => { + return adminApi.post('/system-parameter-config/admin/save', data) + }, + getTencentMapKey: () => { + return adminApi.get<{ key: string }>('/system-parameter-config/admin/tencent-map') as unknown as Promise<{ key: string }> + }, + getMapConfig: () => { + return adminApi.get<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }>('/system-parameter-config/admin/map-config') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; tencentWebKey?: string; amapWebKey?: string; amapMiniKey?: string }> + }, + getUserDefaultPassword: () => { + return adminApi.get('/system-parameter-config/admin/user-default-password') as unknown as Promise + } +} + +export { adminApi } +export default adminApi diff --git a/FM-Frontend/src/api/auth-free-paths.ts b/FM-Frontend/src/api/auth-free-paths.ts new file mode 100644 index 00000000..5b6d4545 --- /dev/null +++ b/FM-Frontend/src/api/auth-free-paths.ts @@ -0,0 +1,84 @@ +/** + * Purpose: WEB_API_AUTH_FREE_PATHS supports auth-free-paths.ts by holding or executing the web api auth free paths page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const WEB_API_AUTH_FREE_PATHS = [ + '/user/login', + '/user/register', + '/user/check/', + '/user/refresh-token', + '/user/send-verification-code', + '/user/phone-login', + '/user/wechat-mini/', + '/user/reset-password-by-phone', + '/legal-agreement/current', + '/api/legal-agreement/current', + '/product/get/', + '/product/list/', + '/comment/list/product/', + '/nail-artist/', + '/shop/get/', + '/shop/trust-profile/', + '/shop/list', + '/shop/list/public', + '/shop/list/simple', + '/tag/list/all', + '/tag/list/filter-options', + '/file/get-signed-url/', + '/admin/auth/login', + '/admin/auth/login-shops/', + '/admin/auth/refresh' +] as const + +/** + * Purpose: ADMIN_API_AUTH_FREE_PATHS supports auth-free-paths.ts by holding or executing the admin api auth free paths page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ADMIN_API_AUTH_FREE_PATHS = [ + '/auth/login', + '/auth/login-shops/', + '/auth/refresh' +] as const + +/** + * Purpose: normalizePathname supports auth-free-paths.ts by holding or executing the normalize pathname page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const normalizePathname = (url?: string) => { + const raw = String(url || '') + const withoutHash = raw.split('#')[0] || '' + const withoutQuery = withoutHash.split('?')[0] || '' + try { + return new URL(withoutQuery, 'http://fingertipdesigner.local').pathname + } catch { + return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}` + } +} + +/** + * Purpose: matchesAuthFreePath supports auth-free-paths.ts by holding or executing the matches auth free path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const matchesAuthFreePath = (url: string | undefined, path: string) => { + const pathname = normalizePathname(url) + if (path.endsWith('/')) { + return pathname === path.slice(0, -1) || pathname.startsWith(path) + } + return pathname === path +} + +/** + * Purpose: isApiAuthFreePath supports auth-free-paths.ts by holding or executing the is api auth free path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isApiAuthFreePath = (url?: string) => { + return WEB_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path)) +} + +/** + * Purpose: isAdminApiAuthFreePath supports auth-free-paths.ts by holding or executing the is admin api auth free path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isAdminApiAuthFreePath = (url?: string) => { + return ADMIN_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path)) +} diff --git a/FM-Frontend/src/api/auth.ts b/FM-Frontend/src/api/auth.ts new file mode 100644 index 00000000..9fe657a0 --- /dev/null +++ b/FM-Frontend/src/api/auth.ts @@ -0,0 +1,251 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: SendVerificationCodeRequest supports auth.ts by holding or executing the send verification code request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SendVerificationCodeRequest { + phone: string + sceneCode?: string +} + +/** + * Purpose: LoginRequest supports auth.ts by holding or executing the login request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LoginRequest { + account: string + password: string + rememberMe?: boolean + shopId?: string | number + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string +} + +/** + * Purpose: PhoneLoginRequest supports auth.ts by holding or executing the phone login request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface PhoneLoginRequest { + phone: string + verificationCode: string + shopId?: string | number + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string +} + +/** + * Purpose: RegisterRequest supports auth.ts by holding or executing the register request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface RegisterRequest { + account: string + password: string + nickname: string + shopId?: string | number + inviteCode?: string + phone?: string + verificationCode?: string + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string +} + +/** + * Purpose: LegalAgreement supports auth.ts by holding or executing the legal agreement page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LegalAgreement { + id: IdType + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + agreementTypeName: string + title: string + version: string + content: string + status: number + statusText?: string + effectiveTime?: string +} + +/** + * Purpose: LoginResponse supports auth.ts by holding or executing the login response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LoginResponse { + accessToken: string + refreshToken: string + userInfo: UserInfo +} + +/** + * Purpose: UserInfo supports auth.ts by holding or executing the user info page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserInfo { + id: IdType + account: string + nickname: string + avatar?: string + signature?: string + type?: number + shopId?: IdType + shopName?: string + shopAuthorizationExpireTime?: string + shopAuthorizationExpired?: boolean + shopIds?: IdType[] + shopNames?: string[] + createTime: string + updateTime?: string +} + +/** + * Purpose: RefreshTokenRequest supports auth.ts by holding or executing the refresh token request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface RefreshTokenRequest { + refreshToken: string +} + +/** + * Purpose: RefreshTokenResponse supports auth.ts by holding or executing the refresh token response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface RefreshTokenResponse { + accessToken: string + refreshToken: string +} + +/** + * Purpose: ResetPasswordRequest supports auth.ts by holding or executing the reset password request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ResetPasswordRequest { + phone: string + verificationCode: string + newPassword: string +} + +/** + * Purpose: SwitchShopRequest supports auth.ts by holding or executing the switch shop request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SwitchShopRequest { + shopId?: string | number +} + +/** + * authApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const authApi = { + /** + * `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SendVerificationCodeRequest caller-supplied value for `data: SendVerificationCodeRequest` + */ + sendVerificationCode: (data: SendVerificationCodeRequest) => { + return api.post('/user/send-verification-code', data) + }, + + /** + * `login` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: LoginRequest caller-supplied value for `data: LoginRequest` + */ + login: (data: LoginRequest) => { + return api.post('/user/login', data) + }, + + /** + * `phoneLogin` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: PhoneLoginRequest caller-supplied value for `data: PhoneLoginRequest` + */ + phoneLogin: (data: PhoneLoginRequest) => { + return api.post('/user/phone-login', data) + }, + + /** + * `adminLogin` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: LoginRequest caller-supplied value for `data: LoginRequest` + */ + adminLogin: (data: LoginRequest) => { + return api.post('/admin/auth/login', data) + }, + + /** + * `register` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: RegisterRequest caller-supplied value for `data: RegisterRequest` + */ + register: (data: RegisterRequest) => { + return api.post('/user/register', data) + }, + + /** + * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: RefreshTokenRequest caller-supplied value for `data: RefreshTokenRequest` + */ + refreshToken: (data: RefreshTokenRequest) => { + return api.post('/user/refresh-token', data) + }, + + /** + * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + logout: () => { + return api.post('/user/logout') + }, + + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SwitchShopRequest caller-supplied value for `data: SwitchShopRequest` + */ + switchShop: (data: SwitchShopRequest) => { + return api.post('/user/switch-shop', data) + }, + + /** + * `getUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getUserInfo: () => { + return api.get('/user/info') + }, + + /** + * `resetPasswordByPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ResetPasswordRequest caller-supplied value for `data: ResetPasswordRequest` + */ + resetPasswordByPhone: (data: ResetPasswordRequest) => { + return api.post('/user/reset-password-by-phone', data) + } +} + +/** + * Purpose: legalAgreementApi supports auth.ts by holding or executing the legal agreement api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const legalAgreementApi = { + listCurrent: () => { + return api.get('/legal-agreement/current') + }, + getCurrent: (type: 'USER_TERMS' | 'PRIVACY_POLICY') => { + return api.get(`/legal-agreement/current/${type}`) + }, + getMyConsent: () => { + return api.get<{ consentVersions: Record }>('/user/agreement-consent/me') + } +} diff --git a/FM-Frontend/src/api/cart.ts b/FM-Frontend/src/api/cart.ts new file mode 100644 index 00000000..5586962e --- /dev/null +++ b/FM-Frontend/src/api/cart.ts @@ -0,0 +1,79 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +interface CartItem { + productId: IdType + quantity: number +} + +/** + * cartApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const cartApi = { + // 添加作品到购物车 + /** + * `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param item: CartItem caller-supplied value for `item: CartItem` + */ + addToCart: (item: CartItem) => { + return api.post('/cart/add', item) + }, + + // 从购物车移除作品 + /** + * `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ + removeFromCart: (productId: IdType) => { + return api.delete(`/cart/remove/${productId}`) + }, + + // 批量从购物车移除作品 + /** + * `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]` + */ + batchRemoveFromCart: (cartItemIds: IdType[]) => { + return api.post('/cart/batch-remove', cartItemIds) + }, + + // 更新购物车作品数量 + /** + * `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param item: CartItem caller-supplied value for `item: CartItem` + */ + updateCartQuantity: (item: CartItem) => { + return api.put('/cart/update', item) + }, + + // 获取购物车列表 + /** + * `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getCartList: () => { + return api.get('/cart/list') + }, + + // 清空购物车 + /** + * `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + clearCart: () => { + return api.delete('/cart/clear') + } +} diff --git a/FM-Frontend/src/api/comment.ts b/FM-Frontend/src/api/comment.ts new file mode 100644 index 00000000..dc7a08b2 --- /dev/null +++ b/FM-Frontend/src/api/comment.ts @@ -0,0 +1,114 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { AxiosProgressEvent } from 'axios' +import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file' +import type { IdType } from '@/utils/id' + +/** + * Purpose: CommentVO supports comment.ts by holding or executing the comment vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CommentVO { + id: IdType + userId: IdType + userNickname?: string + shopId?: IdType + shopName?: string + productId?: IdType + productTitle?: string + commentContent: string + parentCommentId?: IdType + parentCommentContent?: string + likeCount?: number + ratingScore?: number + imageFileIds?: IdType[] + imageUrls?: string[] + createTime?: string + updateTime?: string + replies?: CommentVO[] +} + +export interface CommentCreateRequest { + productId: IdType + shopId?: IdType | null + parentCommentId?: IdType | null + commentContent: string + ratingScore?: number + imageFileIds?: IdType[] +} + +export interface CommentImageFileVO { + id: IdType + fileName?: string + fileUrl?: string + createTime?: string +} + +/** + * commentApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const commentApi = { + /** + * `listByProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ + listByProduct: (productId: IdType) => { + return api.get(`/comment/list/product/${productId}`) as unknown as Promise + }, + /** + * `create` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string } caller-supplied value for `data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }` + */ + create: (data: CommentCreateRequest) => { + return api.post('/comment/create', data) as unknown as Promise + }, + uploadImage: (file: File) => { + const formData = new FormData() + formData.append('file', file) + return api.post('/comment/upload-image', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + } + }) as unknown as Promise + }, + initImageChunkUpload: (data: ChunkUploadInitRequest) => { + return api.post('/comment/upload-image/init', data) as unknown as Promise + }, + uploadImageChunk: ( + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return api.post('/comment/upload-image/chunk', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + }, + signal: config?.signal, + onUploadProgress: config?.onUploadProgress + }) + }, + completeImageChunkUpload: (uploadId: string) => { + return api.post('/comment/upload-image/complete', { uploadId }) as unknown as Promise + }, + cancelImageChunkUpload: (uploadId: string) => { + return api.delete(`/comment/upload-image/${uploadId}`) + }, + /** + * `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + delete: (id: IdType) => { + return api.delete(`/comment/delete/${id}`) as unknown as Promise + } +} diff --git a/FM-Frontend/src/api/coupon.ts b/FM-Frontend/src/api/coupon.ts new file mode 100644 index 00000000..edc87861 --- /dev/null +++ b/FM-Frontend/src/api/coupon.ts @@ -0,0 +1,221 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import request from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Coupon { + id: IdType + couponCode: string + couponName: string + couponType: number + couponTypeName: string + discountValue?: number + minAmount?: number + reduceAmount?: number + totalCount: number + usedCount: number + remainingCount: number + startTime: string + endTime: string + status: number + statusName: string + shopId?: IdType + couponScene?: string + requiredVipLevel?: string + autoMatch?: number + availableTags: Tag[] + unavailableTags: Tag[] +} + +/** + * Purpose: Tag supports coupon.ts by holding or executing the tag page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface Tag { + id: IdType + tagName?: string +} + +/** + * Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserCoupon { + id: IdType + couponId: IdType + couponName: string + couponType: number + couponTypeName: string + discountValue: string + minAmount: string + reduceAmount: string + startTime: string + endTime: string + status: number + statusName: string + obtainTime: string + useTime: string + sourceType?: string + requiredVipLevel?: string + autoMatched?: boolean +} + +/** + * Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateCouponRequest { + couponCode: string + couponName: string + couponType: number + discountValue?: number + minAmount?: number + reduceAmount?: number + totalCount: number + startTime: string + endTime: string + couponScene?: string + requiredVipLevel?: string + autoMatch?: number + availableTagIds: IdType[] + unavailableTagIds: IdType[] +} + +/** + * Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CouponListResponse { + list: Coupon[] + total: number + page: number + size: number +} + +/** + * couponApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const couponApi = { + // 创建优惠券 + /** + * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` + */ + createCoupon: (data: CreateCouponRequest) => { + return request({ + url: '/coupon/create', + method: 'post', + data + }) + }, + + // 更新优惠券 + /** + * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` + */ + updateCoupon: (id: IdType, data: CreateCouponRequest) => { + return request({ + url: `/coupon/update/${id}`, + method: 'put', + data + }) + }, + + // 删除优惠券 + /** + * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteCoupon: (id: IdType) => { + return request({ + url: `/coupon/delete/${id}`, + method: 'delete' + }) + }, + + // 获取优惠券详情 + /** + * `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + getCouponById: (id: IdType) => { + return request({ + url: `/coupon/detail/${id}`, + method: 'get' + }) + }, + + // 获取优惠券列表 + /** + * `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }` + */ + listCoupons: (params: { page: number; size: number; shopId?: IdType }) => { + return request({ + url: '/coupon/list', + method: 'get', + params + }) + }, + + // 为用户分配优惠券 + /** + * `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + * @param couponId: IdType caller-supplied value for `couponId: IdType` + */ + assignCouponToUser: (userId: IdType, couponId: IdType) => { + return request({ + url: '/coupon/assign', + method: 'post', + params: { userId, couponId } + }) + }, + + // 获取用户优惠券列表 + listUserCoupons: async (status?: number): Promise => { + return await request({ + url: '/coupon/user/list', + method: 'get', + params: { status } + }) as UserCoupon[] + }, + + // 使用优惠券 + /** + * `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userCouponId: IdType caller-supplied value for `userCouponId: IdType` + */ + useCoupon: (userCouponId: IdType) => { + return request({ + url: '/coupon/use', + method: 'post', + params: { userCouponId } + }) + }, + + // 获取作品可用的优惠券 + getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise => { + return await request({ + url: '/coupon/available', + method: 'get', + params: { productTags, productPrice, shopId } + }) as UserCoupon[] + } +} diff --git a/FM-Frontend/src/api/error.test.ts b/FM-Frontend/src/api/error.test.ts new file mode 100644 index 00000000..2a0ad844 --- /dev/null +++ b/FM-Frontend/src/api/error.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import type { AxiosError } from 'axios' +import { + getApiResponseMessage, + isPermissionErrorMessage, + isSystemFailureResponse, + isTokenExpiredMessage, + normalizeApiErrorMessage, + shouldShowDedupedError, + updateSystemFailureWindow +} from './error' + +describe('api error helpers', () => { + it('extracts messages and classifies error types', () => { + const error = { message: 'fallback', response: { data: { message: '服务异常' } } } as AxiosError + expect(getApiResponseMessage(error, '请求失败')).toBe('服务异常') + expect(isPermissionErrorMessage('权限不足')).toBe(true) + expect(isPermissionErrorMessage('permission denied')).toBe(true) + expect(isTokenExpiredMessage('登录已过期,请重新登录')).toBe(true) + }) + + it('dedupes prompts by message and time', () => { + expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'a', 40, 50)).toBe(false) + expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'b', 100, 50)).toBe(true) + }) + + it('normalizes garbled booking unavailable messages', () => { + expect(normalizeApiErrorMessage('涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试') + expect(normalizeApiErrorMessage('创建订单失败:涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试') + }) + + it('classifies system failure responses', () => { + expect(isSystemFailureResponse({ response: { status: 500 } } as AxiosError)).toBe(true) + expect(isSystemFailureResponse({ response: { status: 503 } } as AxiosError)).toBe(true) + expect(isSystemFailureResponse({ response: { status: 400 } } as AxiosError)).toBe(false) + expect(isSystemFailureResponse({ response: undefined } as AxiosError)).toBe(true) + }) + + it('tracks failure windows with pruning and threshold', () => { + expect(updateSystemFailureWindow([1_000, 12_000], 40_000, 30_000, 3)).toEqual({ + failureTimes: [12_000, 40_000], + triggered: false + }) + expect(updateSystemFailureWindow([1_000, 12_000, 20_000], 30_000, 30_000, 3)).toEqual({ + failureTimes: [1_000, 12_000, 20_000, 30_000], + triggered: true + }) + }) +}) diff --git a/FM-Frontend/src/api/error.ts b/FM-Frontend/src/api/error.ts new file mode 100644 index 00000000..cdf20ad7 --- /dev/null +++ b/FM-Frontend/src/api/error.ts @@ -0,0 +1,90 @@ +import type { AxiosError } from 'axios' + +export interface ApiResponseBody { + message?: string +} + +export interface ErrorPromptState { + lastErrorTime: number + lastErrorMessage: string +} + +export interface SystemFailureWindowState { + failureTimes: number[] + triggered: boolean +} + +const BOOKING_UNAVAILABLE_MESSAGE = '不可预约,请调整美甲师或预约时间后重试' +const GARbled_BOOKING_UNAVAILABLE_MESSAGES = [ + '涓嶅彲棰勭害' +] + +export const normalizeApiErrorMessage = (messageText: string): string => { + const trimmedMessage = String(messageText || '').trim() + if (!trimmedMessage) return trimmedMessage + if (GARbled_BOOKING_UNAVAILABLE_MESSAGES.some(message => trimmedMessage.includes(message))) { + return BOOKING_UNAVAILABLE_MESSAGE + } + return trimmedMessage +} + +export const getApiResponseMessage = (error: AxiosError, fallbackMessage: string): string => { + const responseData = error.response?.data as ApiResponseBody | undefined + return normalizeApiErrorMessage(responseData?.message || error.message || fallbackMessage) +} + +export const isPermissionErrorMessage = (messageText: string): boolean => + messageText.includes('权限') || messageText.includes('permission') + +export const isTokenExpiredMessage = (messageText: string): boolean => ( + messageText.includes('Token') + || messageText.includes('token') + || messageText.includes('登录态') + || messageText.includes('登录已过期') + || messageText.includes('未登录') + || messageText.includes('认证') + || messageText.includes('重新登录') +) + +export const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null): boolean => + Boolean(requestToken && isTokenExpiredMessage(getApiResponseMessage(error, '请求失败'))) + +export const isSystemFailureResponse = (error: AxiosError): boolean => { + const status = error.response?.status + if (typeof status === 'number') { + return status >= 500 + } + + return !error.response +} + +export const shouldShowDedupedError = ( + state: ErrorPromptState, + messageText: string, + now: number, + debounceTime: number +): boolean => now - state.lastErrorTime > debounceTime || messageText !== state.lastErrorMessage + +export const updateErrorPromptState = ( + messageText: string, + now: number +): ErrorPromptState => ({ + lastErrorTime: now, + lastErrorMessage: messageText +}) + +export const updateSystemFailureWindow = ( + failureTimes: number[], + now: number, + windowMs: number, + threshold: number +): SystemFailureWindowState => { + const nextFailureTimes = failureTimes + .filter(failureTime => now - failureTime <= windowMs) + .concat(now) + + return { + failureTimes: nextFailureTimes, + triggered: nextFailureTimes.length >= threshold + } +} diff --git a/FM-Frontend/src/api/file.ts b/FM-Frontend/src/api/file.ts new file mode 100644 index 00000000..dd1de53c --- /dev/null +++ b/FM-Frontend/src/api/file.ts @@ -0,0 +1,159 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import type { AxiosProgressEvent } from 'axios' +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: ChunkUploadInitRequest supports file.ts by holding or executing the chunk upload init request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ChunkUploadInitRequest { + fileName: string + fileSize: number + contentType: string + fileFingerprint: string + scene: string +} + +/** + * Purpose: ChunkUploadSessionVO supports file.ts by holding or executing the chunk upload session vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ChunkUploadSessionVO { + uploadId: string + chunkSize: number + totalChunks: number + uploadedChunks: number[] +} + +/** + * fileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const fileApi = { + /** + * `uploadAvatar` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param file: File caller-supplied value for `file: File` + */ + uploadAvatar: (file: File) => { + const formData = new FormData() + formData.append('file', file) + return api.post('/user/upload-avatar', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + } + }) + }, + uploadProfileImage: (file: File) => { + const formData = new FormData() + formData.append('file', file) + return api.post('/user/upload-profile-image', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + } + }) as unknown as Promise + }, + /** + * `initAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest` + */ + initAvatarChunkUpload: (data: ChunkUploadInitRequest) => { + return api.post('/user/upload-avatar/init', data) as unknown as Promise + }, + uploadAvatarChunk: ( + /** + * Purpose: data supports file.ts by holding or executing the data page or API role. + * Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow. + */ + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return api.post('/user/upload-avatar/chunk', formData, { + /** + * Purpose: headers supports file.ts by holding or executing the headers page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + headers: { + 'Content-Type': 'multipart/form-data' + }, + /** + * Purpose: signal supports file.ts by holding or executing the signal page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + signal: config?.signal, + /** + * Purpose: onUploadProgress supports file.ts by holding or executing the on upload progress page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + onUploadProgress: config?.onUploadProgress + }) + }, + /** + * `completeAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ + completeAvatarChunkUpload: (uploadId: string) => { + return api.post('/user/upload-avatar/complete', { uploadId }) as unknown as Promise + }, + /** + * `cancelAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ + cancelAvatarChunkUpload: (uploadId: string) => { + return api.delete(`/user/upload-avatar/${uploadId}`) + }, + initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => { + return api.post('/user/upload-profile-image/init', data) as unknown as Promise + }, + uploadProfileImageChunk: ( + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return api.post('/user/upload-profile-image/chunk', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + }, + signal: config?.signal, + onUploadProgress: config?.onUploadProgress + }) + }, + completeProfileImageChunkUpload: (uploadId: string) => { + return api.post('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise + }, + cancelProfileImageChunkUpload: (uploadId: string) => { + return api.delete(`/user/upload-profile-image/${uploadId}`) + }, + + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param fileId: IdType caller-supplied value for `fileId: IdType` + * @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number` + */ + getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => { + return api.get(`/file/get-signed-url/${fileId}`, { + /** + * Purpose: params supports file.ts by holding or executing the params page or API role. + * Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow. + */ + params: { expiryTimeInMinutes } + }) + } +} diff --git a/FM-Frontend/src/api/index.ts b/FM-Frontend/src/api/index.ts new file mode 100644 index 00000000..f45d9081 --- /dev/null +++ b/FM-Frontend/src/api/index.ts @@ -0,0 +1,398 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import axios, { AxiosError } from 'axios' +import { authApi } from './auth' +import { adminAuthApi } from './admin' +import { wishlistApi } from './wishlist' +import { message, Modal } from 'ant-design-vue' +import { API_BASE_URL } from '../config/api' +import type { IdType } from '@/utils/id' +import { clearAdminSessionStorage } from '@/utils/admin-session' +import { attachRequestSignature } from '@/utils/request-signature' +import { isApiAuthFreePath } from './auth-free-paths' +import { + getApiResponseMessage, + isPermissionErrorMessage, + isSystemFailureResponse, + isTokenExpiredResponse, + normalizeApiErrorMessage, + shouldShowDedupedError, + updateSystemFailureWindow, + updateErrorPromptState, + type ErrorPromptState +} from './error' + +// 防重复提示标志 +let lastErrorTime = 0 +/** + * Purpose: lastErrorMessage supports index.ts by holding or executing the last error message page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let lastErrorMessage = '' +/** + * Purpose: ERROR_DEBOUNCE_TIME supports index.ts by holding or executing the error debounce time page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误 +const SYSTEM_FAILURE_WINDOW_MS = 30 * 1000 +const SYSTEM_FAILURE_THRESHOLD = 3 +const SYSTEM_FAILURE_MODAL_COOLDOWN_MS = 60 * 1000 +const SYSTEM_FAILURE_MODAL_TITLE = '系统暂不可用' +const SYSTEM_FAILURE_MODAL_CONTENT = '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。' +const SYSTEM_FAILURE_MODAL_OK_TEXT = '我知道了' +let systemFailureTimes: number[] = [] +let systemFailureModalVisible = false +let lastSystemFailureModalTime: number | null = null + +/** + * Purpose: api supports index.ts by holding or executing the api page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const api = axios.create({ + baseURL: API_BASE_URL, + timeout: 60000, + headers: { + 'Content-Type': 'application/json' + } +}) + +/** + * Purpose: isRefreshing supports index.ts by holding or executing the is refreshing page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let isRefreshing = false +let failedQueue: Array<{ + resolve: (value?: any) => void + reject: (reason?: any) => void +}> = [] + +/** + * Purpose: getStoredAccessToken supports index.ts by holding or executing the get stored access token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getStoredAccessToken = (isAdmin = false) => { + return isAdmin + ? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) + : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) +} + +/** + * Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getStoredRefreshToken = (isAdmin = false) => { + return isAdmin + ? (localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken')) + : (localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken')) +} + +/** + * Purpose: getRequestToken supports index.ts by holding or executing the get request token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getRequestToken = (request: any) => { + if (request?._authToken) { + return request._authToken as string + } + + const authHeader = request?.headers?.Authorization || request?.headers?.authorization + if (typeof authHeader !== 'string') { + return null + } + + return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null +} + +/** + * Purpose: isCurrentStoredToken supports index.ts by holding or executing the is current stored token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isCurrentStoredToken = (token: string | null, isAdmin = false) => { + return Boolean(token && token === getStoredAccessToken(isAdmin)) +} + +/** + * Purpose: processQueue supports index.ts by holding or executing the process queue page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const processQueue = (error: unknown, token: string | null = null) => { + failedQueue.forEach(prom => { + if (error) { + prom.reject(error) + } else { + prom.resolve(token) + } + }) + failedQueue = [] +} + +// 防抖处理错误提示 +const showError = (msg: string) => { + const now = Date.now() + const state: ErrorPromptState = { lastErrorTime, lastErrorMessage } + if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) { + return + } + + const nextState = updateErrorPromptState(msg, now) + lastErrorTime = nextState.lastErrorTime + lastErrorMessage = nextState.lastErrorMessage + message.error(msg) +} + +const resetSystemFailureWindow = () => { + systemFailureTimes = [] +} + +const showSystemFailureModal = (now: number) => { + if ( + systemFailureModalVisible + || ( + lastSystemFailureModalTime !== null + && now - lastSystemFailureModalTime < SYSTEM_FAILURE_MODAL_COOLDOWN_MS + ) + ) { + return + } + + systemFailureModalVisible = true + lastSystemFailureModalTime = now + Modal.error({ + title: SYSTEM_FAILURE_MODAL_TITLE, + content: SYSTEM_FAILURE_MODAL_CONTENT, + okText: SYSTEM_FAILURE_MODAL_OK_TEXT, + onOk: () => { + systemFailureModalVisible = false + }, + afterClose: () => { + systemFailureModalVisible = false + } + }) +} + +const recordSystemFailure = (error: AxiosError): boolean => { + if (!isSystemFailureResponse(error)) { + return false + } + + const now = Date.now() + const nextState = updateSystemFailureWindow( + systemFailureTimes, + now, + SYSTEM_FAILURE_WINDOW_MS, + SYSTEM_FAILURE_THRESHOLD + ) + systemFailureTimes = nextState.failureTimes + if (nextState.triggered) { + showSystemFailureModal(now) + return true + } + return false +} + +/** + * Purpose: isAuthFreePath supports index.ts by holding or executing the is auth free path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isAuthFreePath = (url?: string) => { + return isApiAuthFreePath(url) +} + +/** + * Purpose: handleTokenExpired supports index.ts by holding or executing the handle token expired page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) => { + if (!isCurrentStoredToken(failedToken, isAdmin)) { + return + } + + // 清理token和用户信息 + if (isAdmin) { + // 清理后台管理的token + clearAdminSessionStorage() + } else { + // 清理前台的token + localStorage.removeItem('accessToken') + localStorage.removeItem('refreshToken') + localStorage.removeItem('userInfo') + sessionStorage.removeItem('accessToken') + sessionStorage.removeItem('refreshToken') + } + + // 显示错误提示 + if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') { + showError('登录已过期,请重新登录') + } + + // 执行跳转,确保无论如何都会跳转 + setTimeout(() => { + if (isAdmin) { + window.location.href = '/admin/login' + } else { + window.location.href = '/' + } + }, 500) // 延迟执行,确保错误提示先显示 +} + +api.interceptors.request.use( + async config => { + const isAdminRequest = config.url?.includes('/admin/') || config.url?.includes('/order/admin/') + let token = isAdminRequest + ? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) + : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) + + // 检查是否是后台管理的API请求 + if (!token && (config.url?.includes('/admin/') || config.url?.includes('/order/admin/'))) { + token = localStorage.getItem('adminAccessToken') + if (!token) { + token = sessionStorage.getItem('adminAccessToken') + } + } + + if (token) { + config.headers.Authorization = `Bearer ${token}` + } + ;(config as any)._authToken = token || null + return attachRequestSignature(config, token, { + authFree: isAuthFreePath(config.url) + }) + }, + error => { + return Promise.reject(error) + } +) + +api.interceptors.response.use( + response => { + resetSystemFailureWindow() + const res = response.data + if (res.code !== 200) { + const errorMsg = normalizeApiErrorMessage(res.message || '请求失败') + if (!isPermissionErrorMessage(errorMsg)) { + showError(errorMsg) + } + return Promise.reject(new Error(errorMsg)) + } + return res.data as any + }, + async (error: AxiosError) => { + const originalRequest = error.config as any + + const isWhitelistedPath = (url: string) => { + return isApiAuthFreePath(url) + } + + if (error.response?.status === 401) { + // 检查是否是后台管理的API请求 + const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/') + const requestToken = getRequestToken(originalRequest) + const isRealTokenExpired = isTokenExpiredResponse(error, requestToken) + + if (!isRealTokenExpired) { + showError(getApiResponseMessage(error, '请求失败')) + return Promise.reject(error) + } + + if (!isCurrentStoredToken(requestToken, isAdminRequest)) { + return Promise.reject(error) + } + + if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) { + if (isRefreshing) { + return new Promise((resolve, reject) => { + failedQueue.push({ resolve, reject }) + }).then(token => { + if (token) { + originalRequest.headers.Authorization = `Bearer ${token}` + originalRequest._authToken = token + } + return api(originalRequest) + }).catch(err => { + return Promise.reject(err) + }) + } + + originalRequest._retry = true + isRefreshing = true + + try { + let refreshToken + if (isAdminRequest) { + refreshToken = getStoredRefreshToken(true) + } else { + refreshToken = getStoredRefreshToken(false) + } + + if (!refreshToken) { + throw new Error('No refresh token available') + } + + // 这里需要根据是否是后台请求调用不同的refreshToken API + // 暂时使用同一个API,实际项目中可能需要分开 + const response = isAdminRequest + ? await adminAuthApi.refreshToken(refreshToken) + : await authApi.refreshToken({ refreshToken }) + const newToken = (response as any).accessToken + const newRefreshToken = (response as any).refreshToken + + if (isAdminRequest) { + localStorage.setItem('adminAccessToken', newToken) + localStorage.setItem('adminRefreshToken', newRefreshToken) + sessionStorage.setItem('adminAccessToken', newToken) + } else { + localStorage.setItem('accessToken', newToken) + localStorage.setItem('refreshToken', newRefreshToken) + sessionStorage.setItem('accessToken', newToken) + sessionStorage.setItem('refreshToken', newRefreshToken) + } + + processQueue(null, newToken) + + originalRequest.headers.Authorization = `Bearer ${newToken}` + originalRequest._authToken = newToken + return api(originalRequest) + } catch (refreshError) { + processQueue(refreshError, null) + handleTokenExpired(isAdminRequest, requestToken) + return Promise.reject(refreshError) + } finally { + isRefreshing = false + } + } else { + handleTokenExpired(isAdminRequest, requestToken) + return Promise.reject(error) + } + } else if (error.response?.status !== 403) { // 403权限不足不提示 + const errorMsg = getApiResponseMessage(error, '请求失败') + if (!recordSystemFailure(error)) { + showError(errorMsg) + } + } + return Promise.reject(error) + } +) + +/** + * fileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const fileApi = { + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param fileId: IdType caller-supplied value for `fileId: IdType` + * @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number` + */ + getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => { + return api.get(`/file/get-signed-url/${fileId}`, { + params: { expiryTimeInMinutes } + }) + } +} + +export { wishlistApi } + +export default api diff --git a/FM-Frontend/src/api/nail-artist.ts b/FM-Frontend/src/api/nail-artist.ts new file mode 100644 index 00000000..b45a06ef --- /dev/null +++ b/FM-Frontend/src/api/nail-artist.ts @@ -0,0 +1,92 @@ +import api from './index' +import type { IdType } from '@/utils/id' + +export interface NailArtistAvailabilityVO { + startTime: string + endTime: string + dateText: string + timeText: string + available: boolean +} + +export interface NailArtistWorkVO { + id: IdType + title?: string + description?: string + price?: number | string + coverImageUrl?: string + imageUrls?: string[] + tags?: string[] + likeCount?: number + collectCount?: number +} + +export interface NailArtistReviewVO { + id: IdType + artistId: IdType + customerId?: IdType + customerName?: string + customerAvatar?: string + productId?: IdType + productTitle?: string + rating?: number | string + content?: string + imageFileIds?: IdType[] + imageUrls?: string[] + submittedAt?: string +} + +export interface NailArtistListItemVO { + id?: IdType + userId?: IdType + identity?: string + experience?: number + skills?: string + rating?: number | string + status?: number + participateProduction?: number + workStartTime?: string + workEndTime?: string + userType?: number + userTypeName?: string + portfolio?: string + nickname?: string + shopId?: IdType + shopName?: string + signature?: string +} + +export interface NailArtistProfileVO { + artistId: IdType + artistName?: string + avatar?: string + identity?: string + signature?: string + experience?: number + status?: number + shopId?: IdType + shopName?: string + rating?: number | string + serviceCount?: number | string + workStartTime?: string + workEndTime?: string + styleTags?: string[] + works?: NailArtistWorkVO[] + reviews?: NailArtistReviewVO[] + availability?: NailArtistAvailabilityVO[] +} + +export const nailArtistApi = { + getPublicProfile: async (artistId: IdType): Promise => { + return await api.get(`/nail-artist/profile/${artistId}`) as unknown as NailArtistProfileVO + }, + getAvailability: async (artistId: IdType): Promise => { + return await api.get(`/nail-artist/${artistId}/availability`) as unknown as NailArtistAvailabilityVO[] + }, + listReviews: async (artistId: IdType): Promise => { + return await api.get(`/nail-artist/${artistId}/reviews`) as unknown as NailArtistReviewVO[] + }, + listByShopId: async (shopId: IdType): Promise => { + return await api.get(`/nail-artist/list/shop/${shopId}`) as unknown as NailArtistListItemVO[] + } +} diff --git a/FM-Frontend/src/api/order.ts b/FM-Frontend/src/api/order.ts new file mode 100644 index 00000000..4a12e9a8 --- /dev/null +++ b/FM-Frontend/src/api/order.ts @@ -0,0 +1,476 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: OrderItem supports order.ts by holding or executing the order item page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderItem { + productId: IdType + quantity: number + artistId?: IdType + appointmentTime?: string +} + +/** + * Purpose: CreateOrderRequest supports order.ts by holding or executing the create order request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateOrderRequest { + couponId?: IdType + couponSourceType?: string + remark?: string + clientRequestId?: string + items: OrderItem[] +} + +export type CheckoutPreviewRequest = CreateOrderRequest + +export interface CheckoutCouponPreview { + id: IdType + couponId?: IdType + userCouponId?: IdType + sourceType?: string + couponName: string + couponType: number + couponTypeName?: string + discountValue?: number + minAmount?: number + reduceAmount?: number + discountAmount?: number + available?: boolean + best?: boolean + vipAuto?: boolean + displayText?: string + savingText?: string + unavailableReason?: string + startTime?: string + endTime?: string +} + +export interface CheckoutIssue { + code: string + message: string + itemId?: IdType + productId?: IdType + productTitle?: string +} + +export interface CheckoutPreview { + subtotalAmount: number + savedAmount: number + payableAmount: number + bestCoupon?: CheckoutCouponPreview + availableCoupons: CheckoutCouponPreview[] + unavailableCoupons: CheckoutCouponPreview[] + bookingAvailable?: boolean + bookingIssues?: CheckoutIssue[] + vipTip?: string + summaryText?: string +} + +export interface PaymentOrderVO { + id: IdType + payNo?: string + orderId: IdType + orderNo?: string + userId?: IdType + shopId?: IdType + channel?: string + status?: string + payAmount?: number + paidAmount?: number + payTime?: string + expireTime?: string + remark?: string +} + +export interface OrderQuoteItem { + orderItemId: IdType + quotedPrice?: number +} + +export interface OrderQuoteSubmitRequest { + remark?: string + items: OrderQuoteItem[] +} + +export interface OrderQuoteReplyRequest { + remark?: string +} + +export interface OrderQuoteMessage { + id: IdType + orderId: IdType + actorId?: IdType + actorType?: string + actorTypeText?: string + action?: string + actionText?: string + remark?: string + items?: any[] + createTime?: string +} + +export interface AfterSaleApplyRequest { + orderId: IdType + orderItemId?: IdType + type: string + reason: string + refundAmount?: number +} + +export interface AfterSaleVO { + id: IdType + afterSaleNo?: string + orderId: IdType + orderItemId?: IdType + userId?: IdType + shopId?: IdType + type?: string + reason?: string + refundAmount?: number + status?: string + auditReason?: string + auditTime?: string + createTime?: string +} + +export interface PageResult { + list: T[] + total: number + page: number + size: number +} + +export interface GrowthSummaryVO { + userId?: IdType + growthValue?: number + levelName?: string + appointmentCount?: number + reviewCount?: number +} + +export const paymentApi = { + prepareOrderPayment: async (orderId: IdType): Promise => { + return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO + }, + mockSuccess: async (orderId: IdType): Promise => { + return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO + } +} + +export const afterSaleApi = { + apply: async (data: AfterSaleApplyRequest): Promise => { + return await api.post('/after-sale/apply', data) as unknown as AfterSaleVO + }, + listMy: async (params: { page: number; size: number }): Promise> => { + return await api.get>('/after-sale/my', { params }) as unknown as PageResult + } +} + +export const growthApi = { + getSummary: async (): Promise => { + return await api.get('/growth/summary') as unknown as GrowthSummaryVO + } +} + +/** + * Purpose: ArtistCalendarAppointment supports order.ts by holding or executing the artist calendar appointment page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ArtistCalendarAppointment { + orderId: IdType + orderNo: string + totalAmount?: number + actualAmount?: number + orderStatus: number + orderStatusText: string + orderItemId: IdType + productId: IdType + productTitle: string + artistId: IdType + artistName?: string + customerNickname?: string + customerPhoneMasked?: string + shopId?: IdType + shopName?: string + appointmentStartTime: string + appointmentEndTime: string + quantity: number + durationMinutes: number +} + +/** + * Purpose: OrderArtistReviewVO supports order.ts by holding or executing the order artist review vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistReviewVO { + id: IdType + orderId: IdType + orderItemId: IdType + productId?: IdType + productTitle?: string + artistId?: IdType + artistName?: string + artistAvatar?: string + userId?: IdType + rating?: number + content?: string + imageFileIds?: IdType[] + status?: number + statusText?: string + submitTime?: string + reviewTime?: string + createTime?: string +} + +/** + * Purpose: OrderArtistReviewSubmitRequest supports order.ts by holding or executing the order artist review submit request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistReviewSubmitRequest { + rating: number + content?: string + imageFileIds: IdType[] +} + +/** + * Purpose: OrderArtistChangeOptionsVO supports order.ts by holding or executing the order artist change options vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistChangeOptionsVO { + orderId: IdType + orderItemId: IdType + currentArtistId?: IdType + currentArtistName?: string + artists: Array<{ + artistId: IdType + artistName: string + artistAvatar?: string + userType?: number + participateProduction?: boolean + }> +} + +/** + * Purpose: OrderArtistChangeRequestVO supports order.ts by holding or executing the order artist change request vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistChangeRequestVO { + id: IdType + orderId: IdType + orderItemId: IdType + productId?: IdType + productTitle?: string + shopId?: IdType + userId?: IdType + customerId?: IdType + originalArtistId?: IdType + originalArtistName?: string + requestedArtistId?: IdType + requestedArtistName?: string + fromArtistId?: IdType + fromArtistName?: string + toArtistId?: IdType + toArtistName?: string + requesterId?: IdType + requesterName?: string + status?: string + statusText?: string + reason?: string + rejectReason?: string + appointmentTime?: string + timeAffected?: boolean + timeImpactText?: string + originalPrice?: number | string + newPrice?: number | string + priceAffected?: boolean + priceImpactText?: string + reviewerId?: IdType + messageId?: IdType + reviewTime?: string + approvedTime?: string + rejectedTime?: string + expireTime?: string + createTime?: string +} + +/** + * Purpose: OrderArtistChangeRequestSubmitRequest supports order.ts by holding or executing the order artist change request submit request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistChangeRequestSubmitRequest { + orderId: IdType + orderItemId: IdType + requestedArtistId: IdType + reason: string +} + +/** + * Purpose: OrderArtistChangeRejectRequest supports order.ts by holding or executing the order artist change reject request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface OrderArtistChangeRejectRequest { + rejectReason?: string +} + +/** + * orderApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const orderApi = { + // 创建订单 + /** + * `createOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateOrderRequest caller-supplied value for `data: CreateOrderRequest` + */ + createOrder: (data: CreateOrderRequest) => { + return api.post('/order/create', data) + }, + + createInquiryAppointment: (data: CreateOrderRequest) => { + return api.post('/order/create', data) + }, + + checkoutPreview: async (data: CheckoutPreviewRequest): Promise => { + return await api.post('/order/checkout-preview', data) as unknown as CheckoutPreview + }, + + replyQuote: async (orderId: IdType, data?: OrderQuoteReplyRequest): Promise => { + return await api.post(`/order/${orderId}/quote/reply`, data || {}) as unknown as any + }, + + confirmUserQuote: async (orderId: IdType): Promise => { + return await api.put(`/order/${orderId}/quote/confirm`) as unknown as any + }, + + submitShopQuote: async (orderId: IdType, data: OrderQuoteSubmitRequest): Promise => { + return await api.post(`/order/${orderId}/quote/shop`, data) as unknown as any + }, + + confirmShopQuote: async (orderId: IdType): Promise => { + return await api.put(`/order/${orderId}/quote/shop/confirm`) as unknown as any + }, + + // 获取订单列表 + getOrderList: async (): Promise => { + return await api.get('/order/list') as unknown as any[] + }, + + getMyPendingReviews: async (): Promise => { + return await api.get('/order/review/my-pending') as unknown as OrderArtistReviewVO[] + }, + + getOrderReviews: async (orderId: IdType): Promise => { + return await api.get(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[] + }, + + submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise => { + return await api.post(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO + }, + + getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise => { + return await api.get(`/order/${orderId}/artist-change/options`, { + params: { orderItemId } + }) as unknown as OrderArtistChangeOptionsVO + }, + + requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise => { + return await api.post('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO + }, + + getMyPendingArtistChangeRequests: async (): Promise => { + return await api.get('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[] + }, + + getOrderArtistChangeRequests: async (orderId: IdType): Promise => { + return await api.get(`/order/${orderId}/artist-change/requests`) as unknown as OrderArtistChangeRequestVO[] + }, + + approveArtistChange: async (requestId: IdType): Promise => { + return await api.put(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO + }, + + rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise => { + return await api.put(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO + }, + + // 获取订单详情 + /** + * `getOrderDetail` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ + getOrderDetail: (orderId: IdType) => { + return api.get(`/order/detail/${orderId}`) + }, + + // 取消订单 + /** + * `cancelOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ + cancelOrder: (orderId: IdType) => { + return api.put(`/order/cancel/${orderId}`) + }, + + // 后台获取所有订单 + /** + * `getAllOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getAllOrders: () => { + return api.get('/order/admin/list') + }, + + // 后台处理订单 + /** + * `processOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + * @param status: number caller-supplied value for `status: number` + */ + processOrder: (orderId: IdType, status: number) => { + return api.put(`/order/admin/process/${orderId}`, {}, { + params: { status } + }) + }, + + // 美甲师查看自己的订单 + /** + * `getArtistOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getArtistOrders: () => { + return api.get('/order/artist/list') + }, + + // 预约日历:recent 取未来 7 天概览,day 传 yyyy-MM-dd 查某天明细。 + /** + * `completeArtistOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ + completeArtistOrder: (orderId: IdType) => { + return api.put(`/order/artist/complete/${orderId}`) + }, + + getArtistCalendarRecent: async (days = 7): Promise => { + return await api.get('/order/artist/calendar/recent', { + params: { days } + }) as unknown as ArtistCalendarAppointment[] + }, + + getArtistCalendarDay: async (date: string): Promise => { + return await api.get('/order/artist/calendar/day', { + params: { date } + }) as unknown as ArtistCalendarAppointment[] + } +} diff --git a/FM-Frontend/src/api/permission.ts b/FM-Frontend/src/api/permission.ts new file mode 100644 index 00000000..c927b779 --- /dev/null +++ b/FM-Frontend/src/api/permission.ts @@ -0,0 +1,115 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import { adminApi } from './admin' +import type { IdType } from '@/utils/id' + +/** + * Purpose: PermissionVO supports permission.ts by holding or executing the permission vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface PermissionVO { + id: IdType + permissionCode: string + permissionName: string + permissionGroup: string + description: string + createTime: string + updateTime: string +} + +/** + * Purpose: CreatePermissionRequest supports permission.ts by holding or executing the create permission request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreatePermissionRequest { + permissionCode: string + permissionName: string + permissionGroup: string + description: string +} + +/** + * Purpose: UpdatePermissionRequest supports permission.ts by holding or executing the update permission request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdatePermissionRequest { + permissionCode?: string + permissionName?: string + permissionGroup?: string + description?: string +} + +/** + * permissionApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const permissionApi = { + /** + * `getUserPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId?: IdType caller-supplied value for `userId?: IdType` + */ + getUserPermissions: (userId?: IdType) => { + if (userId) { + return adminApi.get(`/permission/user/${userId}`) + } + return adminApi.get('/permission/user/current') + }, + + /** + * `getAssignablePermissionIds` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + */ + getAssignablePermissionIds: (userId: IdType) => { + return adminApi.get(`/permission/assignable/${userId}`) + }, + + /** + * `listAllPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAllPermissions: () => { + return adminApi.get('/permission/list/all') + }, + + /** + * `createPermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreatePermissionRequest caller-supplied value for `data: CreatePermissionRequest` + */ + createPermission: (data: CreatePermissionRequest) => { + return adminApi.post('/permission/create', data) + }, + + /** + * `updatePermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: UpdatePermissionRequest caller-supplied value for `data: UpdatePermissionRequest` + */ + updatePermission: (id: IdType, data: UpdatePermissionRequest) => { + return adminApi.put(`/permission/update/${id}`, data) + }, + + /** + * `deletePermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deletePermission: (id: IdType) => { + return adminApi.delete(`/permission/delete/${id}`) + }, + + /** + * `assignUserPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + * @param permissionIds: IdType[] caller-supplied value for `permissionIds: IdType[]` + */ + assignUserPermissions: (userId: IdType, permissionIds: IdType[]) => { + return adminApi.post(`/permission/assign/${userId}`, { permissionIds }) + } +} diff --git a/FM-Frontend/src/api/product.ts b/FM-Frontend/src/api/product.ts new file mode 100644 index 00000000..292db2ac --- /dev/null +++ b/FM-Frontend/src/api/product.ts @@ -0,0 +1,133 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: ProductVO supports product.ts by holding or executing the product vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ProductVO { + id: IdType + shopId: IdType | null + shopName?: string + name: string + title?: string + description: string + targetAudience?: string + precautions?: string + image: string + imageFileIds?: string + imageUrls?: string[] + price: number + estimatedTime: number + approximateDuration?: string + serviceDurationMinutes?: number + bookableArtists?: string + availableBookableArtistCount?: number + bookableArtistRestricted?: boolean + availableCoupons?: string + category: string + tags?: string + tagList?: string[] + tagInfos?: TagInfo[] + status: number + likeCount?: number + collectCount?: number + createTime: string + updateTime: string +} + +/** + * Purpose: TagInfo supports product.ts by holding or executing the tag info page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface TagInfo { + id: IdType + tagName: string + textColor?: string + bgColor?: string + borderColor?: string +} + +/** + * Purpose: ListProductsParams supports product.ts by holding or executing the list products params page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ListProductsParams { + page: number + size: number + keyword?: string + tag?: string + tagIds?: string +} + +/** + * Purpose: CreateProductRequest supports product.ts by holding or executing the create product request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateProductRequest { + name: string + description: string + image: string + price: number + estimatedTime: number + category: string + status: number + shopId: IdType | null +} + +/** + * Purpose: UpdateProductRequest supports product.ts by holding or executing the update product request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdateProductRequest { + name?: string + description?: string + image?: string + price?: number + estimatedTime?: number + category?: string + status?: number + shopId?: IdType | null +} + +/** + * productApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const productApi = { + getAllProducts: async (): Promise => { + return await api.get('/product/list/all') as unknown as ProductVO[] + }, + + getProductById: async (id: IdType): Promise => { + return await api.get(`/product/get/${id}`) as unknown as ProductVO + }, + + getProductsByTag: async (tag: string): Promise => { + return await api.get(`/product/list/tag/${tag}`) as unknown as ProductVO[] + }, + + likeProduct: async (productId: IdType): Promise => { + return await api.post(`/product-like/like/${productId}`) as unknown as boolean + }, + + unlikeProduct: async (productId: IdType): Promise => { + return await api.post(`/product-like/unlike/${productId}`) as unknown as boolean + }, + + searchProducts: async (keyword: string): Promise => { + return await api.get('/product/list/search', { + params: { + keyword: keyword + } + }) as unknown as ProductVO[] + }, + + getProductPage: async (params: ListProductsParams): Promise<{ list: ProductVO[]; total: number; page: number; size: number }> => { + return await api.get('/product/list/page', { params }) as unknown as { list: ProductVO[]; total: number; page: number; size: number } + } +} diff --git a/FM-Frontend/src/api/productLike.ts b/FM-Frontend/src/api/productLike.ts new file mode 100644 index 00000000..5ce0831d --- /dev/null +++ b/FM-Frontend/src/api/productLike.ts @@ -0,0 +1,51 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * productLikeApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const productLikeApi = { + /** + * 点赞作品 + * @param productId 作品ID + */ + /** + * `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ + likeProduct: (productId: IdType) => { + return api.post(`/product-like/like/${productId}`) + }, + + /** + * 取消点赞作品 + * @param productId 作品ID + */ + /** + * `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ + unlikeProduct: (productId: IdType) => { + return api.post(`/product-like/unlike/${productId}`) + }, + + /** + * 检查用户是否已点赞作品 + * @param productId 作品ID + */ + /** + * `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ + checkLikeStatus: (productId: IdType) => { + return api.get(`/product-like/check/${productId}`) + } +} diff --git a/FM-Frontend/src/api/shop.ts b/FM-Frontend/src/api/shop.ts new file mode 100644 index 00000000..6d99ad2c --- /dev/null +++ b/FM-Frontend/src/api/shop.ts @@ -0,0 +1,184 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: ShopVO supports shop.ts by holding or executing the shop vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ShopVO { + id: IdType + shopName: string + description: string + address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string + navigationUrls?: Record + businessHours: string + status?: number + authorizationStartDate?: string + authorizationDays?: number + authorizationExpireTime?: string + authorizationExpired?: boolean + authorizationStatusText?: string + coverImageFileId?: string + coverImageUrls?: string[] + imageFileIds: string + imageUrls?: string[] + themePrimaryColor?: string + themeSecondaryColor?: string + themeAccentColor?: string + themePageBgColor?: string + themeCardBgColor?: string + themeBackgroundImageFileId?: string + createTime: string + updateTime: string +} + +/** + * Purpose: ShopSimpleVO supports shop.ts by holding or executing the shop simple vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ShopSimpleVO { + id: string | number + shopName?: string + name?: string +} + +/** + * Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page. + * Usage: fetch it with getTrustProfile and render ratings, recent reviews, environment images, and booking hints. + */ +export interface ShopTrustProfileVO { + shopId: IdType + shopName?: string + businessHoursText?: string + businessStatusText?: string + locationAvailable?: boolean + distanceCapabilityText?: string + navigationAvailable?: boolean + stats?: { + averageRating?: number + reviewCount?: number + productCount?: number + artistCount?: number + recentReviewCount?: number + } + environmentImages?: string[] + featuredProducts?: Array<{ + id: IdType + title?: string + imageUrl?: string + imageFileIds?: string + price?: number + likeCount?: number + collectCount?: number + availableBookableArtistCount?: number + bookingHint?: string + }> + recentReviews?: Array<{ + id: IdType + productId?: IdType + productTitle?: string + ratingScore?: number + content?: string + imageUrls?: string[] + submittedAt?: string + }> + availabilitySummary?: { + available?: boolean + summaryText?: string + nextSlots?: string[] + } + contactSummary?: { + actionText?: string + phoneExposed?: boolean + phone?: string + } +} + +/** + * Purpose: ListShopsParams supports shop.ts by holding or executing the list shops params page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ListShopsParams { + page: number + size: number + keyword?: string +} + +/** + * Purpose: CreateShopRequest supports shop.ts by holding or executing the create shop request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateShopRequest { + name: string + description: string + image: string + phone: string + address: string + businessHours: string + status: number + authorizationStartDate?: string + authorizationDays?: number + authorizationExpireTime?: string + themePrimaryColor?: string + themeSecondaryColor?: string + themeAccentColor?: string + themePageBgColor?: string + themeCardBgColor?: string + themeBackgroundImageFileId?: string +} + +/** + * Purpose: UpdateShopRequest supports shop.ts by holding or executing the update shop request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdateShopRequest { + name?: string + description?: string + image?: string + phone?: string + address?: string + businessHours?: string + status?: number + authorizationStartDate?: string + authorizationDays?: number + authorizationExpireTime?: string + themePrimaryColor?: string + themeSecondaryColor?: string + themeAccentColor?: string + themePageBgColor?: string + themeCardBgColor?: string + themeBackgroundImageFileId?: string +} + +/** + * shopApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const shopApi = { + getAllShops: async (): Promise => { + return await api.get('/shop/list/all') as unknown as ShopVO[] + }, + + getPublicShops: async (): Promise => { + return await api.get('/shop/list/public') as unknown as ShopVO[] + }, + + getShopsSimple: async (): Promise => { + return await api.get('/shop/list/simple') as unknown as ShopSimpleVO[] + }, + + getShopById: async (id: IdType): Promise => { + return await api.get(`/shop/get/${id}`) as unknown as ShopVO + }, + + getTrustProfile: async (id: IdType): Promise => { + return await api.get(`/shop/trust-profile/${id}`) as unknown as ShopTrustProfileVO + } +} diff --git a/FM-Frontend/src/api/tag.ts b/FM-Frontend/src/api/tag.ts new file mode 100644 index 00000000..1fc0f1e5 --- /dev/null +++ b/FM-Frontend/src/api/tag.ts @@ -0,0 +1,109 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: TagVO supports tag.ts by holding or executing the tag vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface TagVO { + id: IdType + tagName: string + textColor: string + bgColor: string + borderColor: string + sceneGroup?: string + displayName?: string + sortOrder?: number + frontVisible?: number + createTime: string + updateTime: string +} + +/** + * Purpose: TagFilterGroupVO groups public tags for scene filters. + * Usage: render each group as one filter row and pass selected tag ids to product list APIs. + */ +export interface TagFilterGroupVO { + groupName: string + tags: TagVO[] +} + +/** + * Purpose: TagDTO supports tag.ts by holding or executing the tag dto page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface TagDTO { + tagName: string + textColor: string + bgColor: string + borderColor: string + sceneGroup?: string + displayName?: string + sortOrder?: number + frontVisible?: number +} + +/** + * tagApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const tagApi = { + /** + * `getAllTags` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getAllTags: () => { + return api.get('/tag/list/all') + }, + + /** + * `getFilterOptions` API call. Use this method to load customer-facing scene filters. + * Call guide: optionally pass shopId, await the grouped tags, then query products with tagIds. + */ + getFilterOptions: (shopId?: IdType | null) => { + return api.get('/tag/list/filter-options', { + params: shopId ? { shopId } : undefined + }) + }, + + /** + * `getTagById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + getTagById: (id: IdType) => { + return api.get(`/tag/get/${id}`) + }, + + /** + * `createTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: TagDTO caller-supplied value for `data: TagDTO` + */ + createTag: (data: TagDTO) => { + return api.post('/tag/add', data) + }, + + /** + * `updateTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: TagDTO caller-supplied value for `data: TagDTO` + */ + updateTag: (id: IdType, data: TagDTO) => { + return api.put(`/tag/update/${id}`, data) + }, + + /** + * `deleteTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + deleteTag: (id: IdType) => { + return api.delete(`/tag/delete/${id}`) + } +} diff --git a/FM-Frontend/src/api/user.ts b/FM-Frontend/src/api/user.ts new file mode 100644 index 00000000..4c6fc5df --- /dev/null +++ b/FM-Frontend/src/api/user.ts @@ -0,0 +1,469 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { UserInfo } from './auth' +import type { IdType } from '@/utils/id' + +/** + * Purpose: UserVO supports user.ts by holding or executing the user vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserVO extends UserInfo { + id: IdType + shopId?: IdType + shopName?: string + shopIds?: IdType[] + shopNames?: string[] + nickname: string + account: string + avatar: string + signature?: string + level?: string + type: number + vipId?: IdType + createTime: string + updateTime: string + status: number + phone?: string + contactPhone?: string + birthday?: string + wechatId?: string + wechatQrCode?: string + email?: string + maskedPhone?: string + maskedEmail?: string + shopRoleId?: IdType + shopRoleName?: string + parentUserId?: IdType + parentUserName?: string + parentUserTypeName?: string + relationSourceType?: string +} + +/** + * Purpose: UpdateUserInfoRequest supports user.ts by holding or executing the update user info request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdateUserInfoRequest { + nickname?: string + avatar?: string + signature?: string + contactPhone?: string + birthday?: string + wechatId?: string + wechatQrCode?: string +} + +/** + * Purpose: ListUsersParams supports user.ts by holding or executing the list users params page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ListUsersParams { + page: number + size: number + keyword?: string + shopId?: IdType + status?: number +} + +/** + * Purpose: CreateUserRequest supports user.ts by holding or executing the create user request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface CreateUserRequest { + account: string + nickname: string + phone: string + contactPhone?: string + birthday?: string + wechatId?: string + wechatQrCode?: string + password: string + type: number + shopId?: IdType + shopIds?: IdType[] +} + +/** + * Purpose: UpdateUserRequest supports user.ts by holding or executing the update user request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdateUserRequest { + account?: string + nickname?: string + phone?: string + contactPhone?: string + birthday?: string + wechatId?: string + wechatQrCode?: string + type?: number + shopId?: IdType + shopIds?: IdType[] +} + +/** + * Purpose: UpdatePasswordRequest supports user.ts by holding or executing the update password request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdatePasswordRequest { + password: string + verificationCode: string +} + +/** + * Purpose: BindPhoneRequest supports user.ts by holding or executing the bind phone request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface BindPhoneRequest { + phone: string + verificationCode: string +} + +/** + * Purpose: AvailabilityCheckResponse supports user.ts by holding or executing the availability check response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AvailabilityCheckResponse { + available: boolean + message: string +} + +/** + * Purpose: LoginAccountCheckResponse supports user.ts by holding or executing the login account check response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LoginAccountCheckResponse { + exists: boolean + nickname?: string + message: string +} + +/** + * Purpose: LoginShopSelectionResponse supports user.ts by holding or executing the login shop selection response page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface LoginShopSelectionResponse { + allowShoplessLogin: boolean + message: string + shops: Array<{ + id: IdType + shopName: string + }> +} + +/** + * Purpose: UserRelationVO supports user.ts by holding or executing the user relation vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserRelationVO { + userId: IdType + shopId?: IdType + shopName?: string + parentUserId?: IdType + parentUserName?: string + parentRoleType?: number + parentRoleTypeName?: string + sourceType?: string + sourceTypeName?: string +} + +/** + * Purpose: NailArtistInfoVO supports user.ts by holding or executing the nail artist info vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface NailArtistInfoVO { + userId?: IdType + userType?: number + participateProduction?: number | boolean + status?: number +} + +// 用户端常用接口约定: +// - relation 表示当前用户的门店和直属上级归属; +// - announcement 只用于首页滚动公告,不进入消息通知历史; +// - system-message 才是站内消息,popup/read 分开记录。 +export interface InviteCodeVO { + id: IdType + inviteCode: string + ownerUserId?: IdType + ownerUserName?: string + shopId?: IdType + shopName?: string + status?: number + useCount?: number + expireTime?: string + createTime?: string +} + +/** + * Purpose: UpdatePhoneRequest supports user.ts by holding or executing the update phone request page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UpdatePhoneRequest { + oldPhone: string + newPhone: string + verificationCode: string +} + +/** + * Purpose: UserAssetVO supports user.ts by holding or executing the user asset vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface UserAssetVO { + userId: IdType + nickname: string + balance: number + totalRechargeAmount: number + lastRechargeTime?: string + vipInfoId?: IdType + vipLevel: string + benefitId?: IdType + benefitInfo?: string + manualOverride?: boolean + vipStartTime?: string + vipExpireTime?: string +} + +/** + * Purpose: BalanceHistoryItem supports user.ts by holding or executing the balance history item page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface BalanceHistoryItem { + id: IdType + userId: IdType + userNickname?: string + amount: number + type?: string + currentBalance?: number + beforeBalance?: number + afterBalance?: number + changeScene?: string + relatedOrderId?: IdType + relatedOrderNo?: string + externalOrderNo?: string + remark?: string + changeTime?: string +} + +/** + * Purpose: SystemMessageVO supports user.ts by holding or executing the system message vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface SystemMessageVO { + id: IdType + title: string + content: string + imageFileId?: IdType + imageUrl?: string + publisherName?: string + targetType?: string + targetTypeName?: string + businessType?: string + businessId?: IdType + actionPath?: string + popupEnabled?: number + popupShown?: number + readStatus?: number + publishTime?: string + createTime?: string +} + +/** + * Purpose: AnnouncementVO supports user.ts by holding or executing the announcement vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AnnouncementVO { + id: IdType + title: string + content: string + publisherName?: string + targetType?: string + status?: number + sortOrder?: number + publishTime?: string +} + +/** + * Purpose: VipRechargePlanVO supports user.ts by holding or executing the vip recharge plan vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface VipRechargePlanVO { + id: IdType + shopId: IdType + shopName?: string + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status: number +} + +/** + * Purpose: ContactInfoVO supports user.ts by holding or executing the contact info vo page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ContactInfoVO { + contactUserId?: IdType + contactName?: string + roleLabel?: string + phone?: string + phoneAvailable?: boolean + wechatId?: string + wechatAvailable?: boolean + wechatQrCode?: string + platformContactAvailable?: boolean + platformContactText?: string +} + +/** + * userApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const userApi = { + getUserInfo: async (): Promise => { + return await api.get('/user/info') as unknown as UserVO + }, + /** + * `updateUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdateUserInfoRequest caller-supplied value for `data: UpdateUserInfoRequest` + */ + updateUserInfo: (data: UpdateUserInfoRequest) => { + return api.put('/user/update', data) + }, + /** + * `updatePassword` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdatePasswordRequest caller-supplied value for `data: UpdatePasswordRequest` + */ + updatePassword: (data: UpdatePasswordRequest) => { + return api.put('/user/password', data) + }, + /** + * `bindPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: BindPhoneRequest caller-supplied value for `data: BindPhoneRequest` + */ + bindPhone: (data: BindPhoneRequest) => { + return api.post('/user/bind-phone', data) + }, + /** + * `updatePhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdatePhoneRequest caller-supplied value for `data: UpdatePhoneRequest` + */ + updatePhone: (data: UpdatePhoneRequest) => { + return api.put('/user/phone', data) + }, + getUserByAccount: async (account: string): Promise => { + return await api.get(`/user/get/account/${account}`) as unknown as UserVO + }, + checkAccountAvailability: async (account: string): Promise => { + return await api.get(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse + }, + checkLoginAccountAvailability: async (account: string): Promise => { + return await api.get(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse + }, + getLoginShopsByAccount: async (account: string): Promise => { + return await api.get(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse + }, + getLoginShopsByPhone: async (phone: string): Promise => { + return await api.get(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse + }, + checkPhoneAvailability: async (phone: string): Promise => { + return await api.get(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse + }, + listUsersByType: async (type: number): Promise => { + return await api.get(`/user/list/type/${type}`) as unknown as UserVO[] + }, + /** + * `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }` + */ + sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { + return api.post('/user/send-verification-code', data) + }, + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: string | number caller-supplied value for `shopId?: string | number` + */ + switchShop: (shopId?: string | number) => { + return api.post('/user/switch-shop', { shopId }) + }, + getMyAsset: async (): Promise => { + return await api.get('/user/asset/me') as unknown as UserAssetVO + }, + getMyBalanceHistory: async (): Promise => { + return await api.get('/user/balance/history/me') as unknown as BalanceHistoryItem[] + }, + listMyMessages: async (): Promise => { + return await api.get('/system-message/my/list') as unknown as SystemMessageVO[] + }, + listMyPopupMessages: async (): Promise => { + return await api.get('/system-message/my/popup') as unknown as SystemMessageVO[] + }, + getMyUnreadMessageCount: async (): Promise<{ unreadCount: number }> => { + return await api.get<{ unreadCount: number }>('/system-message/my/unread-count') as unknown as { unreadCount: number } + }, + getMyMessage: async (id: IdType): Promise => { + return await api.get(`/system-message/my/${id}`) as unknown as SystemMessageVO + }, + /** + * `markMessagePopupShown` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + markMessagePopupShown: (id: IdType) => { + return api.put(`/system-message/my/${id}/popup-shown`, {}) + }, + /** + * `markMessageRead` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + markMessageRead: (id: IdType) => { + return api.put(`/system-message/my/${id}/read`, {}) + }, + listMyAnnouncements: async (): Promise => { + return await api.get('/announcement/my/list') as unknown as AnnouncementVO[] + }, + listMyVipRechargePlans: async (): Promise => { + return await api.get('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[] + }, + getMyRelation: async (): Promise => { + return await api.get('/user/relation/me') as unknown as UserRelationVO + }, + getNailArtistInfo: async (userId: IdType): Promise => { + return await api.get(`/nail-artist/get/${userId}`) as unknown as NailArtistInfoVO | null + }, + // 注册页输入邀请码时先解析,给用户展示“将归属到谁/哪个店铺”。 + resolveInviteCode: async (code: string): Promise => { + return await api.get('/user/invite-code/resolve', { params: { code } }) as unknown as InviteCodeVO + }, + getShopManagerContact: async (shopId: IdType): Promise => { + return await api.get(`/contact-info/shop/${shopId}/manager`) as unknown as ContactInfoVO + }, + getProductArtistContact: async (productId: IdType, artistId: IdType): Promise => { + return await api.get(`/contact-info/product/${productId}/artist/${artistId}`) as unknown as ContactInfoVO + }, + getOrderArtistContact: async (orderId: IdType, artistId?: IdType): Promise => { + const params = artistId ? { artistId } : {} + return await api.get(`/contact-info/order/${orderId}/artist`, { params }) as unknown as ContactInfoVO + }, + getPlatformContact: async (): Promise => { + return await api.get('/contact-info/platform') as unknown as ContactInfoVO + }, + /** + * `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + deactivateAccount: () => { + return api.delete('/user/deactivate') + } +} diff --git a/FM-Frontend/src/api/wishlist.ts b/FM-Frontend/src/api/wishlist.ts new file mode 100644 index 00000000..aacabd9f --- /dev/null +++ b/FM-Frontend/src/api/wishlist.ts @@ -0,0 +1,123 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ +import api from './index' +import type { IdType } from '@/utils/id' + +/** + * Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface WishlistItem { + id: IdType + userId: IdType + productId: IdType + groupId?: IdType | null + groupName?: string | null + note?: string | null + sortOrder?: number | null + product: { + id: IdType + shopId: IdType | null + shopName?: string + title: string + description: string + imageFileIds?: string + imageUrls?: string[] + price: number + tags?: string + tagList?: string[] + tagInfos?: any[] + likeCount?: number + collectCount?: number + approximateDuration?: string + bookableArtists?: string + availableCoupons?: string + createTime: string + updateTime: string + } +} + +export interface WishlistGroup { + id: IdType + name: string + sortOrder: number + itemCount: number + items?: WishlistItem[] +} + +export interface WishlistInspiration { + total: number + groups: WishlistGroup[] +} + +export interface WishlistGroupPayload { + name: string + sortOrder?: number +} + +export interface WishlistAddWithGroupPayload { + productId: IdType + groupId?: IdType | null + note?: string + sortOrder?: number +} + +export interface WishlistMovePayload { + wishlistId?: IdType + productId?: IdType + groupId?: IdType | null + note?: string + sortOrder?: number +} + +/** + * wishlistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const wishlistApi = { + addToWishlist: async (productId: IdType): Promise => { + return await api.post('/wishlist/add', { productId }) as unknown as boolean + }, + + removeFromWishlist: async (productId: IdType): Promise => { + return await api.post('/wishlist/remove', { productId }) as unknown as boolean + }, + + checkWishlist: async (productId: IdType): Promise => { + return await api.get(`/wishlist/check?productId=${productId}`) as unknown as boolean + }, + + getWishlist: async (): Promise => { + return await api.get('/wishlist/list') as unknown as WishlistItem[] + }, + + getGroups: async (): Promise => { + return await api.get('/wishlist/groups') as unknown as WishlistGroup[] + }, + + createGroup: async (payload: WishlistGroupPayload): Promise => { + return await api.post('/wishlist/groups', payload) as unknown as IdType + }, + + updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise => { + return await api.put(`/wishlist/groups/${id}`, payload) as unknown as boolean + }, + + deleteGroup: async (id: IdType): Promise => { + return await api.delete(`/wishlist/groups/${id}`) as unknown as boolean + }, + + addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise => { + return await api.post('/wishlist/add-with-group', payload) as unknown as boolean + }, + + moveWishlist: async (payload: WishlistMovePayload): Promise => { + return await api.post('/wishlist/move', payload) as unknown as boolean + }, + + getInspiration: async (): Promise => { + return await api.get('/wishlist/inspiration') as unknown as WishlistInspiration + } +} diff --git a/FM-Frontend/src/assets/vue.svg b/FM-Frontend/src/assets/vue.svg new file mode 100644 index 00000000..770e9d33 --- /dev/null +++ b/FM-Frontend/src/assets/vue.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/FM-Frontend/src/auto-import.d.ts b/FM-Frontend/src/auto-import.d.ts new file mode 100644 index 00000000..101b7d6f --- /dev/null +++ b/FM-Frontend/src/auto-import.d.ts @@ -0,0 +1,90 @@ +/* eslint-disable */ +/* prettier-ignore */ +// @ts-nocheck +// noinspection JSUnusedGlobalSymbols +// Generated by unplugin-auto-import +// biome-ignore lint: disable +export {} +declare global { + const EffectScope: typeof import('vue').EffectScope + const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate + const computed: typeof import('vue').computed + const createApp: typeof import('vue').createApp + const createPinia: typeof import('pinia').createPinia + const customRef: typeof import('vue').customRef + const defineAsyncComponent: typeof import('vue').defineAsyncComponent + const defineComponent: typeof import('vue').defineComponent + const defineStore: typeof import('pinia').defineStore + const effectScope: typeof import('vue').effectScope + const getActivePinia: typeof import('pinia').getActivePinia + const getCurrentInstance: typeof import('vue').getCurrentInstance + const getCurrentScope: typeof import('vue').getCurrentScope + const getCurrentWatcher: typeof import('vue').getCurrentWatcher + const h: typeof import('vue').h + const inject: typeof import('vue').inject + const isProxy: typeof import('vue').isProxy + const isReactive: typeof import('vue').isReactive + const isReadonly: typeof import('vue').isReadonly + const isRef: typeof import('vue').isRef + const isShallow: typeof import('vue').isShallow + const mapActions: typeof import('pinia').mapActions + const mapGetters: typeof import('pinia').mapGetters + const mapState: typeof import('pinia').mapState + const mapStores: typeof import('pinia').mapStores + const mapWritableState: typeof import('pinia').mapWritableState + const markRaw: typeof import('vue').markRaw + const nextTick: typeof import('vue').nextTick + const onActivated: typeof import('vue').onActivated + const onBeforeMount: typeof import('vue').onBeforeMount + const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave + const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate + const onBeforeUnmount: typeof import('vue').onBeforeUnmount + const onBeforeUpdate: typeof import('vue').onBeforeUpdate + const onDeactivated: typeof import('vue').onDeactivated + const onErrorCaptured: typeof import('vue').onErrorCaptured + const onMounted: typeof import('vue').onMounted + const onRenderTracked: typeof import('vue').onRenderTracked + const onRenderTriggered: typeof import('vue').onRenderTriggered + const onScopeDispose: typeof import('vue').onScopeDispose + const onServerPrefetch: typeof import('vue').onServerPrefetch + const onUnmounted: typeof import('vue').onUnmounted + const onUpdated: typeof import('vue').onUpdated + const onWatcherCleanup: typeof import('vue').onWatcherCleanup + const provide: typeof import('vue').provide + const reactive: typeof import('vue').reactive + const readonly: typeof import('vue').readonly + const ref: typeof import('vue').ref + const resolveComponent: typeof import('vue').resolveComponent + const setActivePinia: typeof import('pinia').setActivePinia + const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix + const shallowReactive: typeof import('vue').shallowReactive + const shallowReadonly: typeof import('vue').shallowReadonly + const shallowRef: typeof import('vue').shallowRef + const storeToRefs: typeof import('pinia').storeToRefs + const toRaw: typeof import('vue').toRaw + const toRef: typeof import('vue').toRef + const toRefs: typeof import('vue').toRefs + const toValue: typeof import('vue').toValue + const triggerRef: typeof import('vue').triggerRef + const unref: typeof import('vue').unref + const useAttrs: typeof import('vue').useAttrs + const useCssModule: typeof import('vue').useCssModule + const useCssVars: typeof import('vue').useCssVars + const useId: typeof import('vue').useId + const useLink: typeof import('vue-router').useLink + const useModel: typeof import('vue').useModel + const useRoute: typeof import('vue-router').useRoute + const useRouter: typeof import('vue-router').useRouter + const useSlots: typeof import('vue').useSlots + const useTemplateRef: typeof import('vue').useTemplateRef + const watch: typeof import('vue').watch + const watchEffect: typeof import('vue').watchEffect + const watchPostEffect: typeof import('vue').watchPostEffect + const watchSyncEffect: typeof import('vue').watchSyncEffect +} +// for type re-export +declare global { + // @ts-ignore + export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue' + import('vue') +} diff --git a/FM-Frontend/src/components.d.ts b/FM-Frontend/src/components.d.ts new file mode 100644 index 00000000..1afdf514 --- /dev/null +++ b/FM-Frontend/src/components.d.ts @@ -0,0 +1,92 @@ +/* eslint-disable */ +// @ts-nocheck +// biome-ignore lint: disable +// oxlint-disable +// ------ +// Generated by unplugin-vue-components +// Read more: https://github.com/vuejs/core/pull/3399 + +export {} + +/* prettier-ignore */ +declare module 'vue' { + export interface GlobalComponents { + AAlert: typeof import('ant-design-vue/es')['Alert'] + AAvatar: typeof import('ant-design-vue/es')['Avatar'] + ABadge: typeof import('ant-design-vue/es')['Badge'] + AButton: typeof import('ant-design-vue/es')['Button'] + ACard: typeof import('ant-design-vue/es')['Card'] + ACarousel: typeof import('ant-design-vue/es')['Carousel'] + ACheckbox: typeof import('ant-design-vue/es')['Checkbox'] + ACheckboxGroup: typeof import('ant-design-vue/es')['CheckboxGroup'] + ACol: typeof import('ant-design-vue/es')['Col'] + ACollapse: typeof import('ant-design-vue/es')['Collapse'] + ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel'] + ADatePicker: typeof import('ant-design-vue/es')['DatePicker'] + ADescriptions: typeof import('ant-design-vue/es')['Descriptions'] + ADescriptionsItem: typeof import('ant-design-vue/es')['DescriptionsItem'] + ADivider: typeof import('ant-design-vue/es')['Divider'] + AdminFilterPanel: typeof import('./components/admin/AdminFilterPanel.vue')['default'] + AdminMobileCardList: typeof import('./components/admin/AdminMobileCardList.vue')['default'] + AdminMobileFab: typeof import('./components/admin/AdminMobileFab.vue')['default'] + AdminResponsiveModal: typeof import('./components/admin/AdminResponsiveModal.vue')['default'] + ADrawer: typeof import('ant-design-vue/es')['Drawer'] + ADropdown: typeof import('ant-design-vue/es')['Dropdown'] + AEmpty: typeof import('ant-design-vue/es')['Empty'] + AForm: typeof import('ant-design-vue/es')['Form'] + AFormItem: typeof import('ant-design-vue/es')['FormItem'] + AImage: typeof import('ant-design-vue/es')['Image'] + AInput: typeof import('ant-design-vue/es')['Input'] + AInputNumber: typeof import('ant-design-vue/es')['InputNumber'] + AInputPassword: typeof import('ant-design-vue/es')['InputPassword'] + AInputSearch: typeof import('ant-design-vue/es')['InputSearch'] + ALayout: typeof import('ant-design-vue/es')['Layout'] + ALayoutContent: typeof import('ant-design-vue/es')['LayoutContent'] + ALayoutHeader: typeof import('ant-design-vue/es')['LayoutHeader'] + ALayoutSider: typeof import('ant-design-vue/es')['LayoutSider'] + AList: typeof import('ant-design-vue/es')['List'] + AListItem: typeof import('ant-design-vue/es')['ListItem'] + AListItemMeta: typeof import('ant-design-vue/es')['ListItemMeta'] + AMenu: typeof import('ant-design-vue/es')['Menu'] + AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider'] + AMenuItem: typeof import('ant-design-vue/es')['MenuItem'] + AModal: typeof import('ant-design-vue/es')['Modal'] + APageHeader: typeof import('ant-design-vue/es')['PageHeader'] + APopconfirm: typeof import('ant-design-vue/es')['Popconfirm'] + AProgress: typeof import('ant-design-vue/es')['Progress'] + ARadio: typeof import('ant-design-vue/es')['Radio'] + ARadioButton: typeof import('ant-design-vue/es')['RadioButton'] + ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup'] + ARangePicker: typeof import('ant-design-vue/es')['RangePicker'] + AResult: typeof import('ant-design-vue/es')['Result'] + ARow: typeof import('ant-design-vue/es')['Row'] + ASegmented: typeof import('ant-design-vue/es')['Segmented'] + ASelect: typeof import('ant-design-vue/es')['Select'] + ASelectOption: typeof import('ant-design-vue/es')['SelectOption'] + ASkeleton: typeof import('ant-design-vue/es')['Skeleton'] + ASpace: typeof import('ant-design-vue/es')['Space'] + ASpin: typeof import('ant-design-vue/es')['Spin'] + AStatistic: typeof import('ant-design-vue/es')['Statistic'] + ASwitch: typeof import('ant-design-vue/es')['Switch'] + ATable: typeof import('ant-design-vue/es')['Table'] + ATabPane: typeof import('ant-design-vue/es')['TabPane'] + ATabs: typeof import('ant-design-vue/es')['Tabs'] + ATag: typeof import('ant-design-vue/es')['Tag'] + ATextarea: typeof import('ant-design-vue/es')['Textarea'] + ATimeline: typeof import('ant-design-vue/es')['Timeline'] + ATimelineItem: typeof import('ant-design-vue/es')['TimelineItem'] + ATooltip: typeof import('ant-design-vue/es')['Tooltip'] + ATypographyText: typeof import('ant-design-vue/es')['TypographyText'] + AUpload: typeof import('ant-design-vue/es')['Upload'] + BottomNav: typeof import('./components/BottomNav.vue')['default'] + DraftActions: typeof import('./components/DraftActions.vue')['default'] + ElButton: typeof import('element-plus/es')['ElButton'] + ElColorPicker: typeof import('element-plus/es')['ElColorPicker'] + ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider'] + ElIcon: typeof import('element-plus/es')['ElIcon'] + RouterLink: typeof import('vue-router')['RouterLink'] + RouterView: typeof import('vue-router')['RouterView'] + SystemMessageCard: typeof import('./components/SystemMessageCard.vue')['default'] + TableEllipsisText: typeof import('./components/TableEllipsisText.vue')['default'] + } +} diff --git a/FM-Frontend/src/components/BottomNav.vue b/FM-Frontend/src/components/BottomNav.vue new file mode 100644 index 00000000..a779f06e --- /dev/null +++ b/FM-Frontend/src/components/BottomNav.vue @@ -0,0 +1,278 @@ + + + + + + + diff --git a/FM-Frontend/src/components/DraftActions.vue b/FM-Frontend/src/components/DraftActions.vue new file mode 100644 index 00000000..92d6afa4 --- /dev/null +++ b/FM-Frontend/src/components/DraftActions.vue @@ -0,0 +1,71 @@ + + + + + diff --git a/FM-Frontend/src/components/SystemMessageCard.vue b/FM-Frontend/src/components/SystemMessageCard.vue new file mode 100644 index 00000000..51b4efc1 --- /dev/null +++ b/FM-Frontend/src/components/SystemMessageCard.vue @@ -0,0 +1,280 @@ + + + + + diff --git a/FM-Frontend/src/components/TableEllipsisText.vue b/FM-Frontend/src/components/TableEllipsisText.vue new file mode 100644 index 00000000..2afd3cd2 --- /dev/null +++ b/FM-Frontend/src/components/TableEllipsisText.vue @@ -0,0 +1,76 @@ + + + + + diff --git a/FM-Frontend/src/components/admin/AdminFilterPanel.vue b/FM-Frontend/src/components/admin/AdminFilterPanel.vue new file mode 100644 index 00000000..2393b19a --- /dev/null +++ b/FM-Frontend/src/components/admin/AdminFilterPanel.vue @@ -0,0 +1,120 @@ + + + + + diff --git a/FM-Frontend/src/components/admin/AdminMobileCardList.vue b/FM-Frontend/src/components/admin/AdminMobileCardList.vue new file mode 100644 index 00000000..f2d2b870 --- /dev/null +++ b/FM-Frontend/src/components/admin/AdminMobileCardList.vue @@ -0,0 +1,38 @@ + + + diff --git a/FM-Frontend/src/components/admin/AdminMobileFab.vue b/FM-Frontend/src/components/admin/AdminMobileFab.vue new file mode 100644 index 00000000..c4e0bca3 --- /dev/null +++ b/FM-Frontend/src/components/admin/AdminMobileFab.vue @@ -0,0 +1,32 @@ + + + diff --git a/FM-Frontend/src/components/admin/AdminResponsiveModal.vue b/FM-Frontend/src/components/admin/AdminResponsiveModal.vue new file mode 100644 index 00000000..e9a52e16 --- /dev/null +++ b/FM-Frontend/src/components/admin/AdminResponsiveModal.vue @@ -0,0 +1,130 @@ + + + diff --git a/FM-Frontend/src/composables/useAdminViewport.ts b/FM-Frontend/src/composables/useAdminViewport.ts new file mode 100644 index 00000000..de9d0bb7 --- /dev/null +++ b/FM-Frontend/src/composables/useAdminViewport.ts @@ -0,0 +1,80 @@ +import { computed, onBeforeUnmount, onMounted, ref } from 'vue' + +/** + * Purpose: ADMIN_MOBILE_BREAKPOINT supports useAdminViewport.ts by holding or executing the admin mobile breakpoint page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ADMIN_MOBILE_BREAKPOINT = 960 + +/** + * Purpose: viewportWidth supports useAdminViewport.ts by holding or executing the viewport width page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const viewportWidth = ref( + typeof window !== 'undefined' ? window.innerWidth : ADMIN_MOBILE_BREAKPOINT + 1 +) + +/** + * Purpose: listenerCount supports useAdminViewport.ts by holding or executing the listener count page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let listenerCount = 0 + +/** + * Purpose: updateViewportWidth supports useAdminViewport.ts by holding or executing the update viewport width page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const updateViewportWidth = () => { + if (typeof window === 'undefined') { + return + } + viewportWidth.value = window.innerWidth +} + +/** + * Purpose: bindViewportListener supports useAdminViewport.ts by holding or executing the bind viewport listener page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const bindViewportListener = () => { + if (typeof window === 'undefined') { + return + } + if (listenerCount === 0) { + window.addEventListener('resize', updateViewportWidth, { passive: true }) + } + listenerCount += 1 +} + +/** + * Purpose: unbindViewportListener supports useAdminViewport.ts by holding or executing the unbind viewport listener page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const unbindViewportListener = () => { + if (typeof window === 'undefined') { + return + } + listenerCount = Math.max(0, listenerCount - 1) + if (listenerCount === 0) { + window.removeEventListener('resize', updateViewportWidth) + } +} + +/** + * Purpose: useAdminViewport supports useAdminViewport.ts by holding or executing the use admin viewport page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const useAdminViewport = () => { + onMounted(() => { + updateViewportWidth() + bindViewportListener() + }) + + onBeforeUnmount(() => { + unbindViewportListener() + }) + + return { + viewportWidth: computed(() => viewportWidth.value), + isMobile: computed(() => viewportWidth.value <= ADMIN_MOBILE_BREAKPOINT) + } +} diff --git a/FM-Frontend/src/composables/useConfirmEnter.test.ts b/FM-Frontend/src/composables/useConfirmEnter.test.ts new file mode 100644 index 00000000..8063aa24 --- /dev/null +++ b/FM-Frontend/src/composables/useConfirmEnter.test.ts @@ -0,0 +1,274 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createApp } from 'vue' +import { useGlobalConfirmEnter } from './useConfirmEnter' + +/** + * Purpose: visibleRects supports useConfirmEnter.test.ts by holding or executing the visible rects page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const visibleRects = [{ + bottom: 100, + height: 100, + left: 0, + right: 100, + top: 0, + width: 100, + x: 0, + y: 0, + toJSON: () => ({}) +}] as DOMRect[] + +/** + * Purpose: makeVisible supports useConfirmEnter.test.ts by holding or executing the make visible page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const makeVisible = (element: HTMLElement) => { + vi.spyOn(element, 'getClientRects').mockReturnValue(visibleRects as unknown as DOMRectList) +} + +/** + * Purpose: setDesktopViewport supports useConfirmEnter.test.ts by holding or executing the set desktop viewport page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const setDesktopViewport = () => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 1280 + }) + window.matchMedia = vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)' ? false : false, + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn() + })) +} + +/** + * Purpose: setMobileViewport supports useConfirmEnter.test.ts by holding or executing the set mobile viewport page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const setMobileViewport = () => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 640 + }) +} + +/** + * Purpose: setCoarsePointer supports useConfirmEnter.test.ts by holding or executing the set coarse pointer page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const setCoarsePointer = () => { + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 1280 + }) + window.matchMedia = vi.fn().mockImplementation((query: string) => ({ + matches: query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn() + })) +} + +/** + * Purpose: mountGlobalConfirmEnter supports useConfirmEnter.test.ts by holding or executing the mount global confirm enter page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const mountGlobalConfirmEnter = () => { + const host = document.createElement('div') + document.body.appendChild(host) + + const app = createApp({ + setup() { + useGlobalConfirmEnter() + return () => null + } + }) + + app.mount(host) + + return () => { + app.unmount() + host.remove() + } +} + +/** + * Purpose: createModal supports useConfirmEnter.test.ts by holding or executing the create modal page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const createModal = ({ + zIndex = 1000, + buttonClass = '', + disabled = false, + ariaDisabled = false, + footerClass = 'ant-modal-footer' +}: { + zIndex?: number + buttonClass?: string + disabled?: boolean + ariaDisabled?: boolean + footerClass?: 'ant-modal-footer' | 'ant-modal-confirm-btns' +} = {}) => { + const wrap = document.createElement('div') + wrap.className = 'ant-modal-wrap' + wrap.style.zIndex = String(zIndex) + + const footer = document.createElement('div') + footer.className = footerClass + + const button = document.createElement('button') + button.type = 'button' + button.className = `ant-btn ant-btn-primary ${buttonClass}`.trim() + button.disabled = disabled + if (ariaDisabled) { + button.setAttribute('aria-disabled', 'true') + } + + const onClick = vi.fn() + const click = vi.spyOn(button, 'click') + button.addEventListener('click', onClick) + + footer.appendChild(button) + wrap.appendChild(footer) + document.body.appendChild(wrap) + makeVisible(wrap) + makeVisible(button) + + return { wrap, button, click, onClick } +} + +/** + * Purpose: createKeyboardEvent supports useConfirmEnter.test.ts by holding or executing the create keyboard event page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const createKeyboardEvent = () => new KeyboardEvent('keydown', { + key: 'Enter', + bubbles: true, + cancelable: true +}) + +/** + * Purpose: pressEnter supports useConfirmEnter.test.ts by holding or executing the press enter page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const pressEnter = (target: EventTarget = document) => { + const event = createKeyboardEvent() + target.dispatchEvent(event) + return event +} + +describe('useGlobalConfirmEnter', () => { + let unmount: (() => void) | undefined + + beforeEach(() => { + document.body.innerHTML = '' + setDesktopViewport() + unmount = mountGlobalConfirmEnter() + }) + + afterEach(() => { + unmount?.() + document.body.innerHTML = '' + vi.restoreAllMocks() + }) + + it('clicks the visible top modal primary ok button when PC users press Enter', () => { + const { onClick } = createModal() + + const event = pressEnter() + + expect(onClick).toHaveBeenCalledTimes(1) + expect(event.defaultPrevented).toBe(true) + }) + + it('does not click the ok button when Enter starts inside textarea or contenteditable elements', () => { + const { onClick } = createModal() + + const textarea = document.createElement('textarea') + document.body.appendChild(textarea) + pressEnter(textarea) + + const editable = document.createElement('div') + editable.setAttribute('contenteditable', 'true') + document.body.appendChild(editable) + pressEnter(editable) + + expect(onClick).not.toHaveBeenCalled() + }) + + it.each([ + 'ant-select-dropdown', + 'ant-picker-dropdown', + 'ant-dropdown', + 'ant-popover' + ])('does not click the ok button while %s is open', (dropdownClass) => { + const { onClick } = createModal() + const popup = document.createElement('div') + popup.className = dropdownClass + document.body.appendChild(popup) + + pressEnter() + + expect(onClick).not.toHaveBeenCalled() + }) + + it('does not click disabled or loading ok buttons', () => { + const disabledModal = createModal({ disabled: true }) + pressEnter() + expect(disabledModal.click).not.toHaveBeenCalled() + expect(disabledModal.onClick).not.toHaveBeenCalled() + disabledModal.wrap.remove() + + const ariaDisabledModal = createModal({ ariaDisabled: true }) + pressEnter() + expect(ariaDisabledModal.click).not.toHaveBeenCalled() + expect(ariaDisabledModal.onClick).not.toHaveBeenCalled() + ariaDisabledModal.wrap.remove() + + const loadingModal = createModal({ buttonClass: 'ant-btn-loading' }) + pressEnter() + expect(loadingModal.click).not.toHaveBeenCalled() + expect(loadingModal.onClick).not.toHaveBeenCalled() + }) + + it('does not click the ok button on mobile width or coarse pointer devices', () => { + const mobileModal = createModal() + setMobileViewport() + pressEnter() + expect(mobileModal.onClick).not.toHaveBeenCalled() + mobileModal.wrap.remove() + + const coarsePointerModal = createModal() + setCoarsePointer() + pressEnter() + expect(coarsePointerModal.onClick).not.toHaveBeenCalled() + }) + + it('clicks only the z-index and DOM-top modal when multiple modals are visible', () => { + const firstModal = createModal({ zIndex: 1000 }) + const secondModal = createModal({ zIndex: 1000 }) + const topZIndexModal = createModal({ zIndex: 1200 }) + + pressEnter() + + expect(firstModal.onClick).not.toHaveBeenCalled() + expect(secondModal.onClick).not.toHaveBeenCalled() + expect(topZIndexModal.onClick).toHaveBeenCalledTimes(1) + + topZIndexModal.wrap.remove() + pressEnter() + + expect(firstModal.onClick).not.toHaveBeenCalled() + expect(secondModal.onClick).toHaveBeenCalledTimes(1) + }) +}) diff --git a/FM-Frontend/src/composables/useConfirmEnter.ts b/FM-Frontend/src/composables/useConfirmEnter.ts new file mode 100644 index 00000000..fdbeae51 --- /dev/null +++ b/FM-Frontend/src/composables/useConfirmEnter.ts @@ -0,0 +1,231 @@ +/** + * Purpose: ComputedRef supports useConfirmEnter.ts by holding or executing the computed ref page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +import { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue' + +/** + * Purpose: UseConfirmEnterOptions supports useConfirmEnter.ts by holding or executing the use confirm enter options page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +interface UseConfirmEnterOptions { + enabled: ComputedRef + onConfirm: (event: KeyboardEvent) => void + isConfirmDisabled?: () => boolean + isTopLayer?: () => boolean +} + +/** + * Purpose: CONFIRM_ENTER_DISABLED_CLASS supports useConfirmEnter.ts by holding or executing the confirm enter disabled class page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const CONFIRM_ENTER_DISABLED_CLASS = 'confirm-enter-disabled' +/** + * Purpose: DESKTOP_MIN_WIDTH supports useConfirmEnter.ts by holding or executing the desktop min width page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DESKTOP_MIN_WIDTH = 960 + +/** + * Purpose: isEditableTarget supports useConfirmEnter.ts by holding or executing the is editable target page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isEditableTarget = (target: EventTarget | null) => { + if (!(target instanceof HTMLElement)) { + return false + } + + if (target.isContentEditable) { + return true + } + + return target.tagName.toLowerCase() === 'textarea' || Boolean(target.closest('[contenteditable="true"]')) +} + +/** + * Purpose: hasOpenPickerOrDropdown supports useConfirmEnter.ts by holding or executing the has open picker or dropdown page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const hasOpenPickerOrDropdown = () => { + return Boolean(document.querySelector([ + '.ant-select-dropdown:not(.ant-select-dropdown-hidden)', + '.ant-picker-dropdown:not(.ant-picker-dropdown-hidden)', + '.ant-cascader-dropdown:not(.ant-cascader-dropdown-hidden)', + '.ant-dropdown:not(.ant-dropdown-hidden)', + '.ant-popover:not(.ant-popover-hidden)' + ].join(','))) +} + +/** + * Purpose: isDesktopViewport supports useConfirmEnter.ts by holding or executing the is desktop viewport page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isDesktopViewport = () => { + if (typeof window === 'undefined') { + return false + } + + const coarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false + return window.innerWidth > DESKTOP_MIN_WIDTH && !coarsePointer +} + +/** + * Purpose: isVisibleElement supports useConfirmEnter.ts by holding or executing the is visible element page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isVisibleElement = (element: Element) => { + if (!(element instanceof HTMLElement)) { + return false + } + + const style = window.getComputedStyle(element) + return style.display !== 'none' + && style.visibility !== 'hidden' + && style.opacity !== '0' + && element.getClientRects().length > 0 +} + +/** + * Purpose: isDisabledButton supports useConfirmEnter.ts by holding or executing the is disabled button page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isDisabledButton = (button: HTMLButtonElement) => { + return button.disabled + || button.getAttribute('aria-disabled') === 'true' + || button.classList.contains('ant-btn-loading') + || button.classList.contains('ant-btn-disabled') +} + +/** + * Purpose: getTopModalWrap supports useConfirmEnter.ts by holding or executing the get top modal wrap page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getTopModalWrap = () => { + const modals = Array.from(document.querySelectorAll('.ant-modal-wrap')) + .filter(isVisibleElement) + + if (!modals.length) { + return null + } + + const sortedModals = modals + .map((modal, index) => { + const zIndex = Number.parseInt(window.getComputedStyle(modal).zIndex || '0', 10) + return { + modal, + index, + zIndex: Number.isNaN(zIndex) ? 0 : zIndex + } + }) + .sort((left, right) => left.zIndex - right.zIndex || left.index - right.index) + + return sortedModals[sortedModals.length - 1]?.modal ?? null +} + +/** + * Purpose: getTopModalConfirmButton supports useConfirmEnter.ts by holding or executing the get top modal confirm button page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getTopModalConfirmButton = () => { + const topModal = getTopModalWrap() + if (!topModal || topModal.classList.contains(CONFIRM_ENTER_DISABLED_CLASS)) { + return null + } + + const button = topModal.querySelector([ + '.ant-modal-confirm-btns .ant-btn-primary', + '.ant-modal-footer .ant-btn-primary' + ].join(',')) + + if (!button || !isVisibleElement(button) || isDisabledButton(button)) { + return null + } + + return button +} + +/** + * Purpose: useConfirmEnter supports useConfirmEnter.ts by holding or executing the use confirm enter page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const useConfirmEnter = ({ + enabled, + onConfirm, + isConfirmDisabled, + isTopLayer +}: UseConfirmEnterOptions) => { + const canConfirm = computed(() => ( + enabled.value + && !(isConfirmDisabled?.() ?? false) + && (isTopLayer?.() ?? true) + )) + + const handleKeydown = (event: KeyboardEvent) => { + if ( + event.key !== 'Enter' + || event.defaultPrevented + || event.shiftKey + || event.ctrlKey + || event.altKey + || event.metaKey + || event.isComposing + || !canConfirm.value + || isEditableTarget(event.target) + || hasOpenPickerOrDropdown() + ) { + return + } + + event.preventDefault() + onConfirm(event) + } + + onMounted(() => { + document.addEventListener('keydown', handleKeydown) + }) + + onBeforeUnmount(() => { + document.removeEventListener('keydown', handleKeydown) + }) +} + +/** + * Purpose: useGlobalConfirmEnter supports useConfirmEnter.ts by holding or executing the use global confirm enter page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const useGlobalConfirmEnter = () => { + const handleKeydown = (event: KeyboardEvent) => { + if ( + event.key !== 'Enter' + || event.defaultPrevented + || event.shiftKey + || event.ctrlKey + || event.altKey + || event.metaKey + || event.isComposing + || (event as KeyboardEvent & { keyCode?: number }).keyCode === 229 + || !isDesktopViewport() + || isEditableTarget(event.target) + || hasOpenPickerOrDropdown() + ) { + return + } + + const confirmButton = getTopModalConfirmButton() + if (!confirmButton) { + return + } + + event.preventDefault() + event.stopImmediatePropagation() + confirmButton.click() + } + + onMounted(() => { + document.addEventListener('keydown', handleKeydown) + }) + + onBeforeUnmount(() => { + document.removeEventListener('keydown', handleKeydown) + }) +} diff --git a/FM-Frontend/src/composables/useShopTheme.test.ts b/FM-Frontend/src/composables/useShopTheme.test.ts new file mode 100644 index 00000000..bb8bf04a --- /dev/null +++ b/FM-Frontend/src/composables/useShopTheme.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/api/file', () => ({ + fileApi: { + getSignedUrl: vi.fn() + } +})) + +vi.mock('@/api/shop', () => ({ + shopApi: { + getShopById: vi.fn() + } +})) + +import { shopApi } from '@/api/shop' +import { DEFAULT_SHOP_THEME } from '@/utils/shop-theme' +import { useShopTheme } from './useShopTheme' + +describe('useShopTheme', () => { + beforeEach(() => { + localStorage.clear() + sessionStorage.clear() + vi.clearAllMocks() + document.documentElement.removeAttribute('style') + }) + + it('uses the first preset as the default visible theme', async () => { + const { resetShopTheme } = useShopTheme() + + resetShopTheme() + + expect(DEFAULT_SHOP_THEME.primaryColor).toBe('#E8B4B8') + expect(DEFAULT_SHOP_THEME.secondaryColor).toBe('#C5A059') + expect(DEFAULT_SHOP_THEME.accentColor).toBe('#4A443F') + expect(DEFAULT_SHOP_THEME.pageBgColor).toBe('#FDFBF9') + expect(DEFAULT_SHOP_THEME.cardBgColor).toBe('#FFFFFF') + expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8') + expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#C5A059') + expect(document.documentElement.style.getPropertyValue('--theme-neutral')).toBe('#4A443F') + expect(document.documentElement.style.getPropertyValue('--theme-tertiary')).toBe('#FDFBF9') + }) + + it('refreshes the admin theme from the cached admin shop context', async () => { + localStorage.setItem('adminAccessToken', 'admin-token') + localStorage.setItem('adminUserInfo', JSON.stringify({ shopId: 42 })) + vi.mocked(shopApi.getShopById).mockResolvedValue({ + themePrimaryColor: '#123456', + themeSecondaryColor: '#ABCDEF', + themeAccentColor: '#345678', + themePageBgColor: '#F7FAFC', + themeCardBgColor: '#FFFFFF' + } as never) + + const { refreshShopTheme } = useShopTheme() + + await refreshShopTheme({ mode: 'admin' }) + + expect(shopApi.getShopById).toHaveBeenCalledWith('42') + expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#123456') + expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#ABCDEF') + }) + + it('keeps the default theme for login pages without a shop context', async () => { + const { refreshShopTheme } = useShopTheme() + + await refreshShopTheme({ mode: 'admin' }) + + expect(shopApi.getShopById).not.toHaveBeenCalled() + expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8') + }) +}) diff --git a/FM-Frontend/src/composables/useShopTheme.ts b/FM-Frontend/src/composables/useShopTheme.ts new file mode 100644 index 00000000..344a9c03 --- /dev/null +++ b/FM-Frontend/src/composables/useShopTheme.ts @@ -0,0 +1,194 @@ +import { readonly, shallowRef } from 'vue' +import { fileApi } from '@/api/file' +/** + * Purpose: ShopVO supports useShopTheme.ts by holding or executing the shop vo page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +import { shopApi, type ShopVO } from '@/api/shop' +import { + applyShopTheme, + DEFAULT_SHOP_THEME, + resolveShopTheme, + SHOP_THEME_CHANGED_EVENT, + type ResolvedShopTheme +} from '@/utils/shop-theme' + +type ShopThemeMode = 'auto' | 'admin' | 'customer' + +export interface RefreshShopThemeOptions { + mode?: ShopThemeMode + shopId?: string | number | null +} + +/** + * Purpose: currentTheme supports useShopTheme.ts by holding or executing the current theme page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const currentTheme = shallowRef(DEFAULT_SHOP_THEME) +let cleanupThemeSync: (() => void) | undefined +/** + * Purpose: refreshSequence supports useShopTheme.ts by holding or executing the refresh sequence page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let refreshSequence = 0 + +applyShopTheme(DEFAULT_SHOP_THEME) + +/** + * Purpose: useShopTheme supports useShopTheme.ts by holding or executing the use shop theme page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export function useShopTheme() { + return { + currentTheme: readonly(currentTheme), + refreshShopTheme, + resetShopTheme, + setupShopThemeSync + } +} + +/** + * Purpose: refreshShopTheme supports useShopTheme.ts by holding or executing the refresh shop theme page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +async function refreshShopTheme(options: RefreshShopThemeOptions = {}) { + const mode = resolveThemeMode(options.mode) + const token = readToken(mode) + const userInfo = readStoredUserInfo(mode) + const shopId = options.shopId === undefined ? userInfo?.shopId : options.shopId + + if (!token || !shopId) { + resetShopTheme() + return + } + + const sequence = ++refreshSequence + try { + const shop = await shopApi.getShopById(String(shopId)) + if (sequence !== refreshSequence) { + return + } + await applyThemeFromShop(shop) + } catch { + if (sequence === refreshSequence) { + resetShopTheme() + } + } +} + +/** + * Purpose: resetShopTheme supports useShopTheme.ts by holding or executing the reset shop theme page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function resetShopTheme() { + refreshSequence += 1 + currentTheme.value = DEFAULT_SHOP_THEME + applyShopTheme(DEFAULT_SHOP_THEME) +} + +/** + * Purpose: setupShopThemeSync supports useShopTheme.ts by holding or executing the setup shop theme sync page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function setupShopThemeSync() { + if (cleanupThemeSync || typeof window === 'undefined') { + return cleanupThemeSync || (() => {}) + } + + const handleThemeEvent = () => { + void refreshShopTheme() + } + const handleStorage = (event: StorageEvent) => { + if ([ + 'accessToken', + 'userInfo', + 'refreshToken', + 'adminAccessToken', + 'adminRefreshToken', + 'adminUserInfo' + ].includes(event.key || '')) { + void refreshShopTheme() + } + } + + window.addEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent) + window.addEventListener('storage', handleStorage) + window.addEventListener('focus', handleThemeEvent) + + cleanupThemeSync = () => { + window.removeEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent) + window.removeEventListener('storage', handleStorage) + window.removeEventListener('focus', handleThemeEvent) + cleanupThemeSync = undefined + } + return cleanupThemeSync +} + +/** + * Purpose: applyThemeFromShop supports useShopTheme.ts by holding or executing the apply theme from shop page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +async function applyThemeFromShop(shop: ShopVO) { + const theme = resolveShopTheme(shop) + currentTheme.value = theme + const backgroundImageUrl = await resolveBackgroundImageUrl(theme.backgroundImageFileId) + applyShopTheme(theme, backgroundImageUrl) +} + +/** + * Purpose: resolveBackgroundImageUrl supports useShopTheme.ts by holding or executing the resolve background image url page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +async function resolveBackgroundImageUrl(fileId?: string) { + if (!fileId) { + return null + } + try { + return await fileApi.getSignedUrl(fileId, 120) as unknown as string + } catch { + return null + } +} + +/** + * Purpose: readToken supports useShopTheme.ts by holding or executing the read token page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function resolveThemeMode(mode: ShopThemeMode = 'auto'): Exclude { + if (mode !== 'auto') { + return mode + } + if (typeof window !== 'undefined' && window.location.pathname.startsWith('/admin')) { + return 'admin' + } + return 'customer' +} + +function readToken(mode: Exclude) { + if (typeof window === 'undefined') { + return '' + } + if (mode === 'admin') { + return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken') || '' + } + return localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') || '' +} + +/** + * Purpose: readStoredUserInfo supports useShopTheme.ts by holding or executing the read stored user info page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function readStoredUserInfo(mode: Exclude): { shopId?: string | number } | null { + if (typeof window === 'undefined') { + return null + } + const raw = localStorage.getItem(mode === 'admin' ? 'adminUserInfo' : 'userInfo') + if (!raw) { + return null + } + try { + return JSON.parse(raw) as { shopId?: string | number } + } catch { + return null + } +} diff --git a/FM-Frontend/src/config/admin-navigation.test.ts b/FM-Frontend/src/config/admin-navigation.test.ts new file mode 100644 index 00000000..15d62791 --- /dev/null +++ b/FM-Frontend/src/config/admin-navigation.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation' + +describe('admin-navigation', () => { + it('keeps dashboard landing and permission routes aligned', () => { + expect(ADMIN_DASHBOARD_PATH).toBe('/admin/dashboard') + expect(findAdminNavigationItemByPath('/admin/products')?.label).toBe('作品管理') + expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true) + expect(adminNavigationItems[0]?.path).toBe('/admin') + }) +}) diff --git a/FM-Frontend/src/config/admin-navigation.ts b/FM-Frontend/src/config/admin-navigation.ts new file mode 100644 index 00000000..e29e39d2 --- /dev/null +++ b/FM-Frontend/src/config/admin-navigation.ts @@ -0,0 +1,56 @@ +export type AdminNavIconKey = + | 'home' + | 'dashboard' + | 'user' + | 'shop' + | 'gift' + | 'message' + | 'security' + | 'tag' + | 'shopping' + | 'calendar' + | 'tool' + | 'team' + +export interface AdminNavigationItem { + path: string + iconKey: AdminNavIconKey + label: string + permissionCode: string +} + +export const ADMIN_HOME_PATH = '/admin' +export const ADMIN_DASHBOARD_PATH = '/admin/dashboard' + +export const adminNavigationItems: AdminNavigationItem[] = [ + { path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' }, + { path: ADMIN_DASHBOARD_PATH, iconKey: 'dashboard', label: '仪表盘', permissionCode: 'dashboard:view' }, + { path: '/admin/users', iconKey: 'user', label: '用户管理', permissionCode: 'user:view' }, + { path: '/admin/products', iconKey: 'shop', label: '作品管理', permissionCode: 'product:view' }, + { path: '/admin/coupons', iconKey: 'gift', label: '优惠券管理', permissionCode: 'coupon:view' }, + { path: '/admin/comments', iconKey: 'message', label: '评论管理', permissionCode: 'comment:view' }, + { path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' }, + { path: '/admin/permissions', iconKey: 'security', label: '权限管理', permissionCode: 'permission:view' }, + { path: '/admin/tags', iconKey: 'tag', label: '标签管理', permissionCode: 'tag:view' }, + { path: '/admin/orders', iconKey: 'shopping', label: '订单管理', permissionCode: 'order:view' }, + { path: '/admin/schedules', iconKey: 'calendar', label: '排班管理', permissionCode: 'schedule:view' }, + { path: '/admin/after-sales', iconKey: 'message', label: '售后处理', permissionCode: 'after_sale:view' }, + { path: '/admin/inventory', iconKey: 'tool', label: '库存管理', permissionCode: 'inventory:view' }, + { path: '/admin/campaigns', iconKey: 'gift', label: '活动管理', permissionCode: 'campaign:view' }, + { path: '/admin/nail-artists', iconKey: 'team', label: '美甲师管理', permissionCode: 'nail_artist:view' }, + { path: '/admin/messages', iconKey: 'message', label: '消息发布', permissionCode: 'message:view' }, + { path: '/admin/announcements', iconKey: 'message', label: '公告管理', permissionCode: 'announcement:view' }, + { path: '/admin/vip-recharge-plans', iconKey: 'gift', label: 'VIP充值配置', permissionCode: 'user:vip:manage' }, + { path: '/admin/messagehub-push-configs', iconKey: 'message', label: '参数管理', permissionCode: 'messagehub:config:manage' }, + { path: '/admin/legal-agreements', iconKey: 'security', label: '协议管理', permissionCode: 'legal_agreement:manage' } +] + +export const adminPermissionRouteMap = adminNavigationItems + .filter(item => item.permissionCode) + .map(item => ({ + code: item.permissionCode, + path: item.path + })) + +export const findAdminNavigationItemByPath = (path: string) => + adminNavigationItems.find(item => item.path === path) diff --git a/FM-Frontend/src/config/antdv-locale.ts b/FM-Frontend/src/config/antdv-locale.ts new file mode 100644 index 00000000..5e4cbac6 --- /dev/null +++ b/FM-Frontend/src/config/antdv-locale.ts @@ -0,0 +1,58 @@ +import zhCN from 'ant-design-vue/es/locale/zh_CN' + +/** + * Purpose: baseCalendar supports antdv-locale.ts by holding or executing the base calendar page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const baseCalendar = (zhCN.Calendar || { lang: {} }) as any +/** + * Purpose: baseDatePicker supports antdv-locale.ts by holding or executing the base date picker page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const baseDatePicker = (zhCN.DatePicker || { lang: {}, timePickerLocale: {} }) as any +/** + * Purpose: baseTimePicker supports antdv-locale.ts by holding or executing the base time picker page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const baseTimePicker = (zhCN.TimePicker || {}) as any + +const antdLocale: any = { + ...zhCN, + Modal: { + ...zhCN.Modal, + okText: '确认', + cancelText: zhCN.Modal?.cancelText || '取消', + justOkText: zhCN.Modal?.justOkText || '知道了' + }, + Popconfirm: { + ...zhCN.Popconfirm, + okText: '确认', + cancelText: zhCN.Popconfirm?.cancelText || '取消' + }, + Calendar: { + ...baseCalendar, + lang: { + ...baseCalendar.lang, + ok: '确认', + now: '现在时间' + } + }, + DatePicker: { + ...baseDatePicker, + lang: { + ...baseDatePicker.lang, + ok: '确认', + now: '现在时间' + }, + timePickerLocale: { + ...baseDatePicker.timePickerLocale, + now: '现在时间' + } + }, + TimePicker: { + ...baseTimePicker, + now: '现在时间' + } +} + +export default antdLocale diff --git a/FM-Frontend/src/config/api.ts b/FM-Frontend/src/config/api.ts new file mode 100644 index 00000000..47379c58 --- /dev/null +++ b/FM-Frontend/src/config/api.ts @@ -0,0 +1,40 @@ +/** + * Purpose: normalizeBaseUrl supports api.ts by holding or executing the normalize base url page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function normalizeBaseUrl(value: string | undefined, fallbackValue: string) { + const target = String(value || fallbackValue).trim() + return target.replace(/\/+$/, '') +} + +/** + * Purpose: DEFAULT_API_BASE_URL supports api.ts by holding or executing the default api base url page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DEFAULT_API_BASE_URL = import.meta.env.DEV ? '/api' : 'https://yunail.art/api' +/** + * Purpose: DEFAULT_ADMIN_API_BASE_URL supports api.ts by holding or executing the default admin api base url page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DEFAULT_ADMIN_API_BASE_URL = import.meta.env.DEV ? '/admin/api' : 'https://yunail.art/admin/api' + +/** + * Purpose: API_CONFIG supports api.ts by holding or executing the api config page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const API_CONFIG = { + mode: import.meta.env.MODE, + apiBaseUrl: normalizeBaseUrl(import.meta.env.VITE_API_BASE_URL, DEFAULT_API_BASE_URL), + adminApiBaseUrl: normalizeBaseUrl(import.meta.env.VITE_ADMIN_API_BASE_URL, DEFAULT_ADMIN_API_BASE_URL) +} + +/** + * Purpose: API_BASE_URL supports api.ts by holding or executing the api base url page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const API_BASE_URL = API_CONFIG.apiBaseUrl +/** + * Purpose: ADMIN_API_BASE_URL supports api.ts by holding or executing the admin api base url page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ADMIN_API_BASE_URL = API_CONFIG.adminApiBaseUrl diff --git a/FM-Frontend/src/config/brand.ts b/FM-Frontend/src/config/brand.ts new file mode 100644 index 00000000..f595b4ad --- /dev/null +++ b/FM-Frontend/src/config/brand.ts @@ -0,0 +1,12 @@ +function normalizeBrandValue(value: string | undefined, fallbackValue: string): string { + const target = String(value || fallbackValue).trim() + return target || fallbackValue +} + +export const BRAND_CONFIG = { + appName: normalizeBrandValue(import.meta.env.VITE_APP_NAME, '甲屿设计师'), + appNameEn: normalizeBrandValue(import.meta.env.VITE_APP_NAME_EN, 'Jiayu Designer'), + appTitle: normalizeBrandValue(import.meta.env.VITE_APP_TITLE, '甲屿设计师'), + adminAppName: normalizeBrandValue(import.meta.env.VITE_ADMIN_APP_NAME, '甲屿设计师管理台'), + appShortName: normalizeBrandValue(import.meta.env.VITE_APP_SHORT_NAME, 'YN') +} diff --git a/FM-Frontend/src/constants/index.ts b/FM-Frontend/src/constants/index.ts new file mode 100644 index 00000000..fbc95f60 --- /dev/null +++ b/FM-Frontend/src/constants/index.ts @@ -0,0 +1,15 @@ +/** + * Purpose: DEFAULT_AVATAR supports index.ts by holding or executing the default avatar page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const DEFAULT_AVATAR = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default' +/** + * Purpose: DEFAULT_PRODUCT_IMAGE supports index.ts by holding or executing the default product image page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const DEFAULT_PRODUCT_IMAGE = '/assets/images/default-product.png' +/** + * Purpose: DEFAULT_SHOP_IMAGE supports index.ts by holding or executing the default shop image page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const DEFAULT_SHOP_IMAGE = '/assets/images/default-shop.png' diff --git a/FM-Frontend/src/main.ts b/FM-Frontend/src/main.ts new file mode 100644 index 00000000..46f98f7b --- /dev/null +++ b/FM-Frontend/src/main.ts @@ -0,0 +1,26 @@ +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import 'ant-design-vue/dist/reset.css' +import './styles/admin-mobile.css' +import './style.css' +import App from './App.vue' +import router from './router' +import { BRAND_CONFIG } from './config/brand' + +document.title = BRAND_CONFIG.appTitle + +/** + * Purpose: app supports main.ts by holding or executing the app page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const app = createApp(App) +/** + * Purpose: pinia supports main.ts by holding or executing the pinia page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const pinia = createPinia() + +app.use(pinia) +app.use(router) + +app.mount('#app') diff --git a/FM-Frontend/src/router/index.ts b/FM-Frontend/src/router/index.ts new file mode 100644 index 00000000..7443a1ad --- /dev/null +++ b/FM-Frontend/src/router/index.ts @@ -0,0 +1,371 @@ +import { createRouter, createWebHistory } from 'vue-router' +import { + canAccessAdminRoute, + clearAdminBootstrapSession, + ensureAdminAuthBootstrap, + getAdminBootstrapSnapshot, + resolveAdminLandingPath, +} from '@/utils/admin-auth-bootstrap' + +/** + * Purpose: router supports index.ts by holding or executing the router page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const router = createRouter({ + history: createWebHistory(import.meta.env.BASE_URL), + routes: [ + { + path: '/', + name: 'auth', + component: () => import('../views/AuthView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/home', + name: 'home', + component: () => import('../views/HomeView.vue'), + meta: { requiresAuth: false, isAdmin: false } + }, + { + path: '/products', + name: 'products', + component: () => import('../views/ProductListView.vue'), + meta: { requiresAuth: false, isAdmin: false } + }, + { + path: '/product/:id', + name: 'product-detail', + component: () => import('../views/ProductDetailView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/cart', + name: 'cart', + component: () => import('../views/CartView.vue'), + meta: { requiresAuth: true, isAdmin: false } + }, + { + path: '/profile', + name: 'profile', + component: () => import('../views/ProfileView.vue'), + meta: { requiresAuth: true, isAdmin: false } + }, + { + path: '/shop/:id', + name: 'shop-detail', + component: () => import('../views/ShopDetailView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/shop/:shopId/artists', + name: 'shop-artists', + component: () => import('../views/ArtistListView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/artist/:id', + name: 'artist-profile', + component: () => import('../views/ArtistProfileView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/wishlist', + name: 'wishlist', + component: () => import('../views/WishlistView.vue'), + meta: { requiresAuth: true, isAdmin: false } + }, + { + path: '/orders', + name: 'orders', + component: () => import('../views/OrderView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/orders/:id', + name: 'order-detail', + component: () => import('../views/OrderDetailView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/after-sales', + name: 'after-sales', + component: () => import('../views/AfterSalesView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/after-sale/apply', + name: 'after-sale-apply', + component: () => import('../views/AfterSaleApplyView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/service-progress', + name: 'service-progress', + component: () => import('../views/ServiceProgressView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/help', + name: 'help', + component: () => import('../views/HelpView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + }, + { + path: '/artist-orders', + name: 'artist-orders', + component: () => import('../views/ArtistOrderView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' } + }, + { + path: '/artist-calendar', + name: 'artist-calendar', + component: () => import('../views/ArtistCalendarView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' } + }, + { + path: '/settings', + name: 'settings', + component: () => import('../views/SettingsView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/settings/account', + name: 'account-settings', + component: () => import('../views/AccountSettingsView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/settings/password', + name: 'password-settings', + component: () => import('../views/PasswordSettingsView.vue'), + meta: { requiresAuth: true, hideNav: true, isAdmin: false } + }, + { + path: '/coupons', + name: 'coupons', + component: () => import('../views/CouponView.vue'), + meta: { requiresAuth: true, isAdmin: false, hideNav: true } + }, + { + path: '/vip-center', + name: 'vip-center', + component: () => import('../views/VipCenterView.vue'), + meta: { requiresAuth: true, isAdmin: false, hideNav: true } + }, + { + path: '/notifications', + name: 'notifications', + component: () => import('../views/NotificationsView.vue'), + meta: { requiresAuth: true, isAdmin: false, hideNav: true } + }, + { + path: '/admin/login', + name: 'admin-login', + component: () => import('../views/admin/AdminLoginView.vue'), + meta: { requiresAuth: false, isAdmin: true, hideNav: true } + }, + { + path: '/admin', + component: () => import('../views/admin/AdminLayout.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true }, + children: [ + { + path: '', + name: 'admin', + component: () => import('../views/admin/HomeView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true } + }, + { + path: 'dashboard', + name: 'admin-dashboard', + component: () => import('../views/admin/DashboardView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'dashboard:view' } + }, + { + path: 'users', + name: 'admin-users', + component: () => import('../views/admin/UsersView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:view' } + }, + { + path: 'products', + name: 'admin-products', + component: () => import('../views/admin/ProductsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'product:view' } + }, + { + path: 'coupons', + name: 'admin-coupons', + component: () => import('../views/admin/CouponsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'coupon:view' } + }, + { + path: 'comments', + name: 'admin-comments', + component: () => import('../views/admin/CommentsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'comment:view' } + }, + { + path: 'shops', + name: 'admin-shops', + component: () => import('../views/admin/ShopsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'shop:view' } + }, + { + path: 'permissions', + name: 'admin-permissions', + component: () => import('../views/admin/PermissionsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'permission:view' } + }, + { + path: 'orders', + name: 'admin-orders', + component: () => import('../views/admin/OrdersView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' } + }, + { + path: 'schedules', + name: 'admin-schedules', + component: () => import('../views/admin/SchedulesView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'schedule:view' } + }, + { + path: 'after-sales', + name: 'admin-after-sales', + component: () => import('../views/admin/AfterSalesView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'after_sale:view' } + }, + { + path: 'inventory', + name: 'admin-inventory', + component: () => import('../views/admin/InventoryView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'inventory:view' } + }, + { + path: 'campaigns', + name: 'admin-campaigns', + component: () => import('../views/admin/CampaignsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'campaign:view' } + }, + { + path: 'manage', + name: 'admin-manage', + component: () => import('../views/admin/ManageView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true } + }, + { + path: 'profile', + name: 'admin-profile', + component: () => import('../views/admin/ProfileView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true } + }, + { + path: 'tags', + name: 'admin-tags', + component: () => import('../views/admin/TagsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'tag:view' } + }, + { + path: 'nail-artists', + name: 'admin-nail-artists', + component: () => import('../views/admin/NailArtistsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'nail_artist:view' } + }, + { + path: 'messages', + name: 'admin-messages', + component: () => import('../views/admin/SystemMessagesView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'message:view' } + }, + { + path: 'announcements', + name: 'admin-announcements', + component: () => import('../views/admin/AnnouncementsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'announcement:view' } + }, + { + path: 'vip-recharge-plans', + name: 'admin-vip-recharge-plans', + component: () => import('../views/admin/VipRechargePlansView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:vip:manage' } + }, + { + path: 'messagehub-push-configs', + name: 'admin-messagehub-push-configs', + component: () => import('../views/admin/MessageHubPushConfigsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'messagehub:config:manage' } + }, + { + path: 'legal-agreements', + name: 'admin-legal-agreements', + component: () => import('../views/admin/LegalAgreementsView.vue'), + meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'legal_agreement:manage' } + } + ] + }, + { + path: '/:pathMatch(.*)*', + name: 'not-found', + component: () => import('../views/NotFoundView.vue'), + meta: { requiresAuth: false, hideNav: true, isAdmin: false } + } + ] +}) + +router.beforeEach(async (to) => { + const isAdminRoute = Boolean(to.meta.isAdmin) + const requiresAuth = Boolean(to.meta.requiresAuth) + + if (isAdminRoute) { + const snapshot = getAdminBootstrapSnapshot() + + if (to.path === '/admin/login') { + if (!snapshot.token || !snapshot.userInfo) { + return true + } + + const state = await ensureAdminAuthBootstrap() + return state === 'ready' ? resolveAdminLandingPath() : true + } + + if (requiresAuth && (!snapshot.token || !snapshot.userInfo)) { + clearAdminBootstrapSession() + return '/admin/login' + } + + const bootstrapState = await ensureAdminAuthBootstrap() + if (bootstrapState !== 'ready') { + return '/admin/login' + } + + if (!canAccessAdminRoute(to.path, to.meta.permissionCode as string | undefined)) { + return resolveAdminLandingPath() + } + + return true + } + + const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') + + if (requiresAuth && !token) { + return '/' + } + + if (to.path === '/' && token) { + return '/home' + } + + if (requiresAuth && token) { + const userInfo = localStorage.getItem('userInfo') + if (!userInfo) { + localStorage.removeItem('accessToken') + localStorage.removeItem('refreshToken') + sessionStorage.removeItem('accessToken') + return '/' + } + } + + return true +}) + +export default router diff --git a/FM-Frontend/src/style.css b/FM-Frontend/src/style.css new file mode 100644 index 00000000..64e84400 --- /dev/null +++ b/FM-Frontend/src/style.css @@ -0,0 +1,342 @@ +:root { + --primary-color: #E8B4B8; + --theme-primary: #E8B4B8; + --theme-secondary: #C5A059; + --theme-accent: #4A443F; + --theme-neutral: #4A443F; + --theme-tertiary: #FDFBF9; + --theme-primary-action: #766361; + --theme-primary-soft: #FAEFF0; + --theme-secondary-soft: #EADCC2; + --theme-page-bg: #FDFBF9; + --theme-card-bg: #FFFFFF; + --theme-border: #F9EAEC; + --theme-gradient: linear-gradient(135deg, #766361 0%, #C5A059 100%); + --theme-gradient-soft: linear-gradient(145deg, #FFFFFF 0%, #EADCC2 58%, #F5E0E0 100%); + --theme-button-shadow: 0 12px 28px rgba(232, 180, 184, 0.26); + --theme-focus-shadow: 0 0 0 3px rgba(232, 180, 184, 0.2); + --theme-background-image: none; + --bg-color: #FDFBF9; + --secondary-bg-color: #EADCC2; + --surface-color: #FFFFFF; + --text-primary: #4A443F; + --text-secondary: #6B6662; + --border-radius-base: 10px; + --border-radius-large: 30px; + --frontend-min-safe-width: 320px; + --frontend-page-max-width: 430px; + --frontend-content-max-width: 1120px; + --admin-content-max-width: 1440px; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +img, +video, +canvas, +svg { + max-width: 100%; +} + +html, +body { + min-width: var(--frontend-min-safe-width); + overflow-x: hidden; +} + +body { + background: + radial-gradient(circle at 50% 0%, color-mix(in srgb, var(--theme-primary) 24%, transparent), transparent 34%), + linear-gradient(180deg, var(--theme-tertiary), color-mix(in srgb, var(--theme-secondary) 12%, var(--theme-tertiary))); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; + color: var(--text-primary); +} + +.mobile-container { + width: 100%; + min-width: var(--frontend-min-safe-width); + max-width: none; + margin: 0 auto; + min-height: 100vh; + background: + radial-gradient(circle at 82% 2%, color-mix(in srgb, var(--theme-primary) 30%, transparent), transparent 28%), + linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 98%, var(--theme-card-bg))), + var(--theme-background-image), + var(--bg-color); + background-size: auto, cover, cover, auto; + background-position: center top; + position: relative; + overflow-x: hidden; +} + +.fingertip-designer-page { + min-height: 100vh; + padding: 18px 18px calc(88px + env(safe-area-inset-bottom, 0px)); + color: var(--text-primary); + background: + linear-gradient(180deg, rgba(255, 255, 255, 0.7), rgba(253, 251, 249, 0.96)), + var(--theme-background-image), + var(--theme-page-bg); + background-size: cover, cover, auto; + background-position: center top; +} + +.fingertip-designer-page--no-nav { + padding-bottom: calc(28px + env(safe-area-inset-bottom, 0px)); +} + +.fingertip-designer-section { + margin-top: 22px; +} + +.fingertip-designer-section-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 16px; + margin-bottom: 14px; +} + +.fingertip-designer-kicker { + display: block; + color: var(--theme-primary-action); + font-size: 11px; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.fingertip-designer-title { + display: block; + color: var(--text-primary); + font-size: 21px; + font-weight: 760; + line-height: 1.18; +} + +.fingertip-designer-subtitle { + display: block; + margin-top: 6px; + color: var(--text-secondary); + font-size: 13px; + line-height: 1.65; +} + +.fingertip-designer-glass-card { + overflow: hidden; + border: 1px solid rgba(255, 255, 255, 0.9); + border-radius: 24px; + background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); + box-shadow: 0 20px 44px rgba(74, 68, 63, 0.1); + backdrop-filter: blur(16px); +} + +.fingertip-designer-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 34px; + height: 34px; + border: 0; + border-radius: 999px; + color: var(--theme-neutral); + background: color-mix(in srgb, var(--theme-card-bg) 78%, transparent); + box-shadow: 0 10px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent); + cursor: pointer; + backdrop-filter: blur(14px); +} + +.fingertip-designer-icon-button:active { + transform: scale(0.96); +} + +.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .fingertip-designer-icon-button) :where(.anticon), +.app-container--phone-shell :where(.header, .shop-topbar, .detail-header, .artist-topbar, .artist-list-topbar, .auth-topbar, .not-found-topbar, .cart-topbar, .vip-header) :where(.ant-btn .anticon, button .anticon), +.app-container--admin :where(.mobile-icon-btn, .mobile-avatar-btn) :where(.anticon) { + font-size: 21px !important; + line-height: 1; +} + +.app-container--phone-shell :where(.bottom-nav .nav-icon) { + width: 40px; + height: 34px; +} + +.app-container--phone-shell :where(.bottom-nav .nav-icon .anticon) { + font-size: 25px !important; + line-height: 1; +} + +.app-container--admin :where(.mobile-tabbar__item .anticon) { + font-size: 21px !important; + line-height: 1; +} + +.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .fingertip-designer-icon-button, .bottom-nav .nav-icon) :where(.anticon svg), +.app-container--admin :where(.mobile-icon-btn, .mobile-avatar-btn, .mobile-tabbar__item) :where(.anticon svg) { + display: block; + width: 1em; + height: 1em; +} + +.fingertip-designer-page-titlebar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 18px 8px; +} + +.fingertip-designer-page-titlebar__title { + min-width: 0; + flex: 1; + text-align: center; + color: var(--text-primary); + font-size: 16px; + font-weight: 780; +} + +.fingertip-designer-status-chip { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 26px; + padding: 0 12px; + border: 1px solid var(--theme-border); + border-radius: 999px; + color: var(--theme-primary-action); + background: var(--theme-primary-soft); + font-size: 12px; + font-weight: 700; + white-space: nowrap; +} + +.fingertip-designer-bottom-action { + position: sticky; + bottom: 0; + z-index: 20; + display: flex; + gap: 12px; + margin: 24px -18px -18px; + padding: 14px 18px calc(14px + env(safe-area-inset-bottom, 0px)); + border-top: 1px solid var(--theme-border); + background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent); + backdrop-filter: blur(18px); +} + +.app-container--phone-shell :where(.ant-card) { + border-color: var(--theme-border); + border-radius: 24px; + background: rgba(255, 255, 255, 0.86); + box-shadow: 0 18px 42px rgba(74, 68, 63, 0.09); + backdrop-filter: blur(14px); +} + +.app-container--phone-shell :where(.ant-btn-primary) { + border-color: transparent; + background: var(--theme-gradient); + box-shadow: var(--theme-button-shadow); +} + +.app-container--phone-shell :where(.ant-btn-primary:hover, .ant-btn-primary:focus) { + border-color: transparent; + background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary)); +} + +.app-container--phone-shell :where(.ant-input, .ant-input-affix-wrapper, .ant-select-selector, .ant-picker) { + border-color: var(--theme-border); + border-radius: 14px; + background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent); +} + +.app-container--phone-shell :where(.ant-input:hover, .ant-input:focus, .ant-input-affix-wrapper:hover, .ant-input-affix-wrapper-focused, .ant-picker:hover, .ant-picker-focused) { + border-color: var(--theme-primary); + box-shadow: var(--theme-focus-shadow); +} + +.app-container--phone-shell :where(.ant-tag) { + border-radius: 999px; +} + +.app-container--phone-shell .header { + background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent); + border-bottom-color: var(--theme-border); + backdrop-filter: blur(18px); +} + +.fingertip-designer-phone-frame { + width: 100%; + min-width: var(--frontend-min-safe-width); + min-height: 100vh; + margin: 0 auto; + background: var(--theme-page-bg); + position: relative; +} + +.fingertip-designer-phone-frame--hidden-nav { + min-height: 100vh; +} + +@media (min-width: 768px) { + body { + background: + radial-gradient(circle at 18% 8%, rgba(254, 212, 136, 0.28), transparent 30%), + radial-gradient(circle at 82% 12%, rgba(232, 180, 184, 0.24), transparent 34%), + var(--secondary-bg-color); + } + + .app-container--phone-shell { + align-items: center; + padding: 0; + } + + .mobile-container { + max-width: var(--frontend-page-max-width); + } + + .fingertip-designer-phone-frame { + width: min(100%, var(--frontend-page-max-width)); + min-height: 100vh; + margin: 0 auto; + overflow: clip; + border: 1px solid rgba(212, 194, 195, 0.72); + border-radius: 32px; + box-shadow: 0 28px 80px rgba(74, 68, 63, 0.14); + } + + .fingertip-designer-phone-frame > .bottom-nav, + .fingertip-designer-phone-frame > .page-content .header, + .fingertip-designer-phone-frame > .page-content .header-bg, + .fingertip-designer-phone-frame > .page-content .gallery-header, + .fingertip-designer-phone-frame > .page-content .order-header { + left: 50%; + right: auto; + width: var(--frontend-page-max-width); + max-width: calc(100vw - 48px); + transform: translateX(-50%) translateZ(0); + } + + .fingertip-designer-phone-frame > .page-content .header, + .fingertip-designer-phone-frame > .page-content .header-bg, + .fingertip-designer-phone-frame > .page-content .gallery-header, + .fingertip-designer-phone-frame > .page-content .order-header { + top: 0; + } + + .fingertip-designer-phone-frame > .page-content .header, + .fingertip-designer-phone-frame > .page-content .gallery-header, + .fingertip-designer-phone-frame > .page-content .order-header { + border-top-left-radius: 32px; + border-top-right-radius: 32px; + } + + .fingertip-designer-phone-frame > .bottom-nav { + bottom: 0; + border-bottom-right-radius: 32px; + border-bottom-left-radius: 32px; + } +} diff --git a/FM-Frontend/src/styles/admin-mobile.css b/FM-Frontend/src/styles/admin-mobile.css new file mode 100644 index 00000000..ac04f13b --- /dev/null +++ b/FM-Frontend/src/styles/admin-mobile.css @@ -0,0 +1,349 @@ +:root { + --admin-mobile-ink: var(--text-primary); + --admin-mobile-surface: var(--theme-page-bg); + --admin-mobile-surface-alt: var(--theme-primary-soft); + --admin-mobile-card: var(--theme-card-bg); + --admin-mobile-border: var(--theme-border); + --admin-mobile-muted: var(--text-secondary); + --admin-mobile-accent: var(--theme-primary); + --admin-mobile-accent-strong: var(--theme-accent); + --admin-mobile-accent-soft: var(--theme-primary-soft); + --admin-mobile-shell-start: var(--theme-primary); + --admin-mobile-shell-mid: var(--theme-accent); + --admin-mobile-shell-end: color-mix(in srgb, var(--theme-accent) 78%, var(--text-primary)); + --admin-mobile-shell-glass: color-mix(in srgb, var(--theme-primary) 88%, transparent); + --admin-mobile-shell-soft: color-mix(in srgb, var(--theme-card-bg) 18%, transparent); + --admin-mobile-radius: 24px; + --admin-mobile-shadow: var(--theme-button-shadow); +} + +.admin-page-intro { + display: grid; + gap: 10px; + margin-bottom: 18px; + padding: 20px 18px; + color: var(--theme-card-bg); + background: + radial-gradient(circle at top right, color-mix(in srgb, var(--theme-card-bg) 20%, transparent), transparent 38%), + radial-gradient(circle at left top, color-mix(in srgb, var(--theme-secondary) 22%, transparent), transparent 42%), + linear-gradient( + 155deg, + var(--admin-mobile-shell-start) 0%, + var(--admin-mobile-shell-mid) 56%, + var(--admin-mobile-shell-end) 100% + ); + border-radius: 24px; + box-shadow: 0 18px 40px rgba(146, 103, 82, 0.2); +} + +.admin-page-intro__eyebrow { + font-size: 12px; + letter-spacing: 0.12em; + text-transform: uppercase; + color: rgba(255, 248, 241, 0.74); +} + +.admin-page-intro__title { + margin: 0; + font-size: clamp(20px, 4vw, 26px); + line-height: 1.08; + font-weight: 700; +} + +.admin-page-intro__subtitle { + margin: 0; + line-height: 1.65; + color: rgba(255, 248, 241, 0.82); +} + +.shops .admin-page-intro__subtitle, +.permissions .admin-page-intro__subtitle, +.orders .admin-page-intro__subtitle, +.nail-artists .admin-page-intro__subtitle { + display: none; +} + +.admin-page-intro__meta { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.admin-page-chip { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 34px; + padding: 0 12px; + border-radius: 999px; + background: color-mix(in srgb, var(--theme-card-bg) 16%, transparent); + color: var(--theme-card-bg); + font-size: 13px; +} + +.admin-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.admin-toolbar--stacked { + flex-direction: column; + align-items: stretch; +} + +.admin-toolbar__grow { + flex: 1; + min-width: 0; +} + +.admin-mobile-card-list { + display: grid; + gap: 14px; +} + +.admin-mobile-card { + padding: 16px; + background: var(--admin-mobile-card); + border: 1px solid var(--admin-mobile-border); + border-radius: 22px; + box-shadow: 0 12px 28px rgba(144, 103, 84, 0.09); +} + +.admin-mobile-card__cover { + width: 72px; + height: 72px; + border-radius: 18px; + object-fit: cover; + flex-shrink: 0; + background: var(--theme-primary-soft); +} + +.admin-mobile-card__cover--wide { + width: 100%; + height: 148px; + border-radius: 18px; +} + +.admin-mobile-card__head { + display: flex; + justify-content: space-between; + gap: 12px; +} + +.admin-mobile-card__head--media { + align-items: flex-start; +} + +.admin-mobile-card__body { + flex: 1; + min-width: 0; +} + +.admin-mobile-card__title { + font-size: 17px; + font-weight: 700; + line-height: 1.3; + color: var(--admin-mobile-ink); +} + +.admin-mobile-card__subtitle { + margin-top: 4px; + font-size: 13px; + color: var(--admin-mobile-muted); + line-height: 1.6; +} + +.admin-mobile-card__description { + margin-top: 10px; + color: var(--text-secondary); + line-height: 1.6; +} + +.admin-mobile-card__rows { + display: grid; + gap: 9px; + margin-top: 14px; +} + +.admin-mobile-card__row { + display: flex; + justify-content: space-between; + gap: 12px; + font-size: 13px; + color: var(--admin-mobile-muted); +} + +.admin-mobile-card__row span:first-child { + flex-shrink: 0; +} + +.admin-mobile-card__row strong, +.admin-mobile-card__row b { + min-width: 0; + color: var(--admin-mobile-ink); + font-weight: 600; + text-align: right; + word-break: normal; + overflow-wrap: break-word; +} + +.admin-mobile-card__actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 16px; +} + +.admin-mobile-card__badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 30px; + padding: 0 12px; + border-radius: 999px; + background: var(--admin-mobile-accent-soft); + color: var(--theme-accent); + font-size: 12px; + font-weight: 600; + white-space: nowrap; +} + +.admin-mobile-grid { + display: grid; + gap: 14px; +} + +.admin-mobile-grid--two { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.admin-mobile-stat { + padding: 16px; + background: var(--admin-mobile-card); + border: 1px solid var(--admin-mobile-border); + border-radius: 20px; + box-shadow: 0 10px 24px rgba(144, 103, 84, 0.08); +} + +.admin-mobile-stat__label { + font-size: 12px; + color: var(--admin-mobile-muted); +} + +.admin-mobile-stat__value { + margin-top: 10px; + font-size: 24px; + font-weight: 700; + color: var(--admin-mobile-ink); +} + +.admin-mobile-section-card { + padding: 18px; + background: var(--admin-mobile-card); + border: 1px solid var(--admin-mobile-border); + border-radius: 22px; + box-shadow: 0 12px 28px rgba(144, 103, 84, 0.09); +} + +.admin-mobile-section-card__title { + font-size: 17px; + font-weight: 700; + color: var(--admin-mobile-ink); +} + +.admin-mobile-section-card__subtitle { + margin-top: 6px; + color: var(--admin-mobile-muted); + line-height: 1.65; +} + +.admin-mobile-modal .ant-modal { + top: 0 !important; + max-width: 100dvw !important; + width: 100dvw !important; + margin: 0; + padding-bottom: 0; +} + +.admin-mobile-modal .ant-modal-content { + min-height: 100vh; + border-radius: 0; + padding: 0; +} + +.admin-mobile-modal .ant-modal-header { + position: sticky; + top: 0; + z-index: 2; + padding: 18px 18px 14px; + background: var(--theme-card-bg); + border-bottom: 1px solid var(--admin-mobile-border); +} + +.admin-mobile-modal .ant-modal-title { + padding-right: 24px; + font-size: 18px; + font-weight: 700; + color: var(--admin-mobile-ink); +} + +.admin-mobile-modal .ant-modal-close { + top: 12px; + inset-inline-end: 12px; +} + +.admin-mobile-modal .ant-modal-body { + padding: 16px 16px 104px; +} + +.admin-mobile-modal .ant-modal-footer { + position: sticky; + bottom: 0; + z-index: 2; + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 14px 16px calc(14px + env(safe-area-inset-bottom)); + background: color-mix(in srgb, var(--theme-card-bg) 94%, transparent); + border-top: 1px solid var(--admin-mobile-border); + backdrop-filter: blur(14px); +} + +.admin-mobile-fab { + position: fixed; + right: 18px; + bottom: var(--admin-mobile-fab-bottom, calc(96px + env(safe-area-inset-bottom))); + z-index: 120; + width: 56px; + height: 56px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + border-radius: 999px; + background: var(--theme-gradient); + color: #ffffff; + box-shadow: var(--theme-button-shadow); +} + +.admin-mobile-fab .anticon { + font-size: 22px; +} + +@media (max-width: 960px) { + body { + background: var(--admin-mobile-surface); + } + + .admin-mobile-grid--two { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (max-width: 640px) { + .admin-mobile-grid--two { + grid-template-columns: 1fr; + } +} diff --git a/FM-Frontend/src/styles/bottom-nav.css b/FM-Frontend/src/styles/bottom-nav.css new file mode 100644 index 00000000..b4571042 --- /dev/null +++ b/FM-Frontend/src/styles/bottom-nav.css @@ -0,0 +1,12 @@ +.bottom-nav { + position: fixed; + bottom: 0; + width: 100%; + height: 60px; + background: white; + display: flex; + justify-content: space-around; + align-items: center; + box-shadow: 0 -2px 10px rgba(0,0,0,0.05); + z-index: 1000; +} diff --git a/FM-Frontend/src/utils/account.ts b/FM-Frontend/src/utils/account.ts new file mode 100644 index 00000000..a899a592 --- /dev/null +++ b/FM-Frontend/src/utils/account.ts @@ -0,0 +1,22 @@ +/** + * Purpose: ACCOUNT_REGEX supports account.ts by holding or executing the account regex page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/ +/** + * Purpose: ACCOUNT_SANITIZE_REGEX supports account.ts by holding or executing the account sanitize regex page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g + +/** + * Purpose: ACCOUNT_RULE_MESSAGE supports account.ts by holding or executing the account rule message page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字' + +/** + * Purpose: sanitizeAccountInput supports account.ts by holding or executing the sanitize account input page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '') diff --git a/FM-Frontend/src/utils/action-loading.ts b/FM-Frontend/src/utils/action-loading.ts new file mode 100644 index 00000000..6a0edb32 --- /dev/null +++ b/FM-Frontend/src/utils/action-loading.ts @@ -0,0 +1,76 @@ +/** + * Purpose: LoadingInstance supports action-loading.ts by holding or executing the loading instance page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +import { ElLoading, type LoadingInstance } from 'element-plus' +import 'element-plus/es/components/loading/style/css' + +/** + * Purpose: GlobalLoadingOptions supports action-loading.ts by holding or executing the global loading options page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface GlobalLoadingOptions { + text?: string + lock?: boolean +} + +/** + * Purpose: activeLoadingCount supports action-loading.ts by holding or executing the active loading count page or API role. + * Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow. + */ +let activeLoadingCount = 0 +let loadingInstance: LoadingInstance | null = null + +/** + * Purpose: openGlobalLoading supports action-loading.ts by holding or executing the open global loading page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const openGlobalLoading = (options?: GlobalLoadingOptions) => { + activeLoadingCount += 1 + + if (typeof window === 'undefined' || loadingInstance) { + return + } + + loadingInstance = ElLoading.service({ + lock: options?.lock ?? true, + text: options?.text ?? '\u52a0\u8f7d\u4e2d', + background: 'rgba(255, 255, 255, 0.72)' + }) +} + +/** + * Purpose: closeGlobalLoading supports action-loading.ts by holding or executing the close global loading page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const closeGlobalLoading = () => { + activeLoadingCount = Math.max(0, activeLoadingCount - 1) + + if (activeLoadingCount > 0) { + return + } + + loadingInstance?.close() + loadingInstance = null +} + +/** + * Purpose: runWithGlobalLoading supports action-loading.ts by holding or executing the run with global loading page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const runWithGlobalLoading = async ( + task: (() => Promise) | Promise, + options?: GlobalLoadingOptions +) => { + openGlobalLoading(options) + + try { + if (typeof task === 'function') { + return await task() + } + + return await task + } finally { + closeGlobalLoading() + } +} diff --git a/FM-Frontend/src/utils/admin-auth-bootstrap.ts b/FM-Frontend/src/utils/admin-auth-bootstrap.ts new file mode 100644 index 00000000..524b832d --- /dev/null +++ b/FM-Frontend/src/utils/admin-auth-bootstrap.ts @@ -0,0 +1,166 @@ +import { computed, ref } from 'vue' +import { + clearAdminSessionStorage, + getAdminAccessToken, + isBootstrapAdminUser, + loadCachedAdminUserInfo, +} from '@/utils/admin-session' +import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation' +import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' +import { + clearStoredPermissions, + fetchUserPermissionsStrict, + getStoredUserPermissions, +} from '@/utils/permission' + + +/** + * Purpose: AuthBootstrapState supports admin-auth-bootstrap.ts by holding or executing the auth bootstrap state page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +export type AuthBootstrapState = 'pending' | 'ready' | 'invalid' + +/** + * Purpose: adminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the admin bootstrap state page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const adminBootstrapState = ref('pending') +let bootstrapPromise: Promise | null = null + + +/** + * Purpose: useAdminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the use admin bootstrap state page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const useAdminBootstrapState = () => computed(() => adminBootstrapState.value) + +/** + * Purpose: invalidateAdminBootstrap supports admin-auth-bootstrap.ts by holding or executing the invalidate admin bootstrap page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const invalidateAdminBootstrap = () => { + adminBootstrapState.value = 'pending' + bootstrapPromise = null +} + +/** + * Purpose: clearAdminBootstrapSession supports admin-auth-bootstrap.ts by holding or executing the clear admin bootstrap session page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const clearAdminBootstrapSession = () => { + clearAdminSessionStorage() + clearStoredPermissions() + adminBootstrapState.value = 'invalid' + bootstrapPromise = null +} + +/** + * Purpose: getAdminBootstrapSnapshot supports admin-auth-bootstrap.ts by holding or executing the get admin bootstrap snapshot page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminBootstrapSnapshot = () => { + const userInfo = loadCachedAdminUserInfo() + return { + token: getAdminAccessToken(), + userInfo, + isBootstrapAdmin: isBootstrapAdminUser(userInfo), + isPlatformAdmin: Number(userInfo?.type) === 4, + permissions: getStoredUserPermissions() || [], + } +} + +/** + * Purpose: hasAdminPermission supports admin-auth-bootstrap.ts by holding or executing the has admin permission page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const hasAdminPermission = (permissionCode?: string) => { + if (!permissionCode) { + return true + } + + const snapshot = getAdminBootstrapSnapshot() + if (snapshot.isBootstrapAdmin || (snapshot.isPlatformAdmin && isAllowedForShoplessPlatformAdmin(permissionCode))) { + return isAllowedForShoplessPlatformAdmin(permissionCode) + } + + return snapshot.permissions.includes(permissionCode) +} + +/** + * Purpose: resolveAdminLandingPath supports admin-auth-bootstrap.ts by holding or executing the resolve admin landing path page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const resolveAdminLandingPath = () => { + const snapshot = getAdminBootstrapSnapshot() + if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) { + return '/admin' + } + if (snapshot.isBootstrapAdmin) { + return ADMIN_DASHBOARD_PATH + } + + const matchedRoute = adminPermissionRouteMap.find(item => snapshot.permissions.includes(item.code)) + return matchedRoute?.path || '/admin' +} + +/** + * Purpose: canAccessAdminRoute supports admin-auth-bootstrap.ts by holding or executing the can access admin route page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const canAccessAdminRoute = (path: string, permissionCode?: string) => { + const snapshot = getAdminBootstrapSnapshot() + if (snapshot.userInfo?.shopAuthorizationExpired && snapshot.userInfo?.type !== 4) { + return path === '/admin' || path === '/admin/profile' + } + if (snapshot.isBootstrapAdmin) { + return hasAdminPermission(permissionCode) + } + + return hasAdminPermission(permissionCode) +} + +/** + * Purpose: ensureAdminAuthBootstrap supports admin-auth-bootstrap.ts by holding or executing the ensure admin auth bootstrap page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const ensureAdminAuthBootstrap = async (force = false): Promise => { + const snapshot = getAdminBootstrapSnapshot() + if (!snapshot.token || !snapshot.userInfo) { + clearAdminBootstrapSession() + return 'invalid' + } + + if (snapshot.isBootstrapAdmin) { + clearStoredPermissions() + adminBootstrapState.value = 'ready' + bootstrapPromise = null + return 'ready' + } + + const cachedPermissions = getStoredUserPermissions() + if (!force && cachedPermissions) { + adminBootstrapState.value = 'ready' + return 'ready' + } + + if (!force && bootstrapPromise) { + return bootstrapPromise + } + + adminBootstrapState.value = 'pending' + bootstrapPromise = (async () => { + try { + await fetchUserPermissionsStrict() + adminBootstrapState.value = 'ready' + return 'ready' as AuthBootstrapState + } catch (error) { + console.error('Failed to bootstrap admin permissions:', error) + clearAdminBootstrapSession() + return 'invalid' as AuthBootstrapState + } finally { + bootstrapPromise = null + } + })() + + return bootstrapPromise +} diff --git a/FM-Frontend/src/utils/admin-image-assets.test.ts b/FM-Frontend/src/utils/admin-image-assets.test.ts new file mode 100644 index 00000000..797c76e4 --- /dev/null +++ b/FM-Frontend/src/utils/admin-image-assets.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest' +import { + buildAdminUploadFileList, + buildSignedImageUrlMap, + getRecordImageUrls, + resolveSignedImageUrls +} from './admin-image-assets' + +vi.mock('@/utils/signed-image-cache', () => ({ + parseImageFileIds: (value?: string | null) => String(value || '').split(',').map(id => id.trim()).filter(Boolean), + getCachedSignedImageUrl: async (fileId: string | number | null | undefined, fallback = '') => + fileId ? `signed-${fileId}` : fallback, + getCachedSignedImageUrls: async (fileIds: Array, fallback = '') => { + const urls = fileIds.filter(Boolean).map(fileId => `signed-${fileId}`) + return urls.length ? urls : (fallback ? [fallback] : []) + } +})) + +describe('admin-image-assets', () => { + it('resolves comma separated image ids with fallback policy', async () => { + await expect(resolveSignedImageUrls('1, 2,,3', 'fallback.png', true)).resolves.toEqual([ + 'signed-1', + 'signed-2', + 'signed-3' + ]) + await expect(resolveSignedImageUrls('', 'fallback.png', true)).resolves.toEqual(['fallback.png']) + await expect(resolveSignedImageUrls('', 'fallback.png', false)).resolves.toEqual([]) + }) + + it('builds image url maps and respects cancellation', async () => { + await expect(buildSignedImageUrlMap( + [{ id: 7, imageFileIds: '10,11' }], + 'imageFileIds', + 'fallback.png', + true, + () => false + )).resolves.toEqual({ 7: ['signed-10', 'signed-11'] }) + + await expect(buildSignedImageUrlMap( + [{ id: 7, imageFileIds: '10,11' }], + 'imageFileIds', + 'fallback.png', + true, + () => true + )).resolves.toBeNull() + }) + + it('returns mapped record images or fallback images', () => { + expect(getRecordImageUrls({ id: 1 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['a.png']) + expect(getRecordImageUrls({ id: 2 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['fallback.png']) + }) + + it('builds upload file list from ids', async () => { + await expect(buildAdminUploadFileList(['8', ' 9 '], '图片', 'fallback.png')).resolves.toEqual([ + { uid: '8', fileId: '8', name: '图片1', status: 'done', url: 'signed-8' }, + { uid: '9', fileId: '9', name: '图片2', status: 'done', url: 'signed-9' } + ]) + }) +}) diff --git a/FM-Frontend/src/utils/admin-image-assets.ts b/FM-Frontend/src/utils/admin-image-assets.ts new file mode 100644 index 00000000..7d92bf09 --- /dev/null +++ b/FM-Frontend/src/utils/admin-image-assets.ts @@ -0,0 +1,104 @@ +import { + getCachedSignedImageUrl, + getCachedSignedImageUrls, + parseImageFileIds, + refreshCachedSignedImageUrl +} from '@/utils/signed-image-cache' +import type { IdType } from '@/utils/id' + +export interface AdminUploadFileItem { + uid: string + fileId: string + name: string + status: 'done' + url: string +} + +export type SignedImageRecord = { + id?: IdType + imageFileIds?: string + coverImageFileId?: string +} + +export type ImageFieldName = 'imageFileIds' | 'coverImageFileId' + +export const resolveSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback: string +): Promise => getCachedSignedImageUrl(fileId, fallback, 'admin') + +export const refreshSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback: string +): Promise => refreshCachedSignedImageUrl(fileId, fallback, 'admin') + +export const resolveSignedImageUrls = async ( + fileIdsValue: string | null | undefined, + fallback: string, + emptyFallback: boolean +): Promise => { + const fileIds = parseImageFileIds(fileIdsValue) + if (!fileIds.length) { + return emptyFallback ? [fallback] : [] + } + return getCachedSignedImageUrls(fileIds, fallback, 'admin') +} + +export const buildSignedImageUrlMap = async ( + records: TRecord[], + fieldName: ImageFieldName, + fallback: string, + emptyFallback: boolean, + isCancelled: () => boolean +): Promise | null> => { + const nextImageUrls: Record = {} + + for (const record of records) { + if (isCancelled()) { + return null + } + if (record.id === undefined || record.id === null) { + continue + } + + nextImageUrls[String(record.id)] = await resolveSignedImageUrls(record[fieldName], fallback, emptyFallback) + } + + return nextImageUrls +} + +export const getRecordImageUrls = ( + record: TRecord, + imageUrlMap: Record, + fallbackImages: string[] +): string[] => { + if (record.id === undefined || record.id === null) { + return fallbackImages + } + return imageUrlMap[String(record.id)] || fallbackImages +} + +export const buildAdminUploadFileList = async ( + fileIds: string[], + fileNamePrefix: string, + fallback: string +): Promise => { + const fileList: AdminUploadFileItem[] = [] + + for (const [index, fileId] of fileIds.entries()) { + const normalizedFileId = fileId.trim() + if (!normalizedFileId) { + continue + } + const url = await resolveSignedImageUrl(normalizedFileId, fallback) + fileList.push({ + uid: normalizedFileId, + fileId: normalizedFileId, + name: `${fileNamePrefix}${index + 1}`, + status: 'done', + url + }) + } + + return fileList +} diff --git a/FM-Frontend/src/utils/admin-session.ts b/FM-Frontend/src/utils/admin-session.ts new file mode 100644 index 00000000..58b7285a --- /dev/null +++ b/FM-Frontend/src/utils/admin-session.ts @@ -0,0 +1,78 @@ +import type { IdType } from '@/utils/id' + +/** + * Purpose: AdminCachedUserInfo supports admin-session.ts by holding or executing the admin cached user info page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface AdminCachedUserInfo { + id?: IdType + type?: number + account?: string + nickname?: string + avatar?: string + shopId?: IdType + shopName?: string + shopAuthorizationExpireTime?: string + shopAuthorizationExpired?: boolean + shopIds?: IdType[] + shopNames?: string[] +} + +/** + * Purpose: getAdminAccessToken supports admin-session.ts by holding or executing the get admin access token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminAccessToken = () => + localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken') + +/** + * Purpose: getAdminRefreshToken supports admin-session.ts by holding or executing the get admin refresh token page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminRefreshToken = () => + localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken') + +/** + * Purpose: loadCachedAdminUserInfo supports admin-session.ts by holding or executing the load cached admin user info page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const loadCachedAdminUserInfo = (): AdminCachedUserInfo | null => { + const raw = localStorage.getItem('adminUserInfo') + if (!raw) { + return null + } + + try { + return JSON.parse(raw) as AdminCachedUserInfo + } catch (error) { + console.error('Failed to parse cached admin user info:', error) + localStorage.removeItem('adminUserInfo') + return null + } +} + +/** + * Purpose: isBootstrapAdminUser supports admin-session.ts by holding or executing the is bootstrap admin user page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isBootstrapAdminUser = (userInfo?: AdminCachedUserInfo | null) => + userInfo?.type === 4 && !userInfo?.shopId + +/** + * Purpose: isPlatformOverviewAdminUser supports admin-session.ts by holding or executing the is platform overview admin user page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isPlatformOverviewAdminUser = isBootstrapAdminUser + +/** + * Purpose: clearAdminSessionStorage supports admin-session.ts by holding or executing the clear admin session storage page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const clearAdminSessionStorage = () => { + localStorage.removeItem('adminAccessToken') + localStorage.removeItem('adminRefreshToken') + localStorage.removeItem('adminUserInfo') + localStorage.removeItem('userPermissions') + sessionStorage.removeItem('adminAccessToken') + sessionStorage.removeItem('adminRefreshToken') +} diff --git a/FM-Frontend/src/utils/admin-table.test.ts b/FM-Frontend/src/utils/admin-table.test.ts new file mode 100644 index 00000000..380a01eb --- /dev/null +++ b/FM-Frontend/src/utils/admin-table.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { applyAdminTablePaginationChange, createAdminPagination } from './admin-table' + +describe('admin-table', () => { + it('creates default pagination state', () => { + expect(createAdminPagination().current).toBe(1) + expect(createAdminPagination().pageSize).toBe(10) + }) + + it('applies pagination changes', () => { + const pagination = createAdminPagination() + const nextPagination = applyAdminTablePaginationChange(pagination, { current: 3, pageSize: 20 }) + expect(nextPagination.current).toBe(3) + expect(nextPagination.pageSize).toBe(20) + expect(pagination.current).toBe(1) + }) +}) diff --git a/FM-Frontend/src/utils/admin-table.ts b/FM-Frontend/src/utils/admin-table.ts new file mode 100644 index 00000000..1bee7309 --- /dev/null +++ b/FM-Frontend/src/utils/admin-table.ts @@ -0,0 +1,35 @@ +export interface AdminPaginationState { + current: number + pageSize: number + total: number + showSizeChanger: boolean + showQuickJumper: boolean + showTotal: (total: number) => string +} + +export interface AdminTablePaginationChange { + current?: number + pageSize?: number +} + +export interface AdminPaginationPageChange { + current: number + pageSize: number +} + +export const createAdminPagination = (): AdminPaginationState => ({ + current: 1, + pageSize: 10, + total: 0, + showSizeChanger: true, + showQuickJumper: true, + showTotal: (total: number) => `共 ${total} 条` +}) + +export const applyAdminTablePaginationChange = ( + pagination: AdminPaginationState, + change: AdminTablePaginationChange +): AdminPaginationPageChange => ({ + current: change.current || pagination.current, + pageSize: change.pageSize || pagination.pageSize +}) diff --git a/FM-Frontend/src/utils/admin-upload-file.test.ts b/FM-Frontend/src/utils/admin-upload-file.test.ts new file mode 100644 index 00000000..7e0615e3 --- /dev/null +++ b/FM-Frontend/src/utils/admin-upload-file.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { getUploadResponse, resolveUploadedFileId } from './admin-upload-file' + +describe('admin-upload-file', () => { + it('resolves uploaded file id from response or file shape', () => { + expect(resolveUploadedFileId({ response: { id: 7 } })).toBe('7') + expect(resolveUploadedFileId({ fileId: '8' })).toBe('8') + expect(resolveUploadedFileId({ uid: '9' })).toBe('9') + expect(getUploadResponse(null)).toBeNull() + }) +}) diff --git a/FM-Frontend/src/utils/admin-upload-file.ts b/FM-Frontend/src/utils/admin-upload-file.ts new file mode 100644 index 00000000..8c00fe4f --- /dev/null +++ b/FM-Frontend/src/utils/admin-upload-file.ts @@ -0,0 +1,49 @@ +export interface AdminUploadResponseData { + id?: string | number + fileId?: string | number +} + +export interface AdminUploadResponse { + id?: string | number + fileId?: string | number + data?: AdminUploadResponseData +} + +export interface AdminUploadFileLike { + uid?: string | number + url?: string + thumbUrl?: string + fileId?: string | number + response?: AdminUploadResponse +} + +export interface AdminUploadTaskFile extends File { + uid: string +} + +export const getUploadResponse = (file: AdminUploadFileLike | null | undefined): AdminUploadResponse | null => { + if (!file || typeof file !== 'object') { + return null + } + return file.response || null +} + +export const resolveUploadedFileId = (file: AdminUploadFileLike | null | undefined): string => { + const response = getUploadResponse(file) + const responseId = response?.id ?? response?.data?.id ?? response?.fileId ?? response?.data?.fileId ?? file?.fileId + if (responseId !== undefined && responseId !== null && responseId !== '') { + return String(responseId) + } + + const fileUid = String(file?.uid || '') + if (/^\d+$/.test(fileUid)) { + return fileUid + } + + const fileUrl = String(file?.url || '') + if (/^\d+$/.test(fileUrl)) { + return fileUrl + } + + return '' +} diff --git a/FM-Frontend/src/utils/buy-now.test.ts b/FM-Frontend/src/utils/buy-now.test.ts new file mode 100644 index 00000000..0a6f7937 --- /dev/null +++ b/FM-Frontend/src/utils/buy-now.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' + +import { BUY_NOW_MODE, getBuyNowProductIdFromQuery, isBuyNowCartItem } from './buy-now' + +describe('buy-now checkout mode', () => { + it('reads the target product id only when cart query is in buyNow mode', () => { + expect(getBuyNowProductIdFromQuery({ mode: BUY_NOW_MODE, productId: '1001' })).toBe('1001') + expect(getBuyNowProductIdFromQuery({ mode: 'cart', productId: '1001' })).toBe('') + }) + + it('uses the first query value when vue-router provides array values', () => { + expect(getBuyNowProductIdFromQuery({ mode: [BUY_NOW_MODE], productId: ['2002', '3003'] })).toBe('2002') + }) + + it('matches numeric and string product ids for cart selection', () => { + expect(isBuyNowCartItem(1001, '1001')).toBe(true) + expect(isBuyNowCartItem('1002', '1001')).toBe(false) + }) +}) diff --git a/FM-Frontend/src/utils/buy-now.ts b/FM-Frontend/src/utils/buy-now.ts new file mode 100644 index 00000000..1a3bbd2e --- /dev/null +++ b/FM-Frontend/src/utils/buy-now.ts @@ -0,0 +1,15 @@ +export const BUY_NOW_MODE = 'buyNow' + +type QueryValue = string | string[] | null | undefined + +const firstQueryValue = (value: QueryValue) => Array.isArray(value) ? value[0] : value + +export const getBuyNowProductIdFromQuery = (query: Record) => { + const mode = firstQueryValue(query.mode as QueryValue) + const productId = firstQueryValue(query.productId as QueryValue) + return mode === BUY_NOW_MODE && productId ? String(productId) : '' +} + +export const isBuyNowCartItem = (itemProductId: unknown, buyNowProductId: string) => { + return Boolean(buyNowProductId) && String(itemProductId || '') === String(buyNowProductId) +} diff --git a/FM-Frontend/src/utils/cart-state.ts b/FM-Frontend/src/utils/cart-state.ts new file mode 100644 index 00000000..eee97584 --- /dev/null +++ b/FM-Frontend/src/utils/cart-state.ts @@ -0,0 +1,41 @@ +import { cartApi } from '@/api/cart' +import { toOptionalIdString } from '@/utils/id' + +/** + * Purpose: fetchCartProductIdSet supports cart-state.ts by holding or executing the fetch cart product id set page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const fetchCartProductIdSet = async () => { + try { + const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }> + return new Set( + (Array.isArray(response) ? response : []) + .map(item => toOptionalIdString(item && item.productId)) + .filter((id): id is string => Boolean(id)) + ) + } catch (error) { + return new Set() + } +} + +/** + * Purpose: hasCartProduct supports cart-state.ts by holding or executing the has cart product page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const hasCartProduct = (cartProductIdSet: Set, productId: unknown) => { + const normalizedId = toOptionalIdString(productId) + return Boolean(normalizedId && cartProductIdSet.has(normalizedId)) +} + +/** + * Purpose: withAddedCartProduct supports cart-state.ts by holding or executing the with added cart product page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const withAddedCartProduct = (cartProductIdSet: Set, productId: unknown) => { + const next = new Set(cartProductIdSet || []) + const normalizedId = toOptionalIdString(productId) + if (normalizedId) { + next.add(normalizedId) + } + return next +} diff --git a/FM-Frontend/src/utils/chunk-upload.test.ts b/FM-Frontend/src/utils/chunk-upload.test.ts new file mode 100644 index 00000000..f91fdffc --- /dev/null +++ b/FM-Frontend/src/utils/chunk-upload.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest' +import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload' + +const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', { + type: 'image/png', + lastModified: 1 +}) + +describe('chunk-upload', () => { + it('uploads chunks with the requested concurrency', async () => { + const releaseCallbacks: Array<() => void> = [] + let activeUploads = 0 + let maxActiveUploads = 0 + + const api: ChunkUploadApi = { + initUpload: vi.fn().mockResolvedValue({ + uploadId: 'upload-1', + chunkSize: 2, + totalChunks: 4, + uploadedChunks: [] + }), + uploadChunk: vi.fn((_payload, config) => { + activeUploads += 1 + maxActiveUploads = Math.max(maxActiveUploads, activeUploads) + config?.onUploadProgress?.({ loaded: 2, total: 2 } as never) + return new Promise(resolve => { + releaseCallbacks.push(() => { + activeUploads -= 1 + resolve(true) + }) + }) + }), + completeUpload: vi.fn().mockResolvedValue('done'), + cancelUpload: vi.fn() + } + + const task = createChunkUploadTask({ + file: createFile(8), + scene: 'test-image', + concurrency: 3, + api + }) + + await vi.waitFor(() => expect(maxActiveUploads).toBe(3)) + while (releaseCallbacks.length) { + releaseCallbacks.shift()?.() + await Promise.resolve() + } + + await expect(task.promise).resolves.toMatchObject({ + response: 'done', + uploadId: 'upload-1' + }) + expect(api.uploadChunk).toHaveBeenCalledTimes(4) + expect(api.completeUpload).toHaveBeenCalledWith('upload-1') + }) + + it('skips already uploaded chunks', async () => { + const api: ChunkUploadApi = { + initUpload: vi.fn().mockResolvedValue({ + uploadId: 'upload-2', + chunkSize: 2, + totalChunks: 3, + uploadedChunks: [0, 2] + }), + uploadChunk: vi.fn().mockResolvedValue(true), + completeUpload: vi.fn().mockResolvedValue('done') + } + + const task = createChunkUploadTask({ + file: createFile(6), + scene: 'test-image', + concurrency: 3, + api + }) + + await expect(task.promise).resolves.toMatchObject({ response: 'done' }) + expect(api.uploadChunk).toHaveBeenCalledTimes(1) + expect(api.uploadChunk).toHaveBeenCalledWith( + expect.objectContaining({ chunkIndex: 1 }), + expect.any(Object) + ) + }) +}) diff --git a/FM-Frontend/src/utils/chunk-upload.ts b/FM-Frontend/src/utils/chunk-upload.ts new file mode 100644 index 00000000..1cfc3bf1 --- /dev/null +++ b/FM-Frontend/src/utils/chunk-upload.ts @@ -0,0 +1,197 @@ +import type { AxiosProgressEvent } from 'axios' + +export interface ChunkUploadSession { + uploadId: string + chunkSize: number + totalChunks: number + uploadedChunks: number[] +} + +export interface ChunkUploadInitRequest { + fileName: string + fileSize: number + contentType: string + fileFingerprint: string + scene: string +} + +export interface ChunkUploadApi { + initUpload: (payload: ChunkUploadInitRequest) => Promise + uploadChunk: ( + payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => Promise + completeUpload: (uploadId: string) => Promise + cancelUpload?: (uploadId: string) => Promise +} + +export interface ChunkUploadOptions { + file: File + scene: string + api: ChunkUploadApi + concurrency: number + preprocessFile?: (file: File) => Promise + onProgress?: (percent: number) => void +} + +export interface ChunkUploadResult { + response: TResponse + uploadId: string + processedFile: File +} + +export interface ChunkUploadTask { + promise: Promise> + cancel: () => void + getUploadId: () => string +} + +const computeFileFingerprint = async (file: File) => { + const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}` + if (!window.crypto?.subtle) { + return btoa(unescape(encodeURIComponent(fingerprintSeed))) + } + const buffer = new TextEncoder().encode(fingerprintSeed) + const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer) + const hashArray = Array.from(new Uint8Array(hashBuffer)) + return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('') +} + +const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => { + const start = chunkIndex * chunkSize + const end = Math.min(start + chunkSize, fileSize) + return Math.max(end - start, 0) +} + +const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => + uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0) + +const normalizeConcurrency = (concurrency: number) => { + if (!Number.isFinite(concurrency) || concurrency < 1) { + return 1 + } + return Math.floor(concurrency) +} + +const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set) => { + const chunkIndexes: number[] = [] + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + if (!uploadedChunkSet.has(chunkIndex)) { + chunkIndexes.push(chunkIndex) + } + } + return chunkIndexes +} + +export const createChunkUploadTask = (options: ChunkUploadOptions): ChunkUploadTask => { + const abortController = new AbortController() + let uploadId = '' + let cancelled = false + + const cleanupCancelledSession = async () => { + if (uploadId && options.api.cancelUpload) { + await options.api.cancelUpload(uploadId).catch(() => undefined) + } + } + + const promise = (async () => { + const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file + const fileFingerprint = await computeFileFingerprint(processedFile) + const session = await options.api.initUpload({ + fileName: processedFile.name, + fileSize: processedFile.size, + contentType: processedFile.type || 'application/octet-stream', + fileFingerprint, + scene: options.scene + }) + + uploadId = session.uploadId + if (cancelled) { + await cleanupCancelledSession() + throw new Error('上传已取消') + } + + const uploadedChunkSet = new Set(session.uploadedChunks || []) + let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet)) + const uploadingChunkBytes = new Map() + const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet) + const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1)) + + const emitProgress = (limit: number) => { + const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0) + const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100 + options.onProgress?.(Math.min(percent, limit)) + } + + options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100)) + + let nextChunkIndexCursor = 0 + const uploadNextChunk = async (): Promise => { + const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor] + nextChunkIndexCursor += 1 + if (chunkIndex === undefined) { + return + } + if (cancelled) { + await cleanupCancelledSession() + throw new Error('上传已取消') + } + + const start = chunkIndex * session.chunkSize + const end = Math.min(start + session.chunkSize, processedFile.size) + const chunk = processedFile.slice(start, end) + const chunkBytes = end - start + + await options.api.uploadChunk( + { + uploadId: session.uploadId, + chunkIndex, + totalChunks: session.totalChunks, + chunk + }, + { + signal: abortController.signal, + onUploadProgress: (event) => { + const loaded = Math.min(event.loaded || 0, chunkBytes) + uploadingChunkBytes.set(chunkIndex, loaded) + emitProgress(99.9) + } + } + ) + + uploadedChunkSet.add(chunkIndex) + uploadedBytes += chunkBytes + uploadingChunkBytes.delete(chunkIndex) + options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9)) + + await uploadNextChunk() + } + + await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk())) + + if (cancelled) { + await cleanupCancelledSession() + throw new Error('上传已取消') + } + + const response = await options.api.completeUpload(session.uploadId) + options.onProgress?.(100) + return { + response, + uploadId: session.uploadId, + processedFile + } + })() + + return { + promise, + cancel: () => { + cancelled = true + abortController.abort() + if (uploadId && options.api.cancelUpload) { + void options.api.cancelUpload(uploadId).catch(() => undefined) + } + }, + getUploadId: () => uploadId + } +} diff --git a/FM-Frontend/src/utils/comment-review.test.ts b/FM-Frontend/src/utils/comment-review.test.ts new file mode 100644 index 00000000..498ec19a --- /dev/null +++ b/FM-Frontend/src/utils/comment-review.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { buildRatingStars, normalizeCommentRating } from './comment-review' + +describe('comment review helpers', () => { + it('normalizes comment ratings for display and submit', () => { + expect(normalizeCommentRating(undefined)).toBe(5) + expect(normalizeCommentRating(0)).toBe(1) + expect(normalizeCommentRating(6)).toBe(5) + expect(normalizeCommentRating('3')).toBe(3) + }) + + it('builds filled and empty star states from a rating', () => { + expect(buildRatingStars(3)).toEqual([true, true, true, false, false]) + expect(buildRatingStars(5)).toEqual([true, true, true, true, true]) + }) +}) diff --git a/FM-Frontend/src/utils/comment-review.ts b/FM-Frontend/src/utils/comment-review.ts new file mode 100644 index 00000000..aee33323 --- /dev/null +++ b/FM-Frontend/src/utils/comment-review.ts @@ -0,0 +1,12 @@ +export const normalizeCommentRating = (value: unknown, fallback = 5) => { + const numeric = Number(value ?? fallback) + if (!Number.isFinite(numeric)) { + return fallback + } + return Math.min(5, Math.max(1, Math.round(numeric))) +} + +export const buildRatingStars = (rating: unknown) => { + const normalized = normalizeCommentRating(rating) + return Array.from({ length: 5 }, (_, index) => index < normalized) +} diff --git a/FM-Frontend/src/utils/form-draft.ts b/FM-Frontend/src/utils/form-draft.ts new file mode 100644 index 00000000..8e99ab20 --- /dev/null +++ b/FM-Frontend/src/utils/form-draft.ts @@ -0,0 +1,70 @@ +/** + * Purpose: DraftStorageMode supports form-draft.ts by holding or executing the draft storage mode page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +export type DraftStorageMode = 'local' | 'session' + +/** + * Purpose: DraftRecord supports form-draft.ts by holding or executing the draft record page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface DraftRecord { + savedAt: number + payload: T +} + +/** + * Purpose: getStorage supports form-draft.ts by holding or executing the get storage page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage) + +/** + * Purpose: buildDraftStorageKey supports form-draft.ts by holding or executing the build draft storage key page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const buildDraftStorageKey = (...parts: Array) => { + const normalizedParts = parts + .filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0) + .map(part => String(part).trim()) + return `fingertipdesigner:draft:${normalizedParts.join(':')}` +} + +/** + * Purpose: saveDraftRecord supports form-draft.ts by holding or executing the save draft record page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const saveDraftRecord = (key: string, payload: T, mode: DraftStorageMode = 'local') => { + const record: DraftRecord = { + savedAt: Date.now(), + payload + } + getStorage(mode).setItem(key, JSON.stringify(record)) + return record +} + +/** + * Purpose: loadDraftRecord supports form-draft.ts by holding or executing the load draft record page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const loadDraftRecord = (key: string, mode: DraftStorageMode = 'local') => { + const rawValue = getStorage(mode).getItem(key) + if (!rawValue) { + return null + } + + try { + return JSON.parse(rawValue) as DraftRecord + } catch { + getStorage(mode).removeItem(key) + return null + } +} + +/** + * Purpose: clearDraftRecord supports form-draft.ts by holding or executing the clear draft record page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => { + getStorage(mode).removeItem(key) +} diff --git a/FM-Frontend/src/utils/id.ts b/FM-Frontend/src/utils/id.ts new file mode 100644 index 00000000..ff766944 --- /dev/null +++ b/FM-Frontend/src/utils/id.ts @@ -0,0 +1,34 @@ +/** + * Purpose: IdType supports id.ts by holding or executing the id type page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +export type IdType = string | number + +/** + * Purpose: isEmptyId supports id.ts by holding or executing the is empty id page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isEmptyId = (value: unknown): value is undefined | null | '' => { + return value === undefined || value === null || `${value}`.trim() === '' +} + +/** + * Purpose: toIdString supports id.ts by holding or executing the to id string page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const toIdString = (value: IdType) => String(value) + +// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。 +export const toOptionalIdString = (value: unknown) => { + if (isEmptyId(value)) { + return undefined + } + return String(value).trim() +} + +// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。 +export const sameId = (left: unknown, right: unknown) => { + const leftId = toOptionalIdString(left) + const rightId = toOptionalIdString(right) + return leftId !== undefined && leftId === rightId +} diff --git a/FM-Frontend/src/utils/image-upload.ts b/FM-Frontend/src/utils/image-upload.ts new file mode 100644 index 00000000..78b81f51 --- /dev/null +++ b/FM-Frontend/src/utils/image-upload.ts @@ -0,0 +1,271 @@ +/** + * Purpose: DEFAULT_MAX_IMAGE_SIZE supports image-upload.ts by holding or executing the default max image size page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024 +/** + * Purpose: AUTO_COMPRESS_TYPES supports image-upload.ts by holding or executing the auto compress types page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp']) + +/** + * Purpose: inferImageMimeType supports image-upload.ts by holding or executing the infer image mime type page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const inferImageMimeType = (file: File) => { + if (file.type) return file.type.toLowerCase() + const name = file.name.toLowerCase().split(/[?#]/)[0] || '' + if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg' + if (name.endsWith('.png')) return 'image/png' + if (name.endsWith('.webp')) return 'image/webp' + if (name.endsWith('.gif')) return 'image/gif' + return '' +} + +/** + * Purpose: ImageCompressionResult supports image-upload.ts by holding or executing the image compression result page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ImageCompressionResult { + file: File + originalSize: number + finalSize: number + compressed: boolean + converted: boolean + skippedReason?: string +} + +/** + * Purpose: QUALITY_STEPS supports image-upload.ts by holding or executing the quality steps page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52] +/** + * Purpose: SCALE_STEPS supports image-upload.ts by holding or executing the scale steps page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5] + +/** + * Purpose: loadImageElement supports image-upload.ts by holding or executing the load image element page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const loadImageElement = (file: File) => { + return new Promise((resolve, reject) => { + const image = new Image() + const objectUrl = URL.createObjectURL(file) + + image.onload = () => { + URL.revokeObjectURL(objectUrl) + resolve(image) + } + + image.onerror = () => { + URL.revokeObjectURL(objectUrl) + reject(new Error('图片读取失败')) + } + + image.src = objectUrl + }) +} + +/** + * Purpose: canvasToBlob supports image-upload.ts by holding or executing the canvas to blob page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => { + return new Promise((resolve, reject) => { + canvas.toBlob( + (blob) => { + if (!blob) { + reject(new Error('图片压缩失败')) + return + } + resolve(blob) + }, + type, + quality + ) + }) +} + +/** + * Purpose: getOutputExtension supports image-upload.ts by holding or executing the get output extension page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getOutputExtension = (type: string) => { + if (type === 'image/png') { + return '.png' + } + if (type === 'image/webp') { + return '.webp' + } + return '.jpg' +} + +/** + * Purpose: buildOutputName supports image-upload.ts by holding or executing the build output name page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const buildOutputName = (fileName: string, type: string) => { + const extension = getOutputExtension(type) + const dotIndex = fileName.lastIndexOf('.') + const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName + return `${baseName}${extension}` +} + +/** + * Purpose: drawImageToCanvas supports image-upload.ts by holding or executing the draw image to canvas page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => { + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + + const context = canvas.getContext('2d') + if (!context) { + throw new Error('无法初始化图片压缩画布') + } + + if (mimeType !== 'image/png') { + context.fillStyle = '#ffffff' + context.fillRect(0, 0, width, height) + } + + context.drawImage(image, 0, 0, width, height) + return canvas +} + +/** + * Purpose: toCompressedFile supports image-upload.ts by holding or executing the to compressed file page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => { + return new File([blob], buildOutputName(sourceFile.name, mimeType), { + type: mimeType, + lastModified: sourceFile.lastModified + }) +} + +/** + * Purpose: getPreferredMimeTypes supports image-upload.ts by holding or executing the get preferred mime types page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const getPreferredMimeTypes = (file: File) => { + if (file.type === 'image/png') { + return ['image/png', 'image/jpeg'] + } + if (file.type === 'image/webp') { + return ['image/webp', 'image/jpeg'] + } + return ['image/jpeg'] +} + +/** + * Purpose: formatFileSize supports image-upload.ts by holding or executing the format file size page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const formatFileSize = (bytes: number) => { + if (bytes >= 1024 * 1024) { + return `${(bytes / 1024 / 1024).toFixed(2)}MB` + } + return `${(bytes / 1024).toFixed(0)}KB` +} + +/** + * Purpose: compressImageIfNeeded supports image-upload.ts by holding or executing the compress image if needed page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const compressImageIfNeeded = async ( + file: File, + maxSize = DEFAULT_MAX_IMAGE_SIZE +): Promise => { + const sourceType = inferImageMimeType(file) + if (!sourceType.startsWith('image/')) { + return { + file, + originalSize: file.size, + finalSize: file.size, + compressed: false, + converted: false, + skippedReason: '仅支持图片文件上传' + } + } + + if (file.size <= maxSize) { + return { + file, + originalSize: file.size, + finalSize: file.size, + compressed: false, + converted: false + } + } + + if (!AUTO_COMPRESS_TYPES.has(sourceType)) { + return { + file, + originalSize: file.size, + finalSize: file.size, + compressed: false, + converted: false, + skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试' + } + } + + const image = await loadImageElement(file) + const preferredMimeTypes = getPreferredMimeTypes(new File([file], file.name, { type: sourceType || file.type })) + let bestBlob: Blob | null = null + let bestMimeType = sourceType || file.type + + for (const scale of SCALE_STEPS) { + const width = Math.max(1, Math.round(image.naturalWidth * scale)) + const height = Math.max(1, Math.round(image.naturalHeight * scale)) + + for (const mimeType of preferredMimeTypes) { + const canvas = drawImageToCanvas(image, width, height, mimeType) + const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS + + for (const quality of qualitySteps) { + const blob = await canvasToBlob(canvas, mimeType, quality) + + if (!bestBlob || blob.size < bestBlob.size) { + bestBlob = blob + bestMimeType = mimeType + } + + if (blob.size <= maxSize) { + const compressedFile = toCompressedFile(blob, file, mimeType) + return { + file: compressedFile, + originalSize: file.size, + finalSize: blob.size, + compressed: true, + converted: mimeType !== file.type + } + } + } + } + } + + if (!bestBlob) { + throw new Error('图片压缩失败') + } + + const compressedFile = toCompressedFile(bestBlob, file, bestMimeType) + return { + file: compressedFile, + originalSize: file.size, + finalSize: bestBlob.size, + compressed: true, + converted: bestMimeType !== file.type + } +} + +/** + * Purpose: MAX_IMAGE_UPLOAD_SIZE supports image-upload.ts by holding or executing the max image upload size page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE diff --git a/FM-Frontend/src/utils/order-review-focus.test.ts b/FM-Frontend/src/utils/order-review-focus.test.ts new file mode 100644 index 00000000..0780f011 --- /dev/null +++ b/FM-Frontend/src/utils/order-review-focus.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { resolveOrderReviewFocus } from './order-review-focus' + +const orders = [ + { + id: 10, + items: [ + { id: 1001, productTitle: '猫眼款' } + ] + }, + { + id: 11, + items: [ + { id: 1101, productTitle: '法式款' } + ] + } +] + +describe('resolveOrderReviewFocus', () => { + it('focuses the exact pending review from message query parameters', () => { + const result = resolveOrderReviewFocus({ + orders, + pendingReviews: [{ id: 99, orderId: 10, orderItemId: 1001 }], + orderReviews: {}, + query: { reviewId: 99 } + }) + + expect(result.status).toBe('pending') + expect(result.focusOrderId).toBe('10') + expect(result.focusOrderItemId).toBe('1001') + expect(result.focusReviewId).toBe('99') + }) + + it('reports a friendly submitted state when the reminder was already handled', () => { + const result = resolveOrderReviewFocus({ + orders, + pendingReviews: [], + orderReviews: { + 10: [{ id: 99, orderId: 10, orderItemId: 1001, status: 1 }] + }, + query: { reviewId: 99 } + }) + + expect(result.status).toBe('submitted') + expect(result.focusOrderId).toBe('10') + expect(result.focusOrderItemId).toBe('1001') + expect(result.message).toContain('已处理') + }) + + it('chooses the first pending review for profile pending-review entry', () => { + const result = resolveOrderReviewFocus({ + orders, + pendingReviews: [{ id: 88, orderId: 11, orderItemId: 1101 }], + orderReviews: {}, + query: { review: 'pending' } + }) + + expect(result.status).toBe('pending') + expect(result.focusOrderId).toBe('11') + expect(result.focusOrderItemId).toBe('1101') + expect(result.focusReviewId).toBe('88') + }) + + it('keeps an order-level focus when only orderId is provided', () => { + const result = resolveOrderReviewFocus({ + orders, + pendingReviews: [], + orderReviews: {}, + query: { orderId: 10 } + }) + + expect(result.status).toBe('order') + expect(result.focusOrderId).toBe('10') + expect(result.focusOrderItemId).toBe('') + }) + + it('keeps the order visible when a review id is stale but orderId still exists', () => { + const result = resolveOrderReviewFocus({ + orders, + pendingReviews: [], + orderReviews: {}, + query: { orderId: 10, reviewId: 404 } + }) + + expect(result.status).toBe('missing') + expect(result.focusOrderId).toBe('10') + expect(result.message).toContain('失效') + }) +}) diff --git a/FM-Frontend/src/utils/order-review-focus.ts b/FM-Frontend/src/utils/order-review-focus.ts new file mode 100644 index 00000000..1cd58575 --- /dev/null +++ b/FM-Frontend/src/utils/order-review-focus.ts @@ -0,0 +1,120 @@ +import type { OrderArtistReviewVO } from '@/api/order' + +type QueryValue = string | number | null | undefined | Array + +interface OrderLike { + id?: unknown + items?: Array<{ id?: unknown }> +} + +interface ResolveOrderReviewFocusOptions { + orders: OrderLike[] + pendingReviews: OrderArtistReviewVO[] + orderReviews: Record + query: Record +} + +export interface OrderReviewFocusResult { + status: 'none' | 'pending' | 'submitted' | 'missing' | 'order' + focusOrderId: string + focusOrderItemId: string + focusReviewId: string + message: string +} + +const toText = (value: QueryValue | unknown) => { + if (Array.isArray(value)) { + return value[0] === undefined || value[0] === null ? '' : String(value[0]) + } + return value === undefined || value === null ? '' : String(value) +} + +const sameId = (left: unknown, right: unknown) => { + const leftText = toText(left) + const rightText = toText(right) + return leftText !== '' && leftText === rightText +} + +const flattenSubmittedReviews = (orderReviews: Record) => { + return Object.values(orderReviews).flat().filter(review => Number(review.status) === 1 || Boolean(review.rating)) +} + +const findOrder = (orders: OrderLike[], orderId: string) => { + return orders.find(order => sameId(order.id, orderId)) +} + +const buildResult = ( + status: OrderReviewFocusResult['status'], + review?: OrderArtistReviewVO, + fallbackOrderId = '', + message = '' +): OrderReviewFocusResult => ({ + status, + focusOrderId: toText(review?.orderId) || fallbackOrderId, + focusOrderItemId: toText(review?.orderItemId), + focusReviewId: toText(review?.id), + message +}) + +export const resolveOrderReviewFocus = ({ + orders, + pendingReviews, + orderReviews, + query +}: ResolveOrderReviewFocusOptions): OrderReviewFocusResult => { + const reviewId = toText(query.reviewId) + const orderId = toText(query.orderId) + const orderItemId = toText(query.orderItemId) + const reviewMode = toText(query.review) + const submittedReviews = flattenSubmittedReviews(orderReviews) + + if (reviewId) { + const pending = pendingReviews.find(review => sameId(review.id, reviewId)) + if (pending) { + return buildResult('pending', pending, '', '已为你定位到待评价订单。') + } + const submitted = submittedReviews.find(review => sameId(review.id, reviewId)) + if (submitted) { + return buildResult('submitted', submitted, '', '这条评价提醒已处理,可查看已评价内容。') + } + return { + status: 'missing', + focusOrderId: findOrder(orders, orderId) ? orderId : '', + focusOrderItemId: orderItemId, + focusReviewId: reviewId, + message: '这条评价提醒已失效,可在订单页查看最新状态。' + } + } + + if (reviewMode === 'pending') { + const firstPending = pendingReviews[0] + if (firstPending) { + return buildResult('pending', firstPending, '', '已为你定位到待评价订单。') + } + return { + status: 'missing', + focusOrderId: '', + focusOrderItemId: '', + focusReviewId: '', + message: '暂无待评价订单。' + } + } + + if (orderId && findOrder(orders, orderId)) { + return { + status: 'order', + focusOrderId: orderId, + focusOrderItemId: orderItemId, + focusReviewId: '', + message: '' + } + } + + return { + status: 'none', + focusOrderId: '', + focusOrderItemId: '', + focusReviewId: '', + message: '' + } +} diff --git a/FM-Frontend/src/utils/permission.ts b/FM-Frontend/src/utils/permission.ts new file mode 100644 index 00000000..afdc5b26 --- /dev/null +++ b/FM-Frontend/src/utils/permission.ts @@ -0,0 +1,150 @@ +import { permissionApi } from '@/api/permission' +import { computed, ref } from 'vue' +import { isBootstrapAdminUser, loadCachedAdminUserInfo } from '@/utils/admin-session' +import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' + +/** + * Purpose: USER_PERMISSIONS_STORAGE_KEY supports permission.ts by holding or executing the user permissions storage key page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const USER_PERMISSIONS_STORAGE_KEY = 'userPermissions' + +/** + * Purpose: readPermissionsFromStorage supports permission.ts by holding or executing the read permissions from storage page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const readPermissionsFromStorage = () => { + const raw = localStorage.getItem(USER_PERMISSIONS_STORAGE_KEY) + if (!raw) { + return null + } + + try { + const parsed = JSON.parse(raw) + return Array.isArray(parsed) ? parsed.map(item => String(item)) : null + } catch (error) { + console.error('Failed to parse stored user permissions:', error) + localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY) + return null + } +} + +/** + * Purpose: userPermissions supports permission.ts by holding or executing the user permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const userPermissions = ref(readPermissionsFromStorage() || []) +/** + * Purpose: loadingPermissions supports permission.ts by holding or executing the loading permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const loadingPermissions = ref(false) + +/** + * Purpose: isPlatformAdminUser supports permission.ts by holding or executing the is platform admin user page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const isPlatformAdminUser = () => Number(loadCachedAdminUserInfo()?.type) === 4 + +/** + * Purpose: getStoredUserPermissions supports permission.ts by holding or executing the get stored user permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getStoredUserPermissions = () => readPermissionsFromStorage() + +/** + * Purpose: setStoredUserPermissions supports permission.ts by holding or executing the set stored user permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const setStoredUserPermissions = (permissions: string[]) => { + userPermissions.value = Array.from(new Set((permissions || []).map(code => String(code)))) + localStorage.setItem(USER_PERMISSIONS_STORAGE_KEY, JSON.stringify(userPermissions.value)) + return userPermissions.value +} + +/** + * Purpose: clearStoredPermissions supports permission.ts by holding or executing the clear stored permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const clearStoredPermissions = () => { + userPermissions.value = [] + localStorage.removeItem(USER_PERMISSIONS_STORAGE_KEY) +} + +/** + * Purpose: fetchUserPermissionsStrict supports permission.ts by holding or executing the fetch user permissions strict page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const fetchUserPermissionsStrict = async () => { + loadingPermissions.value = true + try { + const permissions = await permissionApi.getUserPermissions() + const normalizedPermissions = permissions && Array.isArray(permissions) + ? permissions.map(permission => permission.permissionCode) + : [] + + return setStoredUserPermissions(normalizedPermissions) + } finally { + loadingPermissions.value = false + } +} + +/** + * Purpose: usePermission supports permission.ts by holding or executing the use permission page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const usePermission = () => { + const hasPermission = (permissionCode: string) => { + if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { + return isAllowedForShoplessPlatformAdmin(permissionCode) + } + if (isPlatformAdminUser() && isAllowedForShoplessPlatformAdmin(permissionCode)) { + return isAllowedForShoplessPlatformAdmin(permissionCode) + } + return userPermissions.value.includes(permissionCode) + } + + const hasAnyPermission = (permissionCodes: string[]) => { + if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { + return permissionCodes.some(isAllowedForShoplessPlatformAdmin) + } + if (isPlatformAdminUser() && permissionCodes.some(isAllowedForShoplessPlatformAdmin)) { + return permissionCodes.some(isAllowedForShoplessPlatformAdmin) + } + return permissionCodes.some(code => userPermissions.value.includes(code)) + } + + const hasAllPermissions = (permissionCodes: string[]) => { + if (isBootstrapAdminUser(loadCachedAdminUserInfo())) { + return permissionCodes.every(isAllowedForShoplessPlatformAdmin) + } + if (isPlatformAdminUser() && permissionCodes.every(isAllowedForShoplessPlatformAdmin)) { + return permissionCodes.every(isAllowedForShoplessPlatformAdmin) + } + return permissionCodes.every(code => userPermissions.value.includes(code)) + } + + const loadUserPermissions = async () => { + try { + return await fetchUserPermissionsStrict() + } catch (error) { + console.error('加载用户权限失败:', error) + clearStoredPermissions() + return [] + } + } + + const clearPermissions = () => { + clearStoredPermissions() + } + + return { + userPermissions: computed(() => userPermissions.value), + loadingPermissions: computed(() => loadingPermissions.value), + hasPermission, + hasAnyPermission, + hasAllPermissions, + loadUserPermissions, + clearPermissions + } +} diff --git a/FM-Frontend/src/utils/platform-admin-permissions.ts b/FM-Frontend/src/utils/platform-admin-permissions.ts new file mode 100644 index 00000000..1c40db11 --- /dev/null +++ b/FM-Frontend/src/utils/platform-admin-permissions.ts @@ -0,0 +1,24 @@ +/** + * Purpose: SHOPLESS_ADMIN_ALLOWED_PREFIXES supports platform-admin-permissions.ts by holding or executing the shopless admin allowed prefixes page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const SHOPLESS_ADMIN_ALLOWED_PREFIXES = ['user:', 'shop:', 'permission:', 'message:', 'announcement:'] +/** + * Purpose: SHOPLESS_ADMIN_ALLOWED_PERMISSIONS supports platform-admin-permissions.ts by holding or executing the shopless admin allowed permissions page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const SHOPLESS_ADMIN_ALLOWED_PERMISSIONS = [ + 'messagehub:config:manage', + 'security:audit:view', + 'legal_agreement:manage' +] + +/** + * Purpose: isAllowedForShoplessPlatformAdmin supports platform-admin-permissions.ts by holding or executing the is allowed for shopless platform admin page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const isAllowedForShoplessPlatformAdmin = (permissionCode: string) => + permissionCode === 'dashboard:view' + || permissionCode.endsWith(':view') + || SHOPLESS_ADMIN_ALLOWED_PERMISSIONS.includes(permissionCode) + || SHOPLESS_ADMIN_ALLOWED_PREFIXES.some(prefix => permissionCode.startsWith(prefix)) diff --git a/FM-Frontend/src/utils/public-image-assets.test.ts b/FM-Frontend/src/utils/public-image-assets.test.ts new file mode 100644 index 00000000..cbb646f5 --- /dev/null +++ b/FM-Frontend/src/utils/public-image-assets.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const publicGetSignedUrl = vi.fn() + +vi.mock('@/api/file', () => ({ + fileApi: { + getSignedUrl: publicGetSignedUrl + } +})) + +vi.mock('@/api/admin', () => ({ + adminFileApi: { + getSignedUrl: vi.fn() + } +})) + +describe('public-image-assets', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' }) + }) + + it('prefers direct image urls over signing file ids', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({ + imageUrls: ['http://img.yunail.art/direct.jpg'], + imageFileIds: '42' + }, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg']) + expect(publicGetSignedUrl).not.toHaveBeenCalled() + }) + + it('normalizes direct image urls without scheme', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({ + imageUrls: ['img.yunail.art/direct.jpg?token=1'] + }, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1']) + }) + + it('signs public file ids when direct urls are missing', async () => { + const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets') + + expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png']) + await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([ + 'http://img.yunail.art/signed.jpg?token=1' + ]) + expect(publicGetSignedUrl).toHaveBeenCalledWith('42') + }) + + it('extracts legacy file ids from old file urls', async () => { + const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets') + + const record = { + imageUrl: '/api/file/get/325517232303947776', + imageFileIds: '325517232303947776,325517220106911744' + } + + expect(getDirectPublicImageUrls(record)).toEqual([]) + expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744']) + }) + + it('uses fallback when no image source is available', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png']) + }) +}) diff --git a/FM-Frontend/src/utils/public-image-assets.ts b/FM-Frontend/src/utils/public-image-assets.ts new file mode 100644 index 00000000..d69b0880 --- /dev/null +++ b/FM-Frontend/src/utils/public-image-assets.ts @@ -0,0 +1,97 @@ +import { DEFAULT_PRODUCT_IMAGE } from '@/constants' +import type { IdType } from '@/utils/id' +import { + extractLegacyFileId, + getCachedSignedImageUrl, + getCachedSignedImageUrlSync, + parseImageFileIds, + refreshCachedSignedImageUrl +} from '@/utils/signed-image-cache' + +export interface PublicImageRecord { + imageUrls?: string[] | string | null + imageFileIds?: string[] | string | null + coverImageUrl?: string | null + coverImageUrls?: string[] | string | null + coverImageFileId?: string[] | string | null + imageUrl?: string | null +} + +const normalizePublicUrl = (value: unknown): string => { + const source = String(value || '').replace(/[`]/g, '').trim() + if (!source) return '' + if (/^\/?api\/file\/get\/\d+/i.test(source)) return '' + if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) { + return source.startsWith('//') ? `http:${source}` : source + } + if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) { + return `http://${source}` + } + return '' +} + +const normalizeUrlList = (value: unknown): string[] => { + const rawValues = Array.isArray(value) ? value : String(value || '').split(',') + return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean))) +} + +export const getPublicImageFileIds = (record: PublicImageRecord): string[] => { + const rawFileIds = [ + ...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))), + ...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))), + extractLegacyFileId(record.coverImageUrl), + extractLegacyFileId(record.imageUrl) + ] + return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean))) +} + +export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => { + return Array.from(new Set([ + ...normalizeUrlList(record.coverImageUrls), + ...normalizeUrlList(record.coverImageUrl), + ...normalizeUrlList(record.imageUrls), + ...normalizeUrlList(record.imageUrl) + ])) +} + +export const resolvePublicImageUrlsSync = ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): string[] => { + const directUrls = getDirectPublicImageUrls(record) + if (directUrls.length) return directUrls + + const cachedUrls = getPublicImageFileIds(record) + .map(fileId => getCachedSignedImageUrlSync(fileId, 'public')) + .filter(Boolean) + if (cachedUrls.length) return cachedUrls + + return fallback ? [fallback] : [] +} + +export const resolvePublicImageUrls = async ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => { + const directUrls = getDirectPublicImageUrls(record) + if (directUrls.length) return directUrls + + const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public'))) + const usableUrls = signedUrls.filter(Boolean) + if (usableUrls.length) return usableUrls + + return fallback ? [fallback] : [] +} + +export const resolvePublicImageUrl = async ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => { + const urls = await resolvePublicImageUrls(record, fallback) + return urls[0] || fallback +} + +export const refreshPublicImageUrl = async ( + fileId: IdType | null | undefined, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => refreshCachedSignedImageUrl(fileId, fallback, 'public') diff --git a/FM-Frontend/src/utils/recovery.test.ts b/FM-Frontend/src/utils/recovery.test.ts new file mode 100644 index 00000000..a3895801 --- /dev/null +++ b/FM-Frontend/src/utils/recovery.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { buildRecoveryActions, getRecoveryMessage, recoveryRouteFor } from './recovery' + +describe('recovery utils', () => { + it('normalizes error messages with fallback text', () => { + expect(getRecoveryMessage(new Error('网络开小差了'), '请求失败')).toBe('网络开小差了') + expect(getRecoveryMessage('', '请求失败')).toBe('请求失败') + }) + + it('adds default routes and primary action state', () => { + const actions = buildRecoveryActions([ + { key: 'retry', text: '重试' }, + { key: 'orders', text: '查看订单' }, + { key: 'cart', text: '返回购物车' } + ]) + const retryAction = actions[0] + const ordersAction = actions[1] + const cartAction = actions[2] + + expect(retryAction?.primary).toBe(true) + expect(ordersAction?.route).toBe('/orders') + expect(cartAction?.route).toBe('/cart') + expect(recoveryRouteFor('products')).toBe('/products') + }) +}) diff --git a/FM-Frontend/src/utils/recovery.ts b/FM-Frontend/src/utils/recovery.ts new file mode 100644 index 00000000..99e45f1c --- /dev/null +++ b/FM-Frontend/src/utils/recovery.ts @@ -0,0 +1,43 @@ +export type RecoveryActionKey = 'retry' | 'orders' | 'cart' | 'products' | 'profile' | 'contact' + +export interface RecoveryAction { + key: RecoveryActionKey + text: string + route?: string + primary?: boolean +} + +const DEFAULT_ROUTES: Record = { + orders: '/orders', + cart: '/cart', + products: '/products', + profile: '/profile' +} + +export const getRecoveryMessage = (error: unknown, fallbackMessage: string): string => { + if (error instanceof Error && error.message.trim()) { + return error.message.trim() + } + if (typeof error === 'string' && error.trim()) { + return error.trim() + } + if (error && typeof error === 'object' && 'message' in error) { + const message = String((error as { message?: unknown }).message || '').trim() + if (message) { + return message + } + } + return fallbackMessage +} + +export const recoveryRouteFor = (key: RecoveryActionKey): string => DEFAULT_ROUTES[key] || '' + +export const buildRecoveryActions = (actions: RecoveryAction[]): RecoveryAction[] => ( + actions + .filter(action => action.key && action.text) + .map((action, index) => ({ + ...action, + route: action.route || recoveryRouteFor(action.key), + primary: action.primary ?? index === 0 + })) +) diff --git a/FM-Frontend/src/utils/request-signature.test.ts b/FM-Frontend/src/utils/request-signature.test.ts new file mode 100644 index 00000000..98bc65ee --- /dev/null +++ b/FM-Frontend/src/utils/request-signature.test.ts @@ -0,0 +1,51 @@ +// @vitest-environment jsdom + +import type { InternalAxiosRequestConfig } from 'axios' +import { createHash, createHmac } from 'node:crypto' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { attachRequestSignature } from './request-signature' + +describe('request signature', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + localStorage.clear() + }) + + it('falls back when Web Crypto subtle digest is unavailable', async () => { + vi.spyOn(Date, 'now').mockReturnValue(1700000000000) + vi.stubGlobal('crypto', { + randomUUID: () => 'fallback-id' + }) + + const config = { + method: 'post', + baseURL: '/api', + url: '/order/checkout-preview', + headers: { + 'Content-Type': 'application/json' + }, + data: { + items: [] + } + } as unknown as InternalAxiosRequestConfig + + await attachRequestSignature(config, 'access-token') + + const headers = config.headers as Record + const payloadHash = createHash('sha256').update(JSON.stringify({ items: [] })).digest('hex') + const canonical = [ + 'POST', + '/order/checkout-preview', + '1700000000000', + '1700000000000-fallback-id', + payloadHash + ].join('\n') + const expectedSignature = createHmac('sha256', 'access-token').update(canonical).digest('hex') + + expect(headers['X-Timestamp']).toBe('1700000000000') + expect(headers['X-Nonce']).toBe('1700000000000-fallback-id') + expect(headers['X-Sign-Version']).toBe('v1') + expect(headers['X-Signature']).toBe(expectedSignature) + }) +}) diff --git a/FM-Frontend/src/utils/request-signature.ts b/FM-Frontend/src/utils/request-signature.ts new file mode 100644 index 00000000..d06b2939 --- /dev/null +++ b/FM-Frontend/src/utils/request-signature.ts @@ -0,0 +1,474 @@ +import type { InternalAxiosRequestConfig } from 'axios' + +/** + * Purpose: HEADER_TIMESTAMP supports request-signature.ts by holding or executing the header timestamp page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const HEADER_TIMESTAMP = 'X-Timestamp' +/** + * Purpose: HEADER_NONCE supports request-signature.ts by holding or executing the header nonce page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const HEADER_NONCE = 'X-Nonce' +/** + * Purpose: HEADER_SIGNATURE supports request-signature.ts by holding or executing the header signature page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const HEADER_SIGNATURE = 'X-Signature' +/** + * Purpose: HEADER_SIGNATURE_VERSION supports request-signature.ts by holding or executing the header signature version page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' +/** + * Purpose: DEVICE_ID_HEADER supports request-signature.ts by holding or executing the device id header page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DEVICE_ID_HEADER = 'X-Device-Id' +/** + * Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const DEVICE_ID_STORAGE_KEY = 'fingertipdesigner-device-id' +/** + * Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the signature version page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const SIGNATURE_VERSION = 'v1' + +/** + * Purpose: HeaderContainer supports request-signature.ts by holding or executing the header container page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +type HeaderContainer = Record & { + set?: (name: string, value: string) => void + get?: (name: string) => unknown +} + +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]) + +/** + * Purpose: RequestSignatureOptions supports request-signature.ts by holding or executing the request signature options page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +interface RequestSignatureOptions { + authFree?: boolean +} + +/** + * Purpose: isSafeMethod supports request-signature.ts by holding or executing the is safe method page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function isSafeMethod(method?: string) { + return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase()) +} + +/** + * Purpose: toHex supports request-signature.ts by holding or executing the to hex page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function toHex(bytes: ArrayBuffer | Uint8Array) { + const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes) + return Array.from(view) + .map(byte => byte.toString(16).padStart(2, '0')) + .join('') +} + +function encodeUtf8(text: string) { + return new TextEncoder().encode(text) +} + +function rightRotate(value: number, bits: number) { + return (value >>> bits) | (value << (32 - bits)) +} + +function concatBytes(left: Uint8Array, right: Uint8Array) { + const result = new Uint8Array(left.length + right.length) + result.set(left, 0) + result.set(right, left.length) + return result +} + +function sha256Bytes(input: Uint8Array) { + const paddedLength = Math.ceil((input.length + 9) / 64) * 64 + const padded = new Uint8Array(paddedLength) + padded.set(input) + padded[input.length] = 0x80 + + const bitLength = input.length * 8 + const view = new DataView(padded.buffer) + view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false) + view.setUint32(paddedLength - 4, bitLength >>> 0, false) + + let h0 = 0x6a09e667 + let h1 = 0xbb67ae85 + let h2 = 0x3c6ef372 + let h3 = 0xa54ff53a + let h4 = 0x510e527f + let h5 = 0x9b05688c + let h6 = 0x1f83d9ab + let h7 = 0x5be0cd19 + const words = new Uint32Array(64) + + for (let offset = 0; offset < paddedLength; offset += 64) { + for (let index = 0; index < 16; index++) { + words[index] = view.getUint32(offset + index * 4, false) + } + for (let index = 16; index < 64; index++) { + const word15 = words[index - 15]! + const word2 = words[index - 2]! + const s0 = rightRotate(word15, 7) ^ rightRotate(word15, 18) ^ (word15 >>> 3) + const s1 = rightRotate(word2, 17) ^ rightRotate(word2, 19) ^ (word2 >>> 10) + words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0 + } + + let a = h0 + let b = h1 + let c = h2 + let d = h3 + let e = h4 + let f = h5 + let g = h6 + let h = h7 + + for (let index = 0; index < 64; index++) { + const s1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25) + const ch = (e & f) ^ (~e & g) + const temp1 = (h + s1 + ch + SHA256_K[index]! + words[index]!) >>> 0 + const s0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22) + const maj = (a & b) ^ (a & c) ^ (b & c) + const temp2 = (s0 + maj) >>> 0 + h = g + g = f + f = e + e = (d + temp1) >>> 0 + d = c + c = b + b = a + a = (temp1 + temp2) >>> 0 + } + + h0 = (h0 + a) >>> 0 + h1 = (h1 + b) >>> 0 + h2 = (h2 + c) >>> 0 + h3 = (h3 + d) >>> 0 + h4 = (h4 + e) >>> 0 + h5 = (h5 + f) >>> 0 + h6 = (h6 + g) >>> 0 + h7 = (h7 + h) >>> 0 + } + + const output = new Uint8Array(32) + const outputView = new DataView(output.buffer) + ;[h0, h1, h2, h3, h4, h5, h6, h7].forEach((value, index) => { + outputView.setUint32(index * 4, value, false) + }) + return output +} + +function hmacSha256Bytes(secret: string, message: string) { + const blockSize = 64 + let key = encodeUtf8(secret) + if (key.length > blockSize) { + key = sha256Bytes(key) + } + + const paddedKey = new Uint8Array(blockSize) + paddedKey.set(key) + const outer = new Uint8Array(blockSize) + const inner = new Uint8Array(blockSize) + for (let index = 0; index < blockSize; index++) { + outer[index] = paddedKey[index]! ^ 0x5c + inner[index] = paddedKey[index]! ^ 0x36 + } + return sha256Bytes(concatBytes(outer, sha256Bytes(concatBytes(inner, encodeUtf8(message))))) +} + +function getSubtleCrypto() { + return globalThis.crypto?.subtle +} + +/** + * Purpose: sha256Hex supports request-signature.ts by holding or executing the sha256 hex page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +async function sha256Hex(text: string) { + const subtle = getSubtleCrypto() + if (!subtle) { + return toHex(sha256Bytes(encodeUtf8(text))) + } + const digest = await subtle.digest('SHA-256', encodeUtf8(text)) + return toHex(digest) +} + +/** + * Purpose: hmacSha256Hex supports request-signature.ts by holding or executing the hmac sha256 hex page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +async function hmacSha256Hex(secret: string, message: string) { + const subtle = getSubtleCrypto() + if (!subtle) { + return toHex(hmacSha256Bytes(secret, message)) + } + const key = await subtle.importKey( + 'raw', + encodeUtf8(secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ) + const signature = await subtle.sign('HMAC', key, encodeUtf8(message)) + return toHex(signature) +} + +/** + * Purpose: randomNonce supports request-signature.ts by holding or executing the random nonce page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function randomNonce() { + if (typeof globalThis.crypto?.randomUUID === 'function') { + return `${Date.now()}-${globalThis.crypto.randomUUID()}` + } + return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}` +} + +/** + * Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export function getDeviceId() { + try { + const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY) + if (stored) { + return stored + } + const next = `web-${randomNonce()}` + localStorage.setItem(DEVICE_ID_STORAGE_KEY, next) + return next + } catch { + return `web-${randomNonce()}` + } +} + +/** + * Purpose: setHeader supports request-signature.ts by holding or executing the set header page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function setHeader(config: InternalAxiosRequestConfig, name: string, value: string) { + const headers = config.headers as HeaderContainer | undefined + if (headers && typeof headers.set === 'function') { + headers.set(name, value) + return + } + config.headers = { + ...(headers || {}), + [name]: value + } as InternalAxiosRequestConfig['headers'] +} + +/** + * Purpose: getHeader supports request-signature.ts by holding or executing the get header page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function getHeader(config: InternalAxiosRequestConfig, name: string) { + const headers = config.headers as HeaderContainer | undefined + if (!headers) { + return '' + } + if (typeof headers.get === 'function') { + const value = headers.get(name) + if (value !== undefined && value !== null) { + return String(value) + } + } + return String(headers[name] || headers[name.toLowerCase()] || '') +} + +/** + * Purpose: extractPath supports request-signature.ts by holding or executing the extract path page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function extractPath(value?: string) { + if (!value) { + return '' + } + try { + return new URL(value, window.location.origin).pathname + } catch { + return value.split('?')[0] || '' + } +} + +/** + * Purpose: joinAxiosPath supports request-signature.ts by holding or executing the join axios path page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function joinAxiosPath(baseUrl?: string, requestUrl?: string) { + if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) { + return extractPath(requestUrl) + } + + const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '') + const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '') + const joined = [basePath, requestPath].filter(Boolean).join('/') + return joined ? `/${joined}` : '/' +} + +/** + * Purpose: toBackendRequestPath supports request-signature.ts by holding or executing the to backend request path page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function toBackendRequestPath(baseUrl?: string, requestUrl?: string) { + const path = joinAxiosPath(baseUrl, requestUrl) + if (path === '/admin/api') { + return '/admin' + } + if (path.startsWith('/admin/api/')) { + return `/admin/${path.slice('/admin/api/'.length)}` + } + if (path === '/api/admin') { + return '/admin' + } + if (path.startsWith('/api/admin/')) { + return `/admin/${path.slice('/api/admin/'.length)}` + } + if (path === '/api') { + return '/' + } + if (path.startsWith('/api/')) { + return `/${path.slice('/api/'.length)}` + } + return path +} + +/** + * Purpose: appendParam supports request-signature.ts by holding or executing the append param page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function appendParam(target: Record, key: string, value: unknown) { + if (value === undefined || value === null || value === '') { + return + } + if (!target[key]) { + target[key] = [] + } + if (Array.isArray(value)) { + value.forEach(item => appendParam(target, key, item)) + return + } + target[key].push(value) +} + +/** + * Purpose: collectParams supports request-signature.ts by holding or executing the collect params page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function collectParams(source: unknown, target: Record) { + if (!source) { + return + } + if (source instanceof URLSearchParams) { + source.forEach((value, key) => appendParam(target, key, value)) + return + } + if (source instanceof FormData) { + source.forEach((value, key) => { + if (!(value instanceof Blob)) { + appendParam(target, key, value) + } + }) + return + } + if (typeof source === 'object') { + Object.entries(source as Record).forEach(([key, value]) => appendParam(target, key, value)) + } +} + +/** + * Purpose: buildCanonicalParams supports request-signature.ts by holding or executing the build canonical params page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function buildCanonicalParams(...sources: unknown[]) { + const params: Record = {} + sources.forEach(source => collectParams(source, params)) + return Object.keys(params) + .sort() + .map(key => { + const normalized = params[key] + ?.map(value => String(value)) + .sort() + .join(',') || '' + return `${key}=${normalized}` + }) + .join('&') +} + +/** + * Purpose: buildJsonPayload supports request-signature.ts by holding or executing the build json payload page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function buildJsonPayload(data: unknown) { + if (data === undefined || data === null || data === '') { + return '' + } + if (typeof data === 'string') { + return data + } + return JSON.stringify(data) +} + +/** + * Purpose: resolvePayload supports request-signature.ts by holding or executing the resolve payload page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function resolvePayload(config: InternalAxiosRequestConfig) { + const contentType = getHeader(config, 'Content-Type').toLowerCase() + const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : '' + if (jsonPayload) { + return jsonPayload + } + return buildCanonicalParams(config.params, config.data) +} + +/** + * Purpose: attachRequestSignature supports request-signature.ts by holding or executing the attach request signature page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export async function attachRequestSignature( + config: InternalAxiosRequestConfig, + accessToken?: string | null, + options: RequestSignatureOptions = {} +) { + setHeader(config, DEVICE_ID_HEADER, getDeviceId()) + + const method = String(config.method || 'GET').toUpperCase() + if (!accessToken || options.authFree || isSafeMethod(method)) { + return config + } + + const timestamp = String(Date.now()) + const nonce = randomNonce() + const payloadHash = await sha256Hex(resolvePayload(config)) + const canonical = [ + method, + toBackendRequestPath(config.baseURL, config.url), + timestamp, + nonce, + payloadHash + ].join('\n') + + setHeader(config, HEADER_TIMESTAMP, timestamp) + setHeader(config, HEADER_NONCE, nonce) + setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical)) + setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION) + return config +} diff --git a/FM-Frontend/src/utils/rich-content.test.ts b/FM-Frontend/src/utils/rich-content.test.ts new file mode 100644 index 00000000..f184720f --- /dev/null +++ b/FM-Frontend/src/utils/rich-content.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { extractRichText, renderRichContent } from './rich-content' + +describe('rich content helpers', () => { + it('renders markdown into html', () => { + const html = renderRichContent('# 标题\n\n- 甲\n- 乙\n\n**加粗** [链接](https://example.com)') + + expect(html).toContain('

标题

') + expect(html).toContain('
    ') + expect(html).toContain('加粗') + expect(html).toContain(' { + const html = renderRichContent('

    hello world

    ') + + expect(html).toBe('

    hello world

    ') + }) + + it('extracts plain text from rich content', () => { + expect(extractRichText('

    Hello world

    ')).toBe('Hello world') + expect(extractRichText('## 标题\n\n内容')).toBe('标题 内容') + }) +}) diff --git a/FM-Frontend/src/utils/rich-content.ts b/FM-Frontend/src/utils/rich-content.ts new file mode 100644 index 00000000..32d9c999 --- /dev/null +++ b/FM-Frontend/src/utils/rich-content.ts @@ -0,0 +1,272 @@ +const HTML_TAG_PATTERN = /<\/?[a-z][\s\S]*>/i +const DANGEROUS_TAGS = new Set(['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'textarea', 'select', 'svg', 'math']) +const ALLOWED_TAGS = new Set([ + 'a', + 'blockquote', + 'br', + 'code', + 'del', + 'div', + 'em', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'hr', + 'img', + 'li', + 'ol', + 'p', + 'pre', + 'span', + 'strong', + 'table', + 'tbody', + 'td', + 'th', + 'thead', + 'tr', + 'ul' +]) +const GLOBAL_ATTRS = new Set(['class', 'title']) +const TAG_ATTRS: Record> = { + a: new Set(['href', 'target', 'rel', 'title']), + img: new Set(['src', 'alt', 'title']), + td: new Set(['colspan', 'rowspan']), + th: new Set(['colspan', 'rowspan']) +} + +const escapeHtml = (value: string) => value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') + +const escapeAttr = (value: string) => escapeHtml(value).replace(/`/g, '`') + +const isSafeUrl = (value: string) => { + const normalized = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, '') + if (!normalized) return false + if (normalized.startsWith('#')) return true + if (normalized.startsWith('/') && !normalized.startsWith('//')) return true + if (/^(https?:|mailto:|tel:)/i.test(normalized)) return true + return /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(normalized) +} + +const isAllowedAttr = (tagName: string, attrName: string) => { + if (attrName.startsWith('on')) return false + return GLOBAL_ATTRS.has(attrName) || TAG_ATTRS[tagName]?.has(attrName) +} + +const sanitizeFallback = (html: string) => html + .replace(/<\s*(script|style|iframe|object|embed|svg|math)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '') + .replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '') + .replace(/\s+(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi, '') + +export const sanitizeRichHtml = (html: string) => { + const source = html.trim() + if (!source) return '' + + if (typeof DOMParser === 'undefined') { + return sanitizeFallback(source) + } + + const parser = new DOMParser() + const doc = parser.parseFromString(source, 'text/html') + + const walk = (node: Node) => { + if (node.nodeType === Node.COMMENT_NODE) { + node.parentNode?.removeChild(node) + return + } + + if (node.nodeType !== Node.ELEMENT_NODE) { + return + } + + const element = node as HTMLElement + const tagName = element.tagName.toLowerCase() + + if (DANGEROUS_TAGS.has(tagName)) { + element.remove() + return + } + + if (!ALLOWED_TAGS.has(tagName)) { + const children = Array.from(element.childNodes) + element.replaceWith(...children) + children.forEach(walk) + return + } + + Array.from(element.attributes).forEach(attribute => { + const attrName = attribute.name.toLowerCase() + const attrValue = attribute.value + + if (!isAllowedAttr(tagName, attrName)) { + element.removeAttribute(attribute.name) + return + } + + if ((attrName === 'href' || attrName === 'src') && !isSafeUrl(attrValue)) { + element.removeAttribute(attribute.name) + } + }) + + if (tagName === 'a' && element.getAttribute('href')) { + element.setAttribute('target', '_blank') + element.setAttribute('rel', 'noopener noreferrer') + } + + Array.from(element.childNodes).forEach(walk) + } + + Array.from(doc.body.childNodes).forEach(walk) + return doc.body.innerHTML.trim() +} + +const renderInlineMarkdown = (value: string) => { + let html = escapeHtml(value) + + html = html.replace(/`([^`]+)`/g, '$1') + html = html.replace(/\*\*([^*]+)\*\*/g, '$1') + html = html.replace(/__([^_]+)__/g, '$1') + html = html.replace(/\*([^*]+)\*/g, '$1') + html = html.replace(/_([^_]+)_/g, '$1') + html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, label: string, url: string) => { + const href = url.replace(/&/g, '&') + if (!isSafeUrl(href)) { + return label + } + return `
    ${label}` + }) + + return html.replace(/\n/g, '
    ') +} + +const markdownToHtml = (markdown: string) => { + const lines = markdown.replace(/\r\n?/g, '\n').split('\n') + const html: string[] = [] + const paragraphs: string[] = [] + const listItems: string[] = [] + let listTag: 'ul' | 'ol' | '' = '' + let inCodeFence = false + let codeLines: string[] = [] + + const flushParagraph = () => { + if (!paragraphs.length) return + html.push(`

    ${renderInlineMarkdown(paragraphs.join('\n'))}

    `) + paragraphs.length = 0 + } + + const flushList = () => { + if (!listTag || !listItems.length) return + html.push(`<${listTag}>${listItems.map(item => `
  • ${renderInlineMarkdown(item)}
  • `).join('')}`) + listItems.length = 0 + listTag = '' + } + + const flushCodeFence = () => { + html.push(`
    ${escapeHtml(codeLines.join('\n'))}
    `) + codeLines = [] + } + + lines.forEach(line => { + if (/^```/.test(line.trim())) { + if (inCodeFence) { + inCodeFence = false + flushCodeFence() + } else { + flushParagraph() + flushList() + inCodeFence = true + codeLines = [] + } + return + } + + if (inCodeFence) { + codeLines.push(line) + return + } + + if (!line.trim()) { + flushParagraph() + flushList() + return + } + + const heading = /^(#{1,6})\s+(.+)$/.exec(line) + if (heading) { + flushParagraph() + flushList() + const level = heading[1]!.length + html.push(`${renderInlineMarkdown(heading[2]!.trim())}`) + return + } + + const blockquote = /^>\s?(.*)$/.exec(line) + if (blockquote) { + flushParagraph() + flushList() + html.push(`
    ${renderInlineMarkdown(blockquote[1] || '')}
    `) + return + } + + const unordered = /^\s*[-*+]\s+(.+)$/.exec(line) + if (unordered) { + flushParagraph() + if (listTag && listTag !== 'ul') flushList() + listTag = 'ul' + listItems.push(unordered[1] || '') + return + } + + const ordered = /^\s*\d+\.\s+(.+)$/.exec(line) + if (ordered) { + flushParagraph() + if (listTag && listTag !== 'ol') flushList() + listTag = 'ol' + listItems.push(ordered[1] || '') + return + } + + flushList() + paragraphs.push(line) + }) + + if (inCodeFence) { + flushCodeFence() + } + flushParagraph() + flushList() + + return html.join('') +} + +export const renderRichContent = (content?: string | null) => { + const source = String(content || '').trim() + if (!source) return '' + + const html = HTML_TAG_PATTERN.test(source) ? source : markdownToHtml(source) + return sanitizeRichHtml(html) +} + +export const extractRichText = (content?: string | null) => { + const html = renderRichContent(content) + if (!html) return '' + const spacedHtml = html + .replace(//gi, ' ') + .replace(/<\/(p|div|h[1-6]|li|blockquote|tr)>/gi, ' ') + + if (typeof DOMParser === 'undefined') { + return spacedHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() + } + + const parser = new DOMParser() + const doc = parser.parseFromString(spacedHtml, 'text/html') + return (doc.body.textContent || '').replace(/\s+/g, ' ').trim() +} diff --git a/FM-Frontend/src/utils/shop-theme.ts b/FM-Frontend/src/utils/shop-theme.ts new file mode 100644 index 00000000..97bc3d51 --- /dev/null +++ b/FM-Frontend/src/utils/shop-theme.ts @@ -0,0 +1,252 @@ +/** + * Purpose: SHOP_THEME_CHANGED_EVENT supports shop-theme.ts by holding or executing the shop theme changed event page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const SHOP_THEME_CHANGED_EVENT = 'fingertip-designer-shop-theme-updated' + +/** + * Purpose: ShopThemeSource supports shop-theme.ts by holding or executing the shop theme source page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ShopThemeSource { + themePrimaryColor?: string | null + themeSecondaryColor?: string | null + themeAccentColor?: string | null + themePageBgColor?: string | null + themeCardBgColor?: string | null + themeBackgroundImageFileId?: string | number | null +} + +/** + * Purpose: ResolvedShopTheme supports shop-theme.ts by holding or executing the resolved shop theme page or API role. + * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. + */ +export interface ResolvedShopTheme { + primaryColor: string + secondaryColor: string + accentColor: string + tertiaryColor: string + neutralColor: string + pageBgColor: string + cardBgColor: string + textPrimary: string + textSecondary: string + borderColor: string + primarySoftColor: string + secondarySoftColor: string + primaryActionColor: string + gradient: string + softGradient: string + backgroundImageFileId?: string + cssVars: Record +} + +/** + * Purpose: HEX_COLOR_PATTERN supports shop-theme.ts by holding or executing the hex color pattern page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +const HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/ + +export const DEFAULT_SHOP_THEME: ResolvedShopTheme = resolveShopThemeSource() + +/** + * Purpose: resolveShopTheme supports shop-theme.ts by holding or executing the resolve shop theme page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export function resolveShopTheme(source?: ShopThemeSource | null): ResolvedShopTheme { + return resolveShopThemeSource(source) +} + +/** + * Purpose: applyShopTheme supports shop-theme.ts by holding or executing the apply shop theme page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export function applyShopTheme(theme: ResolvedShopTheme, backgroundImageUrl?: string | null) { + if (typeof document === 'undefined') { + return + } + const root = document.documentElement + Object.entries(theme.cssVars).forEach(([key, value]) => { + root.style.setProperty(key, value) + }) + root.style.setProperty('--theme-background-image', backgroundImageUrl ? `url("${backgroundImageUrl}")` : 'none') +} + +/** + * Purpose: notifyShopThemeChanged supports shop-theme.ts by holding or executing the notify shop theme changed page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +export function notifyShopThemeChanged() { + if (typeof window === 'undefined') { + return + } + window.dispatchEvent(new Event(SHOP_THEME_CHANGED_EVENT)) +} + +/** + * Purpose: resolveShopThemeSource supports shop-theme.ts by holding or executing the resolve shop theme source page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function resolveShopThemeSource(source?: ShopThemeSource | null): ResolvedShopTheme { + const normalizedPrimaryColor = normalizeHexColor(source?.themePrimaryColor) + const primaryColor = normalizedPrimaryColor || '#E8B4B8' + const secondaryColor = normalizeHexColor(source?.themeSecondaryColor) + || (normalizedPrimaryColor ? mixColor(primaryColor, '#C5A059', 0.35) : '#C5A059') + const neutralColor = normalizeHexColor(source?.themeAccentColor) + || (normalizedPrimaryColor ? mixColor('#4A443F', primaryColor, 0.14) : '#4A443F') + const accentColor = neutralColor + const tertiaryColor = normalizeHexColor(source?.themePageBgColor) || '#FDFBF9' + const pageBgColor = tertiaryColor + const cardBgColor = normalizeHexColor(source?.themeCardBgColor) || '#FFFFFF' + const textPrimary = readableTextColor(pageBgColor, neutralColor) + const textSecondary = textPrimary === neutralColor + ? mixColor(neutralColor, cardBgColor, 0.18) + : mixColor('#FFFFFF', primaryColor, 0.3) + const borderColor = mixColor(primaryColor, cardBgColor, 0.72) + const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.78) + const secondarySoftColor = mixColor(secondaryColor, pageBgColor, 0.66) + const primaryActionColor = mixColor(neutralColor, primaryColor, 0.28) + const gradient = `linear-gradient(135deg, ${primaryActionColor} 0%, ${secondaryColor} 100%)` + const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${secondarySoftColor} 58%, ${mixColor(primaryColor, pageBgColor, 0.62)} 100%)` + const backgroundImageFileId = source?.themeBackgroundImageFileId === undefined || source?.themeBackgroundImageFileId === null + ? undefined + : String(source.themeBackgroundImageFileId).trim() || undefined + + return { + primaryColor, + secondaryColor, + accentColor, + tertiaryColor, + neutralColor, + pageBgColor, + cardBgColor, + textPrimary, + textSecondary, + borderColor, + primarySoftColor, + secondarySoftColor, + primaryActionColor, + gradient, + softGradient, + backgroundImageFileId, + cssVars: { + '--primary-color': primaryColor, + '--theme-primary': primaryColor, + '--theme-secondary': secondaryColor, + '--theme-accent': accentColor, + '--theme-neutral': neutralColor, + '--theme-tertiary': tertiaryColor, + '--theme-primary-action': primaryActionColor, + '--theme-primary-soft': primarySoftColor, + '--theme-secondary-soft': secondarySoftColor, + '--theme-page-bg': pageBgColor, + '--theme-card-bg': cardBgColor, + '--theme-border': borderColor, + '--theme-gradient': gradient, + '--theme-gradient-soft': softGradient, + '--theme-button-shadow': `0 12px 28px ${rgba(primaryColor, 0.22)}`, + '--theme-focus-shadow': `0 0 0 3px ${rgba(primaryColor, 0.16)}`, + '--bg-color': pageBgColor, + '--secondary-bg-color': mixColor(secondaryColor, pageBgColor, 0.58), + '--surface-color': cardBgColor, + '--text-primary': textPrimary, + '--text-secondary': textSecondary + } + } +} + +/** + * Purpose: normalizeHexColor supports shop-theme.ts by holding or executing the normalize hex color page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function normalizeHexColor(value?: string | null): string | undefined { + if (!value) { + return undefined + } + const normalized = value.trim() + return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : undefined +} + +/** + * Purpose: mixColor supports shop-theme.ts by holding or executing the mix color page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function mixColor(foreground: string, background: string, backgroundWeight: number): string { + const fg = hexToRgb(foreground) + const bg = hexToRgb(background) + const weight = clamp(backgroundWeight, 0, 1) + return rgbToHex({ + r: Math.round(fg.r * (1 - weight) + bg.r * weight), + g: Math.round(fg.g * (1 - weight) + bg.g * weight), + b: Math.round(fg.b * (1 - weight) + bg.b * weight) + }) +} + +/** + * Purpose: readableTextColor supports shop-theme.ts by holding or executing the readable text color page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function readableTextColor(background: string, preferred: string): string { + return relativeLuminance(hexToRgb(background)) > 0.48 ? preferred : '#FFFFFF' +} + +/** + * Purpose: rgba supports shop-theme.ts by holding or executing the rgba page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function rgba(color: string, alpha: number): string { + const rgb = hexToRgb(color) + return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamp(alpha, 0, 1)})` +} + +/** + * Purpose: relativeLuminance supports shop-theme.ts by holding or executing the relative luminance page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function relativeLuminance(rgb: { r: number; g: number; b: number }): number { + const toLinearChannel = (value: number) => { + const channel = value / 255 + return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4) + } + const r = toLinearChannel(rgb.r) + const g = toLinearChannel(rgb.g) + const b = toLinearChannel(rgb.b) + return 0.2126 * r + 0.7152 * g + 0.0722 * b +} + +/** + * Purpose: hexToRgb supports shop-theme.ts by holding or executing the hex to rgb page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function hexToRgb(color: string): { r: number; g: number; b: number } { + const value = color.replace('#', '') + return { + r: Number.parseInt(value.slice(0, 2), 16), + g: Number.parseInt(value.slice(2, 4), 16), + b: Number.parseInt(value.slice(4, 6), 16) + } +} + +/** + * Purpose: rgbToHex supports shop-theme.ts by holding or executing the rgb to hex page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function rgbToHex(rgb: { r: number; g: number; b: number }): string { + return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}` +} + +/** + * Purpose: toHex supports shop-theme.ts by holding or executing the to hex page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function toHex(value: number): string { + return clamp(value, 0, 255).toString(16).padStart(2, '0').toUpperCase() +} + +/** + * Purpose: clamp supports shop-theme.ts by holding or executing the clamp page or API role. + * Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow. + */ +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)) +} diff --git a/FM-Frontend/src/utils/signed-image-cache.test.ts b/FM-Frontend/src/utils/signed-image-cache.test.ts new file mode 100644 index 00000000..57fb2a8e --- /dev/null +++ b/FM-Frontend/src/utils/signed-image-cache.test.ts @@ -0,0 +1,70 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const publicGetSignedUrl = vi.fn() +const adminGetSignedUrl = vi.fn() + +vi.mock('@/api/file', () => ({ + fileApi: { + getSignedUrl: publicGetSignedUrl + } +})) + +vi.mock('@/api/admin', () => ({ + adminFileApi: { + getSignedUrl: adminGetSignedUrl + } +})) + +describe('signed-image-cache', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + publicGetSignedUrl.mockResolvedValue({ data: 'https://public.test/image.jpg' }) + adminGetSignedUrl.mockResolvedValue('https://admin.test/image.jpg') + }) + + it('keeps public and admin signed url cache entries isolated', async () => { + const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache') + + await expect(getCachedSignedImageUrl('42', '', 'public')).resolves.toBe('https://public.test/image.jpg') + await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/image.jpg') + + expect(publicGetSignedUrl).toHaveBeenCalledTimes(1) + expect(adminGetSignedUrl).toHaveBeenCalledTimes(1) + expect(getCachedSignedImageUrlSync('42', 'public')).toBe('https://public.test/image.jpg') + expect(getCachedSignedImageUrlSync('42', 'admin')).toBe('https://admin.test/image.jpg') + }) + + it('uses fallback when file id is empty or signing fails', async () => { + const { getCachedSignedImageUrl } = await import('./signed-image-cache') + + await expect(getCachedSignedImageUrl('', 'fallback.png', 'public')).resolves.toBe('fallback.png') + publicGetSignedUrl.mockRejectedValueOnce(new Error('sign failed')) + await expect(getCachedSignedImageUrl('99', 'fallback.png', 'public')).resolves.toBe('fallback.png') + }) + + it('normalizes signed image urls without scheme', async () => { + const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache') + + adminGetSignedUrl.mockResolvedValueOnce('img.yunail.art/325517220106911744.jpg?e=1&token=test') + + await expect(getCachedSignedImageUrl('325517232303947776', '', 'admin')).resolves.toBe( + 'http://img.yunail.art/325517220106911744.jpg?e=1&token=test' + ) + expect(getCachedSignedImageUrlSync('325517232303947776', 'admin')).toBe( + 'http://img.yunail.art/325517220106911744.jpg?e=1&token=test' + ) + }) + + it('refreshes a cached signed image url after clearing the old entry', async () => { + const { getCachedSignedImageUrl, refreshCachedSignedImageUrl } = await import('./signed-image-cache') + + adminGetSignedUrl + .mockResolvedValueOnce('https://admin.test/old.jpg') + .mockResolvedValueOnce('https://admin.test/new.jpg') + + await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/old.jpg') + await expect(refreshCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/new.jpg') + expect(adminGetSignedUrl).toHaveBeenCalledTimes(2) + }) +}) diff --git a/FM-Frontend/src/utils/signed-image-cache.ts b/FM-Frontend/src/utils/signed-image-cache.ts new file mode 100644 index 00000000..dcfa2490 --- /dev/null +++ b/FM-Frontend/src/utils/signed-image-cache.ts @@ -0,0 +1,135 @@ +import { fileApi } from '@/api/file' +import { adminFileApi } from '@/api/admin' +import type { IdType } from '@/utils/id' + +const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000 + +export type SignedImageSource = 'public' | 'admin' + +type SignedImageCacheEntry = { + url: string + expiresAt: number +} + +const signedImageUrlCache = new Map() +const pendingSignedImageUrlRequests = new Map>() + +const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim() +const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}` +const normalizeImageUrl = (url: string): string => { + const trimmedUrl = url.trim() + if (!trimmedUrl) return '' + if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) { + return trimmedUrl + } + return `http://${trimmedUrl}` +} + +const requestSignedImageUrl = (source: SignedImageSource, fileId: string): Promise => { + if (source === 'admin') { + return adminFileApi.getSignedUrl(fileId) + } + return fileApi.getSignedUrl(fileId).then(response => String(response.data || '')) +} + +const getUsableCacheEntry = (key: string) => { + const cached = signedImageUrlCache.get(key) + if (!cached) return undefined + if (cached.expiresAt <= Date.now()) { + signedImageUrlCache.delete(key) + return undefined + } + return cached.url +} + +export const parseImageFileIds = (value?: string | null): string[] => + String(value || '') + .split(',') + .map(id => id.trim()) + .filter(Boolean) + +export const getCachedSignedImageUrlSync = ( + fileId: IdType | null | undefined, + source: SignedImageSource = 'public' +): string => { + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return '' + return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || '' +} + +export const getCachedSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback = '', + source: SignedImageSource = 'public' +): Promise => { + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return fallback + const key = buildCacheKey(source, fileIdKey) + + const cachedUrl = getUsableCacheEntry(key) + if (cachedUrl) return cachedUrl + + const pendingRequest = pendingSignedImageUrlRequests.get(key) + if (pendingRequest) { + return pendingRequest.then(url => url || fallback).catch(() => fallback) + } + + const request = requestSignedImageUrl(source, fileIdKey) + .then(response => { + const url = normalizeImageUrl(String(response || '')) + if (url) { + signedImageUrlCache.set(key, { + url, + expiresAt: Date.now() + SIGNED_IMAGE_CACHE_TTL_MS + }) + } + return url + }) + .finally(() => { + pendingSignedImageUrlRequests.delete(key) + }) + + pendingSignedImageUrlRequests.set(key, request) + return request.then(url => url || fallback).catch(() => fallback) +} + +export const clearCachedSignedImageUrl = ( + fileId: IdType | null | undefined, + source: SignedImageSource = 'public' +): void => { + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return + const cacheKey = buildCacheKey(source, fileIdKey) + signedImageUrlCache.delete(cacheKey) + pendingSignedImageUrlRequests.delete(cacheKey) +} + +export const refreshCachedSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback = '', + source: SignedImageSource = 'public' +): Promise => { + clearCachedSignedImageUrl(fileId, source) + return getCachedSignedImageUrl(fileId, fallback, source) +} + +export const getCachedSignedImageUrls = async ( + fileIds: Array, + fallback = '', + source: SignedImageSource = 'public' +): Promise => { + const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source))) + const validUrls = urls.filter(Boolean) + return validUrls.length ? validUrls : (fallback ? [fallback] : []) +} + +export const getCachedSignedImageUrlsSync = ( + fileIds: Array, + source: SignedImageSource = 'public' +): string[] => + fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean) + +export const extractLegacyFileId = (value?: string | null): string => { + const source = String(value || '').replace(/<[^>]*>/g, '') + return source.match(/\/api\/file\/get\/([^/?#"'<>]+)/)?.[1] || '' +} diff --git a/FM-Frontend/src/utils/system-message-action.test.ts b/FM-Frontend/src/utils/system-message-action.test.ts new file mode 100644 index 00000000..d0420bad --- /dev/null +++ b/FM-Frontend/src/utils/system-message-action.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' +import { buildSystemMessageActionPath } from './system-message-action' + +describe('buildSystemMessageActionPath', () => { + it('keeps safe review action paths with order and review query parameters', () => { + expect(buildSystemMessageActionPath({ + actionPath: '/orders?orderId=10&reviewId=99&orderItemId=1001', + businessType: 'ORDER_ARTIST_REVIEW', + businessId: 99 + })).toBe('/orders?orderId=10&reviewId=99&orderItemId=1001') + }) + + it('uses reviewId fallback for review reminder messages when actionPath is absent', () => { + expect(buildSystemMessageActionPath({ + businessType: 'ORDER_ARTIST_REVIEW', + businessId: 99 + })).toBe('/orders?reviewId=99&source=message') + }) + + it('opens pending reviews when a review reminder has no business id', () => { + expect(buildSystemMessageActionPath({ + businessType: 'ORDER_ARTIST_REVIEW' + })).toBe('/orders?review=pending&source=message') + }) + + it('uses orderId fallback for generic order messages', () => { + expect(buildSystemMessageActionPath({ + businessType: 'ORDER', + businessId: 10 + })).toBe('/orders/10') + }) + + it('uses after-sale fallback for after-sale messages', () => { + expect(buildSystemMessageActionPath({ + businessType: 'AFTER_SALE', + businessId: 10 + })).toBe('/after-sales?orderId=10&source=message') + }) + + it('keeps safe order detail and after-sale action paths', () => { + expect(buildSystemMessageActionPath({ actionPath: '/orders/10' })).toBe('/orders/10') + expect(buildSystemMessageActionPath({ actionPath: '/after-sales?orderId=10' })).toBe('/after-sales?orderId=10') + expect(buildSystemMessageActionPath({ actionPath: '/after-sale/apply?orderId=10&orderItemId=99' })).toBe('/after-sale/apply?orderId=10&orderItemId=99') + expect(buildSystemMessageActionPath({ actionPath: '/service-progress?orderId=10' })).toBe('/service-progress?orderId=10') + }) + + it('rejects unsafe or backend-only action paths', () => { + expect(buildSystemMessageActionPath({ actionPath: '//evil.example/orders' })).toBe('') + expect(buildSystemMessageActionPath({ actionPath: 'https://evil.example/orders' })).toBe('') + expect(buildSystemMessageActionPath({ actionPath: '/admin/users' })).toBe('') + expect(buildSystemMessageActionPath({ actionPath: '/orders-admin' })).toBe('') + }) +}) diff --git a/FM-Frontend/src/utils/system-message-action.ts b/FM-Frontend/src/utils/system-message-action.ts new file mode 100644 index 00000000..52b21e91 --- /dev/null +++ b/FM-Frontend/src/utils/system-message-action.ts @@ -0,0 +1,95 @@ +import type { SystemMessageVO } from '@/api/user' + +type MessageLike = Pick + +const USER_ACTION_PREFIXES = [ + '/orders', + '/after-sales', + '/after-sale/apply', + '/service-progress', + '/help', + '/product/', + '/shop/', + '/coupons', + '/vip-center', + '/cart', + '/notifications', + '/wishlist', + '/profile', + '/settings', + '/artist-orders', + '/artist-calendar' +] + +const appendQuery = (path: string, query: Record) => { + const params = new URLSearchParams() + Object.entries(query).forEach(([key, value]) => { + if (value !== undefined && value !== '') { + params.set(key, String(value)) + } + }) + const queryString = params.toString() + return queryString ? `${path}?${queryString}` : path +} + +const isAllowedUserActionPath = (actionPath: string) => { + const pathOnly = actionPath.split('?')[0] || '' + return USER_ACTION_PREFIXES.some(prefix => { + if (prefix.endsWith('/')) { + return pathOnly.startsWith(prefix) + } + return pathOnly === prefix || pathOnly.startsWith(`${prefix}/`) + }) +} + +export const normalizeSystemMessageActionPath = (value?: string) => { + const actionPath = String(value || '').trim() + if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//') || actionPath.includes('\\')) { + return '' + } + return isAllowedUserActionPath(actionPath) ? actionPath : '' +} + +export const buildSystemMessageActionPath = (message: MessageLike) => { + const actionPath = normalizeSystemMessageActionPath(message.actionPath) + if (actionPath) { + return actionPath + } + + const businessType = String(message.businessType || '').toUpperCase() + const businessId = message.businessId === undefined || message.businessId === null ? '' : String(message.businessId) + if (businessType === 'ORDER_ARTIST_REVIEW') { + return businessId + ? appendQuery('/orders', { reviewId: businessId, source: 'message' }) + : appendQuery('/orders', { review: 'pending', source: 'message' }) + } + if (businessType === 'ORDER' && businessId) { + return `/orders/${encodeURIComponent(businessId)}` + } + if (businessType === 'ORDER_ARTIST_CHANGE' && businessId) { + return appendQuery('/service-progress', { orderId: businessId, source: 'message' }) + } + if (businessType === 'ORDER_ARTIST_CHANGE' || businessType === 'ORDER') { + return appendQuery('/orders', { orderId: businessId || undefined, source: 'message' }) + } + if (businessType === 'AFTER_SALE') { + return appendQuery('/after-sales', { orderId: businessId || undefined, source: 'message' }) + } + if (businessType === 'PRODUCT' && businessId) { + return `/product/${encodeURIComponent(businessId)}` + } + if (businessType === 'SHOP' && businessId) { + return `/shop/${encodeURIComponent(businessId)}` + } + if (businessType === 'VIP') { + return '/vip-center' + } + if (businessType === 'COUPON') { + return '/coupons' + } + if (businessType === 'CART') { + return '/cart' + } + + return '' +} diff --git a/FM-Frontend/src/views/AccountSettingsView.vue b/FM-Frontend/src/views/AccountSettingsView.vue new file mode 100644 index 00000000..b0ff9783 --- /dev/null +++ b/FM-Frontend/src/views/AccountSettingsView.vue @@ -0,0 +1,835 @@ + + + + + diff --git a/FM-Frontend/src/views/AfterSaleApplyView.vue b/FM-Frontend/src/views/AfterSaleApplyView.vue new file mode 100644 index 00000000..b3d27477 --- /dev/null +++ b/FM-Frontend/src/views/AfterSaleApplyView.vue @@ -0,0 +1,141 @@ + + + + + diff --git a/FM-Frontend/src/views/AfterSalesView.vue b/FM-Frontend/src/views/AfterSalesView.vue new file mode 100644 index 00000000..fc701677 --- /dev/null +++ b/FM-Frontend/src/views/AfterSalesView.vue @@ -0,0 +1,122 @@ + + + + + diff --git a/FM-Frontend/src/views/ArtistCalendarView.vue b/FM-Frontend/src/views/ArtistCalendarView.vue new file mode 100644 index 00000000..386ef997 --- /dev/null +++ b/FM-Frontend/src/views/ArtistCalendarView.vue @@ -0,0 +1,288 @@ + + + + + diff --git a/FM-Frontend/src/views/ArtistListView.vue b/FM-Frontend/src/views/ArtistListView.vue new file mode 100644 index 00000000..32033380 --- /dev/null +++ b/FM-Frontend/src/views/ArtistListView.vue @@ -0,0 +1,340 @@ + + + + + diff --git a/FM-Frontend/src/views/ArtistOrderView.vue b/FM-Frontend/src/views/ArtistOrderView.vue new file mode 100644 index 00000000..d78c4289 --- /dev/null +++ b/FM-Frontend/src/views/ArtistOrderView.vue @@ -0,0 +1,748 @@ + + + + + diff --git a/FM-Frontend/src/views/ArtistProfileView.vue b/FM-Frontend/src/views/ArtistProfileView.vue new file mode 100644 index 00000000..9dec8136 --- /dev/null +++ b/FM-Frontend/src/views/ArtistProfileView.vue @@ -0,0 +1,951 @@ + + + + + diff --git a/FM-Frontend/src/views/AuthView.vue b/FM-Frontend/src/views/AuthView.vue new file mode 100644 index 00000000..7f7c68eb --- /dev/null +++ b/FM-Frontend/src/views/AuthView.vue @@ -0,0 +1,1880 @@ + + + + + diff --git a/FM-Frontend/src/views/CartView.vue b/FM-Frontend/src/views/CartView.vue new file mode 100644 index 00000000..825192b7 --- /dev/null +++ b/FM-Frontend/src/views/CartView.vue @@ -0,0 +1,3267 @@ + + + + + diff --git a/FM-Frontend/src/views/CouponView.vue b/FM-Frontend/src/views/CouponView.vue new file mode 100644 index 00000000..a9797b0f --- /dev/null +++ b/FM-Frontend/src/views/CouponView.vue @@ -0,0 +1,446 @@ + + + + + diff --git a/FM-Frontend/src/views/HelpView.vue b/FM-Frontend/src/views/HelpView.vue new file mode 100644 index 00000000..3e503e01 --- /dev/null +++ b/FM-Frontend/src/views/HelpView.vue @@ -0,0 +1,96 @@ + + + + + diff --git a/FM-Frontend/src/views/HomeView.vue b/FM-Frontend/src/views/HomeView.vue new file mode 100644 index 00000000..a5adf994 --- /dev/null +++ b/FM-Frontend/src/views/HomeView.vue @@ -0,0 +1,1601 @@ + + + + + diff --git a/FM-Frontend/src/views/NotFoundView.vue b/FM-Frontend/src/views/NotFoundView.vue new file mode 100644 index 00000000..49a083ed --- /dev/null +++ b/FM-Frontend/src/views/NotFoundView.vue @@ -0,0 +1,224 @@ + + + + + diff --git a/FM-Frontend/src/views/NotificationsView.vue b/FM-Frontend/src/views/NotificationsView.vue new file mode 100644 index 00000000..9375a0cf --- /dev/null +++ b/FM-Frontend/src/views/NotificationsView.vue @@ -0,0 +1,331 @@ + + + + + diff --git a/FM-Frontend/src/views/OrderDetailView.vue b/FM-Frontend/src/views/OrderDetailView.vue new file mode 100644 index 00000000..1367717a --- /dev/null +++ b/FM-Frontend/src/views/OrderDetailView.vue @@ -0,0 +1,429 @@ + + + + + diff --git a/FM-Frontend/src/views/OrderView.vue b/FM-Frontend/src/views/OrderView.vue new file mode 100644 index 00000000..b765db9c --- /dev/null +++ b/FM-Frontend/src/views/OrderView.vue @@ -0,0 +1,2666 @@ + + + + + diff --git a/FM-Frontend/src/views/PasswordSettingsView.vue b/FM-Frontend/src/views/PasswordSettingsView.vue new file mode 100644 index 00000000..82d3c055 --- /dev/null +++ b/FM-Frontend/src/views/PasswordSettingsView.vue @@ -0,0 +1,343 @@ + + + + + diff --git a/FM-Frontend/src/views/ProductDetailView.vue b/FM-Frontend/src/views/ProductDetailView.vue new file mode 100644 index 00000000..83b98984 --- /dev/null +++ b/FM-Frontend/src/views/ProductDetailView.vue @@ -0,0 +1,1935 @@ + + + + + diff --git a/FM-Frontend/src/views/ProductListView.vue b/FM-Frontend/src/views/ProductListView.vue new file mode 100644 index 00000000..f8a5a635 --- /dev/null +++ b/FM-Frontend/src/views/ProductListView.vue @@ -0,0 +1,1053 @@ + + + + + diff --git a/FM-Frontend/src/views/ProfileView.vue b/FM-Frontend/src/views/ProfileView.vue new file mode 100644 index 00000000..37eb972e --- /dev/null +++ b/FM-Frontend/src/views/ProfileView.vue @@ -0,0 +1,1436 @@ + + + + + diff --git a/FM-Frontend/src/views/ServiceProgressView.vue b/FM-Frontend/src/views/ServiceProgressView.vue new file mode 100644 index 00000000..e894389d --- /dev/null +++ b/FM-Frontend/src/views/ServiceProgressView.vue @@ -0,0 +1,147 @@ + + + + + diff --git a/FM-Frontend/src/views/SettingsView.vue b/FM-Frontend/src/views/SettingsView.vue new file mode 100644 index 00000000..bb15e1d9 --- /dev/null +++ b/FM-Frontend/src/views/SettingsView.vue @@ -0,0 +1,258 @@ + + + + + diff --git a/FM-Frontend/src/views/ShopDetailView.vue b/FM-Frontend/src/views/ShopDetailView.vue new file mode 100644 index 00000000..afa5215c --- /dev/null +++ b/FM-Frontend/src/views/ShopDetailView.vue @@ -0,0 +1,1916 @@ + + + + + diff --git a/FM-Frontend/src/views/VipCenterView.vue b/FM-Frontend/src/views/VipCenterView.vue new file mode 100644 index 00000000..56c3fcd8 --- /dev/null +++ b/FM-Frontend/src/views/VipCenterView.vue @@ -0,0 +1,957 @@ + + + + + diff --git a/FM-Frontend/src/views/WishlistView.vue b/FM-Frontend/src/views/WishlistView.vue new file mode 100644 index 00000000..8d159eed --- /dev/null +++ b/FM-Frontend/src/views/WishlistView.vue @@ -0,0 +1,520 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/AdminLayout.vue b/FM-Frontend/src/views/admin/AdminLayout.vue new file mode 100644 index 00000000..ff9c3e64 --- /dev/null +++ b/FM-Frontend/src/views/admin/AdminLayout.vue @@ -0,0 +1,1196 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/AdminLoginView.vue b/FM-Frontend/src/views/admin/AdminLoginView.vue new file mode 100644 index 00000000..878a9dbb --- /dev/null +++ b/FM-Frontend/src/views/admin/AdminLoginView.vue @@ -0,0 +1,514 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/AfterSalesView.vue b/FM-Frontend/src/views/admin/AfterSalesView.vue new file mode 100644 index 00000000..2b9ead61 --- /dev/null +++ b/FM-Frontend/src/views/admin/AfterSalesView.vue @@ -0,0 +1,295 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/AnnouncementsView.vue b/FM-Frontend/src/views/admin/AnnouncementsView.vue new file mode 100644 index 00000000..45cf77d4 --- /dev/null +++ b/FM-Frontend/src/views/admin/AnnouncementsView.vue @@ -0,0 +1,216 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/CampaignsView.vue b/FM-Frontend/src/views/admin/CampaignsView.vue new file mode 100644 index 00000000..201f2944 --- /dev/null +++ b/FM-Frontend/src/views/admin/CampaignsView.vue @@ -0,0 +1,312 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/CommentsView.vue b/FM-Frontend/src/views/admin/CommentsView.vue new file mode 100644 index 00000000..b47887df --- /dev/null +++ b/FM-Frontend/src/views/admin/CommentsView.vue @@ -0,0 +1,245 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/CouponsView.vue b/FM-Frontend/src/views/admin/CouponsView.vue new file mode 100644 index 00000000..dcda0898 --- /dev/null +++ b/FM-Frontend/src/views/admin/CouponsView.vue @@ -0,0 +1,987 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/DashboardView.vue b/FM-Frontend/src/views/admin/DashboardView.vue new file mode 100644 index 00000000..e8130901 --- /dev/null +++ b/FM-Frontend/src/views/admin/DashboardView.vue @@ -0,0 +1,1088 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/HomeView.vue b/FM-Frontend/src/views/admin/HomeView.vue new file mode 100644 index 00000000..e045f490 --- /dev/null +++ b/FM-Frontend/src/views/admin/HomeView.vue @@ -0,0 +1,583 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/InventoryView.vue b/FM-Frontend/src/views/admin/InventoryView.vue new file mode 100644 index 00000000..428a3554 --- /dev/null +++ b/FM-Frontend/src/views/admin/InventoryView.vue @@ -0,0 +1,344 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/LegalAgreementsView.vue b/FM-Frontend/src/views/admin/LegalAgreementsView.vue new file mode 100644 index 00000000..1dedd5e1 --- /dev/null +++ b/FM-Frontend/src/views/admin/LegalAgreementsView.vue @@ -0,0 +1,215 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/ManageView.vue b/FM-Frontend/src/views/admin/ManageView.vue new file mode 100644 index 00000000..f8f76ecf --- /dev/null +++ b/FM-Frontend/src/views/admin/ManageView.vue @@ -0,0 +1,405 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/MessageHubPushConfigsView.vue b/FM-Frontend/src/views/admin/MessageHubPushConfigsView.vue new file mode 100644 index 00000000..5efeb287 --- /dev/null +++ b/FM-Frontend/src/views/admin/MessageHubPushConfigsView.vue @@ -0,0 +1,480 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/NailArtistsView.vue b/FM-Frontend/src/views/admin/NailArtistsView.vue new file mode 100644 index 00000000..1b66ab79 --- /dev/null +++ b/FM-Frontend/src/views/admin/NailArtistsView.vue @@ -0,0 +1,708 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/OrdersView.vue b/FM-Frontend/src/views/admin/OrdersView.vue new file mode 100644 index 00000000..b510ea02 --- /dev/null +++ b/FM-Frontend/src/views/admin/OrdersView.vue @@ -0,0 +1,1053 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/PermissionsView.vue b/FM-Frontend/src/views/admin/PermissionsView.vue new file mode 100644 index 00000000..fc632889 --- /dev/null +++ b/FM-Frontend/src/views/admin/PermissionsView.vue @@ -0,0 +1,835 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/ProductsView.vue b/FM-Frontend/src/views/admin/ProductsView.vue new file mode 100644 index 00000000..002f0a3b --- /dev/null +++ b/FM-Frontend/src/views/admin/ProductsView.vue @@ -0,0 +1,1602 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/ProfileView.vue b/FM-Frontend/src/views/admin/ProfileView.vue new file mode 100644 index 00000000..0a87cdcb --- /dev/null +++ b/FM-Frontend/src/views/admin/ProfileView.vue @@ -0,0 +1,260 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/SchedulesView.vue b/FM-Frontend/src/views/admin/SchedulesView.vue new file mode 100644 index 00000000..c47cbcf2 --- /dev/null +++ b/FM-Frontend/src/views/admin/SchedulesView.vue @@ -0,0 +1,309 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/ShopsView.vue b/FM-Frontend/src/views/admin/ShopsView.vue new file mode 100644 index 00000000..d82f45d7 --- /dev/null +++ b/FM-Frontend/src/views/admin/ShopsView.vue @@ -0,0 +1,2795 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/SystemMessagesView.vue b/FM-Frontend/src/views/admin/SystemMessagesView.vue new file mode 100644 index 00000000..64414ea3 --- /dev/null +++ b/FM-Frontend/src/views/admin/SystemMessagesView.vue @@ -0,0 +1,742 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/TagsView.vue b/FM-Frontend/src/views/admin/TagsView.vue new file mode 100644 index 00000000..d617d644 --- /dev/null +++ b/FM-Frontend/src/views/admin/TagsView.vue @@ -0,0 +1,662 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/UsersView.vue b/FM-Frontend/src/views/admin/UsersView.vue new file mode 100644 index 00000000..d46416ca --- /dev/null +++ b/FM-Frontend/src/views/admin/UsersView.vue @@ -0,0 +1,1978 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/VipRechargePlansView.vue b/FM-Frontend/src/views/admin/VipRechargePlansView.vue new file mode 100644 index 00000000..f7bebe30 --- /dev/null +++ b/FM-Frontend/src/views/admin/VipRechargePlansView.vue @@ -0,0 +1,189 @@ + + + + + diff --git a/FM-Frontend/src/views/admin/admin-helpers.ts b/FM-Frontend/src/views/admin/admin-helpers.ts new file mode 100644 index 00000000..2e5c2b57 --- /dev/null +++ b/FM-Frontend/src/views/admin/admin-helpers.ts @@ -0,0 +1,45 @@ +/** + * Purpose: AdminCachedUserInfo supports admin-helpers.ts by holding or executing the admin cached user info page or API role. + * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. + */ +import { loadCachedAdminUserInfo, isBootstrapAdminUser, type AdminCachedUserInfo } from '@/utils/admin-session' + +export { loadCachedAdminUserInfo, isBootstrapAdminUser } +export type { AdminCachedUserInfo } + +/** + * Purpose: getAdminRoleLabel supports admin-helpers.ts by holding or executing the get admin role label page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminRoleLabel = (type?: number) => { + switch (type) { + case 4: + return '平台管理员' + case 2: + return '店长' + case 3: + return '美甲师' + default: + return '后台账号' + } +} + +/** + * Purpose: getAdminShopOptions supports admin-helpers.ts by holding or executing the get admin shop options page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminShopOptions = (userInfo?: AdminCachedUserInfo | null) => { + const ids = userInfo?.shopIds || [] + const names = userInfo?.shopNames || [] + return ids.map((id, index) => ({ + id: String(id), + name: names[index] || `门店 ${id}` + })) +} + +/** + * Purpose: getAdminCurrentShopName supports admin-helpers.ts by holding or executing the get admin current shop name page or API role. + * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. + */ +export const getAdminCurrentShopName = (userInfo?: AdminCachedUserInfo | null) => + userInfo?.shopName || (isBootstrapAdminUser(userInfo) ? '平台总览模式' : '游客模式') diff --git a/FM-Frontend/src/views/admin/admin-modal-user-form.test.ts b/FM-Frontend/src/views/admin/admin-modal-user-form.test.ts new file mode 100644 index 00000000..6082d794 --- /dev/null +++ b/FM-Frontend/src/views/admin/admin-modal-user-form.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { readFileSync, readdirSync } from 'node:fs' +import { join } from 'node:path' + +const sourceRoot = join(process.cwd(), 'src') +const adminViewsPath = join(sourceRoot, 'views', 'admin') + +function readSource(relativePath: string) { + return readFileSync(join(sourceRoot, relativePath), 'utf-8') +} + +function findModalTags(source: string) { + return Array.from(source.matchAll(//g), match => match[0]) +} + +function findUserFormModal(source: string) { + const match = source.match(//) + return match?.[0] ?? '' +} + +function findFormItem(source: string, name: string) { + const match = source.match(new RegExp(``)) + return match?.[0] ?? '' +} + +describe('admin modal and user form behavior', () => { + it('keeps every backend modal open when users click the blank mask area', () => { + const responsiveModal = readSource('components/admin/AdminResponsiveModal.vue') + expect(responsiveModal).toMatch(/ fileName.endsWith('.vue')) + .flatMap(fileName => { + const source = readFileSync(join(adminViewsPath, fileName), 'utf-8') + return findModalTags(source) + .map((tag, index) => ({ fileName, index: index + 1, tag })) + .filter(({ tag }) => !/:mask-closable\s*=\s*"false"/.test(tag)) + .map(({ fileName, index }) => `${fileName} modal #${index}`) + }) + + expect(missingMaskLock).toEqual([]) + }) + + it('shows only one editable phone field in the user create and edit form', () => { + const usersView = readSource('views/admin/UsersView.vue') + const userFormModal = findUserFormModal(usersView) + + expect(userFormModal).toContain('name="phone"') + expect(userFormModal).not.toContain('name="contactPhone"') + expect(userFormModal).not.toContain('formState.contactPhone') + expect(usersView).toContain('const primaryPhone = formState.phone.trim()') + expect(usersView).toContain('phone: primaryPhone') + expect(usersView).toContain('contactPhone: primaryPhone') + }) + + it('uses a polished date picker and visible required markers for conditional user fields', () => { + const usersView = readSource('views/admin/UsersView.vue') + const userFormModal = findUserFormModal(usersView) + const wechatIdField = findFormItem(userFormModal, 'wechatId') + const shopIdsField = findFormItem(userFormModal, 'shopIds') + + expect(userFormModal).not.toContain('type="date"') + expect(userFormModal).toContain('/g), match => match[0]) +} + +describe('admin table layout', () => { + it('keeps every admin table wide enough to scroll horizontally', () => { + const missingScrollX = readdirSync(adminViewsPath) + .filter(fileName => fileName.endsWith('.vue')) + .flatMap(fileName => { + const source = readFileSync(join(adminViewsPath, fileName), 'utf-8') + return findTableTags(source) + .map((tag, index) => ({ fileName, index: index + 1, tag })) + .filter(({ tag }) => !/:scroll\s*=\s*"\{[\s\S]*x:\s*'max-content'/.test(tag)) + .map(({ fileName, index }) => `${fileName} table #${index}`) + }) + + expect(missingScrollX).toEqual([]) + }) + + it('prevents backend table cells from breaking text into vertical columns', () => { + const adminLayout = readSource('views/admin/AdminLayout.vue') + + expect(adminLayout).not.toMatch(/\.mobile-content\s+:deep\(\.ant-table-cell\)\s*\{[\s\S]*overflow-wrap:\s*anywhere/) + expect(adminLayout).toContain('table-layout: auto;') + expect(adminLayout).toContain('width: max-content;') + expect(adminLayout).toContain('word-break: keep-all;') + }) + + it('keeps table ellipsis text content-sized without arbitrary character breaking', () => { + const ellipsisText = readSource('components/TableEllipsisText.vue') + + expect(ellipsisText).toContain('display: inline-block;') + expect(ellipsisText).not.toMatch(/^\s*width:\s*100%;$/m) + expect(ellipsisText).not.toContain('word-break: break-all;') + }) +}) diff --git a/FM-Frontend/src/views/web-theme-governance.test.ts b/FM-Frontend/src/views/web-theme-governance.test.ts new file mode 100644 index 00000000..c9fbbf76 --- /dev/null +++ b/FM-Frontend/src/views/web-theme-governance.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' + +const sourceRoot = join(process.cwd(), 'src') +const coreRoot = join(process.cwd(), '..', 'FM-Core', 'src', 'main', 'java') + +function readSource(relativePath: string) { + return readFileSync(join(sourceRoot, relativePath), 'utf-8') +} + +describe('web theme governance', () => { + it('keeps login pages on the shared shop theme variables', () => { + const authView = readSource('views/AuthView.vue') + const adminLoginView = readSource('views/admin/AdminLoginView.vue') + + expect(authView).not.toMatch(/#667eea|#764ba2/) + expect(authView).toContain('var(--theme-gradient)') + expect(authView).toContain('var(--theme-card-bg)') + expect(adminLoginView).not.toMatch(/--admin-mobile-accent|#d4866c|#c26e52/) + expect(adminLoginView).toContain('var(--theme-gradient)') + expect(adminLoginView).toContain('var(--theme-card-bg)') + }) + + it('does not reset admin routes back to an unrelated theme', () => { + const app = readSource('App.vue') + + expect(app).not.toMatch(/if\s*\(\s*isAdminPage\s*\)\s*\{\s*resetShopTheme\(\)/) + expect(app).not.toMatch(/route\.matched\.some\(r => r\.meta\.isAdmin\)\)\s*\{\s*resetShopTheme\(\)/) + expect(app).toContain("mode: 'admin'") + }) + + it('derives backend mobile colors from the active shop theme', () => { + const adminMobile = readSource('styles/admin-mobile.css') + + expect(adminMobile).toContain('--admin-mobile-ink: var(--text-primary);') + expect(adminMobile).toContain('--admin-mobile-card: var(--theme-card-bg);') + expect(adminMobile).toContain('--admin-mobile-accent: var(--theme-primary);') + expect(adminMobile).not.toMatch(/--admin-mobile-(?:ink|surface|card|accent|accent-strong|shell-start|shell-mid|shell-end):\s*#[0-9a-fA-F]{3,8}/) + expect(adminMobile).toContain('.admin-mobile-card__row strong') + expect(adminMobile).toContain('overflow-wrap: break-word;') + }) + + it('does not let feature pages redefine global theme variables', () => { + const systemMessages = readSource('views/admin/SystemMessagesView.vue') + + expect(systemMessages).not.toMatch(/--theme-primary:\s*#[0-9a-fA-F]{3,8}/) + expect(systemMessages).not.toMatch(/--theme-gradient:\s*linear-gradient\([^;]*#[0-9a-fA-F]{3,8}/) + }) + + it('keeps the web customer surface in a centered phone shell on desktop', () => { + const app = readSource('App.vue') + const globalStyle = readSource('style.css') + + expect(app).toContain('fingertip-designer-phone-frame') + expect(app).toContain('fingertip-designer-phone-frame--hidden-nav') + expect(globalStyle).toMatch(/--frontend-page-max-width:\s*430px/) + expect(globalStyle).toContain('--theme-neutral: #4A443F;') + expect(globalStyle).toContain('--theme-tertiary: #FDFBF9;') + expect(globalStyle).toContain('.fingertip-designer-phone-frame') + expect(globalStyle).toContain('.fingertip-designer-page') + expect(globalStyle).toContain('.fingertip-designer-glass-card') + expect(globalStyle).toContain('.fingertip-designer-status-chip') + expect(globalStyle).toContain('.fingertip-designer-bottom-action') + expect(globalStyle).toContain('max-width: var(--frontend-page-max-width);') + expect(globalStyle).not.toMatch(/--theme-primary:\s*#7C5357/) + }) + + it('keeps frontend and backend platform overview permission allowlists aligned', () => { + const frontend = readSource('utils/platform-admin-permissions.ts') + const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'fingertipdesigner', 'core', 'modules', 'security', 'support', 'PermissionCatalog.java'), 'utf-8') + + expect(backend).toContain('"security:audit:view"') + expect(frontend).toContain("'security:audit:view'") + }) +}) diff --git a/FM-Frontend/tests/api/admin.stale-token.test.ts b/FM-Frontend/tests/api/admin.stale-token.test.ts new file mode 100644 index 00000000..378a93af --- /dev/null +++ b/FM-Frontend/tests/api/admin.stale-token.test.ts @@ -0,0 +1,112 @@ +// @vitest-environment jsdom + +import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const messageError = vi.hoisted(() => vi.fn()) + +vi.mock('ant-design-vue', () => ({ + message: { + error: messageError + } +})) + +import adminApi from '../../src/api/admin' + +function createTokenExpiredError(config: InternalAxiosRequestConfig) { + const response = { + data: { + code: 401, + message: 'Token expired' + }, + status: 401, + statusText: 'Unauthorized', + headers: {}, + config, + request: {} + } as AxiosResponse + + return new AxiosError( + 'Request failed with status code 401', + AxiosError.ERR_BAD_REQUEST, + config, + {}, + response + ) +} + +describe('admin api stale token handling', () => { + const originalAdapter = adminApi.defaults.adapter + + beforeEach(() => { + vi.useFakeTimers() + messageError.mockClear() + window.history.replaceState(null, '', '/admin') + localStorage.clear() + sessionStorage.clear() + }) + + afterEach(() => { + adminApi.defaults.adapter = originalAdapter + localStorage.clear() + sessionStorage.clear() + vi.useRealTimers() + }) + + it('keeps a newer admin session when an old-token request returns 401', async () => { + localStorage.setItem('adminAccessToken', 'old-admin-token') + localStorage.setItem('adminRefreshToken', 'old-admin-refresh') + sessionStorage.setItem('adminAccessToken', 'old-admin-token') + + const requests: Array<{ url?: string, authorization?: string }> = [] + let markRequestStarted!: () => void + let releaseStale401!: () => void + const requestStarted = new Promise(resolve => { + markRequestStarted = resolve + }) + + adminApi.defaults.adapter = ((config: InternalAxiosRequestConfig) => { + if (config.url !== '/user/info') { + return Promise.reject(new Error(`Unexpected request: ${config.url}`)) + } + requests.push({ + url: config.url, + authorization: String(config.headers.Authorization || '') + }) + markRequestStarted() + return new Promise((_resolve, reject) => { + releaseStale401 = () => reject(createTokenExpiredError(config)) + }) + }) as AxiosAdapter + + const staleRequest = adminApi.get('/user/info') + + await requestStarted + expect(requests).toEqual([ + { + url: '/user/info', + authorization: 'Bearer old-admin-token' + } + ]) + + localStorage.setItem('adminAccessToken', 'new-admin-token') + localStorage.setItem('adminRefreshToken', 'new-admin-refresh') + sessionStorage.setItem('adminAccessToken', 'new-admin-token') + const hrefBefore401 = window.location.href + + releaseStale401() + + await expect(staleRequest).rejects.toMatchObject({ + response: { + status: 401 + } + }) + await vi.runAllTimersAsync() + + expect(localStorage.getItem('adminAccessToken')).toBe('new-admin-token') + expect(localStorage.getItem('adminRefreshToken')).toBe('new-admin-refresh') + expect(sessionStorage.getItem('adminAccessToken')).toBe('new-admin-token') + expect(window.location.href).toBe(hrefBefore401) + expect(messageError).not.toHaveBeenCalled() + }) +}) diff --git a/FM-Frontend/tests/api/auth-free-paths.test.ts b/FM-Frontend/tests/api/auth-free-paths.test.ts new file mode 100644 index 00000000..209c29a2 --- /dev/null +++ b/FM-Frontend/tests/api/auth-free-paths.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { isApiAuthFreePath, WEB_API_AUTH_FREE_PATHS } from '@/api/auth-free-paths' + +describe('auth-free API contract', () => { + it('covers public paths and rejects protected business APIs', () => { + expect(isApiAuthFreePath('/comment/list/product/1')).toBe(true) + expect(isApiAuthFreePath('/user/wechat-mini/auto-login')).toBe(true) + expect(isApiAuthFreePath('/admin/auth/login-shops/1')).toBe(true) + expect(isApiAuthFreePath('/nail-artist/profile/1')).toBe(true) + expect(isApiAuthFreePath('/nail-artist/1/availability')).toBe(true) + expect(isApiAuthFreePath('/nail-artist/1/reviews')).toBe(true) + expect(isApiAuthFreePath('/shop/list')).toBe(true) + + expect(isApiAuthFreePath('/order/list')).toBe(false) + expect(isApiAuthFreePath('/shop/delete/1')).toBe(false) + expect(isApiAuthFreePath('/permission/list')).toBe(false) + expect(isApiAuthFreePath('/order/list?next=/user/login')).toBe(false) + expect(isApiAuthFreePath('/user/profile/admin/auth/refresh')).toBe(false) + }) + + it('keeps auth-free path constants unique', () => { + expect(new Set(WEB_API_AUTH_FREE_PATHS).size).toBe(WEB_API_AUTH_FREE_PATHS.length) + }) +}) diff --git a/FM-Frontend/tests/api/index.stale-token.test.ts b/FM-Frontend/tests/api/index.stale-token.test.ts new file mode 100644 index 00000000..9512fa68 --- /dev/null +++ b/FM-Frontend/tests/api/index.stale-token.test.ts @@ -0,0 +1,124 @@ +// @vitest-environment jsdom + +import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const messageError = vi.hoisted(() => vi.fn()) +const modalError = vi.hoisted(() => vi.fn()) + +vi.mock('ant-design-vue', () => ({ + message: { + error: messageError + }, + Modal: { + error: modalError + } +})) + +import api from '../../src/api' + +function createTokenExpiredError(config: InternalAxiosRequestConfig) { + const response = { + data: { + code: 401, + message: 'Token expired' + }, + status: 401, + statusText: 'Unauthorized', + headers: {}, + config, + request: {} + } as AxiosResponse + + return new AxiosError( + 'Request failed with status code 401', + AxiosError.ERR_BAD_REQUEST, + config, + {}, + response + ) +} + +describe('api stale token handling', () => { + const originalAdapter = api.defaults.adapter + + beforeEach(() => { + vi.useFakeTimers() + messageError.mockClear() + modalError.mockClear() + window.history.replaceState(null, '', '/profile') + localStorage.clear() + sessionStorage.clear() + }) + + afterEach(() => { + api.defaults.adapter = originalAdapter + localStorage.clear() + sessionStorage.clear() + vi.useRealTimers() + }) + + it('keeps a newer login session when an old-token request returns 401', async () => { + localStorage.setItem('accessToken', 'old-token') + sessionStorage.setItem('accessToken', 'old-token') + + const requests: Array<{ url?: string, authorization?: string }> = [] + let markRequestStarted!: () => void + let releaseStale401!: () => void + const requestStarted = new Promise(resolve => { + markRequestStarted = resolve + }) + + api.defaults.adapter = ((config: InternalAxiosRequestConfig) => { + if (config.url !== '/user/info') { + return Promise.reject(new Error(`Unexpected request: ${config.url}`)) + } + + requests.push({ + url: config.url, + authorization: String(config.headers.Authorization || '') + }) + markRequestStarted() + + return new Promise((_resolve, reject) => { + releaseStale401 = () => reject(createTokenExpiredError(config)) + }) + }) as AxiosAdapter + + const staleRequest = api.get('/user/info') + + await requestStarted + expect(requests).toEqual([ + { + url: '/user/info', + authorization: 'Bearer old-token' + } + ]) + + localStorage.setItem('accessToken', 'new-token') + localStorage.setItem('refreshToken', 'new-refresh') + localStorage.setItem('userInfo', JSON.stringify({ id: 2, nickname: 'new-user' })) + sessionStorage.setItem('accessToken', 'new-token') + sessionStorage.setItem('refreshToken', 'new-refresh') + const hrefBefore401 = window.location.href + + releaseStale401() + + await expect(staleRequest).rejects.toMatchObject({ + response: { + status: 401 + } + }) + await vi.runAllTimersAsync() + + expect(requests).toHaveLength(1) + expect(localStorage.getItem('accessToken')).toBe('new-token') + expect(localStorage.getItem('refreshToken')).toBe('new-refresh') + expect(localStorage.getItem('userInfo')).toBe(JSON.stringify({ id: 2, nickname: 'new-user' })) + expect(sessionStorage.getItem('accessToken')).toBe('new-token') + expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh') + expect(window.location.href).toBe(hrefBefore401) + expect(messageError).not.toHaveBeenCalled() + expect(modalError).not.toHaveBeenCalled() + }) +}) diff --git a/FM-Frontend/tests/api/system-unavailable.test.ts b/FM-Frontend/tests/api/system-unavailable.test.ts new file mode 100644 index 00000000..ba8223f4 --- /dev/null +++ b/FM-Frontend/tests/api/system-unavailable.test.ts @@ -0,0 +1,146 @@ +// @vitest-environment jsdom + +import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const messageError = vi.hoisted(() => vi.fn()) +const modalError = vi.hoisted(() => vi.fn()) + +vi.mock('ant-design-vue', () => ({ + message: { + error: messageError + }, + Modal: { + error: modalError + } +})) + +import api from '../../src/api' + +const createResponseError = (config: InternalAxiosRequestConfig, status: number): AxiosError => { + const response = { + data: { + code: status, + message: `HTTP ${status}` + }, + status, + statusText: 'Error', + headers: {}, + config, + request: {} + } as AxiosResponse + + return new AxiosError( + `Request failed with status code ${status}`, + AxiosError.ERR_BAD_RESPONSE, + config, + {}, + response + ) +} + +const createNetworkError = (config: InternalAxiosRequestConfig): AxiosError => + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, {}) + +type MockRequestResult = AxiosError | null + +const mockRequestResults = (results: MockRequestResult[]) => { + let currentResultIndex = 0 + api.defaults.adapter = ((config: InternalAxiosRequestConfig) => { + const result = results[currentResultIndex] + currentResultIndex += 1 + if (!result) { + return Promise.resolve({ + data: { code: 200, data: { ok: true } }, + status: 200, + statusText: 'OK', + headers: {}, + config, + request: {} + } as AxiosResponse) + } + result.config = config + return Promise.reject(result) + }) as AxiosAdapter +} + +describe('api system unavailable handling', () => { + const originalAdapter = api.defaults.adapter + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + messageError.mockClear() + modalError.mockClear() + localStorage.clear() + sessionStorage.clear() + }) + + afterEach(() => { + api.defaults.adapter = originalAdapter + localStorage.clear() + sessionStorage.clear() + vi.useRealTimers() + }) + + it('shows one system unavailable modal after three server failures in the window', async () => { + const config = {} as InternalAxiosRequestConfig + mockRequestResults([ + createResponseError(config, 500), + createResponseError(config, 502), + createResponseError(config, 503), + createResponseError(config, 500) + ]) + + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } }) + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 502 } }) + expect(modalError).not.toHaveBeenCalled() + + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 503 } }) + expect(modalError).toHaveBeenCalledTimes(1) + expect(modalError).toHaveBeenCalledWith(expect.objectContaining({ + title: '系统暂不可用', + content: '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。', + okText: '我知道了' + })) + + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } }) + expect(modalError).toHaveBeenCalledTimes(1) + modalError.mock.calls[0]?.[0]?.afterClose?.() + }) + + it('counts network failures as system failures', async () => { + const config = {} as InternalAxiosRequestConfig + vi.setSystemTime(70_000) + mockRequestResults([ + createNetworkError(config), + createNetworkError(config), + createNetworkError(config) + ]) + + await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError) + await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError) + await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError) + + expect(modalError).toHaveBeenCalledTimes(1) + expect(messageError).toHaveBeenCalledTimes(1) + }) + + it('resets failure count after a successful response', async () => { + const config = {} as InternalAxiosRequestConfig + vi.setSystemTime(140_000) + mockRequestResults([ + createResponseError(config, 500), + createResponseError(config, 500), + null, + createResponseError(config, 500) + ]) + + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } }) + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } }) + await expect(api.get('/health')).resolves.toEqual({ ok: true }) + await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } }) + + expect(modalError).not.toHaveBeenCalled() + }) +}) diff --git a/FM-Frontend/tests/api/vnext-api-contracts.test.ts b/FM-Frontend/tests/api/vnext-api-contracts.test.ts new file mode 100644 index 00000000..b0793889 --- /dev/null +++ b/FM-Frontend/tests/api/vnext-api-contracts.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment jsdom + +import type { AxiosAdapter, AxiosResponse, InternalAxiosRequestConfig } from 'axios' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const messageError = vi.hoisted(() => vi.fn()) + +vi.mock('ant-design-vue', () => ({ + message: { + error: messageError + } +})) + +import adminApi, { + adminAfterSaleApi, + adminArtistScheduleApi, + adminCampaignApi, + adminDashboardApi, + adminInventoryApi, + adminPaymentApi +} from '../../src/api/admin' +import api from '../../src/api' +import { afterSaleApi, growthApi, paymentApi } from '../../src/api/order' + +type CapturedRequest = { + method?: string + url?: string + params?: any + data?: any +} + +function okResponse(config: InternalAxiosRequestConfig): AxiosResponse { + return { + data: { + code: 200, + message: 'ok', + data: {} + }, + status: 200, + statusText: 'OK', + headers: {}, + config, + request: {} + } +} + +function parseData(data: unknown) { + return typeof data === 'string' && data ? JSON.parse(data) : data +} + +function captureAdapter(requests: CapturedRequest[]): AxiosAdapter { + return (config: InternalAxiosRequestConfig) => { + requests.push({ + method: config.method, + url: config.url, + params: config.params, + data: parseData(config.data) + }) + return Promise.resolve(okResponse(config)) + } +} + +describe('vNext API contracts', () => { + const originalAdminAdapter = adminApi.defaults.adapter + const originalApiAdapter = api.defaults.adapter + + beforeEach(() => { + messageError.mockClear() + localStorage.clear() + sessionStorage.clear() + }) + + afterEach(() => { + adminApi.defaults.adapter = originalAdminAdapter + api.defaults.adapter = originalApiAdapter + localStorage.clear() + sessionStorage.clear() + }) + + it('uses backend admin vNext endpoints', async () => { + const requests: CapturedRequest[] = [] + adminApi.defaults.adapter = captureAdapter(requests) + + await adminArtistScheduleApi.listSchedules({ artistId: 9, startDate: '2026-06-01', endDate: '2026-06-07' }) + await adminArtistScheduleApi.saveSchedule({ artistId: 9, workDate: '2026-06-01', startTime: '09:00', endTime: '18:00' }) + await adminPaymentApi.manualConfirmOrder(42, 'cash verified') + await adminAfterSaleApi.listAfterSales({ status: 'APPLIED', page: 1, size: 20 }) + await adminAfterSaleApi.approveAfterSale(5, { auditReason: 'approved' }) + await adminInventoryApi.saveItem({ itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 }) + await adminInventoryApi.adjustStock(7, { changeType: 'IN', changeQuantity: 3, remark: 'restock' }) + await adminCampaignApi.saveCampaign({ title: 'Summer Set', scene: 'HOME', status: 1 }) + await adminDashboardApi.getAnalytics() + + expect(requests).toEqual([ + { method: 'get', url: '/artist-schedule/list', params: { artistId: 9, startDate: '2026-06-01', endDate: '2026-06-07' }, data: undefined }, + { method: 'post', url: '/artist-schedule/save', params: undefined, data: { artistId: 9, workDate: '2026-06-01', startTime: '09:00', endTime: '18:00' } }, + { method: 'post', url: '/payment/order/42/manual-confirm', params: { remark: 'cash verified' }, data: undefined }, + { method: 'get', url: '/after-sale/list', params: { status: 'APPLIED', page: 1, size: 20 }, data: undefined }, + { method: 'put', url: '/after-sale/5/approve', params: undefined, data: { auditReason: 'approved' } }, + { method: 'post', url: '/inventory/save', params: undefined, data: { itemName: 'Base Gel', category: 'gel', unit: 'bottle', stockQuantity: 12 } }, + { method: 'post', url: '/inventory/7/adjust', params: undefined, data: { changeType: 'IN', changeQuantity: 3, remark: 'restock' } }, + { method: 'post', url: '/campaign/save', params: undefined, data: { title: 'Summer Set', scene: 'HOME', status: 1 } }, + { method: 'get', url: '/dashboard/analytics', params: undefined, data: undefined } + ]) + }) + + it('uses backend user vNext endpoints', async () => { + const requests: CapturedRequest[] = [] + api.defaults.adapter = captureAdapter(requests) + + await paymentApi.prepareOrderPayment(42) + await paymentApi.mockSuccess(42) + await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 }) + await afterSaleApi.listMy({ page: 1, size: 5 }) + await growthApi.getSummary() + + expect(requests).toEqual([ + { method: 'post', url: '/payment/order/42/prepare', params: undefined, data: undefined }, + { method: 'post', url: '/payment/order/42/mock-success', params: undefined, data: undefined }, + { method: 'post', url: '/after-sale/apply', params: undefined, data: { orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 } }, + { method: 'get', url: '/after-sale/my', params: { page: 1, size: 5 }, data: undefined }, + { method: 'get', url: '/growth/summary', params: undefined, data: undefined } + ]) + }) +}) diff --git a/FM-Frontend/tsconfig.app.json b/FM-Frontend/tsconfig.app.json new file mode 100644 index 00000000..46dfbfa5 --- /dev/null +++ b/FM-Frontend/tsconfig.app.json @@ -0,0 +1,20 @@ +{ + "extends": "@vue/tsconfig/tsconfig.dom.json", + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "baseUrl": ".", + "paths": { + "@/*": ["src/*"] + }, + "types": ["vite/client"], + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/FM-Frontend/tsconfig.json b/FM-Frontend/tsconfig.json new file mode 100644 index 00000000..1ffef600 --- /dev/null +++ b/FM-Frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/FM-Frontend/tsconfig.node.json b/FM-Frontend/tsconfig.node.json new file mode 100644 index 00000000..8a67f62f --- /dev/null +++ b/FM-Frontend/tsconfig.node.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "ES2023", + "lib": ["ES2023"], + "module": "ESNext", + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["vite.config.ts"] +} diff --git a/FM-Frontend/vite.config.ts b/FM-Frontend/vite.config.ts new file mode 100644 index 00000000..e1fc04bd --- /dev/null +++ b/FM-Frontend/vite.config.ts @@ -0,0 +1,89 @@ +import { defineConfig, loadEnv } from 'vite' +import vue from '@vitejs/plugin-vue' +import path from 'path' +import AutoImport from 'unplugin-auto-import/vite' +import Components from 'unplugin-vue-components/vite' +import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' +import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers' + +export default defineConfig(({ mode }) => { + const env = loadEnv(mode, process.cwd(), '') + const proxyTarget = (env.VITE_DEV_PROXY_TARGET || 'http://127.0.0.1:80').trim() + const proxyToCoreDirectly = /(^|:)81(\/|$)/.test(proxyTarget) + const shouldWriteDeclarationFiles = mode === 'development' + + return { + plugins: [ + vue(), + AutoImport({ + resolvers: [ElementPlusResolver()], + imports: ['vue', 'vue-router', 'pinia'], + dts: shouldWriteDeclarationFiles ? 'src/auto-import.d.ts' : false + }), + Components({ + resolvers: [ElementPlusResolver(), AntDesignVueResolver({ importStyle: 'less' })], + dts: shouldWriteDeclarationFiles ? 'src/components.d.ts' : false + }), + { + name: 'ip-access-control', + configureServer(server) { + server.middlewares.use((_req, _res, next) => { + next() + }) + } + } + ], + resolve: { + alias: { + '@': path.resolve(__dirname, './src') + } + }, + server: { + port: 3000, + host: true, + proxy: { + '/admin/api': { + target: proxyTarget, + changeOrigin: true, + rewrite: path => proxyToCoreDirectly ? path.replace(/^\/admin\/api/, '/admin') : path + }, + '/api': { + target: proxyTarget, + changeOrigin: true, + rewrite: path => proxyToCoreDirectly ? path.replace(/^\/api/, '') : path + } + }, + allowedHosts: [ + 'localhost', + '127.0.0.1', + '2666.online', + 'wcy111.top' + ] + }, + build: { + rollupOptions: { + output: { + manualChunks(id) { + if (!id.includes('node_modules')) { + return undefined + } + const normalizedId = id.replaceAll('\\', '/') + if (normalizedId.includes('@ant-design/icons-vue')) { + return 'antdv-icons' + } + if (normalizedId.includes('ant-design-vue')) { + return 'antdv' + } + if (normalizedId.includes('element-plus') || normalizedId.includes('@element-plus')) { + return 'element-plus' + } + if (normalizedId.includes('vue-router') || normalizedId.includes('pinia') || normalizedId.includes('/vue/')) { + return 'vue-core' + } + return 'vendor' + } + } + } + } + } +}) diff --git a/FM-Frontend/vitest.config.ts b/FM-Frontend/vitest.config.ts new file mode 100644 index 00000000..d99b14cd --- /dev/null +++ b/FM-Frontend/vitest.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vitest/config' +import path from 'node:path' + +export default defineConfig({ + test: { + environment: 'jsdom', + globals: false + }, + resolve: { + alias: { + '@': path.resolve(__dirname, './src') + } + } +}) diff --git a/FM-Gateway/pom.xml b/FM-Gateway/pom.xml new file mode 100644 index 00000000..52477166 --- /dev/null +++ b/FM-Gateway/pom.xml @@ -0,0 +1,202 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + + com.xiaowang + JayuCloud-Salon-Gateway + 0.0.1 + JayuCloud-Salon-Gateway + JayuCloud-Salon-Gateway - 店务服务网关 + + + 17 + 2021.0.8 + 2021.0.5.0 + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.cloud + spring-cloud-starter-bootstrap + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.cloud + spring-cloud-starter-loadbalancer + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + org.springframework.boot + spring-boot-starter-logging + + + + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + + + + org.projectlombok + lombok + 1.18.32 + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + + + + JayuCloud-Salon-Gateway + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy-release-jar + package + + run + + + + + + + + + + + + + + diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/FingertipDesignerGatewayApplication.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/FingertipDesignerGatewayApplication.java new file mode 100644 index 00000000..e857b4c0 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/FingertipDesignerGatewayApplication.java @@ -0,0 +1,21 @@ +package com.xiaowang.fingertipdesigner.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; + +/** + * Fingertip Designer 网关启动类 + * + * @author xiaowang + * @date 2026-02-12 + */ +@EnableDiscoveryClient +@SpringBootApplication +public class FingertipDesignerGatewayApplication { + + public static void main(String[] args) { + SpringApplication.run(FingertipDesignerGatewayApplication.class, args); + } + +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/CorsConfig.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/CorsConfig.java new file mode 100644 index 00000000..6c791128 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/CorsConfig.java @@ -0,0 +1,35 @@ +package com.xiaowang.fingertipdesigner.gateway.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.reactive.CorsWebFilter; +import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; + +import java.util.Arrays; + +/** + * Gateway CORS 配置 + * + * @author xiaowang + * @date 2026-02-13 + */ +@Configuration +public class CorsConfig { + + @Bean + public CorsWebFilter corsWebFilter() { + CorsConfiguration config = new CorsConfiguration(); + + config.addAllowedOriginPattern("*"); + config.addAllowedMethod("*"); + config.addAllowedHeader("*"); + config.setAllowCredentials(true); + config.setMaxAge(3600L); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + + return new CorsWebFilter(source); + } +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/GatewayConfig.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/GatewayConfig.java new file mode 100644 index 00000000..08f0fcbe --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/GatewayConfig.java @@ -0,0 +1,33 @@ +package com.xiaowang.fingertipdesigner.gateway.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +/** + * 网关白名单配置。 + * + * @author xiaowang + * @date 2026-02-12 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.gateway") +public class GatewayConfig { + + /** + * 白名单路径列表。 + */ + private List whitelist; + + private SlowRequest slowRequest = new SlowRequest(); + + @Data + public static class SlowRequest { + private boolean enabled = true; + private long thresholdMs = 300; + private boolean logResponseHeaderRequestId = true; + } +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/JwtProperties.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/JwtProperties.java new file mode 100644 index 00000000..4cb495a6 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/config/JwtProperties.java @@ -0,0 +1,20 @@ +package com.xiaowang.fingertipdesigner.gateway.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * Gateway JWT 校验配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "fingertip-designer.security.jwt") +public class JwtProperties { + + private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + + private String issuer = "fingertip-designer"; + + private long clockSkewSeconds = 30; +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/controller/HealthController.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/controller/HealthController.java new file mode 100644 index 00000000..65569590 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/controller/HealthController.java @@ -0,0 +1,65 @@ +package com.xiaowang.fingertipdesigner.gateway.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/health") +@RequiredArgsConstructor +public class HealthController { + + private final DiscoveryClient discoveryClient; + private final Environment environment; + + @GetMapping("/check") + public Map check() { + Map result = new LinkedHashMap<>(); + result.put("code", 200); + result.put("message", "Fingertip Designer gateway is running"); + result.put("data", diagnosticsPayload()); + return result; + } + + @GetMapping("/diagnostics") + public Map diagnostics() { + Map result = new LinkedHashMap<>(); + result.put("code", 200); + result.put("message", "operation successful"); + result.put("data", diagnosticsPayload()); + return result; + } + + private Map diagnosticsPayload() { + Map diagnostics = new LinkedHashMap<>(); + String serviceName = environment.getProperty("spring.application.name", "jayucloud-salon-gateway"); + diagnostics.put("service", serviceName); + diagnostics.put("port", environment.getProperty("server.port", "")); + diagnostics.put("gatewayService", discoverySummary(serviceName)); + diagnostics.put("coreService", discoverySummary("jayucloud-salon-core")); + return diagnostics; + } + + private Map discoverySummary(String serviceName) { + Map result = new LinkedHashMap<>(); + try { + List instances = discoveryClient.getInstances(serviceName); + result.put("ok", !instances.isEmpty()); + result.put("service", serviceName); + result.put("instanceCount", instances.size()); + } catch (Exception exception) { + result.put("ok", false); + result.put("service", serviceName); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/AuthGlobalFilter.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/AuthGlobalFilter.java new file mode 100644 index 00000000..ac7db1e1 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/AuthGlobalFilter.java @@ -0,0 +1,137 @@ +package com.xiaowang.fingertipdesigner.gateway.filter; + +import com.xiaowang.fingertipdesigner.gateway.config.GatewayConfig; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.StringUtils; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashSet; +import java.util.List; + +@Slf4j +@Component +public class AuthGlobalFilter implements GlobalFilter, Ordered { + + private static final List DEFAULT_WHITELIST = AuthWhitelist.defaultPatterns(); + + @Autowired + private GatewayConfig gatewayConfig; + + @Autowired + private GatewayJwtValidator gatewayJwtValidator; + + private final AntPathMatcher pathMatcher = new AntPathMatcher(); + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + String path = request.getURI().getPath(); + + if (isWhitelist(path)) { + return chain.filter(exchange); + } + + String authorization = request.getHeaders().getFirst("Authorization"); + if (!StringUtils.hasText(authorization)) { + return unAuthorized(exchange, "未携带Token,拒绝访问"); + } + + if (!authorization.startsWith("Bearer ")) { + return unAuthorized(exchange, "Token格式错误"); + } + + String token = authorization.substring("Bearer ".length()); + if (!gatewayJwtValidator.validateAccessToken(token)) { + return unAuthorized(exchange, "Token无效或已过期"); + } + + return chain.filter(exchange); + } + + private boolean isWhitelist(String path) { + return AuthWhitelist.effectivePatterns(gatewayConfig).stream() + .anyMatch(pattern -> pathMatcher.match(pattern, path)); + } + + private Mono unAuthorized(ServerWebExchange exchange, String msg) { + ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(HttpStatus.UNAUTHORIZED); + response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); + + String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}"; + DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8)); + + return response.writeWith(Mono.just(buffer)); + } + + @Override + public int getOrder() { + return -1; + } + + public static final class AuthWhitelist { + + private AuthWhitelist() { + } + + public static List defaultPatterns() { + return List.of( + "/api/user/login", + "/api/user/register", + "/api/user/check/**", + "/api/user/refresh-token", + "/api/user/send-verification-code", + "/api/user/phone-login", + "/api/user/wechat-mini/**", + "/api/user/reset-password-by-phone", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", + "/api/nail-artist/profile/**", + "/api/nail-artist/*/availability", + "/api/nail-artist/*/reviews", + "/api/product/get/**", + "/api/product/list/**", + "/api/comment/list/product/**", + "/api/shop/get/**", + "/api/shop/list", + "/api/shop/list/public", + "/api/shop/list/simple", + "/api/tag/list/all", + "/api/tag/list/filter-options", + "/api/file/get-signed-url/**", + "/api/admin/auth/login", + "/api/admin/auth/login-shops/**", + "/api/admin/auth/refresh", + "/admin/auth/login", + "/admin/auth/login-shops/**", + "/admin/auth/refresh", + "/admin/api/auth/login", + "/admin/api/auth/login-shops/**", + "/admin/api/auth/refresh", + "/api/health/**", + "/api/error" + ); + } + + public static List effectivePatterns(GatewayConfig gatewayConfig) { + if (gatewayConfig == null || gatewayConfig.getWhitelist() == null || gatewayConfig.getWhitelist().isEmpty()) { + return defaultPatterns(); + } + LinkedHashSet patterns = new LinkedHashSet<>(gatewayConfig.getWhitelist()); + patterns.addAll(DEFAULT_WHITELIST); + return List.copyOf(patterns); + } + } +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/GatewayJwtValidator.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/GatewayJwtValidator.java new file mode 100644 index 00000000..48370a6e --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/GatewayJwtValidator.java @@ -0,0 +1,40 @@ +package com.xiaowang.fingertipdesigner.gateway.filter; + +import com.xiaowang.fingertipdesigner.gateway.config.JwtProperties; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; + +/** + * Gateway 侧 JWT 快速校验。 + */ +@Component +@RequiredArgsConstructor +public class GatewayJwtValidator { + + private final JwtProperties jwtProperties; + + public boolean validateAccessToken(String token) { + try { + Claims claims = Jwts.parserBuilder() + .setSigningKey(getKey()) + .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) + .requireIssuer(jwtProperties.getIssuer()) + .build() + .parseClaimsJws(token) + .getBody(); + return "access".equals(claims.get("type", String.class)); + } catch (Exception exception) { + return false; + } + } + + private SecretKey getKey() { + return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/SlowRequestLoggingGlobalFilter.java b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/SlowRequestLoggingGlobalFilter.java new file mode 100644 index 00000000..ee2ab9c0 --- /dev/null +++ b/FM-Gateway/src/main/java/com/xiaowang/fingertipdesigner/gateway/filter/SlowRequestLoggingGlobalFilter.java @@ -0,0 +1,114 @@ +package com.xiaowang.fingertipdesigner.gateway.filter; + +import com.xiaowang.fingertipdesigner.gateway.config.GatewayConfig; +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.cloud.gateway.route.Route; +import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; +import org.springframework.core.Ordered; +import org.springframework.http.HttpHeaders; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class SlowRequestLoggingGlobalFilter implements GlobalFilter, Ordered { + + public static final String REQUEST_ID_HEADER = "X-Request-Id"; + + private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("gateway-slow"); + + private final GatewayConfig gatewayConfig; + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest originalRequest = exchange.getRequest(); + String requestId = resolveRequestId(originalRequest.getHeaders()); + ServerHttpRequest decoratedRequest = originalRequest.mutate() + .headers(headers -> headers.set(REQUEST_ID_HEADER, requestId)) + .build(); + ServerWebExchange decoratedExchange = exchange.mutate().request(decoratedRequest).build(); + GatewayConfig.SlowRequest slowRequest = gatewayConfig.getSlowRequest(); + if (slowRequest != null && slowRequest.isLogResponseHeaderRequestId()) { + decoratedExchange.getResponse().getHeaders().set(REQUEST_ID_HEADER, requestId); + } + + if (slowRequest == null || !slowRequest.isEnabled()) { + return chain.filter(decoratedExchange); + } + + long startNanos = System.nanoTime(); + return chain.filter(decoratedExchange) + .doFinally(signalType -> logIfSlow(decoratedExchange, requestId, startNanos, slowRequest.getThresholdMs())); + } + + @Override + public int getOrder() { + return -2; + } + + private void logIfSlow(ServerWebExchange exchange, String requestId, long startNanos, long thresholdMs) { + long durationMs = Math.max(0L, (System.nanoTime() - startNanos) / 1_000_000L); + if (durationMs < thresholdMs) { + return; + } + + ServerHttpRequest request = exchange.getRequest(); + Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); + String query = request.getURI().getRawQuery(); + String routeId = route == null ? "" : route.getId(); + String status = exchange.getResponse().getStatusCode() == null + ? "" + : String.valueOf(exchange.getResponse().getStatusCode().value()); + + SLOW_REQUEST_LOGGER.warn( + "requestId={} method={} path={} query={} routeId={} status={} durationMs={} clientIp={} userAgent={} contentLength={}", + requestId, + request.getMethodValue(), + request.getURI().getPath(), + sanitize(query), + sanitize(routeId), + status, + durationMs, + resolveClientIp(request), + sanitize(request.getHeaders().getFirst(HttpHeaders.USER_AGENT)), + request.getHeaders().getContentLength() + ); + } + + private String resolveRequestId(HttpHeaders headers) { + String requestId = headers.getFirst(REQUEST_ID_HEADER); + return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", ""); + } + + private String resolveClientIp(ServerHttpRequest request) { + String forwarded = request.getHeaders().getFirst("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeaders().getFirst("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + InetSocketAddress remoteAddress = request.getRemoteAddress(); + return remoteAddress == null || remoteAddress.getAddress() == null + ? "" + : remoteAddress.getAddress().getHostAddress(); + } + + private String sanitize(String value) { + if (!StringUtils.hasText(value)) { + return ""; + } + return value.replace('\n', '_').replace('\r', '_'); + } +} diff --git a/FM-Gateway/src/main/resources/application.yaml b/FM-Gateway/src/main/resources/application.yaml new file mode 100644 index 00000000..253dc226 --- /dev/null +++ b/FM-Gateway/src/main/resources/application.yaml @@ -0,0 +1,163 @@ +spring: + cloud: + gateway: + routes: + # 前台API路由 + - id: product-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/product/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: product-like-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/product-like/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: shop-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/shop/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: user-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/user/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: comment-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/comment/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: balance-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/balance/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: tag-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/tag/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: file-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/file/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: permission-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/permission/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: coupon-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/coupon/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: cart-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/cart/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: order-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/order/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: wishlist-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/wishlist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: nail-artist-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/nail-artist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: legal-agreement-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/legal-agreement/** + filters: + - RewritePath=/api/(?.*), /${remaining} + # 后台管理API路由(/api/admin/** 格式) + - id: admin-api-route + order: -10 + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/admin/** + filters: + - RewritePath=/api/admin/(?.*), /admin/${remaining} + # 后台管理API路由(/admin/api/** 格式) + - id: admin-route + order: -9 + uri: lb://jayucloud-salon-core + predicates: + - Path=/admin/api/** + filters: + - RewritePath=/admin/api/(?.*), /admin/${remaining} + - id: admin-auth-compat-route + order: -8 + uri: lb://jayucloud-salon-core + predicates: + - Path=/admin/auth/** + # 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404 + - id: frontend-fallback-route + order: 100 + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/** + filters: + - RewritePath=/api/(?.*), /${remaining} + +fingertip-designer: + security: + jwt: + issuer: fingertip-designer + clock-skew-seconds: 30 + gateway: + whitelist: + - /api/user/login + - /api/user/register + - /api/user/check/** + - /api/user/refresh-token + - /api/user/send-verification-code + - /api/user/phone-login + - /api/user/wechat-mini/** + - /api/user/reset-password-by-phone + - /api/nail-artist/profile/** + - /api/nail-artist/*/availability + - /api/nail-artist/*/reviews + - /api/shop/list + - /api/shop/list/simple + - /api/legal-agreement/current + - /api/legal-agreement/current/** + - /api/health/** + - /api/error + - /api/admin/auth/login + - /api/admin/auth/login-shops/** + - /api/admin/auth/refresh + - /api/admin/auth/register + - /admin/auth/login + - /admin/auth/login-shops/** + - /admin/auth/refresh + - /admin/api/auth/login + - /admin/api/auth/login-shops/** + - /admin/api/auth/refresh + slow-request: + enabled: true + threshold-ms: 300 + log-response-header-request-id: true diff --git a/FM-Gateway/src/main/resources/bootstrap.yaml b/FM-Gateway/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..fb81a929 --- /dev/null +++ b/FM-Gateway/src/main/resources/bootstrap.yaml @@ -0,0 +1,45 @@ +spring: + application: + name: jayucloud-salon-gateway + + cloud: + nacos: + discovery: + # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} + # Nacos 命名空间,默认指向开发环境 + namespace: ${NACOS_NAMESPACE:jayucloud-salon} + # 服务注册分组。 + group: ${NACOS_GROUP:DEFAULT_GROUP} + # 注册到 Nacos 的服务名。 + service: ${spring.application.name} + # Nacos 认证用户名。 + username: ${NACOS_USERNAME} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD} + config: + # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 + server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} + # Nacos 配置中心命名空间,默认指向开发环境。 + namespace: ${NACOS_NAMESPACE:jayucloud-salon} + # 配置分组。 + group: ${NACOS_GROUP:DEFAULT_GROUP} + # Gateway 服务独有配置文件。 + name: gateway + # 所有 Nacos 配置均使用 YAML。 + file-extension: yaml + # Nacos 认证用户名。 + username: ${NACOS_USERNAME} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD} + # Core 与 Gateway 共享的公共配置文件。 + shared-configs: + - data-id: infra.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true + - data-id: secret.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true + - data-id: logging.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} + refresh: true diff --git a/FM-Gateway/src/main/resources/log4j2.xml b/FM-Gateway/src/main/resources/log4j2.xml new file mode 100644 index 00000000..8a2e24be --- /dev/null +++ b/FM-Gateway/src/main/resources/log4j2.xml @@ -0,0 +1,81 @@ + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + E:/code/xiaowang/JayuCloud-Salon-Gateway/logs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml new file mode 100644 index 00000000..d4a612ad --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -0,0 +1,138 @@ +spring: + datasource: + url: jdbc:mysql://192.168.10.200:6033/jayucloud_artlist?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + servlet: + multipart: + max-file-size: 5MB + max-request-size: 10MB + jackson: + time-zone: Asia/Shanghai + date-format: yyyy-MM-dd HH:mm:ss + +logging: + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" + +server: + servlet: + encoding: + charset: UTF-8 + force: true + enabled: true + timezone: Asia/Shanghai + +mybatis: + configuration: + map-underscore-to-camel-case: true + +fingertip-designer: + brand: + message-template-name: ${PLATFORM_MESSAGE_TEMPLATE_NAME:JayuCloud-Artlist} + manager-register-shop-description: ${PLATFORM_MANAGER_REGISTER_SHOP_DESCRIPTION:甲屿店务注册店铺} + security: + jwt: + issuer: jayucloud-artlist + access-token-expiration-seconds: 7200 + remember-me-access-token-expiration-seconds: 604800 + refresh-token-expiration-seconds: 604800 + clock-skew-seconds: 30 + signature: + enabled: true + window-seconds: 300 + nonce-retention-seconds: 600 + rate-limit: + login: + limit: 10 + window-seconds: 60 + send-code: + limit: 5 + window-seconds: 60 + reset-password: + limit: 5 + window-seconds: 600 + authenticated-write: + limit: 80 + window-seconds: 60 + order-create: + limit: 10 + window-seconds: 60 + cache: + local-max-size: 2048 + product-detail: + local-ttl-seconds: 120 + redis-ttl-seconds: 900 + product-list: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + product-search: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + shop: + local-ttl-seconds: 180 + redis-ttl-seconds: 900 + tag: + local-ttl-seconds: 300 + redis-ttl-seconds: 1200 + object-storage-file: + local-ttl-seconds: 300 + redis-ttl-seconds: 1800 + dashboard: + local-ttl-seconds: 30 + redis-ttl-seconds: 90 + 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 + +object-storage: + provider-order: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + replica-required-providers: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + primary-provider: MINIO + backup-provider: QINIU_KODO,ALIYUN_OSS + signed-url-expire-minutes: 60 + backup-queue-name: jayucloud-artlist.file.object-storage.backup.queue + backup-exchange-name: jayucloud-artlist.file.object-storage.backup.exchange + backup-routing-key: jayucloud-artlist.file.object-storage.backup + backup-retry-batch-limit: 500 + backup-retry-cron: "0 0 2 * * ?" + +qiniu: + kodo: + access-key: ${QINIU_KODO_ACCESS_KEY:} + secret-key: ${QINIU_KODO_SECRET_KEY:} + bucket-name: ${QINIU_KODO_BUCKET_NAME:} + domain: ${QINIU_KODO_DOMAIN:} + zone: ${QINIU_KODO_ZONE:z2} + private-bucket: ${QINIU_KODO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${QINIU_KODO_SIGNED_URL_EXPIRE_MINUTES:60} + +minio: + enabled: ${MINIO_ENABLED:false} + endpoint: ${MINIO_ENDPOINT:} + bucket-name: ${MINIO_BUCKET_NAME:} + access-key: ${MINIO_ACCESS_KEY:} + secret-key: ${MINIO_SECRET_KEY:} + private-bucket: ${MINIO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${MINIO_SIGNED_URL_EXPIRE_MINUTES:60} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:false} + endpoint: ${ALIYUN_OSS_ENDPOINT:} + region: ${ALIYUN_OSS_REGION:} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID:} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET:} + signed-url-expire-minutes: ${ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES:60} diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/gateway.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/gateway.yaml new file mode 100644 index 00000000..841c26d1 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/gateway.yaml @@ -0,0 +1,163 @@ +spring: + cloud: + gateway: + routes: + # 前台API路由 + - id: product-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/product/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: product-like-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/product-like/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: shop-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/shop/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: user-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/user/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: comment-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/comment/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: balance-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/balance/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: tag-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/tag/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: file-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/file/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: permission-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/permission/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: coupon-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/coupon/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: cart-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/cart/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: order-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/order/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: wishlist-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/wishlist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: nail-artist-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/nail-artist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: legal-agreement-route + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/legal-agreement/** + filters: + - RewritePath=/api/(?.*), /${remaining} + # 后台管理API路由(/api/admin/** 格式) + - id: admin-api-route + order: -10 + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/admin/** + filters: + - RewritePath=/api/admin/(?.*), /admin/${remaining} + # 后台管理API路由(/admin/api/** 格式) + - id: admin-route + order: -9 + uri: lb://jayucloud-artlist-core + predicates: + - Path=/admin/api/** + filters: + - RewritePath=/admin/api/(?.*), /admin/${remaining} + - id: admin-auth-compat-route + order: -8 + uri: lb://jayucloud-artlist-core + predicates: + - Path=/admin/auth/** + # 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404 + - id: frontend-fallback-route + order: 100 + uri: lb://jayucloud-artlist-core + predicates: + - Path=/api/** + filters: + - RewritePath=/api/(?.*), /${remaining} + +fingertip-designer: + security: + jwt: + issuer: fingertip-designer + clock-skew-seconds: 30 + gateway: + whitelist: + - /api/user/login + - /api/user/register + - /api/user/check/** + - /api/user/refresh-token + - /api/user/send-verification-code + - /api/user/phone-login + - /api/user/wechat-mini/** + - /api/user/reset-password-by-phone + - /api/nail-artist/profile/** + - /api/nail-artist/*/availability + - /api/nail-artist/*/reviews + - /api/shop/list + - /api/shop/list/simple + - /api/legal-agreement/current + - /api/legal-agreement/current/** + - /api/health/** + - /api/error + - /api/admin/auth/login + - /api/admin/auth/login-shops/** + - /api/admin/auth/refresh + - /api/admin/auth/register + - /admin/auth/login + - /admin/auth/login-shops/** + - /admin/auth/refresh + - /admin/api/auth/login + - /admin/api/auth/login-shops/** + - /admin/api/auth/refresh + slow-request: + enabled: true + threshold-ms: 300 + log-response-header-request-id: true diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/infra.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/infra.yaml new file mode 100644 index 00000000..0c66fe41 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/infra.yaml @@ -0,0 +1,54 @@ +spring: + redis: + sentinel: + master: ${REDIS_SENTINEL_MASTER:mymaster} + nodes: ${REDIS_SENTINEL_NODES:192.168.10.17:26379,192.168.10.18:26379,192.168.10.19:26379,192.168.20.13:26379,10.66.0.4:26379} + username: ${REDIS_USERNAME:xiaowang} + password: ${REDIS_PASSWORD} + database: ${REDIS_DATABASE:0} + rabbitmq: + addresses: ${RABBITMQ_ADDRESSES:mq-prod.internal:5672} + virtual-host: ${RABBITMQ_VHOST} + username: ${RABBITMQ_USERNAME} + password: ${RABBITMQ_PASSWORD} + publisher-confirm-type: correlated + publisher-returns: true + listener: + simple: + acknowledge-mode: manual + auto-startup: true + +database: + business: + jdbc-url: ${BUSINESS_JDBC_URL} + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} + +object-storage: + primary-provider: ${OBJECT_STORAGE_PRIMARY_PROVIDER:MINIO} + provider-order: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + +minio: + enabled: ${MINIO_ENABLED:true} + endpoint: ${MINIO_ENDPOINT} + bucket-name: ${MINIO_BUCKET_NAME:jayucloud} + access-key: ${MINIO_ACCESS_KEY} + secret-key: ${MINIO_SECRET_KEY} + +qiniu: + kodo: + bucket-name: ${QINIU_KODO_BUCKET_NAME:jayucloud} + access-key: ${QINIU_KODO_ACCESS_KEY} + secret-key: ${QINIU_KODO_SECRET_KEY} + domain: ${QINIU_KODO_DOMAIN} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:true} + endpoint: ${ALIYUN_OSS_ENDPOINT} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:jayucloud} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET} diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/logging.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/logging.yaml new file mode 100644 index 00000000..83b867a9 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/logging.yaml @@ -0,0 +1,4 @@ +logging: + level: + root: INFO + com.xiaowang.fingertipdesigner: INFO diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml new file mode 100644 index 00000000..e597387b --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml @@ -0,0 +1,17 @@ +security: + nacos: + username: ${NACOS_USERNAME} + password: ${NACOS_PASSWORD} + database: + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} + redis: + password: ${REDIS_PASSWORD} + rabbitmq: + username: ${RABBITMQ_USERNAME} + password: ${RABBITMQ_PASSWORD} + +spring: + datasource: + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml new file mode 100644 index 00000000..4192278b --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -0,0 +1,138 @@ +spring: + datasource: + url: jdbc:mysql://192.168.10.200:6033/jayucloud_salon?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + servlet: + multipart: + max-file-size: 5MB + max-request-size: 10MB + jackson: + time-zone: Asia/Shanghai + date-format: yyyy-MM-dd HH:mm:ss + +logging: + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" + +server: + servlet: + encoding: + charset: UTF-8 + force: true + enabled: true + timezone: Asia/Shanghai + +mybatis: + configuration: + map-underscore-to-camel-case: true + +fingertip-designer: + brand: + message-template-name: ${PLATFORM_MESSAGE_TEMPLATE_NAME:JayuCloud-Salon} + manager-register-shop-description: ${PLATFORM_MANAGER_REGISTER_SHOP_DESCRIPTION:甲屿店务注册店铺} + security: + jwt: + issuer: jayucloud-salon + access-token-expiration-seconds: 7200 + remember-me-access-token-expiration-seconds: 604800 + refresh-token-expiration-seconds: 604800 + clock-skew-seconds: 30 + signature: + enabled: true + window-seconds: 300 + nonce-retention-seconds: 600 + rate-limit: + login: + limit: 10 + window-seconds: 60 + send-code: + limit: 5 + window-seconds: 60 + reset-password: + limit: 5 + window-seconds: 600 + authenticated-write: + limit: 80 + window-seconds: 60 + order-create: + limit: 10 + window-seconds: 60 + cache: + local-max-size: 2048 + product-detail: + local-ttl-seconds: 120 + redis-ttl-seconds: 900 + product-list: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + product-search: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + shop: + local-ttl-seconds: 180 + redis-ttl-seconds: 900 + tag: + local-ttl-seconds: 300 + redis-ttl-seconds: 1200 + object-storage-file: + local-ttl-seconds: 300 + redis-ttl-seconds: 1800 + dashboard: + local-ttl-seconds: 30 + redis-ttl-seconds: 90 + 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 + +object-storage: + provider-order: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + replica-required-providers: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + primary-provider: MINIO + backup-provider: QINIU_KODO,ALIYUN_OSS + signed-url-expire-minutes: 60 + backup-queue-name: jayucloud-salon.file.object-storage.backup.queue + backup-exchange-name: jayucloud-salon.file.object-storage.backup.exchange + backup-routing-key: jayucloud-salon.file.object-storage.backup + backup-retry-batch-limit: 500 + backup-retry-cron: "0 0 2 * * ?" + +qiniu: + kodo: + access-key: ${QINIU_KODO_ACCESS_KEY:} + secret-key: ${QINIU_KODO_SECRET_KEY:} + bucket-name: ${QINIU_KODO_BUCKET_NAME:} + domain: ${QINIU_KODO_DOMAIN:} + zone: ${QINIU_KODO_ZONE:z2} + private-bucket: ${QINIU_KODO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${QINIU_KODO_SIGNED_URL_EXPIRE_MINUTES:60} + +minio: + enabled: ${MINIO_ENABLED:false} + endpoint: ${MINIO_ENDPOINT:} + bucket-name: ${MINIO_BUCKET_NAME:} + access-key: ${MINIO_ACCESS_KEY:} + secret-key: ${MINIO_SECRET_KEY:} + private-bucket: ${MINIO_PRIVATE_BUCKET:true} + signed-url-expire-minutes: ${MINIO_SIGNED_URL_EXPIRE_MINUTES:60} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:false} + endpoint: ${ALIYUN_OSS_ENDPOINT:} + region: ${ALIYUN_OSS_REGION:} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID:} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET:} + signed-url-expire-minutes: ${ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES:60} diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/gateway.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/gateway.yaml new file mode 100644 index 00000000..253dc226 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/gateway.yaml @@ -0,0 +1,163 @@ +spring: + cloud: + gateway: + routes: + # 前台API路由 + - id: product-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/product/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: product-like-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/product-like/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: shop-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/shop/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: user-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/user/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: comment-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/comment/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: balance-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/balance/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: tag-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/tag/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: file-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/file/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: permission-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/permission/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: coupon-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/coupon/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: cart-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/cart/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: order-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/order/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: wishlist-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/wishlist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: nail-artist-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/nail-artist/** + filters: + - RewritePath=/api/(?.*), /${remaining} + - id: legal-agreement-route + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/legal-agreement/** + filters: + - RewritePath=/api/(?.*), /${remaining} + # 后台管理API路由(/api/admin/** 格式) + - id: admin-api-route + order: -10 + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/admin/** + filters: + - RewritePath=/api/admin/(?.*), /admin/${remaining} + # 后台管理API路由(/admin/api/** 格式) + - id: admin-route + order: -9 + uri: lb://jayucloud-salon-core + predicates: + - Path=/admin/api/** + filters: + - RewritePath=/admin/api/(?.*), /admin/${remaining} + - id: admin-auth-compat-route + order: -8 + uri: lb://jayucloud-salon-core + predicates: + - Path=/admin/auth/** + # 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404 + - id: frontend-fallback-route + order: 100 + uri: lb://jayucloud-salon-core + predicates: + - Path=/api/** + filters: + - RewritePath=/api/(?.*), /${remaining} + +fingertip-designer: + security: + jwt: + issuer: fingertip-designer + clock-skew-seconds: 30 + gateway: + whitelist: + - /api/user/login + - /api/user/register + - /api/user/check/** + - /api/user/refresh-token + - /api/user/send-verification-code + - /api/user/phone-login + - /api/user/wechat-mini/** + - /api/user/reset-password-by-phone + - /api/nail-artist/profile/** + - /api/nail-artist/*/availability + - /api/nail-artist/*/reviews + - /api/shop/list + - /api/shop/list/simple + - /api/legal-agreement/current + - /api/legal-agreement/current/** + - /api/health/** + - /api/error + - /api/admin/auth/login + - /api/admin/auth/login-shops/** + - /api/admin/auth/refresh + - /api/admin/auth/register + - /admin/auth/login + - /admin/auth/login-shops/** + - /admin/auth/refresh + - /admin/api/auth/login + - /admin/api/auth/login-shops/** + - /admin/api/auth/refresh + slow-request: + enabled: true + threshold-ms: 300 + log-response-header-request-id: true diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/infra.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/infra.yaml new file mode 100644 index 00000000..0c66fe41 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/infra.yaml @@ -0,0 +1,54 @@ +spring: + redis: + sentinel: + master: ${REDIS_SENTINEL_MASTER:mymaster} + nodes: ${REDIS_SENTINEL_NODES:192.168.10.17:26379,192.168.10.18:26379,192.168.10.19:26379,192.168.20.13:26379,10.66.0.4:26379} + username: ${REDIS_USERNAME:xiaowang} + password: ${REDIS_PASSWORD} + database: ${REDIS_DATABASE:0} + rabbitmq: + addresses: ${RABBITMQ_ADDRESSES:mq-prod.internal:5672} + virtual-host: ${RABBITMQ_VHOST} + username: ${RABBITMQ_USERNAME} + password: ${RABBITMQ_PASSWORD} + publisher-confirm-type: correlated + publisher-returns: true + listener: + simple: + acknowledge-mode: manual + auto-startup: true + +database: + business: + jdbc-url: ${BUSINESS_JDBC_URL} + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} + +object-storage: + primary-provider: ${OBJECT_STORAGE_PRIMARY_PROVIDER:MINIO} + provider-order: + - MINIO + - QINIU_KODO + - ALIYUN_OSS + +minio: + enabled: ${MINIO_ENABLED:true} + endpoint: ${MINIO_ENDPOINT} + bucket-name: ${MINIO_BUCKET_NAME:jayucloud} + access-key: ${MINIO_ACCESS_KEY} + secret-key: ${MINIO_SECRET_KEY} + +qiniu: + kodo: + bucket-name: ${QINIU_KODO_BUCKET_NAME:jayucloud} + access-key: ${QINIU_KODO_ACCESS_KEY} + secret-key: ${QINIU_KODO_SECRET_KEY} + domain: ${QINIU_KODO_DOMAIN} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:true} + endpoint: ${ALIYUN_OSS_ENDPOINT} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:jayucloud} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET} diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/logging.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/logging.yaml new file mode 100644 index 00000000..83b867a9 --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/logging.yaml @@ -0,0 +1,4 @@ +logging: + level: + root: INFO + com.xiaowang.fingertipdesigner: INFO diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/secret.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/secret.yaml new file mode 100644 index 00000000..e597387b --- /dev/null +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/secret.yaml @@ -0,0 +1,17 @@ +security: + nacos: + username: ${NACOS_USERNAME} + password: ${NACOS_PASSWORD} + database: + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} + redis: + password: ${REDIS_PASSWORD} + rabbitmq: + username: ${RABBITMQ_USERNAME} + password: ${RABBITMQ_PASSWORD} + +spring: + datasource: + username: ${BUSINESS_DB_USERNAME} + password: ${BUSINESS_DB_PASSWORD} diff --git a/scripts/deploy-jayucloud-salon-production.ps1 b/scripts/deploy-jayucloud-salon-production.ps1 new file mode 100644 index 00000000..b62d22ca --- /dev/null +++ b/scripts/deploy-jayucloud-salon-production.ps1 @@ -0,0 +1,841 @@ +param( + [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot), + [string]$ServerInfoPath = "", + [switch]$DryRun, + [switch]$Deploy, + [switch]$UsePuttyPassword, + [switch]$SkipBuild, + [switch]$SkipTests, + [switch]$AllowDirtyWorkingTree, + [switch]$SkipDatabaseInit, + [string]$DatabaseTargetName = "mysql02", + [int]$DatabasePort = 3306, + [string]$DatabaseName = "jayucloud_salon", + [string]$DatabaseUser = "", + [string]$DatabasePassword = "", + [string]$InitSqlPath = "", + [string]$CorePattern = "^FM-Core", + [string]$GatewayPattern = "^FM-Gateway", + [string]$WebTargetName = "", + [string]$WebTargetHost = "8.137.35.61", + [string]$CoreRemoteAppDir = "/opt/jayucloud-salon-core", + [string]$GatewayRemoteAppDir = "/opt/jayucloud-salon-gateway", + [string]$WebRemoteDir = "/opt/jayucloud-salon-frontend", + [string]$CoreServiceName = "jayucloud-salon-core", + [string]$GatewayServiceName = "jayucloud-salon-gateway", + [int]$CoreHealthPort = 81, + [int]$GatewayHealthPort = 80, + [string]$HealthPath = "/health/check", + [int]$HealthTimeoutSeconds = 120, + [string]$PublicBaseUrl = "https://salon.yunail.art", + [string]$MavenPath = "" +) + +$ErrorActionPreference = "Stop" + +$releaseTimestamp = Get-Date -Format "yyyyMMdd-HHmmss" +$resolvedRepoRoot = (Resolve-Path -LiteralPath $RepoRoot).Path +$releaseRoot = Join-Path $resolvedRepoRoot "artifacts\release" +$releaseDir = Join-Path $releaseRoot $releaseTimestamp +$backendDir = Join-Path $releaseDir "backend" +$frontendDir = Join-Path $releaseDir "frontend" +$sqlDir = Join-Path $releaseDir "sql" +$manifestPath = Join-Path $releaseDir "manifest.json" +$defaultInitSqlPath = Join-Path $resolvedRepoRoot "scripts\sql\migrations\20260825-双端独立数据库\店务独立数据库_20260825.sql" +if (-not $InitSqlPath) { + $InitSqlPath = $defaultInitSqlPath +} + +function Write-Step { + param([string]$Message) + + Write-Host "" + Write-Host "==> $Message" +} + +function ConvertTo-BashSingleQuoted { + param([AllowNull()][string]$Value) + + if ($null -eq $Value) { + $Value = "" + } + return "'" + $Value.Replace("'", "'""'""'") + "'" +} + +function Resolve-Maven { + param([string]$PreferredPath) + + if ($PreferredPath -and (Test-Path -LiteralPath $PreferredPath)) { + return (Resolve-Path -LiteralPath $PreferredPath).Path + } + + $fromPath = Get-Command mvn.cmd -ErrorAction SilentlyContinue + if ($fromPath) { + return $fromPath.Source + } + + $fromPath = Get-Command mvn -ErrorAction SilentlyContinue + if ($fromPath) { + return $fromPath.Source + } + + throw "找不到 Maven,请通过 -MavenPath 传入 Maven 可执行文件绝对路径。" +} + +function Invoke-Native { + param( + [string]$FilePath, + [string[]]$Arguments, + [string]$WorkingDirectory = "", + [switch]$RemoteMutation, + [switch]$Sensitive + ) + + if ($Sensitive) { + Write-Host ">> $FilePath <敏感参数已隐藏>" + } + else { + Write-Host ">> $FilePath $($Arguments -join ' ')" + } + + if ($DryRun -and $RemoteMutation) { + return + } + + $previousLocation = Get-Location + try { + if ($WorkingDirectory) { + Set-Location -LiteralPath $WorkingDirectory + } + & $FilePath @Arguments + if ($LASTEXITCODE -ne 0) { + throw "命令执行失败,退出码 ${LASTEXITCODE}:$FilePath" + } + } + finally { + Set-Location $previousLocation + } +} + +function Read-ZipEntryText { + param($Zip, [string]$Name) + + $entry = $Zip.GetEntry($Name) + if (-not $entry) { + return $null + } + + $stream = $entry.Open() + try { + $reader = [System.IO.StreamReader]::new($stream, [System.Text.Encoding]::UTF8) + try { + return $reader.ReadToEnd() + } + finally { + $reader.Dispose() + } + } + finally { + $stream.Dispose() + } +} + +function Get-RelationshipId { + param($Element) + + foreach ($attribute in $Element.Attributes) { + if ($attribute.LocalName -eq "id") { + return $attribute.Value + } + } + return "" +} + +function Get-ColumnIndex { + param([string]$CellRef) + + $letters = ([regex]::Match($CellRef, "^[A-Z]+")).Value + $index = 0 + foreach ($character in $letters.ToCharArray()) { + $index = ($index * 26) + ([int][char]$character - [int][char]"A" + 1) + } + return $index +} + +function Get-XlsxFirstSheetRows { + param([string]$Path) + + Add-Type -AssemblyName System.IO.Compression.FileSystem + $zip = [System.IO.Compression.ZipFile]::OpenRead($Path) + try { + $sharedStrings = @() + $sharedText = Read-ZipEntryText $zip "xl/sharedStrings.xml" + if ($sharedText) { + [xml]$sharedXml = $sharedText + foreach ($sharedItem in $sharedXml.GetElementsByTagName("si")) { + $sharedStrings += $sharedItem.InnerText + } + } + + [xml]$workbookXml = Read-ZipEntryText $zip "xl/workbook.xml" + [xml]$relsXml = Read-ZipEntryText $zip "xl/_rels/workbook.xml.rels" + $firstSheet = $workbookXml.GetElementsByTagName("sheet").Item(0) + if (-not $firstSheet) { + throw "服务器清单没有工作表:$Path" + } + + $relationshipId = Get-RelationshipId $firstSheet + $relationship = $null + foreach ($candidate in $relsXml.GetElementsByTagName("Relationship")) { + if ($candidate.GetAttribute("Id") -eq $relationshipId) { + $relationship = $candidate + break + } + } + if (-not $relationship) { + throw "无法解析工作表关系:$relationshipId" + } + + $target = $relationship.Target + $sheetPath = if ($target.StartsWith("/")) { + $target.TrimStart("/") + } + elseif ($target.StartsWith("xl/")) { + $target + } + else { + "xl/$target" + } + + [xml]$sheetXml = Read-ZipEntryText $zip $sheetPath + $rows = @() + foreach ($row in $sheetXml.GetElementsByTagName("row")) { + $valuesByIndex = @{} + $maxIndex = 0 + foreach ($cell in $row.GetElementsByTagName("c")) { + $index = Get-ColumnIndex $cell.r + $maxIndex = [Math]::Max($maxIndex, $index) + $valueNodes = $cell.GetElementsByTagName("v") + $valueNode = if ($valueNodes.Count -gt 0) { $valueNodes.Item(0) } else { $null } + $value = "" + if ($cell.GetAttribute("t") -eq "s" -and $valueNode -and $valueNode.InnerText -ne "") { + $sharedIndex = [int]$valueNode.InnerText + if ($sharedIndex -lt $sharedStrings.Count) { + $value = $sharedStrings[$sharedIndex] + } + } + elseif ($cell.GetAttribute("t") -eq "inlineStr") { + $value = $cell.InnerText + } + elseif ($valueNode) { + $value = $valueNode.InnerText + } + $valuesByIndex[$index] = $value + } + + if ($maxIndex -gt 0) { + $values = for ($index = 1; $index -le $maxIndex; $index++) { + if ($valuesByIndex.ContainsKey($index)) { $valuesByIndex[$index] } else { "" } + } + if (($values -join "").Trim()) { + $rows += ,$values + } + } + } + return $rows + } + finally { + $zip.Dispose() + } +} + +function Get-HeaderIndex { + param([string[]]$Header, [string[]]$Candidates) + + foreach ($candidate in $Candidates) { + $index = [Array]::IndexOf($Header, $candidate.ToLowerInvariant()) + if ($index -ge 0) { + return $index + } + } + return -1 +} + +function Get-CellValue { + param([object[]]$Row, [int]$Index) + + if ($Index -lt 0 -or $Index -ge $Row.Count) { + return "" + } + return ([string]$Row[$Index]).Trim() +} + +function Get-ServerPort { + param([object[]]$Row, [int]$Index) + + $value = Get-CellValue $Row $Index + if (-not $value) { + return 22 + } + $value = ($value -split "[/,;,;\s]+")[0] + $port = 0 + if (-not [int]::TryParse($value, [ref]$port)) { + throw "服务器清单端口不是数字:$value" + } + return $port +} + +function Get-ServersFromWorkbook { + param([string]$Path) + + if (-not (Test-Path -LiteralPath $Path)) { + throw "服务器清单不存在:$Path" + } + + $rows = @(Get-XlsxFirstSheetRows (Resolve-Path -LiteralPath $Path).Path) + if ($rows.Count -lt 2) { + throw "服务器清单没有数据行:$Path" + } + + $header = @($rows[0] | ForEach-Object { ([string]$_).Trim().ToLowerInvariant() }) + $nameIndex = Get-HeaderIndex $header @("name", "名称", "服务器名称") + $hostIndex = Get-HeaderIndex $header @("host", "ip", "ip/域名", "ip地址", "主机", "公网ip", "内网ip") + $portIndex = Get-HeaderIndex $header @("port", "端口", "ssh端口") + $userIndex = Get-HeaderIndex $header @("user", "username", "用户名", "账号") + $passwordIndex = Get-HeaderIndex $header @("password", "密码", "口令") + $purposeIndex = Get-HeaderIndex $header @("purpose", "功能定位", "业务作用", "用途", "类型") + $noteIndex = Get-HeaderIndex $header @("note", "备注", "说明") + $environmentIndex = Get-HeaderIndex $header @("environment", "环境", "所属中心") + + foreach ($row in $rows[1..($rows.Count - 1)]) { + if ((-not (Get-CellValue $row $nameIndex)) -or (-not (Get-CellValue $row $hostIndex))) { + continue + } + [pscustomobject]@{ + Name = Get-CellValue $row $nameIndex + Host = Get-CellValue $row $hostIndex + Port = Get-ServerPort $row $portIndex + User = Get-CellValue $row $userIndex + Password = Get-CellValue $row $passwordIndex + Purpose = Get-CellValue $row $purposeIndex + Note = Get-CellValue $row $noteIndex + Environment = Get-CellValue $row $environmentIndex + } + } +} + +function Resolve-ServerInfoPath { + param([string]$ExplicitPath) + + if ($ExplicitPath) { + if (-not (Test-Path -LiteralPath $ExplicitPath)) { + throw "服务器清单不存在:$ExplicitPath" + } + return (Resolve-Path -LiteralPath $ExplicitPath).Path + } + + $codeRoot = "Y:\code" + if (-not (Test-Path -LiteralPath $codeRoot)) { + throw "未传入 -ServerInfoPath,且默认目录不存在:$codeRoot" + } + + $workbooks = @(Get-ChildItem -LiteralPath $codeRoot -Filter "*.xlsx" -File | Sort-Object LastWriteTime -Descending) + if ($workbooks.Count -eq 0) { + throw "默认目录下没有服务器清单 xlsx,请显式传入 -ServerInfoPath。" + } + + return $workbooks[0].FullName +} + +function Assert-ProductionTarget { + param([object[]]$Servers) + + $blocked = @($Servers | Where-Object { $_.Name -match "^(?i:MessageHub|mysql|nacos|redis|rabbitmq)" }) + if ($blocked.Count -gt 0) { + throw "拒绝把应用发布到基础设施节点:$($blocked.Name -join ', ')" + } + + $knownNonProduction = @($Servers | Where-Object { $_.Environment -match "(?i)\b(dev|test|local|staging)\b" }) + if ($knownNonProduction.Count -gt 0) { + throw "拒绝发布到非生产环境节点:$($knownNonProduction.Name -join ', ')" + } +} + +function Get-SshTarget { + param([object]$Server) + + return "$($Server.User)@$($Server.Host)" +} + +function Invoke-RemoteShell { + param( + [object]$Server, + [string]$Command, + [switch]$Sensitive + ) + + if ($UsePuttyPassword) { + $plink = Get-Command plink -ErrorAction SilentlyContinue + if ((-not $DryRun) -and (-not $plink)) { + throw "找不到 PuTTY plink,请安装 PuTTY 工具或改用 SSH key。" + } + $plinkPath = if ($plink) { $plink.Source } else { "plink" } + Invoke-Native $plinkPath @("-batch", "-ssh", "-P", [string]$Server.Port, "-l", $Server.User, "-pw", $Server.Password, $Server.Host, $Command) -Sensitive:$Sensitive -RemoteMutation + } + else { + Invoke-Native "ssh" @("-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-p", [string]$Server.Port, (Get-SshTarget $Server), $Command) -Sensitive:$Sensitive -RemoteMutation + } +} + +function Copy-FileToRemote { + param( + [string]$LocalPath, + [object]$Server, + [string]$RemotePath, + [switch]$Sensitive + ) + + if (-not (Test-Path -LiteralPath $LocalPath)) { + throw "本地上传文件不存在:$LocalPath" + } + + if ($UsePuttyPassword) { + $pscp = Get-Command pscp -ErrorAction SilentlyContinue + if ((-not $DryRun) -and (-not $pscp)) { + throw "找不到 PuTTY pscp,请安装 PuTTY 工具或改用 SSH key。" + } + $pscpPath = if ($pscp) { $pscp.Source } else { "pscp" } + Invoke-Native $pscpPath @("-batch", "-P", [string]$Server.Port, "-pw", $Server.Password, $LocalPath, "$(Get-SshTarget $Server):$RemotePath") -Sensitive:$Sensitive -RemoteMutation + } + else { + Invoke-Native "scp" @("-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-P", [string]$Server.Port, $LocalPath, "$(Get-SshTarget $Server):$RemotePath") -Sensitive:$Sensitive -RemoteMutation + } +} + +function Invoke-RemoteShellMany { + param( + [object[]]$Servers, + [string]$Command, + [string]$GroupName + ) + + foreach ($server in $Servers) { + Write-Host "$GroupName target: $($server.Name) $($server.User)@$($server.Host):$($server.Port)" + Invoke-RemoteShell $server $Command + } +} + +function Test-GitState { + Push-Location $resolvedRepoRoot + try { + $commit = (& git rev-parse HEAD).Trim() + $branch = (& git branch --show-current).Trim() + $status = @(& git status --porcelain) + if ($status.Count -gt 0) { + Write-Warning "当前工作区有 $($status.Count) 个变更路径。" + $status | Select-Object -First 40 | ForEach-Object { Write-Warning $_ } + if ($Deploy -and (-not $DryRun) -and (-not $AllowDirtyWorkingTree)) { + throw "拒绝从脏工作区发布生产,请先提交/暂存,或显式传入 -AllowDirtyWorkingTree。" + } + } + return [pscustomobject]@{ + Branch = $branch + Commit = $commit + Dirty = $status.Count -gt 0 + ChangedPathCount = $status.Count + } + } + finally { + Pop-Location + } +} + +function Assert-InitSqlSafe { + param([string]$Path) + + if (-not (Test-Path -LiteralPath $Path)) { + throw "初始化 SQL 不存在:$Path" + } + + $content = Get-Content -LiteralPath $Path -Raw + if ($content -notmatch "CREATE DATABASE IF NOT EXISTS\s+jayucloud_salon") { + throw "初始化 SQL 未声明目标库 jayucloud_salon:$Path" + } + if ($content -notmatch "(?im)^\s*use\s+jayucloud_salon\s*;") { + throw "初始化 SQL 未切换到目标库 jayucloud_salon:$Path" + } + + $dangerousMatch = [regex]::Match($content, "(?im)^\s*(drop\s+(database|schema|table)|truncate\s+table)\b") + if ($dangerousMatch.Success) { + throw "初始化 SQL 包含危险语句:$($dangerousMatch.Value)" + } +} + +function Build-ReleasePackage { + param([object]$GitState) + + New-Item -ItemType Directory -Force -Path $backendDir, $frontendDir, $sqlDir | Out-Null + $maven = Resolve-Maven $MavenPath + + if (-not $SkipBuild) { + $mavenArgs = @("-q", "package") + if ($SkipTests) { + $mavenArgs += "-DskipTests" + } + + Write-Step "构建 FM-Core" + Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "FM-Core") + + Write-Step "构建 FM-Gateway" + Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "FM-Gateway") + + Write-Step "构建 FM-Frontend" + $frontendRoot = Join-Path $resolvedRepoRoot "FM-Frontend" + if (-not (Test-Path -LiteralPath (Join-Path $frontendRoot "node_modules"))) { + Invoke-Native "npm" @("ci") $frontendRoot + } + Invoke-Native "npm" @("run", "build") $frontendRoot + } + + $coreJar = Join-Path $resolvedRepoRoot "FM-Core\target\JayuCloud-Salon-Core.jar" + $gatewayJar = Join-Path $resolvedRepoRoot "FM-Gateway\target\JayuCloud-Salon-Gateway.jar" + $frontendDist = Join-Path $resolvedRepoRoot "FM-Frontend\dist" + foreach ($requiredPath in @($coreJar, $gatewayJar, $frontendDist, $InitSqlPath)) { + if (-not (Test-Path -LiteralPath $requiredPath)) { + throw "缺少发布产物:$requiredPath" + } + } + + $coreArtifact = Join-Path $backendDir "JayuCloud-Salon-Core.jar" + $gatewayArtifact = Join-Path $backendDir "JayuCloud-Salon-Gateway.jar" + $frontendArtifact = Join-Path $frontendDir "jayucloud-salon-frontend-dist.tar.gz" + $sqlArtifact = Join-Path $sqlDir "店务独立数据库_20260825.sql" + Copy-Item -LiteralPath $coreJar -Destination $coreArtifact -Force + Copy-Item -LiteralPath $gatewayJar -Destination $gatewayArtifact -Force + Copy-Item -LiteralPath $InitSqlPath -Destination $sqlArtifact -Force + + $tar = Get-Command tar -ErrorAction SilentlyContinue + if (-not $tar) { + throw "缺少 tar,无法打包前端 dist。" + } + if (Test-Path -LiteralPath $frontendArtifact) { + Remove-Item -LiteralPath $frontendArtifact -Force + } + Invoke-Native $tar.Source @("-czf", $frontendArtifact, "-C", (Join-Path $resolvedRepoRoot "FM-Frontend"), "dist") + + $hashes = foreach ($artifact in @($coreArtifact, $gatewayArtifact, $frontendArtifact, $sqlArtifact)) { + $hash = Get-FileHash -LiteralPath $artifact -Algorithm SHA256 + [pscustomobject]@{ + Path = $artifact.Replace($resolvedRepoRoot, "").TrimStart("\", "/") + Sha256 = $hash.Hash + } + } + + return [pscustomobject]@{ + Directory = $releaseDir + CoreJar = $coreArtifact + GatewayJar = $gatewayArtifact + FrontendArchive = $frontendArtifact + InitSql = $sqlArtifact + Hashes = @($hashes) + Git = $GitState + } +} + +function Get-BackendDeployCommand { + param( + [string]$RemoteAppDir, + [string]$ServiceName, + [string]$ReleaseName, + [int]$HealthPort + ) + + $appDir = ConvertTo-BashSingleQuoted $RemoteAppDir + $service = ConvertTo-BashSingleQuoted $ServiceName + $releaseName = ConvertTo-BashSingleQuoted $ReleaseName + $healthPath = ConvertTo-BashSingleQuoted $HealthPath + $timeout = [string]$HealthTimeoutSeconds + $healthPortText = [string]$HealthPort + + return @" +set -e +APP_DIR=$appDir +SERVICE=$service +RELEASE_NAME=$releaseName +HEALTH_PATH=$healthPath +HEALTH_PORT=$healthPortText +HEALTH_TIMEOUT=$timeout +RELEASE="`$APP_DIR/releases/`$RELEASE_NAME" +BACKUP_NAME="app-$releaseTimestamp.jar" +mkdir -p "`$APP_DIR/releases" "`$APP_DIR/backups" "`$APP_DIR/logs" +test -f "`$RELEASE" +if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then + systemctl stop "`$SERVICE" || true +fi +if [ -f "`$APP_DIR/app.jar" ]; then + cp "`$APP_DIR/app.jar" "`$APP_DIR/backups/`$BACKUP_NAME" +fi +cp "`$RELEASE" "`$APP_DIR/app.jar" +if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then + systemctl start "`$SERVICE" +else + if [ -f "`$APP_DIR/app.pid" ]; then kill "`$(cat "`$APP_DIR/app.pid")" >/dev/null 2>&1 || true; fi + pkill -f "java .*`$APP_DIR/app.jar" >/dev/null 2>&1 || true + nohup java -jar "`$APP_DIR/app.jar" > "`$APP_DIR/logs/app-$releaseTimestamp.log" 2>&1 & + echo `$! > "`$APP_DIR/app.pid" +fi +deadline=`$((`$(date +%s) + `$HEALTH_TIMEOUT)) +until curl -fsS "http://127.0.0.1:`$HEALTH_PORT`$HEALTH_PATH" >/tmp/jayucloud-salon-health.out 2>/tmp/jayucloud-salon-health.err; do + if [ "`$(date +%s)" -ge "`$deadline" ]; then + echo "Health check failed for `$SERVICE on port `$HEALTH_PORT" + cat /tmp/jayucloud-salon-health.err || true + if command -v systemctl >/dev/null 2>&1; then journalctl -u "`$SERVICE" -n 80 --no-pager || true; fi + exit 43 + fi + sleep 3 +done +cat /tmp/jayucloud-salon-health.out +"@ +} + +function Publish-BackendGroup { + param( + [string]$GroupName, + [object[]]$Servers, + [string]$ArtifactPath, + [string]$RemoteAppDir, + [string]$ServiceName, + [int]$HealthPort + ) + + $artifactBaseName = [System.IO.Path]::GetFileNameWithoutExtension($ArtifactPath) + $releaseName = "$artifactBaseName-$releaseTimestamp.jar" + $quotedRemoteAppDir = ConvertTo-BashSingleQuoted $RemoteAppDir + Write-Step "准备 $GroupName 目标机器" + foreach ($server in $Servers) { + Write-Host "$GroupName target: $($server.Name) $($server.User)@$($server.Host):$($server.Port)" + Invoke-RemoteShell $server "mkdir -p $quotedRemoteAppDir/releases $quotedRemoteAppDir/backups $quotedRemoteAppDir/logs" + Copy-FileToRemote $ArtifactPath $server "$RemoteAppDir/releases/$releaseName" + } + + Write-Step "切换 $GroupName 发布版本" + $deployCommand = Get-BackendDeployCommand $RemoteAppDir $ServiceName $releaseName $HealthPort + Invoke-RemoteShellMany $Servers $deployCommand $GroupName +} + +function Get-WebDeployCommand { + param([string]$ArchiveName) + + $webDir = ConvertTo-BashSingleQuoted $WebRemoteDir + $archiveName = ConvertTo-BashSingleQuoted $ArchiveName + return @" +set -e +WEB_DIR=$webDir +ARCHIVE_NAME=$archiveName +RELEASE_BASE="`$WEB_DIR/releases/$releaseTimestamp" +ARCHIVE="`$WEB_DIR/releases/`$ARCHIVE_NAME" +mkdir -p "`$RELEASE_BASE" +if [ -L "`$WEB_DIR/current" ]; then readlink "`$WEB_DIR/current" > "`$WEB_DIR/previous-release.txt"; fi +tar -xzf "`$ARCHIVE" -C "`$RELEASE_BASE" +if [ -d "`$RELEASE_BASE/dist" ]; then + TARGET="`$RELEASE_BASE/dist" +else + TARGET="`$RELEASE_BASE" +fi +ln -sfn "`$TARGET" "`$WEB_DIR/current" +nginx -t +if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^nginx.service"; then + systemctl reload nginx +else + nginx -s reload +fi +echo "Web current -> `$TARGET" +"@ +} + +function Publish-Web { + param([object]$Server, [string]$ArchivePath) + + $archiveName = "jayucloud-salon-frontend-dist-$releaseTimestamp.tar.gz" + $quotedWebRemoteDir = ConvertTo-BashSingleQuoted $WebRemoteDir + Write-Step "准备 Web 目标机器" + Invoke-RemoteShell $Server "mkdir -p $quotedWebRemoteDir/releases" + Copy-FileToRemote $ArchivePath $Server "$WebRemoteDir/releases/$archiveName" + + Write-Step "切换 Web 发布版本" + Invoke-RemoteShell $Server (Get-WebDeployCommand $archiveName) +} + +function Initialize-ProductionDatabase { + param([object]$DatabaseServer, [string]$SqlArtifact) + + Assert-InitSqlSafe $SqlArtifact + + $dbUserValue = if ($DatabaseUser) { $DatabaseUser } else { $DatabaseServer.User } + $dbPasswordValue = if ($DatabasePassword) { $DatabasePassword } else { $DatabaseServer.Password } + if (-not $dbUserValue) { + throw "数据库用户名为空,请传入 -DatabaseUser 或在服务器清单中填写。" + } + + $remoteSqlPath = "/tmp/jayucloud-salon-init-$releaseTimestamp.sql" + Write-Step "初始化生产空库" + Write-Host "数据库目标:$($DatabaseServer.Name) $($DatabaseServer.Host):$DatabasePort/$DatabaseName" + Invoke-RemoteShell $DatabaseServer "rm -f '$remoteSqlPath'" + Copy-FileToRemote $SqlArtifact $DatabaseServer $remoteSqlPath -Sensitive + + $dbName = ConvertTo-BashSingleQuoted $DatabaseName + $dbUser = ConvertTo-BashSingleQuoted $dbUserValue + $dbPassword = ConvertTo-BashSingleQuoted $dbPasswordValue + $dbPort = [string]$DatabasePort + $sqlFile = ConvertTo-BashSingleQuoted $remoteSqlPath + $command = @' +set -e +DB_NAME=__DB_NAME__ +DB_PORT=__DB_PORT__ +DB_USER=__DB_USER__ +SQL_FILE=__SQL_FILE__ +export MYSQL_PWD=__DB_PASSWORD__ +if ! command -v mysql >/dev/null 2>&1; then + echo "mysql client not found on database host" + exit 48 +fi +mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" +TABLE_COUNT=$(mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${DB_NAME}';") +if [ "$TABLE_COUNT" != "0" ]; then + echo "Database ${DB_NAME} is not empty: ${TABLE_COUNT} tables. Refusing initialization." + rm -f "$SQL_FILE" + unset MYSQL_PWD + exit 49 +fi +mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 < "$SQL_FILE" +ADMIN_COUNT=$(mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names "$DB_NAME" -e "SELECT COUNT(*) FROM t_user WHERE account='xiaowang';") +rm -f "$SQL_FILE" +unset MYSQL_PWD +echo "Database initialized. Admin account rows: ${ADMIN_COUNT}" +'@ + $command = $command.Replace("__DB_NAME__", $dbName) + $command = $command.Replace("__DB_PORT__", $dbPort) + $command = $command.Replace("__DB_USER__", $dbUser) + $command = $command.Replace("__DB_PASSWORD__", $dbPassword) + $command = $command.Replace("__SQL_FILE__", $sqlFile) + Invoke-RemoteShell $DatabaseServer $command -Sensitive +} + +function Write-ReleaseManifest { + param( + [object]$Package, + [object[]]$CoreServers, + [object[]]$GatewayServers, + [object]$WebServer, + [object]$DatabaseServer, + [string]$ResolvedServerInfoPath + ) + + $manifest = [pscustomobject]@{ + releaseTimestamp = $releaseTimestamp + repoRoot = $resolvedRepoRoot + git = $Package.Git + artifacts = $Package.Hashes + targets = [pscustomobject]@{ + core = @($CoreServers | Select-Object Name, Host, Port, User, Purpose, Environment) + gateway = @($GatewayServers | Select-Object Name, Host, Port, User, Purpose, Environment) + web = $WebServer | Select-Object Name, Host, Port, User, Purpose, Environment + database = if ($DatabaseServer) { $DatabaseServer | Select-Object Name, Host, Port, User, Purpose, Environment } else { $null } + } + parameters = [pscustomobject]@{ + initializeDatabase = -not [bool]$SkipDatabaseInit + databaseName = $DatabaseName + serverInfoPath = $ResolvedServerInfoPath + coreRemoteAppDir = $CoreRemoteAppDir + gatewayRemoteAppDir = $GatewayRemoteAppDir + webRemoteDir = $WebRemoteDir + publicBaseUrl = $PublicBaseUrl + managerMiniProgramApi = "$PublicBaseUrl/api/admin" + nacosNamespace = "jayucloud-salon" + dryRun = [bool]$DryRun + deploy = [bool]$Deploy + } + } + $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $manifestPath -Encoding UTF8 + Write-Host "Manifest: $manifestPath" +} + +function Invoke-PublicSmokeTests { + if ($DryRun) { + Write-Host "DryRun public smoke tests:" + Write-Host "GET $PublicBaseUrl/health/check" + Write-Host "GET $PublicBaseUrl/api/shop/list" + return + } + + Write-Step "生产公开冒烟" + foreach ($url in @("$PublicBaseUrl/health/check", "$PublicBaseUrl/api/shop/list")) { + Write-Host "GET $url" + $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 20 + Write-Host "Status $($response.StatusCode) Length $($response.RawContentLength)" + } +} + +Write-Step "读取服务器清单" +$resolvedServerInfoPath = Resolve-ServerInfoPath $ServerInfoPath +$servers = @(Get-ServersFromWorkbook $resolvedServerInfoPath) +$coreServers = @($servers | Where-Object { $_.Name -match $CorePattern }) +$gatewayServers = @($servers | Where-Object { $_.Name -match $GatewayPattern }) +$webServers = @(if ($WebTargetName) { + $servers | Where-Object { $_.Name -eq $WebTargetName } +} +else { + $servers | Where-Object { $_.Host -eq $WebTargetHost } +}) +$databaseServers = @($servers | Where-Object { $_.Name -eq $DatabaseTargetName }) + +if ($coreServers.Count -eq 0) { + throw "没有匹配到 Core 服务器,匹配规则:$CorePattern" +} +if ($gatewayServers.Count -eq 0) { + throw "没有匹配到 Gateway 服务器,匹配规则:$GatewayPattern" +} +if ($webServers.Count -ne 1) { + $webSelector = if ($WebTargetName) { "名称 $WebTargetName" } else { "主机 $WebTargetHost" } + throw "Web 目标必须唯一,当前按 $webSelector 找到 $($webServers.Count) 个。" +} +if ((-not $SkipDatabaseInit) -and $databaseServers.Count -ne 1) { + throw "数据库初始化目标必须唯一,当前按 $DatabaseTargetName 找到 $($databaseServers.Count) 个。" +} + +Assert-ProductionTarget (@($coreServers) + @($gatewayServers) + @($webServers)) +$databaseServer = if (-not $SkipDatabaseInit) { $databaseServers[0] } else { $null } + +Write-Host "服务器清单:$resolvedServerInfoPath" +@($coreServers + $gatewayServers + $webServers) | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize +if ($databaseServer) { + Write-Host "数据库初始化目标:" + $databaseServer | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize +} + +Write-Step "检查工作区" +$gitState = Test-GitState + +Write-Step "构建发布包" +$package = Build-ReleasePackage $gitState +Write-ReleaseManifest $package $coreServers $gatewayServers $webServers[0] $databaseServer $resolvedServerInfoPath + +if (-not $Deploy) { + Write-Host "发布包已生成。传入 -Deploy 才会发布到生产;传入 -DryRun 可打印远程动作但不修改远端。" + exit 0 +} + +if (-not $SkipDatabaseInit) { + Initialize-ProductionDatabase $databaseServer $package.InitSql +} +else { + Write-Host "已跳过数据库初始化。" +} + +Publish-BackendGroup "Core" $coreServers $package.CoreJar $CoreRemoteAppDir $CoreServiceName $CoreHealthPort +Publish-BackendGroup "Gateway" $gatewayServers $package.GatewayJar $GatewayRemoteAppDir $GatewayServiceName $GatewayHealthPort +Publish-Web $webServers[0] $package.FrontendArchive +Invoke-PublicSmokeTests + +Write-Host "" +Write-Host "jayucloud_salon 生产发布流程完成。" diff --git a/scripts/sql/migrations/20260825-双端独立数据库/店务独立数据库_20260825.sql b/scripts/sql/migrations/20260825-双端独立数据库/店务独立数据库_20260825.sql new file mode 100644 index 00000000..e7511b16 --- /dev/null +++ b/scripts/sql/migrations/20260825-双端独立数据库/店务独立数据库_20260825.sql @@ -0,0 +1,2313 @@ +-- jayucloud_salon 唯一初始化 SQL +-- 本文件用于开发、测试、上线空库初始化,后续环境基线均以本文件为准。 +-- 执行范围:建库、建表、索引、约束、平台管理员、基础权限、系统参数、协议、MessageHub 与 VIP 基础配置。 +-- 种子数据原则:只保留运行必需配置;不写入门店、商品、订单、客户、库存流水、测试消息等业务样例数据。 +-- 默认平台管理员账号:xiaowang,默认密码沿用当前 bcrypt 值。 +-- Linux MySQL 环境库名大小写敏感,数据源必须指向 jayucloud_salon。 +CREATE DATABASE IF NOT EXISTS jayucloud_salon DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +use jayucloud_salon; + +-- auto-generated definition +create table t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +create table t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +create index idx_change_time + on t_balance_change_detail (change_time) + comment '按时间查询余额变动的索引'; + +create index idx_user_id + on t_balance_change_detail (user_id) + comment '按用户查询余额变动的索引'; + +-- auto-generated definition +create table t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +create index idx_user_id + on t_cart (user_id) + comment '按用户查询购物车的索引'; + +-- auto-generated definition +create table t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +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 '按用户查询评论的索引';s + +-- auto-generated definition +create table t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +create index idx_status + on t_coupon (status) + comment '按状态查询优惠券的索引'; + +-- auto-generated definition +create table t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +create index idx_coupon_id + on t_coupon_tag (coupon_id) + comment '按优惠券查询标签的索引'; + +create index idx_tag_id + on t_coupon_tag (tag_id) + comment '按标签查询优惠券的索引'; + +-- auto-generated definition +create table t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +create index idx_product_id + on t_effect_diagram (product_id) + comment '按商品查询效果图的索引'; + +-- auto-generated definition +create table t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +create index idx_login_method + on t_login_identity (login_method) + comment '按登录方式查询的索引'; + +create index idx_user_id + on t_login_identity (user_id) + comment '按用户查询登录标识的索引'; + +-- auto-generated definition +create table t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +create index idx_wechat_mini_unionid + on t_wechat_mini_binding (unionid) + comment '按unionid查询的索引'; + +-- auto-generated definition +create table t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +create index idx_status + on t_nail_artist_info (status) + comment '按状态查询美甲师的索引'; + +create index idx_user_id + on t_nail_artist_info (user_id) + comment '按用户查询美甲师信息的索引'; + +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + +-- auto-generated definition +create table t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +create index idx_status + on t_object_storage_file (status) + comment '??????'; + +create index idx_object_storage_file_backup_retry + on t_object_storage_file (backup_upload_status, primary_upload_status, status) + comment '????????'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +create table t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned not null comment '关联用户表主键', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +create index idx_status + on t_order (status) + comment '按状态查询订单的索引'; + +create index idx_user_id + on t_order (user_id) + comment '按用户查询订单的索引'; + +-- auto-generated definition +create table t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +create index idx_order_id + on t_order_item (order_id) + comment '按订单查询商品的索引'; + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +create unique index uk_order_artist_review_item + on t_order_artist_review (order_item_id, is_delete); + +create index idx_order_artist_review_customer + on t_order_artist_review (customer_id, status, create_time); + +create index idx_order_artist_review_artist + on t_order_artist_review (artist_id, status); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +create index idx_order_artist_change_customer + on t_order_artist_change_request (customer_id, status, create_time); + +create index idx_order_artist_change_artist + on t_order_artist_change_request (from_artist_id, to_artist_id, status); + +create index idx_order_artist_change_shop + on t_order_artist_change_request (shop_id, status, create_time); + +create unique index uk_order_artist_change_pending_key + on t_order_artist_change_request (pending_key); + +-- auto-generated definition +create table t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +create table t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +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 index idx_t_product_front_visible + on t_product (shop_id, front_visible, source_type) + comment '按门店、前台展示和来源筛选商品'; + +-- auto-generated definition +create table t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +create index idx_product_id_like + on t_product_like (product_id) + comment '按商品查询点赞的索引'; + +create index idx_user_id_like + on t_product_like (user_id) + comment '按用户查询点赞的索引'; + +-- auto-generated definition +create table t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +create index idx_shop_name + on t_shop (shop_name) + comment '按店铺名称查询的索引'; + +-- auto-generated definition +create table t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +create table t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(50) not null comment '用户账号(登录用)', + phone varchar(50) null comment '手机号', + contact_phone varchar(50) null comment '联系电话', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) not null comment '用户密码(加密存储)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_account + unique (account) comment '用户账号唯一索引' +) + comment '系统用户信息表'; + +create index idx_email + on t_user (email) + comment '按邮箱查询的索引'; + +create index idx_phone + on t_user (phone) + comment '按手机号查询的索引'; + +create index idx_shop_id + on t_user (shop_id) + comment '按店铺查询用户的索引'; + +create index idx_type + on t_user (type) + comment '按用户类型查询的索引'; + +-- auto-generated definition +create table t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +create index idx_status + on t_user_coupon (status) + comment '按状态查询用户优惠券的索引'; + +create index idx_user_id + on t_user_coupon (user_id) + comment '按用户查询优惠券的索引'; + +-- auto-generated definition +create table t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +create index idx_permission_id + on t_user_permission (permission_id) + comment '权限ID索引'; + +create index idx_user_id + on t_user_permission (user_id) + comment '用户ID索引'; + +create table if not exists t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create unique index uk_t_system_message_idempotency + on t_system_message (idempotency_key); + +create table if not exists t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (user_id, read_status, popup_shown); + +create table if not exists t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (sort_order, publish_time); + +create table if not exists t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + +-- auto-generated definition +create table t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +create index idx_required_vip_level + on t_vip_benefit (required_vip_level) + comment '按VIP等级查询权益的索引'; + +-- auto-generated definition +create table t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +create index idx_vip_level + on t_vip_info (vip_level) + comment '按VIP等级查询的索引'; + +-- auto-generated definition +create table t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + +-- auto-generated definition +create table t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +create index idx_product_id + on t_wishlist (product_id) + comment '按商品查询收藏的索引'; + +create index idx_user_id + on t_wishlist (user_id) + comment '按用户查询收藏的索引'; + +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); + +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-salon' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='Fingertip Designer按业务场景投递MessageHub的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + ('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$I3mV64NhISqMmm7soSki1.Y36ve.TOINGOrVt0U0kxjO7GtxavE16', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-salon', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NOT NULL COMMENT '用户ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + device_id varchar(128) NULL COMMENT '设备ID', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + device_id varchar(128) NULL COMMENT '设备ID', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 Fingertip Designer 指尖设计师。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'Fingertip Designer 指尖设计师会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); diff --git a/scripts/sql/migrations/20260825-双端独立数据库/设计师独立数据库_20260825.sql b/scripts/sql/migrations/20260825-双端独立数据库/设计师独立数据库_20260825.sql new file mode 100644 index 00000000..cb36ca2c --- /dev/null +++ b/scripts/sql/migrations/20260825-双端独立数据库/设计师独立数据库_20260825.sql @@ -0,0 +1,2313 @@ +-- jayucloud_artlist 唯一初始化 SQL +-- 本文件用于开发、测试、上线空库初始化,后续环境基线均以本文件为准。 +-- 执行范围:建库、建表、索引、约束、平台管理员、基础权限、系统参数、协议、MessageHub 与 VIP 基础配置。 +-- 种子数据原则:只保留运行必需配置;不写入门店、商品、订单、客户、库存流水、测试消息等业务样例数据。 +-- 默认平台管理员账号:xiaowang,默认密码沿用当前 bcrypt 值。 +-- Linux MySQL 环境库名大小写敏感,数据源必须指向 jayucloud_artlist。 +CREATE DATABASE IF NOT EXISTS jayucloud_artlist DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +use jayucloud_artlist; + +-- auto-generated definition +create table t_balance +( + id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' + primary key comment '余额表主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) default 0.00 not null comment '当前余额', + total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', + last_recharge_time datetime null comment '最近一次充值时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', + last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_user_id + unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' +) + comment '用户余额信息表'; + + +-- auto-generated definition +create table t_balance_change_detail +( + id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' + primary key comment '余额变动明细主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', + type varchar(20) not null comment '变动类型(如充值、消费、退款)', + current_balance decimal(10, 2) not null comment '变动后的当前余额', + before_balance decimal(10, 2) null comment '变动前余额', + after_balance decimal(10, 2) null comment '变动后余额', + change_scene varchar(32) null comment '余额变动场景', + related_order_id bigint unsigned null comment '关联系统订单ID', + related_order_no varchar(64) null comment '关联系统订单号', + external_order_no varchar(64) null comment '手工录入的外部订单号', + operator_id bigint unsigned null comment '操作人ID', + remark varchar(255) null comment '备注', + change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' +) + comment '用户余额变动明细表'; + +create index idx_change_time + on t_balance_change_detail (change_time) + comment '按时间查询余额变动的索引'; + +create index idx_user_id + on t_balance_change_detail (user_id) + comment '按用户查询余额变动的索引'; + +-- auto-generated definition +create table t_cart +( + id bigint unsigned auto_increment comment '购物车主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned default 1 not null comment '商品数量', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '购物车表'; + +create index idx_user_id + on t_cart (user_id) + comment '按用户查询购物车的索引'; + +-- auto-generated definition +create table t_comment +( + id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' + primary key comment '评论主键索引', + user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', + shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', + product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', + comment_content text not null comment '评论内容', + parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', + rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', + image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', + like_count int unsigned default 0 null comment '评论点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '用户评论信息表'; + +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 '按用户查询评论的索引';s + +-- auto-generated definition +create table t_coupon +( + id bigint unsigned auto_increment comment '优惠券主键索引' + primary key, + coupon_code varchar(50) not null comment '优惠券编码', + coupon_name varchar(100) not null comment '优惠券名称', + coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', + discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', + min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', + reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', + total_count int unsigned default 100 not null comment '优惠券总数量', + used_count int unsigned default 0 not null comment '已使用数量', + start_time datetime not null comment '开始时间', + end_time datetime not null comment '结束时间', + status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '所属店铺ID', + coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', + required_vip_level varchar(20) null comment '要求的VIP等级', + auto_match tinyint unsigned default 0 not null comment '是否自动匹配', + constraint uk_coupon_code + unique (coupon_code) comment '优惠券编码唯一索引' +) + comment '优惠券信息表'; + +create index idx_status + on t_coupon (status) + comment '按状态查询优惠券的索引'; + +-- auto-generated definition +create table t_coupon_tag +( + id bigint unsigned auto_increment comment '优惠券标签关联主键索引' + primary key, + coupon_id bigint unsigned not null comment '关联优惠券表主键', + tag_id bigint unsigned not null comment '关联标签表主键', + is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_coupon_tag + unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' +) + comment '优惠券标签关联表'; + +create index idx_coupon_id + on t_coupon_tag (coupon_id) + comment '按优惠券查询标签的索引'; + +create index idx_tag_id + on t_coupon_tag (tag_id) + comment '按标签查询优惠券的索引'; + +-- auto-generated definition +create table t_effect_diagram +( + id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' + primary key comment '效果图主键索引', + product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', + category varchar(50) default '' null comment '效果图类别', + image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', + description text null comment '效果图描述', + price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', + duration varchar(50) default '' null comment '效果图对应服务耗时', + tag varchar(50) default '' null comment '效果图标签', + like_count int unsigned default 0 null comment '效果图点赞数', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '商品效果图信息表'; + +create index idx_product_id + on t_effect_diagram (product_id) + comment '按商品查询效果图的索引'; + +-- auto-generated definition +create table t_login_identity +( + id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' + primary key comment '登录标识主键索引', + user_id bigint unsigned not null comment '关联用户表主键', + login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', + input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', + input_time datetime not null comment '输入时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' +) + comment '用户登录标识信息表'; + +create index idx_login_method + on t_login_identity (login_method) + comment '按登录方式查询的索引'; + +create index idx_user_id + on t_login_identity (user_id) + comment '按用户查询登录标识的索引'; + +-- auto-generated definition +create table t_wechat_mini_binding +( + id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' + primary key, + user_id bigint unsigned not null comment '关联用户ID', + app_id varchar(64) not null comment '微信小程序appId', + openid varchar(100) not null comment '微信小程序openid', + unionid varchar(100) null comment '微信开放平台unionid', + status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + constraint uk_wechat_mini_app_openid + unique (app_id, openid), + constraint uk_wechat_mini_app_user + unique (app_id, user_id) +) + comment '微信小程序账号绑定表'; + +create index idx_wechat_mini_unionid + on t_wechat_mini_binding (unionid) + comment '按unionid查询的索引'; + +-- auto-generated definition +create table t_nail_artist_info +( + id bigint unsigned auto_increment comment '美甲师信息主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', + identity varchar(50) default '' null comment '身份', + experience int unsigned default 0 null comment '从业年限', + skills text null comment '技能标签ID集合,多个ID以逗号分隔', + rating decimal(3, 1) default 4.5 null comment '评分', + status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', + portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_id + unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' +) + comment '美甲师信息表'; + +create index idx_status + on t_nail_artist_info (status) + comment '按状态查询美甲师的索引'; + +create index idx_user_id + on t_nail_artist_info (user_id) + comment '按用户查询美甲师信息的索引'; + +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + +-- auto-generated definition +create table t_object_storage_file +( + id bigint unsigned auto_increment comment '????ID' + primary key comment '????????', + file_name varchar(100) not null comment '????', + file_url text not null comment '??????', + object_name varchar(512) null comment '????Key', + primary_provider varchar(64) null comment '??????', + primary_url text null comment '???????', + backup_provider varchar(64) null comment '???????', + backup_url text null comment '????????', + content_type varchar(128) null comment '??Content-Type', + file_size bigint unsigned null comment '?????????', + primary_upload_status tinyint unsigned default 0 not null comment '????????0????1???2??', + backup_upload_status tinyint unsigned default 0 not null comment '?????????0????1???2??', + backup_retry_count int unsigned default 0 not null comment '??????', + backup_last_error varchar(500) null comment '??????????', + backup_uploaded_at datetime null comment '??????', + backup_last_retry_time datetime null comment '??????????', + create_time datetime default CURRENT_TIMESTAMP not null comment '??????', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '??????', + status tinyint unsigned default 1 null comment '?????1???0????2???', + delete_time datetime null comment '??????', + recycle_time datetime null comment '?????????' +) + comment '?????????'; + +create index idx_status + on t_object_storage_file (status) + comment '??????'; + +create index idx_object_storage_file_backup_retry + on t_object_storage_file (backup_upload_status, primary_upload_status, status) + comment '????????'; + +-- auto-generated definition +CREATE TABLE IF NOT EXISTS `t_object_storage_file_replica` +( + `id` bigint unsigned NOT NULL COMMENT '副本ID', + `file_id` bigint unsigned NOT NULL COMMENT '文件ID', + `provider` varchar(64) NOT NULL COMMENT '对象存储提供方', + `object_name` varchar(512) NOT NULL COMMENT '对象Key', + `object_url` text NULL COMMENT '对象访问地址', + `upload_status` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '上传状态:0-待上传,1-成功,2-失败', + `retry_count` int unsigned NOT NULL DEFAULT 0 COMMENT '重试次数', + `last_error` varchar(500) NULL COMMENT '最近一次错误', + `uploaded_at` datetime NULL COMMENT '上传成功时间', + `last_retry_time` datetime NULL COMMENT '最近一次重试时间', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_object_storage_file_replica_file_provider` (`file_id`, `provider`), + KEY `idx_object_storage_file_replica_retry` (`upload_status`, `provider`, `file_id`), + KEY `idx_object_storage_file_replica_file_status` (`file_id`, `upload_status`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COLLATE = utf8mb4_unicode_ci + COMMENT = '对象存储文件副本表'; + +-- auto-generated definition +create table t_order +( + id bigint unsigned auto_increment comment '订单主键索引' + primary key, + order_no varchar(50) not null comment '订单编号', + user_id bigint unsigned not null comment '关联用户表主键', + shop_id bigint unsigned null comment '所属店铺ID', + total_amount decimal(10, 2) not null comment '订单总金额', + actual_amount decimal(10, 2) not null comment '实际支付金额', + coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', + user_coupon_id bigint unsigned null comment '用户券ID', + coupon_source_type varchar(32) null comment '优惠来源类型', + status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_order_no + unique (order_no) comment '订单编号唯一索引' +) + comment '订单表'; + +create index idx_status + on t_order (status) + comment '按状态查询订单的索引'; + +create index idx_user_id + on t_order (user_id) + comment '按用户查询订单的索引'; + +-- auto-generated definition +create table t_order_item +( + id bigint unsigned auto_increment comment '订单商品主键索引' + primary key, + order_id bigint unsigned not null comment '关联订单表主键', + product_id bigint unsigned not null comment '关联商品表主键', + quantity int unsigned not null comment '商品数量', + price decimal(10, 2) not null comment '商品单价', + artist_id bigint unsigned null comment '关联美甲师ID', + appointment_time datetime null comment '预约开始时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单商品表'; + +create index idx_order_id + on t_order_item (order_id) + comment '按订单查询商品的索引'; + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +create unique index uk_order_artist_review_item + on t_order_artist_review (order_item_id, is_delete); + +create index idx_order_artist_review_customer + on t_order_artist_review (customer_id, status, create_time); + +create index idx_order_artist_review_artist + on t_order_artist_review (artist_id, status); + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +create index idx_order_artist_change_customer + on t_order_artist_change_request (customer_id, status, create_time); + +create index idx_order_artist_change_artist + on t_order_artist_change_request (from_artist_id, to_artist_id, status); + +create index idx_order_artist_change_shop + on t_order_artist_change_request (shop_id, status, create_time); + +create unique index uk_order_artist_change_pending_key + on t_order_artist_change_request (pending_key); + +-- auto-generated definition +create table t_permission +( + id bigint unsigned auto_increment comment '权限唯一主键ID' + primary key, + permission_code varchar(100) not null comment '权限编码(唯一标识)', + permission_name varchar(100) not null comment '权限名称', + permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', + description varchar(255) null comment '权限描述', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_permission_code + unique (permission_code) comment '权限编码唯一索引' +) + comment '系统权限表'; + +-- auto-generated definition +create table t_product +( + id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' + primary key comment '商品主键索引', + shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', + title varchar(100) not null comment '商品标题', + description text null comment '商品描述', + target_audience text null comment '适合人群说明', + precautions text null comment '注意事项说明', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', + price decimal(10, 2) not null comment '商品价格,保留2位小数', + tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', + like_count int unsigned default 0 null comment '商品点赞数', + collect_count int unsigned default 0 null comment '商品收藏数', + approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', + bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', + available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', + front_visible tinyint unsigned default 1 not null comment '前台是否展示:0-隐藏,1-展示', + source_type varchar(64) default 'BACKEND' not null comment '来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约', + create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' +) + comment '商品信息表'; + +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 index idx_t_product_front_visible + on t_product (shop_id, front_visible, source_type) + comment '按门店、前台展示和来源筛选商品'; + +-- auto-generated definition +create table t_product_like +( + id bigint unsigned auto_increment comment '商品点赞主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product_like + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品点赞记录表'; + +create index idx_product_id_like + on t_product_like (product_id) + comment '按商品查询点赞的索引'; + +create index idx_user_id_like + on t_product_like (user_id) + comment '按用户查询点赞的索引'; + +-- auto-generated definition +create table t_shop +( + id bigint unsigned auto_increment comment '店铺唯一主键ID' + primary key comment '店铺主键索引', + shop_name varchar(100) not null comment '店铺名称', + description text null comment '店铺描述', + address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', + business_hours varchar(100) default '' null comment '店铺营业时间', + cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', + theme_primary_color varchar(20) null comment '前台主题主色', + theme_secondary_color varchar(20) null comment '前台主题辅色', + theme_accent_color varchar(20) null comment '前台主题强调色', + theme_page_bg_color varchar(20) null comment '前台主题页面背景色', + theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', + theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', + status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', + authorization_start_date date null comment '店铺授权起始日', + authorization_days int null comment '店铺授权有效天数', + authorization_expire_time datetime null comment '店铺授权到期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' +) + comment '店铺信息表'; + +create index idx_shop_name + on t_shop (shop_name) + comment '按店铺名称查询的索引'; + +-- auto-generated definition +create table t_tag +( + id bigint unsigned auto_increment comment '标签唯一主键ID' + primary key comment '标签主键索引', + tag_name varchar(50) not null comment '标签名称', + text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', + bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', + border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', + scene_group varchar(50) null comment '前台场景筛选分组', + display_name varchar(80) null comment '前台展示名称', + sort_order int default 100 null comment '前台筛选排序', + front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + shop_id bigint null comment '店铺ID', + constraint uk_tag_shop_name + unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' +) + comment '系统标签信息表'; + +-- auto-generated definition +create table t_user +( + id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' + primary key comment '用户主键索引', + shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', + nickname varchar(50) not null comment '用户昵称', + account varchar(50) not null comment '用户账号(登录用)', + phone varchar(50) null comment '手机号', + contact_phone varchar(50) null comment '联系电话', + birthday date null comment '生日', + wechat_id varchar(100) null comment '微信号', + wechat_qr_code varchar(512) null comment '微信二维码', + email varchar(100) null comment '邮箱', + phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', + email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', + password varchar(100) not null comment '用户密码(加密存储)', + signature varchar(200) default '' null comment '用户签名', + level varchar(20) default '普通' null comment '用户等级', + type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', + vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', + avatar varchar(512) null comment '头像链接', + constraint uk_account + unique (account) comment '用户账号唯一索引' +) + comment '系统用户信息表'; + +create index idx_email + on t_user (email) + comment '按邮箱查询的索引'; + +create index idx_phone + on t_user (phone) + comment '按手机号查询的索引'; + +create index idx_shop_id + on t_user (shop_id) + comment '按店铺查询用户的索引'; + +create index idx_type + on t_user (type) + comment '按用户类型查询的索引'; + +-- auto-generated definition +create table t_user_coupon +( + id bigint unsigned auto_increment comment '用户优惠券关联主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + coupon_id bigint unsigned not null comment '关联优惠券表主键', + status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', + obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', + use_time datetime null comment '使用时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_coupon + unique (user_id, coupon_id) comment '用户-优惠券唯一索引' +) + comment '用户优惠券关联表'; + +create index idx_status + on t_user_coupon (status) + comment '按状态查询用户优惠券的索引'; + +create index idx_user_id + on t_user_coupon (user_id) + comment '按用户查询优惠券的索引'; + +-- auto-generated definition +create table t_user_permission +( + id bigint unsigned auto_increment comment '关联ID' + primary key, + user_id bigint unsigned not null comment '用户ID', + permission_id bigint unsigned not null comment '权限ID', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + create_by bigint unsigned null comment '创建人ID', + update_by bigint unsigned null comment '更新人ID', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_user_permission + unique (user_id, permission_id) comment '用户-权限唯一索引' +) + comment '用户权限关联表'; + +create index idx_permission_id + on t_user_permission (permission_id) + comment '权限ID索引'; + +create index idx_user_id + on t_user_permission (user_id) + comment '用户ID索引'; + +create table if not exists t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + business_type varchar(64) null comment '业务类型', + business_id bigint unsigned null comment '业务ID', + action_path varchar(255) null comment '业务跳转路径', + idempotency_key varchar(160) null comment '业务消息幂等键', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create unique index uk_t_system_message_idempotency + on t_system_message (idempotency_key); + +create table if not exists t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (user_id, read_status, popup_shown); + +create table if not exists t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (sort_order, publish_time); + +create table if not exists t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + +-- auto-generated definition +create table t_vip_benefit +( + id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' + primary key comment 'VIP权益主键索引', + benefit_info text not null comment '权益详情(如折扣、专属服务)', + required_vip_level varchar(20) not null comment '所需VIP等级', + level_rank int default 0 not null comment '等级序号', + recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', + status tinyint unsigned default 1 not null comment '状态', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment 'VIP权益信息表'; + +create index idx_required_vip_level + on t_vip_benefit (required_vip_level) + comment '按VIP等级查询权益的索引'; + +-- auto-generated definition +create table t_vip_info +( + id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' + primary key comment 'VIP信息主键索引', + user_id bigint unsigned null comment '所属用户ID', + vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', + start_time datetime not null comment 'VIP开通时间', + expire_time datetime null comment 'VIP到期时间', + activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', + benefit_id bigint unsigned null comment '关联VIP权益信息表主键', + manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' +) + comment '用户VIP信息表'; + +create index idx_vip_level + on t_vip_info (vip_level) + comment '按VIP等级查询的索引'; + +-- auto-generated definition +create table t_wishlist_group +( + id bigint unsigned auto_increment comment '收藏分组主键' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', + sort_order int default 100 not null comment '分组排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' +) + comment '商品收藏分组表'; + +create index idx_t_wishlist_group_sort + on t_wishlist_group (user_id, sort_order, create_time) + comment '按用户和排序查询收藏分组的索引'; + +create index idx_t_wishlist_group_user + on t_wishlist_group (user_id) + comment '按用户查询收藏分组的索引'; + +-- auto-generated definition +create table t_wishlist +( + id bigint unsigned auto_increment comment '商品收藏主键索引' + primary key, + user_id bigint unsigned not null comment '关联用户表主键', + product_id bigint unsigned not null comment '关联商品表主键', + group_id bigint unsigned null comment '收藏分组ID', + note varchar(500) null comment '收藏灵感备注', + sort_order int default 100 not null comment '分组内排序', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', + constraint uk_user_product + unique (user_id, product_id) comment '用户-商品唯一索引' +) + comment '商品收藏表'; + +create index idx_product_id + on t_wishlist (product_id) + comment '按商品查询收藏的索引'; + +create index idx_user_id + on t_wishlist (user_id) + comment '按用户查询收藏的索引'; + +create index idx_t_wishlist_user_group_sort + on t_wishlist (user_id, group_id, sort_order, create_time) + comment '按用户分组查询收藏灵感的索引'; + +-- ======================================== +-- 首次部署整合区:用户资产 / VIP / 优惠券补丁 +-- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); +CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); +CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); + +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''????Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_provider', 'varchar(64) NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_url', 'text NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_provider', 'varchar(64) NULL COMMENT ''???????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_url', 'text NULL COMMENT ''????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''??Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''?????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'primary_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''?????????0????1???2??'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_error', 'varchar(500) NULL COMMENT ''??????????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_uploaded_at', 'datetime NULL COMMENT ''??????'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'backup_last_retry_time', 'datetime NULL COMMENT ''??????????'''); +UPDATE t_object_storage_file +SET primary_provider = COALESCE(primary_provider, 'QINIU_KODO'), + primary_url = COALESCE(primary_url, file_url), + backup_provider = COALESCE(backup_provider, 'ALIYUN_OSS'), + primary_upload_status = CASE WHEN primary_upload_status IS NULL OR primary_upload_status = 0 THEN 1 ELSE primary_upload_status END, + backup_upload_status = COALESCE(backup_upload_status, 0), + backup_retry_count = COALESCE(backup_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_backup_retry', '(`backup_upload_status`, `primary_upload_status`, `status`)'); +UPDATE t_balance +SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) +WHERE total_recharge_amount IS NULL; + +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); +CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); +CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); + +CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); +CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); +CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); + +UPDATE t_balance_change_detail +SET before_balance = COALESCE(before_balance, current_balance - amount), + after_balance = COALESCE(after_balance, current_balance), + change_scene = COALESCE(NULLIF(change_scene, ''), type) +WHERE before_balance IS NULL + OR after_balance IS NULL + OR change_scene IS NULL + OR change_scene = ''; + +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); +CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); + +CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); +CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); + +CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); +CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); + +SET @drop_old_tag_unique_sql = ( + SELECT IF( + EXISTS( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_tag' + AND INDEX_NAME = 'uk_tag_name' + ), + 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', + 'SELECT 1' + ) +); +PREPARE stmt FROM @drop_old_tag_unique_sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); +CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); +CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); +CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); +CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); +UPDATE t_tag +SET front_visible = 1 +WHERE front_visible IS NULL; +CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); + +CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); +CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); +CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); + +UPDATE t_coupon +SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), + auto_match = COALESCE(auto_match, 0) +WHERE coupon_scene IS NULL + OR coupon_scene = '' + OR auto_match IS NULL; + +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); +CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); + +CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); +CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); + +UPDATE t_vip_benefit +SET level_rank = CASE required_vip_level + WHEN '普通' THEN 0 + WHEN '青铜' THEN 1 + WHEN '白银' THEN 2 + WHEN '黄金' THEN 3 + ELSE level_rank + END, + recharge_threshold = CASE required_vip_level + WHEN '普通' THEN 0.00 + WHEN '青铜' THEN 500.00 + WHEN '白银' THEN 1000.00 + WHEN '黄金' THEN 2000.00 + ELSE recharge_threshold + END, + status = COALESCE(status, 1) +WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); + +CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); + +CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); +CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); + +ALTER TABLE t_vip_info + MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', + MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; + +UPDATE t_vip_info vi +INNER JOIN t_user u ON u.vip_id = vi.id +SET vi.user_id = u.id +WHERE (vi.user_id IS NULL OR vi.user_id = 0) + AND u.vip_id IS NOT NULL + AND u.vip_id <> 0; + +UPDATE t_vip_info +SET start_time = COALESCE(start_time, create_time, NOW()), + activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), + manual_override = COALESCE(manual_override, 0); + +CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); + +UPDATE t_user u +LEFT JOIN t_vip_info vi ON vi.id = u.vip_id +SET u.level = CASE + WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level + WHEN u.type = 0 THEN '普通' + ELSE u.level + END, + u.vip_id = CASE + WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 + ELSE u.vip_id + END, + u.update_time = NOW() +WHERE u.is_delete = 0 + AND u.type = 0 + AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); + +UPDATE t_vip_benefit +SET benefit_info = '普通用户,无额外VIP折扣', + level_rank = 0, + recharge_threshold = 0.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '普通'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '普通' +); + +UPDATE t_vip_benefit +SET benefit_info = '青铜VIP,系统自动匹配9.5折券', + level_rank = 1, + recharge_threshold = 500.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '青铜'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '青铜' +); + +UPDATE t_vip_benefit +SET benefit_info = '白银VIP,系统自动匹配9.2折券', + level_rank = 2, + recharge_threshold = 1000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '白银'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '白银' +); + +UPDATE t_vip_benefit +SET benefit_info = '黄金VIP,系统自动匹配9.0折券', + level_rank = 3, + recharge_threshold = 2000.00, + status = 1, + update_time = NOW() +WHERE required_vip_level = '黄金'; + +INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) +SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() +WHERE NOT EXISTS ( + SELECT 1 + FROM t_vip_benefit + WHERE required_vip_level = '黄金' +); + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 +-- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql +-- ======================================== + +SET NAMES utf8mb4; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); +CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); + +UPDATE t_shop +SET status = 1 +WHERE status IS NULL; + +CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); + +CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', + `user_id` bigint unsigned NOT NULL COMMENT '用户ID', + `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', + `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (`id`) +) COMMENT='用户与店铺绑定关系表'; + +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); + +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); +CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); +CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); + +INSERT INTO t_user_shop_binding ( + user_id, + shop_id, + status, + create_time, + update_time, + is_delete +) +SELECT + u.id, + u.shop_id, + CASE + WHEN COALESCE(u.status, 1) = 1 THEN 1 + ELSE 0 + END AS binding_status, + COALESCE(u.create_time, NOW()), + COALESCE(u.update_time, NOW()), + 0 +FROM t_user u +INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 +LEFT JOIN t_user_shop_binding b + ON b.user_id = u.id + AND b.shop_id = u.shop_id + AND COALESCE(b.is_delete, 0) = 0 +WHERE COALESCE(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 + AND b.id IS NULL; + +UPDATE t_user_shop_binding b +INNER JOIN t_user u ON u.id = b.user_id +SET b.status = CASE + WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END + ELSE b.status + END, + b.is_delete = COALESCE(b.is_delete, 0), + b.update_time = COALESCE(b.update_time, NOW()) +WHERE b.status IS NULL + OR b.is_delete IS NULL + OR b.update_time IS NULL; + +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); +CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); +CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); +CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); + +CREATE TABLE IF NOT EXISTS t_order_artist_review +( + id bigint unsigned auto_increment comment '评价任务ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + artist_id bigint unsigned not null comment '被评价美甲师ID', + product_id bigint unsigned null comment '商品ID', + rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', + content varchar(1000) null comment '评价文字', + image_file_ids text null comment '评价图片文件ID集合', + status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', + reminder_message_id bigint unsigned null comment '提醒消息ID', + submitted_at datetime null comment '提交时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师评价任务表'; + +CREATE TABLE IF NOT EXISTS t_order_artist_change_request +( + id bigint unsigned auto_increment comment '改派申请ID' + primary key, + order_id bigint unsigned not null comment '订单ID', + order_item_id bigint unsigned not null comment '订单项ID', + customer_id bigint unsigned not null comment '下单客户ID', + shop_id bigint unsigned null comment '店铺ID', + product_id bigint unsigned null comment '商品ID', + from_artist_id bigint unsigned not null comment '原美甲师ID', + to_artist_id bigint unsigned not null comment '新美甲师ID', + requester_id bigint unsigned not null comment '申请人ID', + status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', + reason varchar(500) null comment '申请原因', + reject_reason varchar(500) null comment '拒绝原因', + message_id bigint unsigned null comment '提醒消息ID', + pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', + approved_time datetime null comment '同意时间', + rejected_time datetime null comment '拒绝时间', + expire_time datetime null comment '过期时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单美甲师改派申请表'; + +CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); +CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); +CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); +CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_business_event_outbox +( + id bigint unsigned auto_increment comment '事件ID' + primary key, + event_key varchar(160) not null comment '事件幂等键', + event_type varchar(64) not null comment '事件类型', + business_type varchar(64) not null comment '业务类型', + business_id bigint unsigned not null comment '业务ID', + payload_json text null comment '事件载荷', + status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', + retry_count int unsigned default 0 not null comment '重试次数', + next_retry_time datetime null comment '下次重试时间', + last_error varchar(500) null comment '最近错误', + claimed_at datetime null comment '认领时间', + processed_at datetime null comment '处理完成时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除' +) + comment '业务事件Outbox表'; + +CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); +CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); + +-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. +-- EXPIRED + +-- ======================================== +-- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth +-- ======================================== + +CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); +CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); +CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); +CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); + +CREATE TABLE IF NOT EXISTS t_artist_schedule +( + id bigint unsigned NOT NULL COMMENT '排班ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + work_date date NOT NULL COMMENT '工作日期', + start_time time NOT NULL COMMENT '班次开始时间', + end_time time NOT NULL COMMENT '班次结束时间', + slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', + capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', + remark varchar(255) NULL COMMENT '排班备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '美甲师排班表'; + +CREATE TABLE IF NOT EXISTS t_appointment_reservation +( + id bigint unsigned NOT NULL COMMENT '预约占用ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', + product_title varchar(200) NULL COMMENT '预约作品标题快照', + appointment_start_time datetime NOT NULL COMMENT '预约开始时间', + appointment_end_time datetime NOT NULL COMMENT '预约结束时间', + status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', + client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单预约时段占用表'; + +CREATE TABLE IF NOT EXISTS t_payment_order +( + id bigint unsigned NOT NULL COMMENT '支付单ID', + pay_no varchar(64) NOT NULL COMMENT '支付单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_no varchar(64) NOT NULL COMMENT '订单号快照', + user_id bigint unsigned NOT NULL COMMENT '支付用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', + status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', + pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', + paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', + pay_time datetime NULL COMMENT '支付完成时间', + expire_time datetime NULL COMMENT '支付单过期时间', + operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', + remark varchar(255) NULL COMMENT '支付备注', + idempotency_key varchar(160) NULL COMMENT '支付幂等键', + raw_payload text NULL COMMENT '支付渠道原始载荷', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单支付单表'; + +CREATE TABLE IF NOT EXISTS t_refund_order +( + id bigint unsigned NOT NULL COMMENT '退款单ID', + refund_no varchar(64) NOT NULL COMMENT '退款单号', + after_sale_id bigint unsigned NULL COMMENT '售后单ID', + payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', + refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', + refund_time datetime NULL COMMENT '退款完成时间', + channel varchar(32) NULL COMMENT '退款渠道', + external_refund_no varchar(64) NULL COMMENT '外部退款单号', + fail_reason varchar(255) NULL COMMENT '失败原因或备注', + idempotency_key varchar(160) NULL COMMENT '退款幂等键', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单退款单表'; + +CREATE TABLE IF NOT EXISTS t_after_sale +( + id bigint unsigned NOT NULL COMMENT '售后单ID', + after_sale_no varchar(64) NOT NULL COMMENT '售后单号', + order_id bigint unsigned NOT NULL COMMENT '订单ID', + order_item_id bigint unsigned NULL COMMENT '订单项ID', + user_id bigint unsigned NOT NULL COMMENT '申请用户ID', + shop_id bigint unsigned NULL COMMENT '店铺ID', + type varchar(32) NOT NULL COMMENT '售后类型', + reason varchar(1000) NULL COMMENT '申请原因', + refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', + status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', + audit_user_id bigint unsigned NULL COMMENT '审核人ID', + audit_reason varchar(500) NULL COMMENT '审核说明', + audit_time datetime NULL COMMENT '审核时间', + refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '订单售后申请表'; + +CREATE TABLE IF NOT EXISTS t_after_sale_log +( + id bigint unsigned NOT NULL COMMENT '售后日志ID', + after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', + action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', + from_status varchar(20) NULL COMMENT '变更前状态', + to_status varchar(20) NULL COMMENT '变更后状态', + operator_id bigint unsigned NULL COMMENT '操作人ID', + operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', + remark varchar(500) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '订单售后流转日志表'; + +CREATE TABLE IF NOT EXISTS t_inventory_item +( + id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + category varchar(50) NULL COMMENT '物料分类', + item_name varchar(100) NOT NULL COMMENT '物料名称', + unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', + stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', + warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', + status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '门店库存物料表'; + +CREATE TABLE IF NOT EXISTS t_inventory_record +( + id bigint unsigned NOT NULL COMMENT '库存流水ID', + inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', + shop_id bigint unsigned NOT NULL COMMENT '店铺ID', + change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', + change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', + before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', + after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', + operator_id bigint unsigned NULL COMMENT '操作人ID', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '门店库存变动流水表'; + +CREATE TABLE IF NOT EXISTS t_campaign +( + id bigint unsigned NOT NULL COMMENT '营销活动ID', + shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', + title varchar(120) NOT NULL COMMENT '活动标题', + description varchar(1000) NULL COMMENT '活动说明', + scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', + product_ids text NULL COMMENT '关联作品ID集合', + coupon_ids text NULL COMMENT '关联优惠券ID集合', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', + start_time datetime NULL COMMENT '开始时间', + end_time datetime NULL COMMENT '结束时间', + sort_order int NOT NULL DEFAULT 100 COMMENT '排序', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', + PRIMARY KEY (id) +) + COMMENT '营销活动配置表'; + +CREATE TABLE IF NOT EXISTS t_user_growth_record +( + id bigint unsigned NOT NULL COMMENT '成长值记录ID', + user_id bigint unsigned NOT NULL COMMENT '用户ID', + source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', + source_id bigint unsigned NULL COMMENT '来源业务ID', + growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id) +) + COMMENT '用户成长值流水表'; + +CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); +CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); +CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); +CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); +CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); +CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); +CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); +CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); +CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); +CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), + (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), + (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), + (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), + (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), + (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), + (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), + (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), + (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), + (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), + (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), + (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), + (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), + (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), + (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), + (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); +CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); +CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); + +CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); +CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); +CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); + +CREATE TABLE IF NOT EXISTS t_order_quote_message +( + id bigint unsigned auto_increment comment '报价交互消息主键' + primary key, + order_id bigint unsigned not null comment '订单ID', + actor_id bigint unsigned null comment '操作人ID', + actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', + action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', + remark varchar(500) null comment '备注', + items_snapshot text null comment '订单项报价快照JSON', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '订单询价报价交互消息表'; + +CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'jayucloud-artlist' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='Fingertip Designer按业务场景投递MessageHub的配置'; + +DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; + +-- ======================================== +-- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 +-- 来源:2026-03-20_init_admin_permission_template.sql +-- ======================================== + +SET NAMES utf8mb4; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), + ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), + ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), + ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), + ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), + ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), + ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), + ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), + ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), + ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), + ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), + ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), + ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), + ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), + ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), + ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), + ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), + ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), + ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), + ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), + ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), + ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), + ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), + ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), + ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), + ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), + ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), + ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), + ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), + ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), + ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), + ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), + ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), + ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), + ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), + ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), + ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), + ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), + ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), + ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), + ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), + ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), + ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), + ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + ('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_user ( + shop_id, + nickname, + account, + phone_verified, + email_verified, + password, + signature, + level, + type, + vip_id, + create_time, + update_time, + is_delete, + status +) +SELECT + 0, + '系统管理员', + 'xiaowang', + 0, + 0, + '$2a$10$I3mV64NhISqMmm7soSki1.Y36ve.TOINGOrVt0U0kxjO7GtxavE16', + '', + '管理员', + 4, + 0, + NOW(), + NOW(), + 0, + 1 +WHERE NOT EXISTS ( + SELECT 1 + FROM t_user + WHERE account = 'xiaowang' +); + +-- ======================================== +-- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT +-- 说明: +-- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 +-- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 +-- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 +-- ======================================== + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) +BEGIN + DECLARE v_column_type VARCHAR(128) DEFAULT NULL; + DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; + DECLARE v_extra VARCHAR(128) DEFAULT NULL; + + SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA + INTO v_column_type, v_column_comment, v_extra + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = 'id' + LIMIT 1; + + IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN + SET @alter_sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', + v_column_type, + ' NOT NULL' + ); + + IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN + SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); + END IF; + + PREPARE stmt FROM @alter_sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); +CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); +CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); +CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); +CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product'); +CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); +CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); +CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); +CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); +CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); +CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); +CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); +CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); +CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); +CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); +CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); + +DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'jayucloud-artlist', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NOT NULL COMMENT '用户ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + device_id varchar(128) NULL COMMENT '设备ID', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + device_id varchar(128) NULL COMMENT '设备ID', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +SET @system_parameter_enabled_missing := ( + SELECT COUNT(1) = 0 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 't_system_parameter_config' + AND COLUMN_NAME = 'enabled' +); +SET @system_parameter_enabled_sql := IF( + @system_parameter_enabled_missing, + 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', + 'SELECT 1' +); +PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; +EXECUTE stmt_system_parameter_enabled; +DEALLOCATE PREPARE stmt_system_parameter_enabled; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 Fingertip Designer 指尖设计师。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'Fingertip Designer 指尖设计师会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), + (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), + (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), + (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), + is_delete = 0, + update_time = NOW(); + +-- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + 313931273556000000 + p.id, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 最终权限兜底:确保平台管理员拥有当前权限目录中的全部基础权限。 +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT + (CAST(u.id AS UNSIGNED) << 20) + (CAST(p.id AS UNSIGNED) & 1048575), + u.id, + p.id, + NOW(), + NOW(), + 0, + 0, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 +WHERE u.account = 'xiaowang' + AND u.is_delete = 0 + AND u.type = 4 +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_by = VALUES(update_by), + update_time = NOW(); diff --git a/scripts/双端独立部署配置说明20260825.md b/scripts/双端独立部署配置说明20260825.md new file mode 100644 index 00000000..167141e2 --- /dev/null +++ b/scripts/双端独立部署配置说明20260825.md @@ -0,0 +1,44 @@ +# 设计师端与店务端独立部署配置说明 + +## 适用范围 + +本说明对应 2026-08-25 的双端隔离改造,当前只适配生产环境。设计师端和店务端先保留完整后端代码,分别构建、注册和连接独立资源。 + +## 端侧边界 + +| 端侧 | 后端目录 | 前端目录 | Nacos namespace | 数据库 | +| --- | --- | --- | --- | --- | +| 设计师端 | `FD-Core`、`FD-Gateway` | `FD-Frontend`、`FD-WeChat-Fronted` | `jayucloud-artlist` | `jayucloud_artlist` | +| 店务端 | `FM-Core`、`FM-Gateway` | `FM-Frontend`、`FM-Wechat-Fronted` | `jayucloud-salon` | `jayucloud_salon` | + +店务端可只启动 `FM-Core` 和 `FM-Gateway`,不依赖设计师端进程或数据库。 + +## Nacos 配置源 + +生产配置位于 `nacos/namespaces/prod//DEFAULT_GROUP/`,包含 `core.yaml`、`gateway.yaml`、`infra.yaml`、`secret.yaml` 和 `logging.yaml`。 + +配置发布使用 `.gitea/workflows/publish-nacos.yml`,通过 Gitea Secrets 注入 `NACOS_URLS`、`NACOS_USERNAME` 和 `NACOS_PASSWORD`。发布脚本先写入第一个 Nacos 节点,再从至少两个节点读取并按 SHA-256 校验配置内容。 + +## 生产中间件入口 + +- Nacos 客户端:`192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848`。 +- Nacos 元数据库:`192.168.10.200:3306/nacos`,不使用 ProxySQL `6033`。 +- 业务数据库:使用中心1 ProxySQL `192.168.10.200:6033`,设计师端连接 `jayucloud_artlist`,店务端连接 `jayucloud_salon`。 +- Redis:Sentinel master `mymaster`,节点列表来自《中间件服务器信息表.md》生产配置。 +- RabbitMQ:使用 `mq-prod.internal:5672`,账号、vhost 和密码通过 Gitea Secrets 或部署环境注入。 +- 对象存储:生产 bucket 统一使用 `jayucloud`,各供应商 Endpoint 和密钥通过私有配置注入。 + +## 数据库脚本 + +- `scripts/sql/migrations/20260825-双端独立数据库/设计师独立数据库_20260825.sql` +- `scripts/sql/migrations/20260825-双端独立数据库/店务独立数据库_20260825.sql` + +两份脚本均为完整可执行空库初始化脚本,不修改冻结的 `scripts/sql/init/FingertipDesigner.sql`,本次不迁移既有生产数据。 + +## 发布前验证 + +1. 分别构建 `FD-Core/FD-Gateway/FD-Frontend` 和 `FM-Core/FM-Gateway/FM-Frontend`。 +2. 只启动店务 Core/Gateway,确认服务注册为 `jayucloud-salon-core` 和 `jayucloud-salon-gateway`。 +3. 确认店务 datasource 指向 `jayucloud_salon`,设计师 datasource 指向 `jayucloud_artlist`。 +4. 发布 Nacos 配置后,从两个节点读取相同 Data ID 并校验摘要一致。 +5. 完成店务 Web、小程序登录、员工、客户、排班、规划、预约、订单和设置冒烟验证后,再进行后端裁剪。