diff --git a/.gitea/workflows/environment-promotion-guard.yml b/.gitea/workflows/environment-promotion-guard.yml new file mode 100644 index 00000000..57f26035 --- /dev/null +++ b/.gitea/workflows/environment-promotion-guard.yml @@ -0,0 +1,43 @@ +name: 环境分支晋级检查 + +on: + pull_request_target: + branches: + - sit + - prod + +jobs: + validate-source: + name: environment-promotion-source + runs-on: jayucloud + steps: + - name: 校验环境分支晋级链路 + shell: bash + env: + TARGET_BRANCH: ${{ gitea.base_ref }} + SOURCE_BRANCH: ${{ gitea.head_ref }} + SOURCE_REPOSITORY: ${{ gitea.event.pull_request.head.repo.full_name }} + TARGET_REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + + test -n "$TARGET_BRANCH" + test -n "$SOURCE_BRANCH" + test -n "$SOURCE_REPOSITORY" + test -n "$TARGET_REPOSITORY" + + if [[ "$SOURCE_REPOSITORY" != "$TARGET_REPOSITORY" ]]; then + echo "拒绝跨仓库环境晋级:$SOURCE_REPOSITORY -> $TARGET_REPOSITORY" + exit 1 + fi + + case "$TARGET_BRANCH:$SOURCE_BRANCH" in + sit:dev|prod:sit) + echo "允许环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH" + ;; + *) + echo "拒绝环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH" + echo "允许链路仅为 dev -> sit -> prod" + exit 1 + ;; + esac diff --git a/.gitea/workflows/publish-nacos.yml b/.gitea/workflows/publish-nacos.yml index 10b7c5a5..be611cfc 100644 --- a/.gitea/workflows/publish-nacos.yml +++ b/.gitea/workflows/publish-nacos.yml @@ -24,12 +24,23 @@ jobs: env: GITHUB_SERVER_URL: http://192.168.5.15:3000 steps: - - name: 检出配置源 - uses: actions/checkout@v4 - - name: 准备 Node.js 运行时 - uses: actions/setup-node@v4 - with: - node-version: 20 + - name: 从内网 Gitea 检出配置源 + shell: bash + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + test -n "$GITEA_TOKEN" + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 检查 Node.js 运行时 + shell: bash + run: | + set -euo pipefail + node_version="$(node --version)" + [[ "$node_version" == v20.* ]] - name: 发布并校验配置 env: NACOS_ENVIRONMENT: ${{ inputs.environment || github.ref_name }} diff --git a/.gitea/workflows/salon-prod-deploy.yml b/.gitea/workflows/salon-prod-deploy.yml index edf960ac..87a93260 100644 --- a/.gitea/workflows/salon-prod-deploy.yml +++ b/.gitea/workflows/salon-prod-deploy.yml @@ -17,10 +17,11 @@ jobs: runs-on: jayucloud env: GITHUB_SERVER_URL: http://192.168.5.15:3000 - WEB_TARGET_HOST: ${{ secrets.SALON_PROD_WEB_HOST }} - WEB_TARGET_PORT: ${{ secrets.SALON_PROD_WEB_PORT }} - WEB_TARGET_USER: ${{ secrets.SALON_PROD_WEB_USER }} - WEB_REMOTE_DIR: ${{ secrets.SALON_PROD_WEB_DIR }} + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + WEB_REMOTE_DIR: /opt/jc-salon-frontend + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} steps: - name: 从内网 Gitea 检出发布脚本 shell: bash @@ -39,48 +40,36 @@ jobs: shell: bash run: | set -euo pipefail - java -version 2>&1 | grep -q '17\.' - node --version | grep -q '^v20\.' + java_version="$(java -version 2>&1)" + [[ "$java_version" == *'17.'* ]] + node_version="$(node --version)" + [[ "$node_version" == v20.* ]] pwsh --version - - name: 下载已审核发布包 + - name: 准备 SSH 密码登录工具 shell: bash - env: - GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PREPARE_RUN_ID: ${{ inputs.prepare_run_id }} - ARTIFACT_NAME: salon-prod-${{ inputs.release_sha }} run: | set -euo pipefail - test -n "$GITEA_TOKEN" - test -n "$PREPARE_RUN_ID" - test -n "$ARTIFACT_NAME" - api_base="$GITHUB_SERVER_URL/api/actions_pipeline/_apis/pipelines/workflows/$PREPARE_RUN_ID/artifacts?api-version=6.0-preview" - response_file="$RUNNER_TEMP/salon-prod-artifacts.json" - curl --fail-with-body --silent --show-error --retry 3 --retry-all-errors \ - -H "Authorization: Bearer $GITEA_TOKEN" "$api_base" > "$response_file" - artifact_id=$(node -e 'const fs=require("fs"); const name=process.argv[1]; const data=JSON.parse(fs.readFileSync(process.argv[2],"utf8")); const item=(data.value||[]).find(v=>v.name===name); if(!item||!item.fileContainerResourceUrl) process.exit(2); const m=item.fileContainerResourceUrl.match(/\\/(\\d+)\\/path$/); if(!m) process.exit(3); process.stdout.write(m[1]);' "$ARTIFACT_NAME" "$response_file") - path_url="$GITHUB_SERVER_URL/api/actions_pipeline/_apis/pipelines/workflows/$PREPARE_RUN_ID/artifacts/$artifact_id/path?api-version=6.0-preview" - curl --fail-with-body --silent --show-error --retry 3 --retry-all-errors \ - -H "Authorization: Bearer $GITEA_TOKEN" "$path_url" > "$RUNNER_TEMP/salon-prod-artifact-path.json" + if ! command -v sshpass >/dev/null 2>&1; then + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + fi + sshpass -V >/dev/null 2>&1 + - name: 读取已审核发布包 + shell: bash + env: + RELEASE_SHA: ${{ inputs.release_sha }} + run: | + set -euo pipefail + test -n "$RELEASE_SHA" + shared_dir="/salon-release/$RELEASE_SHA" + test -d "$shared_dir" + test -f "$shared_dir/.manifest.sha256" + (cd "$shared_dir" && sha256sum -c .manifest.sha256) mkdir -p artifacts/release - node - "$RUNNER_TEMP/salon-prod-artifact-path.json" "$GITHUB_SERVER_URL" "$PREPARE_RUN_ID" "$artifact_id" "$GITEA_TOKEN" <<'NODE' - const fs = require('fs'); - const { execFileSync } = require('child_process'); - const [pathFile, server, runId, artifactId, token] = process.argv.slice(2); - const data = JSON.parse(fs.readFileSync(pathFile, 'utf8')); - const files = data.value || []; - if (files.length === 0) throw new Error('Artifact 未返回任何文件'); - for (const file of files) { - if (!file.contentLocation || !file.path) throw new Error('Artifact 文件项缺少下载地址或路径'); - const relativePath = file.path.split('/').slice(1).join('/'); - if (!relativePath || relativePath.includes('..')) throw new Error(`非法 Artifact 路径: ${file.path}`); - const output = `artifacts/release/${relativePath}`; - fs.mkdirSync(require('path').dirname(output), { recursive: true }); - execFileSync('curl', ['--fail-with-body', '--silent', '--show-error', '--retry', '3', '--retry-all-errors', '-H', `Authorization: Bearer ${token}`, `${server}${file.contentLocation}?itemPath=${encodeURIComponent(file.path)}`, '-o', output], { stdio: 'inherit' }); - } - NODE + cp -a "$shared_dir/." artifacts/release/ test -f artifacts/release/manifest.json - test -f artifacts/release/backend/JC-Salon-Core.jar || find artifacts/release -name 'JC-Salon-Core.jar' -exec cp {} artifacts/release/backend/JC-Salon-Core.jar \; - test -f artifacts/release/backend/JC-Salon-Gateway.jar || find artifacts/release -name 'JC-Salon-Gateway.jar' -exec cp {} artifacts/release/backend/JC-Salon-Gateway.jar \; + test -f artifacts/release/backend/JC-Salon-Core.jar + test -f artifacts/release/backend/JC-Salon-Gateway.jar - name: 发布并校验 Salon 生产 Nacos shell: bash env: @@ -95,20 +84,15 @@ jobs: - name: 写入临时 SSH 配置和目标清单 shell: bash env: - SALON_PROD_SSH_PRIVATE_KEY: ${{ secrets.SALON_PROD_SSH_PRIVATE_KEY }} - SALON_PROD_KNOWN_HOSTS: ${{ secrets.SALON_PROD_KNOWN_HOSTS }} + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} run: | set -euo pipefail - test -n "$SALON_PROD_SSH_PRIVATE_KEY" - test -n "$SALON_PROD_KNOWN_HOSTS" + test -n "$SALON_PROD_SSH_PASSWORD" test -n "$WEB_TARGET_HOST" test -n "$WEB_TARGET_PORT" test -n "$WEB_TARGET_USER" test -n "$WEB_REMOTE_DIR" mkdir -p "$RUNNER_TEMP/salon-prod" - printf '%s\n' "$SALON_PROD_SSH_PRIVATE_KEY" > "$RUNNER_TEMP/salon-prod/id_ed25519" - printf '%s\n' "$SALON_PROD_KNOWN_HOSTS" > "$RUNNER_TEMP/salon-prod/known_hosts" - chmod 600 "$RUNNER_TEMP/salon-prod/id_ed25519" "$RUNNER_TEMP/salon-prod/known_hosts" cat > "$RUNNER_TEMP/salon-prod/servers.json" <- ./docs/scripts/deploy-jayucloud-salon-production.ps1 @@ -133,7 +116,8 @@ jobs: -RequireSystemd -PackageDirectory "artifacts/release" -ServerInfoJsonPath "$env:SERVER_INFO_JSON" - -SshKeyPath "$env:SSH_KEY_PATH" - -KnownHostsPath "$env:KNOWN_HOSTS_PATH" + -SshPassword "$env:SALON_PROD_SSH_PASSWORD" + -CorePattern "^core01-" + -GatewayPattern "^gateway01-" -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" diff --git a/.gitea/workflows/salon-prod-prepare.yml b/.gitea/workflows/salon-prod-prepare.yml index 27f91778..450169cb 100644 --- a/.gitea/workflows/salon-prod-prepare.yml +++ b/.gitea/workflows/salon-prod-prepare.yml @@ -47,13 +47,19 @@ jobs: -PackageOnly -SkipTests -SkipDatabaseInit - - name: 上传发布包 - uses: actions/upload-artifact@v3 - with: - name: salon-prod-${{ github.event.pull_request.merge_commit_sha }} - path: artifacts/release/* - if-no-files-found: error - retention-days: 30 + - name: 保存发布包到共享目录 + shell: bash + env: + RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }} + run: | + set -euo pipefail + test -n "$RELEASE_SHA" + shared_dir="/salon-release/$RELEASE_SHA" + rm -rf "$shared_dir" + mkdir -p "$shared_dir" + cp -a artifacts/release/. "$shared_dir/" + test -f "$shared_dir/manifest.json" + (cd "$shared_dir" && sha256sum manifest.json > .manifest.sha256) - name: 输出部署参数 shell: bash env: @@ -66,7 +72,7 @@ jobs: echo "" echo "**release_sha**: \`$RELEASE_SHA\`" echo "" - echo "**Artifact**: \`salon-prod-$RELEASE_SHA\`" + echo "**共享目录**: \`/salon-release/$RELEASE_SHA\`" } >> "$GITHUB_STEP_SUMMARY" echo "prepare_run_id=${{ github.run_id }}" diff --git a/.gitea/workflows/salon-sit-deploy.yml b/.gitea/workflows/salon-sit-deploy.yml new file mode 100644 index 00000000..1fd0eb54 --- /dev/null +++ b/.gitea/workflows/salon-sit-deploy.yml @@ -0,0 +1,115 @@ +name: Salon SIT 自动发布 + +on: + push: + branches: + - sit + workflow_dispatch: + +jobs: + deploy: + runs-on: jayucloud + env: + GITHUB_SERVER_URL: http://192.168.5.15:3000 + WEB_TARGET_HOST: 10.66.0.3 + WEB_TARGET_PORT: 22 + WEB_TARGET_USER: root + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }} + WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit + steps: + - name: 从内网 Gitea 检出代码 + shell: bash + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + test -n "$GITEA_TOKEN" + git init . + git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" + git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git checkout --detach "$GITHUB_SHA" + - name: 检查发布工具链 + shell: bash + run: | + set -euo pipefail + java_version="$(java -version 2>&1)" + [[ "$java_version" == *'17.'* ]] + node_version="$(node --version)" + [[ "$node_version" == v20.* ]] + mvn_version="$(mvn --version 2>&1)" + [[ "$mvn_version" == *'Java version: 17.'* ]] + pwsh --version + - name: 构建 Salon SIT 发布包 + shell: pwsh + env: + VITE_API_BASE_URL: https://sit.yunail.art/api + VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api + run: >- + ./docs/scripts/deploy-jayucloud-salon-production.ps1 + -PackageOnly + -SkipTests + -SkipDatabaseInit + - name: 准备 SSH 密码登录工具 + shell: bash + run: | + set -euo pipefail + if ! command -v sshpass >/dev/null 2>&1; then + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass + fi + sshpass -V >/dev/null 2>&1 + - name: 写入 SIT SSH 配置和目标清单 + shell: bash + env: + SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }} + run: | + set -euo pipefail + test -n "$SALON_PROD_SSH_PASSWORD" + test -n "$WEB_TARGET_HOST" + test -n "$WEB_TARGET_PORT" + test -n "$WEB_TARGET_USER" + mkdir -p "$RUNNER_TEMP/salon-sit" + cat > "$RUNNER_TEMP/salon-sit/servers.json" <- + ./docs/scripts/deploy-jayucloud-salon-production.ps1 + -Deploy + -SkipDatabaseInit + -AllowSitTarget + -RequireSystemd + -PackageDirectory "artifacts/release" + -ServerInfoJsonPath "$env:SERVER_INFO_JSON" + -SshPassword "$env:SALON_PROD_SSH_PASSWORD" + -CoreRemoteAppDir "/opt/jc-salon-core-sit" + -GatewayRemoteAppDir "/opt/jc-salon-gateway-sit" + -CorePattern "^sit-app01$" + -GatewayPattern "^sit-app01$" + -CoreServiceName "jc-salon-core-sit" + -GatewayServiceName "jc-salon-gateway-sit" + -CoreHealthPort 181 + -GatewayHealthPort 180 + -WebTargetName "salon-web-sit" + -WebRemoteDir "$env:WEB_REMOTE_DIR" + -PublicBaseUrl "https://sit.yunail.art" diff --git a/JC-ArtList-Core/src/main/resources/application.yaml b/JC-ArtList-Core/src/main/resources/application.yaml index a5f6cc9a..d10cea30 100644 --- a/JC-ArtList-Core/src/main/resources/application.yaml +++ b/JC-ArtList-Core/src/main/resources/application.yaml @@ -1,138 +1 @@ -spring: - datasource: - url: jdbc:mysql://localhost:3306/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: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} +# 除 bootstrap.yaml 中的 Nacos 启动引导参数外,后端运行参数统一由 Nacos 配置源管理。 diff --git a/JC-ArtList-Core/src/main/resources/bootstrap.yaml b/JC-ArtList-Core/src/main/resources/bootstrap.yaml index f3f17fd9..618b53c8 100644 --- a/JC-ArtList-Core/src/main/resources/bootstrap.yaml +++ b/JC-ArtList-Core/src/main/resources/bootstrap.yaml @@ -5,26 +5,25 @@ spring: 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 命名空间,默认指向开发环境。 + # 运行环境可覆盖 Nacos 地址;未设置时使用开发配置中心。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # 运行环境可覆盖 Nacos 命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 服务注册分组。 - group: DEFAULT_GROUP + group: ${NACOS_GROUP:DEFAULT_GROUP} # 注册到 Nacos 的服务名。 - service: ${spring.application.name} + service: jc-artlist-core # 是否启用服务发现。 enabled: true # 是否将当前服务注册到 Nacos。 register-enabled: true - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} config: - # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 - server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} - # Nacos 配置中心命名空间,默认指向开发环境。 + # Nacos 配置中心与服务发现使用同一运行环境参数。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # Nacos 配置中心命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} @@ -34,18 +33,17 @@ spring: file-extension: yaml # 是否启用配置中心。 enabled: true - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: secret.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: logging.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true diff --git a/JC-ArtList-Gateway/src/main/resources/application.yaml b/JC-ArtList-Gateway/src/main/resources/application.yaml index 7ff5a640..2c9ab1f1 100644 --- a/JC-ArtList-Gateway/src/main/resources/application.yaml +++ b/JC-ArtList-Gateway/src/main/resources/application.yaml @@ -1,132 +1 @@ -spring: - cloud: - gateway: - routes: - # 前台API路由 - - id: product-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/product/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: product-like-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/product-like/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: shop-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/shop/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: user-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/user/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: comment-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/comment/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: balance-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/balance/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: tag-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/tag/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: file-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/file/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: permission-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/permission/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: coupon-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/coupon/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: cart-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/cart/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: order-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/order/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: wishlist-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/wishlist/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: nail-artist-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/nail-artist/** - filters: - - RewritePath=/api/(?.*), /${remaining} - - id: legal-agreement-route - uri: lb://jc-artlist-core - predicates: - - Path=/api/legal-agreement/** - filters: - - RewritePath=/api/(?.*), /${remaining} - # 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404 - - id: frontend-fallback-route - order: 100 - uri: lb://jc-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 - slow-request: - enabled: true - threshold-ms: 300 - log-response-header-request-id: true +# 除 bootstrap.yaml 中的 Nacos 启动引导参数外,Gateway 路由与运行参数统一由 Nacos 配置源管理。 diff --git a/JC-ArtList-Gateway/src/main/resources/bootstrap.yaml b/JC-ArtList-Gateway/src/main/resources/bootstrap.yaml index 0622b0a8..2bdee95f 100644 --- a/JC-ArtList-Gateway/src/main/resources/bootstrap.yaml +++ b/JC-ArtList-Gateway/src/main/resources/bootstrap.yaml @@ -5,22 +5,21 @@ spring: 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 命名空间,默认指向开发环境 + # 运行环境可覆盖 Nacos 地址;未设置时使用开发配置中心。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # 运行环境可覆盖 Nacos 命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 服务注册分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} # 注册到 Nacos 的服务名。 - service: ${spring.application.name} - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + service: jc-artlist-gateway + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} config: - # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 - server-addr: ${NACOS_SERVER_ADDR:192.168.10.11:8848,192.168.10.12:8848,192.168.10.13:8848} - # Nacos 配置中心命名空间,默认指向开发环境。 + # Nacos 配置中心与服务发现使用同一运行环境参数。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} + # Nacos 配置中心命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-artlist} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} @@ -28,18 +27,17 @@ spring: name: gateway # 所有 Nacos 配置均使用 YAML。 file-extension: yaml - # Nacos 认证用户名。 - username: ${NACOS_USERNAME} - # Nacos 认证密码。 - password: ${NACOS_PASSWORD} + # Nacos 认证信息可由运行环境覆盖。 + username: ${NACOS_USERNAME:jayucloud} + password: ${NACOS_PASSWORD:122503wcy....} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: secret.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: logging.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true diff --git a/JC-ArtList-WeChat/utils/config.js b/JC-ArtList-WeChat/utils/config.js index 60785d4a..0a970d5f 100644 --- a/JC-ArtList-WeChat/utils/config.js +++ b/JC-ArtList-WeChat/utils/config.js @@ -123,7 +123,7 @@ const DEFAULT_DOMAINS = { local: 'http://127.0.0.1:80', tunnel: 'https://yunail.art', 'dev-remote': 'https://yunail.art', - trial: 'https://yunail.art', + trial: 'https://sit.yunail.art', release: 'https://yunail.art' } @@ -140,7 +140,7 @@ const DOMAIN_MAP = { * Purpose: DEFAULT_DEVELOP_TARGET supports config.js by holding or executing the default develop 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 DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote' +const DEFAULT_DEVELOP_TARGET = 'local' /** * Purpose: DEVELOP_TARGET supports config.js by holding or executing the develop 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. diff --git a/JC-ArtList-WeChat/utils/config.local.example.js b/JC-ArtList-WeChat/utils/config.local.example.js index 14b0cd41..292e1e73 100644 --- a/JC-ArtList-WeChat/utils/config.local.example.js +++ b/JC-ArtList-WeChat/utils/config.local.example.js @@ -9,7 +9,7 @@ module.exports = { local: 'http://127.0.0.1:80', tunnel: 'https://yunail.art', 'dev-remote': 'https://yunail.art', - trial: 'https://yunail.art', + trial: 'https://sit.yunail.art', release: 'https://yunail.art' } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java index 70606e3b..b2db06ca 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/MyBatisPlusConfig.java @@ -32,6 +32,7 @@ import org.springframework.context.annotation.Configuration; "com.xiaowang.jacyucloudsalon.core.modules.payment.mapper", "com.xiaowang.jacyucloudsalon.core.modules.planning.mapper", "com.xiaowang.jacyucloudsalon.core.modules.product.mapper", + "com.xiaowang.jacyucloudsalon.core.modules.registration.mapper", "com.xiaowang.jacyucloudsalon.core.modules.security.mapper", "com.xiaowang.jacyucloudsalon.core.modules.shop.mapper", "com.xiaowang.jacyucloudsalon.core.modules.system.mapper", diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java index 86988c63..121c1f59 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/config/WebMvcConfig.java @@ -44,7 +44,13 @@ public class WebMvcConfig implements WebMvcConfigurer { "/user/refresh-token", "/user/send-verification-code", "/user/phone-login", - "/user/wechat-mini/**", + "/user/wechat-mini/auto-login", + "/user/wechat-mini/phone-login", + "/user/wechat-mini/confirm-login", + "/user/wechat-mini/status", + "/user/wechat-mini/quick-login", + "/user/workbench/register/**", + "/user/workbench/shops/available", "/user/reset-password-by-phone", "/legal-agreement/current", "/legal-agreement/current/**", diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/PhoneRegistrationTicketService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/PhoneRegistrationTicketService.java new file mode 100644 index 00000000..eece1684 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/PhoneRegistrationTicketService.java @@ -0,0 +1,13 @@ +package com.xiaowang.jacyucloudsalon.core.modules.auth.service; + +import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.PhoneRegistrationTicketVO; + +/** + * 管理已完成手机号验证的注册引导凭证。 + */ +public interface PhoneRegistrationTicketService { + + PhoneRegistrationTicketVO issue(String phone, Long userId, Long applicationId); + + PhoneRegistrationTicketVO consume(String ticket, String phone); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/PhoneRegistrationTicketServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/PhoneRegistrationTicketServiceImpl.java new file mode 100644 index 00000000..33e82364 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/PhoneRegistrationTicketServiceImpl.java @@ -0,0 +1,63 @@ +package com.xiaowang.jacyucloudsalon.core.modules.auth.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jacyucloudsalon.core.modules.auth.service.PhoneRegistrationTicketService; +import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.PhoneRegistrationTicketVO; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.UUID; + +/** + * 基于 Redis 的一次性手机号注册凭证服务。 + */ +@Service +@RequiredArgsConstructor +public class PhoneRegistrationTicketServiceImpl implements PhoneRegistrationTicketService { + private static final String KEY_PREFIX = "workbench:registration:ticket:"; + private static final Duration TTL = Duration.ofMinutes(10); + + private final StringRedisTemplate redisTemplate; + private final ObjectMapper objectMapper; + + @Override + public PhoneRegistrationTicketVO issue(String phone, Long userId, Long applicationId) { + String normalizedPhone = requireText(phone, "手机号不能为空"); + String ticket = UUID.randomUUID().toString().replace("-", ""); + PhoneRegistrationTicketVO value = new PhoneRegistrationTicketVO(ticket, normalizedPhone, userId, applicationId); + try { + redisTemplate.opsForValue().set(KEY_PREFIX + ticket, objectMapper.writeValueAsString(value), TTL); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("生成手机号注册凭证失败", exception); + } + return value; + } + + @Override + public PhoneRegistrationTicketVO consume(String ticket, String phone) { + String normalizedTicket = requireText(ticket, "手机号注册凭证不能为空"); + String payload = redisTemplate.opsForValue().getAndDelete(KEY_PREFIX + normalizedTicket); + if (payload == null) { + throw new IllegalStateException("手机号注册凭证已过期或已使用,请重新验证手机号"); + } + try { + PhoneRegistrationTicketVO value = objectMapper.readValue(payload, PhoneRegistrationTicketVO.class); + if (!value.getPhone().equals(requireText(phone, "手机号不能为空"))) { + throw new IllegalStateException("手机号与已验证凭证不一致"); + } + return value; + } catch (JsonProcessingException exception) { + throw new IllegalStateException("手机号注册凭证无效", exception); + } + } + + private String requireText(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException(message); + } + return value.trim(); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index 37017c0c..b15c35bd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -97,11 +97,10 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { String codeKey = CODE_PREFIX + phone; String sendTimeKey = SEND_TIME_PREFIX + phone; + messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); 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); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java index eafb6115..51b0522a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/LoginResponseVO.java @@ -36,6 +36,21 @@ public class LoginResponseVO { */ private boolean needSetPassword; // 是否需要设置密码 + private boolean registrationRequired; + + private String phone; + + private String registrationTicket; + + private String registrationReason; + + private String registrationStatus; + + private String registrationRejectReason; + + @JsonSerialize(using = ToStringSerializer.class) + private Long registrationApplicationId; + @Data /** * Purpose: UserInfo supports LoginResponseVO.java by holding or executing the user info business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/PhoneRegistrationTicketVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/PhoneRegistrationTicketVO.java new file mode 100644 index 00000000..ae05d1e7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/auth/vo/PhoneRegistrationTicketVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jacyucloudsalon.core.modules.auth.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * 已验证手机号注册引导凭证。 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class PhoneRegistrationTicketVO { + private String ticket; + private String phone; + private Long userId; + private Long applicationId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniBindPhoneRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniBindPhoneRequestDTO.java new file mode 100644 index 00000000..4d54d273 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniBindPhoneRequestDTO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +/** 微信小程序一键绑定手机号请求。 */ +@Data +public class WechatMiniBindPhoneRequestDTO { + @NotBlank(message = "微信手机号凭证不能为空") + private String phoneCode; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniQuickLoginRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniQuickLoginRequestDTO.java new file mode 100644 index 00000000..54abf229 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniQuickLoginRequestDTO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; + +import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.Map; + +/** 微信小程序 OpenID 快捷登录请求。 */ +@Data +public class WechatMiniQuickLoginRequestDTO implements AgreementAwareRequest { + @NotBlank(message = "微信登录凭证不能为空") + private String wxCode; + private Long preferredShopId; + private Boolean agreementAccepted; + private Map agreementVersions; + private String clientType; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniRegistrationTicket.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniRegistrationTicket.java new file mode 100644 index 00000000..0188a03c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/dto/WechatMiniRegistrationTicket.java @@ -0,0 +1,15 @@ +package com.xiaowang.jacyucloudsalon.core.modules.integration.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** 仅供后端消费的微信注册票据载荷。 */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class WechatMiniRegistrationTicket { + private Long userId; + private String appId; + private String openId; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java index 65994c02..9a25aa3b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/MessageHubPushConfigService.java @@ -68,4 +68,6 @@ public interface MessageHubPushConfigService { * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend */ MessageHubPushConfigDO getEnabledConfig(String sceneCode); + + void switchSmsProvider(UserDO currentUser, String provider); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java index 125288da..45131d5b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/WechatMiniAuthService.java @@ -3,6 +3,9 @@ package com.xiaowang.jacyucloudsalon.core.modules.integration.service; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniQuickLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniBindPhoneRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniRegistrationTicket; import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginResultVO; /** @@ -10,6 +13,14 @@ import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginR */ public interface WechatMiniAuthService { + WechatMiniLoginResultVO status(WechatMiniAutoLoginRequestDTO requestDTO); + + WechatMiniLoginResultVO quickLogin(WechatMiniQuickLoginRequestDTO requestDTO); + + boolean bindPhone(Long userId, WechatMiniBindPhoneRequestDTO requestDTO); + + WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket); + /** * 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 01b2f593..4b8d6095 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -1,11 +1,11 @@ package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; import com.xiaowang.jacyucloudsalon.core.config.BrandProperties; import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.MessageHubPushConfigDO; import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService; -import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; @@ -13,17 +13,22 @@ 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.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** - * FingertipDesigner 到 MessageHub 的投递客户端。 + * Salon 到 MessageHub 的投递客户端。 * - *

FingertipDesigner 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、 + *

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

*/ @Slf4j @@ -35,14 +40,11 @@ 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; + private final RestTemplate restTemplate; /** * 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. */ @@ -52,6 +54,18 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { */ private final BrandProperties brandProperties; + @Value("${messagehub.client.base-url:http://192.168.10.107:8080}") + private String messageHubBaseUrl; + + @Value("${messagehub.client.access-token:}") + private String messageHubAccessToken; + + @Value("${messagehub.client.ingress-exchange:messagehub.ingress.exchange}") + private String ingressExchange; + + @Value("${messagehub.client.ingress-routing-key:message.send}") + private String ingressRoutingKey; + @Value("${messagehub.client.sms-queue:smsQueue}") /** * Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role. @@ -59,14 +73,14 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { */ private String smsQueue; - @Value("${messagehub.client.source-system:fingertipdesigner}") + @Value("${messagehub.client.source-system:jayucloud-salon}") /** * 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}") + @Value("${messagehub.client.verify-template-code:SPUG_SMS_VERIFY_1}") /** * 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. @@ -110,7 +124,8 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { public void sendSmsVerificationCode(String sceneCode, String phone, String code) { try { MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); - String messageId = snowflakeIdGenerator.nextIdString(); + String resolvedSourceSystem = resolveSourceSystem(config); + String messageId = reserveMessageId(resolvedSourceSystem); Map messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId); String jsonBody = objectMapper.writeValueAsString(messageBody); Message message = MessageBuilder @@ -120,16 +135,68 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { .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")); + message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken()); + rabbitTemplate.send(ingressExchange, ingressRoutingKey, message); + log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}", + sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode")); } catch (Exception exception) { log.error("发送短信验证码失败", exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); } } + private String reserveMessageId(String resolvedSourceSystem) throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("X-MessageHub-Access-Token", requireAccessToken()); + Map requestBody = Map.of("sourceSystem", resolvedSourceSystem); + ResponseEntity response = restTemplate.postForEntity( + requireBaseUrl() + "/api/v1/messages/ids", + new HttpEntity<>(requestBody, headers), + JsonNode.class); + if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) { + throw new IllegalStateException("MessageHub 预留消息 ID 失败,HTTP 状态: " + response.getStatusCode().value()); + } + JsonNode body = response.getBody(); + if (body.path("code").asInt(-1) != 0) { + throw new IllegalStateException("MessageHub 预留消息 ID 失败,响应码: " + body.path("code").asInt(-1) + + ",原因: " + body.path("message").asText("未知错误")); + } + String messageId = body.path("data").path("messageId").asText(""); + if (!StringUtils.hasText(messageId)) { + throw new IllegalStateException("MessageHub 预留消息 ID 响应缺少 data.messageId"); + } + return messageId; + } + + private String resolveSourceSystem(MessageHubPushConfigDO config) { + if (config != null && StringUtils.hasText(config.getSourceSystem())) { + return config.getSourceSystem(); + } + return requireSourceSystem(); + } + + private String requireBaseUrl() { + if (!StringUtils.hasText(messageHubBaseUrl)) { + throw new IllegalStateException("未配置 messagehub.client.base-url"); + } + return messageHubBaseUrl.replaceAll("/$", ""); + } + + private String requireAccessToken() { + if (!StringUtils.hasText(messageHubAccessToken)) { + throw new IllegalStateException("未配置 messagehub.client.access-token"); + } + return messageHubAccessToken; + } + + private String requireSourceSystem() { + if (!StringUtils.hasText(sourceSystem)) { + throw new IllegalStateException("未配置 messagehub.client.source-system"); + } + return sourceSystem; + } + /** * 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. @@ -151,14 +218,17 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { 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("messageId", messageId); messageBody.put("uniqueId", messageId); - messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); + String effectiveSendMethod = StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"; + messageBody.put("sendMethod", effectiveSendMethod); + messageBody.put("platformParams", Map.of("sendMethod", effectiveSendMethod)); if (config != null && config.getChannelId() != null) { messageBody.put("channelId", config.getChannelId()); } Map templateParams = new HashMap<>(); - templateParams.put("name", brandProperties.getMessageTemplateName()); + templateParams.put("name", resolveSmsTemplateName()); templateParams.put("code", code); templateParams.put("min", "5"); templateParams.put("minutes", "5"); @@ -167,4 +237,20 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { messageBody.put("templateParams", templateParams); return messageBody; } + + private String resolveSmsTemplateName() { + String configuredName = brandProperties.getMessageTemplateName(); + if (!StringUtils.hasText(configuredName)) { + return "Salon"; + } + StringBuilder normalizedName = new StringBuilder(); + configuredName.codePoints() + .filter(codePoint -> (codePoint >= 'A' && codePoint <= 'Z') + || (codePoint >= 'a' && codePoint <= 'z') + || (codePoint >= '0' && codePoint <= '9') + || Character.UnicodeScript.of(codePoint) == Character.UnicodeScript.HAN) + .limit(10) + .forEach(normalizedName::appendCodePoint); + return normalizedName.length() == 0 ? "Salon" : normalizedName.toString(); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java index 05ae64d9..381d7755 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/MessageHubPushConfigServiceImpl.java @@ -26,6 +26,12 @@ import java.util.stream.Collectors; * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. */ public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigService { + private static final String SPUG_PROVIDER = "SPUG"; + private static final String ALIYUN_PROVIDER = "ALIYUN_SMS_VERIFY"; + private static final long ALIYUN_CHANNEL_ID = 314055468907909120L; + private static final List SMS_SCENES = List.of( + "USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE", "USER_RESET_PASSWORD_SMS_CODE", + "USER_BIND_PHONE_SMS_CODE", "USER_CHANGE_PHONE_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE"); /** * Variable `configMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -214,6 +220,48 @@ public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigServ .last("LIMIT 1")); } + @Override + @Transactional(rollbackFor = Exception.class) + public void switchSmsProvider(UserDO currentUser, String provider) { + ensurePlatformAdmin(currentUser); + String normalizedProvider = normalizeSmsProvider(provider); + String templateCode = SPUG_PROVIDER.equals(normalizedProvider) ? "SPUG_SMS_VERIFY_1" : null; + String sendMethod = normalizedProvider; + Long channelId = SPUG_PROVIDER.equals(normalizedProvider) ? null : ALIYUN_CHANNEL_ID; + List configs = configMapper.selectList(new LambdaQueryWrapper() + .in(MessageHubPushConfigDO::getSceneCode, SMS_SCENES) + .eq(MessageHubPushConfigDO::getPlatform, "SMS") + .eq(MessageHubPushConfigDO::getIsDelete, 0)); + if (configs.size() != SMS_SCENES.size()) { + throw new IllegalStateException("短信场景配置不完整,无法切换供应商"); + } + for (MessageHubPushConfigDO config : configs) { + String sceneTemplate = templateCode == null ? aliyunTemplate(config.getSceneCode()) : templateCode; + config.setTemplateCode(sceneTemplate); + config.setChannelId(channelId); + config.setSendMethod(sendMethod); + configMapper.updateById(config); + } + } + + private String normalizeSmsProvider(String provider) { + String value = normalizeUpper(provider, ""); + if (!SPUG_PROVIDER.equals(value) && !ALIYUN_PROVIDER.equals(value)) { + throw new IllegalArgumentException("短信供应商仅支持 SPUG 或 ALIYUN_SMS_VERIFY"); + } + return value; + } + + private String aliyunTemplate(String sceneCode) { + return switch (sceneCode) { + case "USER_REGISTER_SMS_CODE", "USER_LOGIN_SMS_CODE" -> "100001"; + case "USER_CHANGE_PHONE_SMS_CODE" -> "100002"; + case "USER_RESET_PASSWORD_SMS_CODE", "USER_CHANGE_PASSWORD_SMS_CODE" -> "100003"; + case "USER_BIND_PHONE_SMS_CODE" -> "100004"; + default -> throw new IllegalArgumentException("不支持的短信场景: " + sceneCode); + }; + } + /** * 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java index 54b455cd..89dbd38a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -8,6 +8,12 @@ import com.xiaowang.jacyucloudsalon.core.common.BusinessException; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniQuickLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniBindPhoneRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniRegistrationTicket; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jacyucloudsalon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.WechatMiniBindingDO; import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; @@ -54,6 +60,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { * 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 String REGISTRATION_TICKET_KEY_PREFIX = "user:wechat-mini:registration-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. @@ -87,6 +94,124 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final WorkbenchRegistrationApplicationMapper registrationApplicationMapper; + + @Override + public WechatMiniLoginResultVO status(WechatMiniAutoLoginRequestDTO requestDTO) { + WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); + WechatMiniBindingDO binding = findAnyBindingByOpenId(sessionInfo.openId()); + if (binding == null) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_NEW_USER, "当前微信尚未申请使用"); + } + if (!Integer.valueOf(1).equals(binding.getStatus())) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "微信身份关联已停用,请联系管理员"); + } + UserDO user = userMapper.selectById(binding.getUserId()); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "账号已失效,请联系管理员"); + } + WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId()); + if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) { + return applicationState(WechatMiniLoginResultVO.STATUS_REJECTED, "申请已被驳回,可修改后重新提交", application); + } + if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) { + return applicationState(WechatMiniLoginResultVO.STATUS_PENDING_REVIEW, "申请审核中", application); + } + if (Integer.valueOf(1).equals(user.getStatus())) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_READY, "账号可以登录"); + } + if (Integer.valueOf(0).equals(user.getType()) && application == null) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_NEW_USER, "请继续完成身份申请"); + } + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "账号已停用,请联系管理员"); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public WechatMiniLoginResultVO quickLogin(WechatMiniQuickLoginRequestDTO requestDTO) { + WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); + WechatMiniBindingDO binding = findAnyBindingByOpenId(sessionInfo.openId()); + if (binding == null) { + UserDO user = new UserDO(); + user.setNickname("微信用户" + snowflakeIdGenerator.nextIdString().substring(13)); + user.setType(0); + user.setStatus(0); + user.setPhoneVerified(0); + user.setEmailVerified(0); + user.setIsDelete(0); + userMapper.insert(user); + ensureBinding(user.getId(), sessionInfo.openId(), sessionInfo.unionId()); + return registrationResult(user.getId(), sessionInfo.openId(), null); + } + if (!Integer.valueOf(1).equals(binding.getStatus())) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "微信身份关联已停用,请联系管理员"); + } + + UserDO user = userMapper.selectById(binding.getUserId()); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "账号已失效,请联系管理员"); + } + WorkbenchRegistrationApplicationDO application = findLatestApplication(user.getId()); + if (application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus())) { + return registrationResult(user.getId(), sessionInfo.openId(), application); + } + if (application != null && (WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()) + || WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()))) { + return applicationState(WechatMiniLoginResultVO.STATUS_PENDING_REVIEW, "申请审核中", application); + } + if (!Integer.valueOf(1).equals(user.getStatus())) { + if (Integer.valueOf(0).equals(user.getType()) && application == null) { + return registrationResult(user.getId(), sessionInfo.openId(), null); + } + return WechatMiniLoginResultVO.state(WechatMiniLoginResultVO.STATUS_DISABLED, "账号已停用,请联系管理员"); + } + return loginOrSelectShop(user, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean bindPhone(Long userId, WechatMiniBindPhoneRequestDTO requestDTO) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + throw new BusinessException("用户不存在"); + } + String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode())); + if (!phone.matches(PHONE_REGEX)) { + throw new BusinessException("获取到的微信手机号格式不正确"); + } + UserDO occupied = findActiveUserByPhone(phone); + if (occupied != null && !Objects.equals(occupied.getId(), userId)) { + throw new BusinessException("该手机号已被其他账号绑定"); + } + user.setPhone(phone); + user.setPhoneVerified(1); + userMapper.updateById(user); + return true; + } + + @Override + public WechatMiniRegistrationTicket consumeRegistrationTicket(String ticket) { + if (!StringUtils.hasText(ticket)) { + throw new BusinessException("注册票据不能为空"); + } + String key = REGISTRATION_TICKET_KEY_PREFIX + ticket; + String payload = redisTemplate.opsForValue().get(key); + if (!StringUtils.hasText(payload) || !Boolean.TRUE.equals(redisTemplate.delete(key))) { + throw new BusinessException("注册票据已失效,请重新发起快捷登录"); + } + try { + WechatMiniRegistrationTicket value = objectMapper.readValue(payload, WechatMiniRegistrationTicket.class); + WechatMiniBindingDO binding = findBindingByOpenId(value.getOpenId()); + if (binding == null || !Objects.equals(binding.getUserId(), value.getUserId()) + || !Objects.equals(value.getAppId(), wechatMiniClientService.getConfiguredAppId())) { + throw new BusinessException("注册票据与微信身份不匹配"); + } + return value; + } catch (JsonProcessingException exception) { + throw new BusinessException("解析微信注册票据失败", exception); + } + } @Override /** @@ -155,25 +280,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { 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); + if (userShopBindingSupport.listActiveShopIdsByUserId(phoneUser.getId()).isEmpty()) { + return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone)); + } 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) - ); + return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone)); } @Override @@ -238,6 +350,46 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + private WorkbenchRegistrationApplicationDO findLatestApplication(Long userId) { + return registrationApplicationMapper.selectOne( + new LambdaQueryWrapper() + .eq(WorkbenchRegistrationApplicationDO::getUserId, userId) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime) + .last("limit 1") + ); + } + + private WechatMiniLoginResultVO applicationState(String status, String message, + WorkbenchRegistrationApplicationDO application) { + WechatMiniLoginResultVO result = WechatMiniLoginResultVO.state(status, message); + result.setRegistrationStatus(application.getStatus()); + result.setRegistrationRejectReason(application.getRejectReason()); + result.setRegistrationApplicationId(application.getId()); + return result; + } + + private WechatMiniLoginResultVO registrationResult(Long userId, String openId, + WorkbenchRegistrationApplicationDO application) { + WechatMiniRegistrationTicket payload = new WechatMiniRegistrationTicket( + userId, wechatMiniClientService.getConfiguredAppId(), openId); + String ticket = "wxreg_" + snowflakeIdGenerator.nextIdString(); + try { + redisTemplate.opsForValue().set(REGISTRATION_TICKET_KEY_PREFIX + ticket, + objectMapper.writeValueAsString(payload), TICKET_TTL); + } catch (JsonProcessingException exception) { + throw new BusinessException("生成微信注册票据失败", exception); + } + WechatMiniLoginResultVO result = WechatMiniLoginResultVO.registration( + ticket, + application == null ? null : application.getStatus(), + application == null ? null : application.getRejectReason(), + application == null ? null : application.getId() + ); + result.setConsentUserId(userId); + return result; + } + private WechatMiniLoginResultVO loginOrSelectShop( UserDO userDO, Long preferredShopId, @@ -372,6 +524,16 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + private WechatMiniBindingDO findAnyBindingByOpenId(String openId) { + return wechatMiniBindingMapper.selectOne( + new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId()) + .eq(WechatMiniBindingDO::getOpenId, openId) + .orderByDesc(WechatMiniBindingDO::getStatus) + .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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java index f67196f4..fa6d61f9 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/integration/vo/WechatMiniLoginResultVO.java @@ -1,5 +1,6 @@ package com.xiaowang.jacyucloudsalon.core.modules.integration.vo; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import java.util.List; @@ -27,6 +28,12 @@ public class WechatMiniLoginResultVO { * 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"; + public static final String STATUS_NEW_USER = "NEW_USER"; + public static final String STATUS_NEED_REGISTRATION = "NEED_REGISTRATION"; + public static final String STATUS_PENDING_REVIEW = "PENDING_REVIEW"; + public static final String STATUS_REJECTED = "REJECTED"; + public static final String STATUS_READY = "READY"; + public static final String STATUS_DISABLED = "DISABLED"; /** * Field `status` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. @@ -65,6 +72,35 @@ public class WechatMiniLoginResultVO { */ private Boolean needSetPassword; + private Boolean registrationRequired; + private String registrationTicket; + private String phone; + private String registrationReason; + private String registrationStatus; + private String registrationRejectReason; + private Long registrationApplicationId; + @JsonIgnore + private Long consentUserId; + + public static WechatMiniLoginResultVO state(String status, String message) { + WechatMiniLoginResultVO result = new WechatMiniLoginResultVO(); + result.setStatus(status); + result.setMessage(message); + return result; + } + + public static WechatMiniLoginResultVO registration(String ticket, String registrationStatus, + String rejectReason, Long applicationId) { + WechatMiniLoginResultVO result = state(STATUS_NEED_REGISTRATION, "请完善身份和门店资料并提交审核"); + result.setNewUser(true); + result.setRegistrationRequired(true); + result.setRegistrationTicket(ticket); + result.setRegistrationStatus(registrationStatus); + result.setRegistrationRejectReason(rejectReason); + result.setRegistrationApplicationId(applicationId); + return result; + } + /** * 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. @@ -81,6 +117,20 @@ public class WechatMiniLoginResultVO { return resultVO; } + public static WechatMiniLoginResultVO registrationRequired(LoginResponseVO loginResponse) { + WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO(); + resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN); + resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册"); + resultVO.setRegistrationRequired(true); + resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket()); + resultVO.setPhone(loginResponse.getPhone()); + resultVO.setRegistrationReason(loginResponse.getRegistrationReason()); + resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus()); + resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason()); + resultVO.setRegistrationApplicationId(loginResponse.getRegistrationApplicationId()); + return resultVO; + } + public static WechatMiniLoginResultVO selectShop( String message, String ticket, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationController.java new file mode 100644 index 00000000..6de52300 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationController.java @@ -0,0 +1,84 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.controller; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jacyucloudsalon.core.common.Result; +import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRejectDTO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.service.WorkbenchRegistrationService; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; +import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +@RequestMapping("/user/workbench") +public class WorkbenchRegistrationController { + private final WorkbenchRegistrationService registrationService; + private final UserMapper userMapper; + private final ShopMapper shopMapper; + + public WorkbenchRegistrationController(WorkbenchRegistrationService registrationService, UserMapper userMapper, ShopMapper shopMapper) { + this.registrationService = registrationService; + this.userMapper = userMapper; + this.shopMapper = shopMapper; + } + + @PostMapping({"/register/phone", "/register/wechat-mini"}) + public Result registerByPhone(@RequestBody WorkbenchRegistrationRequestDTO request) { + return Result.success(registrationService.register(request)); + } + + @PostMapping("/register/resubmit") + public Result resubmit(@RequestBody WorkbenchRegistrationRequestDTO request) { + return Result.success(registrationService.resubmit(request)); + } + + @GetMapping("/register/status") + public Result status(@RequestParam String phone) { + UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone).eq(UserDO::getIsDelete, 0).last("limit 1")); + if (user == null) { + throw new IllegalArgumentException("未找到注册申请"); + } + return Result.success(registrationService.getStatus(user.getId())); + } + + @GetMapping("/shops/available") + public Result> availableShops() { + return Result.success(shopMapper.selectList(Wrappers.lambdaQuery(ShopDO.class).eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0).select(ShopDO::getId, ShopDO::getShopName, ShopDO::getAddress).orderByAsc(ShopDO::getShopName))); + } + + @GetMapping("/registration/list") + public Result> list(HttpServletRequest request) { + Long userId = requireUserId(request); + UserDO user = userMapper.selectById(userId); + return Result.success(registrationService.listForReviewer(userId, user != null && Integer.valueOf(4).equals(user.getType()))); + } + + @PostMapping("/registration/{id}/approve") + public Result approve(HttpServletRequest request, @PathVariable Long id) { + Long userId = requireUserId(request); + UserDO user = userMapper.selectById(userId); + return Result.success(registrationService.approve(userId, user != null && Integer.valueOf(4).equals(user.getType()), id)); + } + + @PostMapping("/registration/{id}/reject") + public Result reject(HttpServletRequest request, @PathVariable Long id, @RequestBody WorkbenchRegistrationRejectDTO requestDTO) { + Long userId = requireUserId(request); + UserDO user = userMapper.selectById(userId); + return Result.success(registrationService.reject(userId, user != null && Integer.valueOf(4).equals(user.getType()), id, requestDTO == null ? null : requestDTO.getReason())); + } + + private Long requireUserId(HttpServletRequest request) { + Object userId = request.getAttribute("userId"); + if (!(userId instanceof Long)) { + throw new IllegalArgumentException("登录状态已失效"); + } + return (Long) userId; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRejectDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRejectDTO.java new file mode 100644 index 00000000..8e7e1ee9 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRejectDTO.java @@ -0,0 +1,10 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationRejectDTO { + private String reason; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java new file mode 100644 index 00000000..7c480b9c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class WorkbenchRegistrationRequestDTO { + private Long applicationId; + private String registrationTicket; + private String roleType; + private Long shopId; + private String shopName; + private String shopAddress; + private Boolean agreementAccepted; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java new file mode 100644 index 00000000..385f5b42 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationApplicationDO.java @@ -0,0 +1,48 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_workbench_registration_application") +public class WorkbenchRegistrationApplicationDO extends BaseEntity { + + @TableField("application_no") + private String applicationNo; + + @TableField("user_id") + private Long userId; + + @TableField("role_type") + private String roleType; + + @TableField("shop_id") + private Long shopId; + + @TableField("shop_name") + private String shopName; + + @TableField("shop_address") + private String shopAddress; + + @TableField("status") + private String status; + + @TableField("reviewer_id") + private Long reviewerId; + + @TableField("reviewed_at") + private LocalDateTime reviewedAt; + + @TableField("reject_reason") + private String rejectReason; + + @TableField("is_delete") + private Integer isDelete; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationRole.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationRole.java new file mode 100644 index 00000000..c44891e9 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationRole.java @@ -0,0 +1,9 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.entity; + +public final class WorkbenchRegistrationRole { + public static final String MANAGER = "MANAGER"; + public static final String STAFF = "STAFF"; + + private WorkbenchRegistrationRole() { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationStatus.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationStatus.java new file mode 100644 index 00000000..49fa508c --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/entity/WorkbenchRegistrationStatus.java @@ -0,0 +1,11 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.entity; + +public final class WorkbenchRegistrationStatus { + public static final String PENDING_ADMIN = "PENDING_ADMIN"; + public static final String PENDING_MANAGER = "PENDING_MANAGER"; + public static final String APPROVED = "APPROVED"; + public static final String REJECTED = "REJECTED"; + + private WorkbenchRegistrationStatus() { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java new file mode 100644 index 00000000..565ce2fe --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; + +public interface WorkbenchRegistrationApplicationMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java new file mode 100644 index 00000000..1779df78 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java @@ -0,0 +1,16 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.service; + +import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; + +import java.util.List; + +public interface WorkbenchRegistrationService { + WorkbenchRegistrationStatusVO register(WorkbenchRegistrationRequestDTO request); + WorkbenchRegistrationStatusVO getStatus(Long userId); + WorkbenchRegistrationStatusVO resubmit(WorkbenchRegistrationRequestDTO request); + List listForReviewer(Long reviewerId, boolean platformAdmin); + boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId); + boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java new file mode 100644 index 00000000..9aff03ff --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -0,0 +1,256 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationRole; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jacyucloudsalon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jacyucloudsalon.core.modules.registration.service.WorkbenchRegistrationService; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniRegistrationTicket; +import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.UserShopBindingDO; +import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapper; +import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; +import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +@Service +public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationService { + private final WorkbenchRegistrationApplicationMapper applicationMapper; + private final UserMapper userMapper; + private final ShopMapper shopMapper; + private final UserService userService; + private final UserShopBindingSupport userShopBindingSupport; + private final UserShopBindingMapper userShopBindingMapper; + private final WechatMiniAuthService wechatMiniAuthService; + + public WorkbenchRegistrationServiceImpl( + WorkbenchRegistrationApplicationMapper applicationMapper, + UserMapper userMapper, + ShopMapper shopMapper, + UserService userService, + UserShopBindingSupport userShopBindingSupport, + UserShopBindingMapper userShopBindingMapper, + WechatMiniAuthService wechatMiniAuthService + ) { + this.applicationMapper = applicationMapper; + this.userMapper = userMapper; + this.shopMapper = shopMapper; + this.userService = userService; + this.userShopBindingSupport = userShopBindingSupport; + this.userShopBindingMapper = userShopBindingMapper; + this.wechatMiniAuthService = wechatMiniAuthService; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public WorkbenchRegistrationStatusVO register(WorkbenchRegistrationRequestDTO request) { + require(request != null, "注册信息不能为空"); + String roleType = requireText(request.getRoleType(), "请选择注册身份").toUpperCase(); + require(WorkbenchRegistrationRole.MANAGER.equals(roleType) || WorkbenchRegistrationRole.STAFF.equals(roleType), "注册身份不合法"); + require(request.getAgreementAccepted() == null || request.getAgreementAccepted(), "请先同意用户协议和隐私政策"); + + String managerShopName = WorkbenchRegistrationRole.MANAGER.equals(roleType) + ? requireText(request.getShopName(), "店铺名称不能为空") : null; + ShopDO selectedStaffShop = null; + if (WorkbenchRegistrationRole.STAFF.equals(roleType)) { + require(request.getShopId() != null, "请选择要加入的店铺"); + selectedStaffShop = shopMapper.selectOne(Wrappers.lambdaQuery(ShopDO.class).eq(ShopDO::getId, request.getShopId()).eq(ShopDO::getStatus, 1).eq(ShopDO::getIsDelete, 0)); + require(selectedStaffShop != null, "店铺不存在或暂未营业"); + } + + WechatMiniRegistrationTicket ticket = wechatMiniAuthService.consumeRegistrationTicket( + requireText(request.getRegistrationTicket(), "注册票据不能为空")); + UserDO user = userMapper.selectById(ticket.getUserId()); + require(user != null && !Integer.valueOf(1).equals(user.getIsDelete()), "注册用户不存在"); + + WorkbenchRegistrationApplicationDO application = request.getApplicationId() == null + ? findLatest(user.getId()) : applicationMapper.selectById(request.getApplicationId()); + if (application != null) { + require(user.getId().equals(application.getUserId()), "注册申请与账号不匹配"); + require(WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus()), "该注册申请当前不可重新提交"); + } else { + application = new WorkbenchRegistrationApplicationDO(); + } + + ShopDO shop = null; + if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) { + shop = WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType()) && application.getShopId() != null + ? shopMapper.selectById(application.getShopId()) : null; + if (shop == null) { + shop = new ShopDO(); + } + shop.setShopName(managerShopName); + shop.setAddress(request.getShopAddress()); + shop.setDescription("Salon店务工作台注册申请"); + shop.setBusinessHours("10:00-22:00"); + shop.setStatus(0); + shop.setIsDelete(0); + if (shop.getId() == null) { + shopMapper.insert(shop); + } else { + shopMapper.updateById(shop); + } + } else { + shop = selectedStaffShop; + } + + user.setShopId(shop.getId()); + if (!StringUtils.hasText(user.getNickname()) || user.getNickname().startsWith("微信用户")) { + user.setNickname(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? shop.getShopName() + "店长" : "Salon店员"); + } + user.setType(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? 2 : 3); + user.setStatus(0); + user.setIsDelete(0); + userMapper.updateById(user); + if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) { + createPendingBinding(user.getId(), shop.getId()); + } else { + userShopBindingSupport.syncUserShopBindings(user.getId(), List.of(shop.getId())); + userShopBindingSupport.updateBindingStatus(user.getId(), shop.getId(), 0); + } + + if (!StringUtils.hasText(application.getApplicationNo())) { + application.setApplicationNo("SALON-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20).toUpperCase()); + } + application.setUserId(user.getId()); + application.setRoleType(roleType); + application.setShopId(shop.getId()); + application.setShopName(shop.getShopName()); + application.setShopAddress(shop.getAddress()); + application.setStatus(WorkbenchRegistrationRole.MANAGER.equals(roleType) ? WorkbenchRegistrationStatus.PENDING_ADMIN : WorkbenchRegistrationStatus.PENDING_MANAGER); + application.setRejectReason(null); + application.setReviewerId(null); + application.setReviewedAt(null); + application.setIsDelete(0); + if (application.getId() == null) { + applicationMapper.insert(application); + } else { + applicationMapper.updateById(application); + } + return toStatus(application); + } + + @Override + public WorkbenchRegistrationStatusVO getStatus(Long userId) { + WorkbenchRegistrationApplicationDO application = findLatest(userId); + require(application != null, "未找到注册申请"); + return toStatus(application); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public WorkbenchRegistrationStatusVO resubmit(WorkbenchRegistrationRequestDTO request) { + require(request != null && request.getApplicationId() != null, "申请信息不能为空"); + return register(request); + } + + @Override + public List listForReviewer(Long reviewerId, boolean platformAdmin) { + if (platformAdmin) { + return applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + } + UserDO reviewer = userMapper.selectById(reviewerId); + require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()), "仅店长可以审核店员申请"); + return applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER).eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, platformAdmin, applicationId); + UserDO user = userMapper.selectById(application.getUserId()); + require(user != null, "申请用户不存在"); + if (WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType())) { + require(platformAdmin && WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()), "无权审核该申请"); + ShopDO shop = shopMapper.selectById(application.getShopId()); + require(shop != null, "申请店铺不存在"); + shop.setStatus(1); + shopMapper.updateById(shop); + } + user.setStatus(1); + userMapper.updateById(user); + userShopBindingSupport.updateBindingStatus(user.getId(), application.getShopId(), 1); + userService.syncManagedPermissions(user.getId()); + application.setStatus(WorkbenchRegistrationStatus.APPROVED); + application.setReviewerId(reviewerId); + application.setReviewedAt(LocalDateTime.now()); + applicationMapper.updateById(application); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason) { + WorkbenchRegistrationApplicationDO application = loadReviewable(reviewerId, platformAdmin, applicationId); + application.setStatus(WorkbenchRegistrationStatus.REJECTED); + application.setReviewerId(reviewerId); + application.setReviewedAt(LocalDateTime.now()); + application.setRejectReason(requireText(reason, "驳回原因不能为空")); + applicationMapper.updateById(application); + return true; + } + + private WorkbenchRegistrationApplicationDO loadReviewable(Long reviewerId, boolean platformAdmin, Long applicationId) { + WorkbenchRegistrationApplicationDO application = applicationMapper.selectById(applicationId); + require(application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus()) == false, "审核申请不存在或已处理"); + if (platformAdmin) { + require(WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()), "管理员只能审核店长申请"); + } else { + UserDO reviewer = userMapper.selectById(reviewerId); + require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()) && reviewer.getShopId().equals(application.getShopId()), "无权审核该店铺申请"); + require(WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()), "店长只能审核店员申请"); + } + return application; + } + + private WorkbenchRegistrationApplicationDO findLatest(Long userId) { + return applicationMapper.selectOne(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getUserId, userId).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime).last("limit 1")); + } + + private WorkbenchRegistrationStatusVO toStatus(WorkbenchRegistrationApplicationDO application) { + return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName()); + } + + private String requireText(String value, String message) { + require(StringUtils.hasText(value), message); + return value.trim(); + } + + private void createPendingBinding(Long userId, Long shopId) { + UserShopBindingDO binding = userShopBindingMapper.selectOne(Wrappers.lambdaQuery(UserShopBindingDO.class) + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getShopId, shopId) + .last("limit 1")); + if (binding == null) { + binding = new UserShopBindingDO(); + binding.setUserId(userId); + binding.setShopId(shopId); + binding.setStatus(0); + binding.setIsDelete(0); + userShopBindingMapper.insert(binding); + return; + } + binding.setStatus(0); + binding.setIsDelete(0); + userShopBindingMapper.updateById(binding); + } + + private void require(boolean condition, String message) { + if (!condition) { + throw new IllegalArgumentException(message); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java new file mode 100644 index 00000000..15b7aa7b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java @@ -0,0 +1,16 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationStatusVO { + private Long applicationId; + private String applicationNo; + private String roleType; + private String status; + private String rejectReason; + private Long shopId; + private String shopName; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java index b4b82638..5a939579 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -8,6 +8,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.system.mapper.SystemParameterCo import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; import com.xiaowang.jacyucloudsalon.core.modules.system.support.AdminDefaultPasswordSupport; import com.xiaowang.jacyucloudsalon.core.modules.system.vo.SystemParameterConfigVO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.service.MessageHubPushConfigService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -30,6 +31,7 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SystemParameterConfigMapper configMapper; + private final MessageHubPushConfigService messageHubPushConfigService; @Override /** @@ -81,6 +83,9 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe } else { configMapper.updateById(config); } + if ("SMS".equals(group) && "SMS_PROVIDER".equals(key)) { + messageHubPushConfigService.switchSmsProvider(currentUser, config.getConfigValue()); + } return true; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java index aeebcbfa..cef84d4d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/controller/front/UserController.java @@ -56,6 +56,8 @@ import com.xiaowang.jacyucloudsalon.core.modules.file.dto.ChunkUploadInitRequest import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniConfirmLoginRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniPhoneLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniQuickLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniBindPhoneRequestDTO; import com.xiaowang.jacyucloudsalon.core.modules.user.dto.UserDTO; import com.xiaowang.jacyucloudsalon.core.modules.user.vo.UserAgreementConsentVO; /** @@ -450,9 +452,11 @@ public class UserController { legalAgreementService.requireAccepted(phoneLoginRequestDTO); try { LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); - legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO, "USER_PHONE_LOGIN", request); + if (loginResponseVO.getUserInfo() != null) { + 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); + securityAuditLogService.record(loginResponseVO.getUserInfo() == null ? null : loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "SUCCESS", null, request); return Result.success(loginResponseVO); } catch (RuntimeException exception) { requestThrottleService.recordLoginFailure(request, phoneLoginRequestDTO.getPhone()); @@ -473,6 +477,23 @@ public class UserController { return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); } + @PostMapping("/wechat-mini/status") + @OperationGuard(action = "wechat-mini-status", ttlSeconds = 2, message = "状态检测中,请稍后重试") + public Result wechatMiniStatus(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { + return Result.success(wechatMiniAuthService.status(requestDTO)); + } + + @PostMapping("/wechat-mini/quick-login") + @OperationGuard(action = "wechat-mini-quick-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result wechatMiniQuickLogin(HttpServletRequest request, + @Valid @RequestBody WechatMiniQuickLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, "wechat-mini-quick"); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.quickLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_QUICK_LOGIN", request); + return Result.success(result); + } + @PostMapping("/wechat-mini/phone-login") @OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") /** @@ -644,9 +665,13 @@ public class UserController { 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); + if (result != null) { + Long userId = result.getUserInfo() == null ? result.getConsentUserId() : result.getUserInfo().getId(); + if (userId == null) { + return; + } + legalAgreementService.recordConsent(userId, dto, entry, request); + securityAuditLogService.record(userId, null, entry, "SUCCESS", null, request); } } @@ -690,6 +715,14 @@ public class UserController { return Result.success(success); } + @PostMapping("/wechat-mini/bind-phone") + @OperationGuard(action = "wechat-mini-bind-phone", ttlSeconds = 10, message = "手机号绑定处理中,请勿重复提交") + public Result bindWechatMiniPhone(HttpServletRequest request, + @Valid @RequestBody WechatMiniBindPhoneRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(wechatMiniAuthService.bindPhone(userId, requestDTO)); + } + /** * 绑定邮箱 * diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java index dcc2cf36..09efb837 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/UserService.java @@ -106,6 +106,8 @@ public interface UserService extends IService { */ LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO); + LoginResponseVO phoneLoginByVerifiedPhone(String phone); + /** * 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java index 77e819e7..70b7e2c0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/service/impl/UserServiceImpl.java @@ -28,6 +28,11 @@ import com.xiaowang.jacyucloudsalon.core.modules.shop.service.ShopService; import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; import com.xiaowang.jacyucloudsalon.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jacyucloudsalon.core.modules.auth.service.PhoneRegistrationTicketService; +import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.PhoneRegistrationTicketVO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationStatus; +import com.xiaowang.jacyucloudsalon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; import com.xiaowang.jacyucloudsalon.core.modules.system.support.AdminDefaultPasswordSupport; import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionCatalog; @@ -167,6 +172,8 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final VerificationCodeService verificationCodeService; + private final PhoneRegistrationTicketService phoneRegistrationTicketService; + private final WorkbenchRegistrationApplicationMapper registrationApplicationMapper; /** * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -777,6 +784,7 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setNickname(userDO.getNickname()); userVO.setAccount(userDO.getAccount()); userVO.setPhone(userDO.getPhone()); + userVO.setPhoneVerified(userDO.getPhoneVerified()); userVO.setContactPhone(userDO.getContactPhone()); userVO.setBirthday(userDO.getBirthday()); userVO.setWechatId(userDO.getWechatId()); @@ -1067,35 +1075,66 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("验证码错误或已过期"); } + return phoneLoginByVerifiedPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId(), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe())); + } + + @Override + public LoginResponseVO phoneLoginByVerifiedPhone(String phone) { + return phoneLoginByVerifiedPhone(phone, null, false); + } + + private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) { + String normalizedPhone = normalizeVerifiedPhone(phone); + UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) + .eq(UserDO::getPhone, normalizedPhone) .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()); + return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED"); } + if (userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()).isEmpty()) { + return buildRegistrationRequiredResponse(normalizedPhone, userDO, "NO_SHOP_BINDING"); + } + 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())); + Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), rememberMe); + } + + private String normalizeVerifiedPhone(String phone) { + String normalizedPhone = phone == null ? null : phone.trim(); + if (!StringUtils.hasText(normalizedPhone) || !normalizedPhone.matches(PHONE_REGEX)) { + throw new RuntimeException("手机号格式不正确"); + } + return normalizedPhone; + } + + private LoginResponseVO buildRegistrationRequiredResponse(String phone, UserDO userDO, String reason) { + WorkbenchRegistrationApplicationDO application = userDO == null ? null : registrationApplicationMapper.selectOne( + Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getUserId, userDO.getId()) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0) + .orderByDesc(WorkbenchRegistrationApplicationDO::getCreateTime) + .last("limit 1") + ); + LoginResponseVO response = new LoginResponseVO(); + response.setRegistrationRequired(true); + response.setPhone(phone); + response.setRegistrationReason(reason); + response.setRegistrationStatus(application == null ? null : application.getStatus()); + response.setRegistrationRejectReason(application == null ? null : application.getRejectReason()); + boolean rejected = application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus()); + boolean approvedWithoutBinding = application != null && WorkbenchRegistrationStatus.APPROVED.equals(application.getStatus()); + response.setRegistrationApplicationId(rejected ? application.getId() : null); + if (application == null || rejected || approvedWithoutBinding) { + PhoneRegistrationTicketVO ticket = phoneRegistrationTicketService.issue(phone, userDO == null ? null : userDO.getId(), rejected ? application.getId() : null); + response.setRegistrationTicket(ticket.getTicket()); + } + return response; } // 未设置密码的特殊标识 diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java index 2ddc0d56..8beccf97 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/user/vo/UserVO.java @@ -111,6 +111,7 @@ public class UserVO { * 手机号 */ private String phone; + private Integer phoneVerified; /** * 联系电话 */ diff --git a/JC-Salon-Core/src/main/resources/bootstrap.yaml b/JC-Salon-Core/src/main/resources/bootstrap.yaml index a3132392..e9039e7d 100644 --- a/JC-Salon-Core/src/main/resources/bootstrap.yaml +++ b/JC-Salon-Core/src/main/resources/bootstrap.yaml @@ -5,26 +5,25 @@ spring: cloud: nacos: discovery: - # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 + # 运行环境可覆盖 Nacos 地址;未设置时使用开发配置中心。 server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} - # Nacos 命名空间,默认指向开发环境。 + # 运行环境可覆盖 Nacos 命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-salon} # 服务注册分组。 - group: DEFAULT_GROUP + group: ${NACOS_GROUP:DEFAULT_GROUP} # 注册到 Nacos 的服务名。 - service: ${spring.application.name} + service: jc-salon-core # 是否启用服务发现。 enabled: true # 是否将当前服务注册到 Nacos。 register-enabled: true - # Nacos 认证用户名。 + # Nacos 认证信息可由运行环境覆盖。 username: ${NACOS_USERNAME:jayucloud} - # Nacos 认证密码。 password: ${NACOS_PASSWORD:122503wcy....} config: - # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 + # Nacos 配置中心与服务发现使用同一运行环境参数。 server-addr: ${NACOS_SERVER_ADDR:192.168.5.15:8848} - # Nacos 配置中心命名空间,默认指向开发环境。 + # Nacos 配置中心命名空间。 namespace: ${NACOS_NAMESPACE:jayucloud-salon} # 配置分组。 group: ${NACOS_GROUP:DEFAULT_GROUP} @@ -34,18 +33,17 @@ spring: file-extension: yaml # 是否启用配置中心。 enabled: true - # Nacos 认证用户名。 + # Nacos 认证信息可由运行环境覆盖。 username: ${NACOS_USERNAME:jayucloud} - # Nacos 认证密码。 password: ${NACOS_PASSWORD:122503wcy....} # Core 与 Gateway 共享的公共配置文件。 shared-configs: - data-id: infra.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: secret.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true - data-id: logging.yaml - group: ${NACOS_GROUP:DEFAULT_GROUP} + group: DEFAULT_GROUP refresh: true diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImplTest.java new file mode 100644 index 00000000..4764fc4b --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/integration/service/impl/WechatMiniAuthServiceImplTest.java @@ -0,0 +1,116 @@ +package com.xiaowang.jacyucloudsalon.core.modules.integration.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniAutoLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniQuickLoginRequestDTO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jacyucloudsalon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jacyucloudsalon.core.modules.integration.vo.WechatMiniLoginResultVO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; +import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; +import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; +import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class WechatMiniAuthServiceImplTest { + @Mock private WechatMiniClientService clientService; + @Mock private WechatMiniBindingMapper bindingMapper; + @Mock private UserMapper userMapper; + @Mock private UserService userService; + @Mock private UserShopBindingSupport shopBindingSupport; + @Mock private StringRedisTemplate redisTemplate; + @Mock private ValueOperations valueOperations; + @Mock private TimeOrderedSnowflakeIdGenerator idGenerator; + @Mock private WorkbenchRegistrationApplicationMapper applicationMapper; + + private WechatMiniAuthServiceImpl service; + + @BeforeEach + void setUp() { + service = new WechatMiniAuthServiceImpl(clientService, bindingMapper, userMapper, userService, + shopBindingSupport, redisTemplate, new ObjectMapper(), idGenerator, applicationMapper); + when(clientService.getConfiguredAppId()).thenReturn("wx-app"); + } + + @Test + void statusDoesNotCreateUnknownUser() { + when(clientService.code2Session("probe-code")) + .thenReturn(new WechatMiniClientService.SessionInfo("openid-1", null, "session")); + when(bindingMapper.selectOne(any())).thenReturn(null); + WechatMiniAutoLoginRequestDTO request = new WechatMiniAutoLoginRequestDTO(); + request.setWxCode("probe-code"); + + WechatMiniLoginResultVO result = service.status(request); + + assertEquals(WechatMiniLoginResultVO.STATUS_NEW_USER, result.getStatus()); + verify(userMapper, never()).insert(any()); + verifyNoInteractions(userService, redisTemplate); + } + + @Test + void quickLoginCreatesSinglePendingIdentityWithoutAccountOrPassword() { + when(clientService.code2Session("login-code")) + .thenReturn(new WechatMiniClientService.SessionInfo("openid-1", "union-1", "session")); + when(bindingMapper.selectOne(any())).thenReturn(null); + when(bindingMapper.selectList(any())).thenReturn(List.of()); + when(userMapper.insert(any())).thenAnswer(invocation -> { + ((UserDO) invocation.getArgument(0)).setId(101L); + return 1; + }); + when(idGenerator.nextIdString()).thenReturn("1234567890123456789"); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + WechatMiniQuickLoginRequestDTO request = new WechatMiniQuickLoginRequestDTO(); + request.setWxCode("login-code"); + + WechatMiniLoginResultVO result = service.quickLogin(request); + + assertEquals(WechatMiniLoginResultVO.STATUS_NEED_REGISTRATION, result.getStatus()); + assertNotNull(result.getRegistrationTicket()); + verify(userMapper, times(1)).insert(argThat(user -> user.getAccount() == null + && user.getPassword() == null && Integer.valueOf(0).equals(user.getStatus()))); + verify(bindingMapper, times(1)).insert(argThat(binding -> "openid-1".equals(binding.getOpenId()) + && Long.valueOf(101L).equals(binding.getUserId()))); + verifyNoInteractions(userService); + } + + @Test + void inactiveReviewedUserCannotReceiveToken() { + WechatMiniBindingDO binding = new WechatMiniBindingDO(); + binding.setUserId(101L); + binding.setStatus(1); + UserDO user = new UserDO(); + user.setId(101L); + user.setType(2); + user.setStatus(0); + user.setIsDelete(0); + when(clientService.code2Session("login-code")) + .thenReturn(new WechatMiniClientService.SessionInfo("openid-1", null, "session")); + when(bindingMapper.selectOne(any())).thenReturn(binding); + when(userMapper.selectById(101L)).thenReturn(user); + when(applicationMapper.selectOne(any())).thenReturn(null); + WechatMiniQuickLoginRequestDTO request = new WechatMiniQuickLoginRequestDTO(); + request.setWxCode("login-code"); + + WechatMiniLoginResultVO result = service.quickLogin(request); + + assertEquals(WechatMiniLoginResultVO.STATUS_DISABLED, result.getStatus()); + assertNull(result.getAccessToken()); + verifyNoInteractions(userService); + } +} diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 700d9423..d4240b76 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1972,5 +1972,30 @@ export const adminSystemParameterConfigApi = { } } +export interface WorkbenchRegistrationApplication { + id: IdType + applicationNo: string + userId: IdType + roleType: 'MANAGER' | 'STAFF' + shopId?: IdType + shopName?: string + shopAddress?: string + status: 'PENDING_ADMIN' | 'PENDING_MANAGER' | 'APPROVED' | 'REJECTED' + rejectReason?: string + createTime?: string +} + +export const adminWorkbenchRegistrationApi = { + list() { + return adminApi.get('/user/workbench/registration/list') as unknown as Promise + }, + approve(id: IdType) { + return adminApi.post(`/user/workbench/registration/${id}/approve`) + }, + reject(id: IdType, reason: string) { + return adminApi.post(`/user/workbench/registration/${id}/reject`, { reason }) + } +} + export { adminApi } export default adminApi diff --git a/JC-Salon-Frontend/src/config/admin-navigation.test.ts b/JC-Salon-Frontend/src/config/admin-navigation.test.ts index dcfb3804..db26d732 100644 --- a/JC-Salon-Frontend/src/config/admin-navigation.test.ts +++ b/JC-Salon-Frontend/src/config/admin-navigation.test.ts @@ -3,7 +3,7 @@ import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemB describe('admin-navigation', () => { it('keeps dashboard landing and permission routes aligned', () => { - expect(ADMIN_DASHBOARD_PATH).toBe('/admin/dashboard') + expect(ADMIN_DASHBOARD_PATH).toBe('/admin') expect(findAdminNavigationItemByPath('/admin/shops')?.label).toBe('店铺管理') expect(findAdminNavigationItemByPath('/admin/products')).toBeUndefined() expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true) diff --git a/JC-Salon-Frontend/src/config/admin-navigation.ts b/JC-Salon-Frontend/src/config/admin-navigation.ts index d2fe3531..dcae102d 100644 --- a/JC-Salon-Frontend/src/config/admin-navigation.ts +++ b/JC-Salon-Frontend/src/config/admin-navigation.ts @@ -20,13 +20,14 @@ export interface AdminNavigationItem { } export const ADMIN_HOME_PATH = '/admin' -export const ADMIN_DASHBOARD_PATH = '/admin/dashboard' +export const ADMIN_DASHBOARD_PATH = ADMIN_HOME_PATH 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/users', iconKey: 'user', label: '店长账号', permissionCode: 'user:view' }, + { path: '/admin/registrations', iconKey: 'team', label: '注册审核', permissionCode: 'user:view' }, { path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' }, + { path: '/admin/settings', iconKey: 'tool', label: '系统设置', permissionCode: 'messagehub:config:manage' }, { path: '/admin/profile', iconKey: 'user', label: '个人设置', permissionCode: '' } ] diff --git a/JC-Salon-Frontend/src/router/index.ts b/JC-Salon-Frontend/src/router/index.ts index a8822bf5..f6d65d59 100644 --- a/JC-Salon-Frontend/src/router/index.ts +++ b/JC-Salon-Frontend/src/router/index.ts @@ -8,12 +8,13 @@ import { } from '@/utils/admin-auth-bootstrap' const pageNames = [ - ['', 'HomeView', 'admin', undefined], ['dashboard', 'DashboardView', 'admin-dashboard', 'dashboard:view'], - ['users', 'UsersView', 'admin-users', 'user:view'], ['shops', 'ShopsView', 'admin-shops', 'shop:view'], - ['profile', 'ProfileView', 'admin-profile', undefined] + ['', 'HomeView', 'admin', undefined], + ['users', 'UsersView', 'admin-users', 'user:view'], ['registrations', 'WorkbenchRegistrationView', 'admin-registrations', 'user:view'], ['shops', 'ShopsView', 'admin-shops', 'shop:view'], + ['profile', 'ProfileView', 'admin-profile', undefined], ['settings', 'SystemSettingsView', 'admin-settings', 'messagehub:config:manage'] ] as const const routes = [ + { path: '/', redirect: '/admin' }, { 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 }, @@ -21,7 +22,7 @@ const routes = [ path, name, component: () => import(`../views/admin/${view}.vue`), meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode } })) }, - { path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('../views/NotFoundView.vue'), meta: { requiresAuth: false, isAdmin: true, hideNav: true } } + { path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('../views/NotFoundView.vue'), meta: { requiresAuth: false, isAdmin: false, hideNav: true } } ] const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes }) diff --git a/JC-Salon-Frontend/src/views/NotFoundView.vue b/JC-Salon-Frontend/src/views/NotFoundView.vue index 49a083ed..da138b88 100644 --- a/JC-Salon-Frontend/src/views/NotFoundView.vue +++ b/JC-Salon-Frontend/src/views/NotFoundView.vue @@ -12,11 +12,11 @@ {{ BRAND_CONFIG.appName }}
404

这页去做护理了

-

您访问的页面不存在或已被删除,我们带您回到首页继续浏览作品。

+

您访问的页面不存在或已被删除,我们将在 5 秒后返回上一页。

- 将在 {{ countdown }} 秒后自动跳转到首页... + 将在 {{ countdown }} 秒后返回上一页...

- 立即前往首页 + 返回上一页 @@ -53,16 +53,20 @@ const handleBackClick = () => { router.back() return } - router.push('/home') + router.replace('/admin/login') } -/** redirectToHome is a local helper used by this page script. */ -const redirectToHome = () => { +/** redirectToLogin 将无历史来源的访问导回管理端登录页。 */ +const redirectToLogin = () => { clearRedirectTimer() - router.push('/home') + router.replace('/admin/login') } onMounted(() => { + if (window.history.length <= 1) { + redirectToLogin() + return + } timer = window.setInterval(() => { if (countdown.value > 0) { countdown.value-- @@ -70,7 +74,7 @@ onMounted(() => { if (timer) { clearInterval(timer) } - redirectToHome() + handleBackClick() } }, 1000) }) diff --git a/JC-Salon-Frontend/src/views/admin/HomeView.vue b/JC-Salon-Frontend/src/views/admin/HomeView.vue index 8f39c049..4d562f65 100644 --- a/JC-Salon-Frontend/src/views/admin/HomeView.vue +++ b/JC-Salon-Frontend/src/views/admin/HomeView.vue @@ -154,7 +154,6 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue' import { useRouter } from 'vue-router' import { - DashboardOutlined, HomeOutlined, SafetyCertificateOutlined, UserOutlined @@ -231,16 +230,9 @@ const quickActions = computed(() => { return [] } const actions = [ - { - key: 'dashboard', - title: '仪表盘', - path: '/admin/dashboard', - icon: DashboardOutlined, - permissionCode: 'dashboard:view' - }, { key: 'users', - title: '用户管理', + title: '店长账号', path: '/admin/users', icon: UserOutlined, permissionCode: 'user:view' diff --git a/JC-Salon-Frontend/src/views/admin/ManageView.vue b/JC-Salon-Frontend/src/views/admin/ManageView.vue index f8f76ecf..39cd3964 100644 --- a/JC-Salon-Frontend/src/views/admin/ManageView.vue +++ b/JC-Salon-Frontend/src/views/admin/ManageView.vue @@ -91,7 +91,7 @@ const visibleModules = computed(() => { key: 'dashboard', title: '仪表盘', description: '查看经营概览、近期动态和重点提醒。', - path: '/admin/dashboard', + path: '/admin', icon: DashboardOutlined, permissionCode: 'dashboard:view' }, @@ -108,7 +108,7 @@ const visibleModules = computed(() => { { key: 'products', title: '作品管理', - description: '维护作品、标签、可预约美甲师和优惠券。', + description: '维护作品、标签、可预约员工和优惠券。', path: '/admin/products', icon: ShopOutlined, permissionCode: 'product:view', @@ -134,8 +134,8 @@ const visibleModules = computed(() => { }, { key: 'artists', - title: '美甲师', - description: '查看状态、技能与作品挂载关系。', + title: '员工', + description: '查看员工状态、技能与排班关系。', path: '/admin/nail-artists', icon: TeamOutlined, permissionCode: 'nail_artist:view', diff --git a/JC-Salon-Frontend/src/views/admin/PermissionsView.vue b/JC-Salon-Frontend/src/views/admin/PermissionsView.vue index fc632889..a3bcc66e 100644 --- a/JC-Salon-Frontend/src/views/admin/PermissionsView.vue +++ b/JC-Salon-Frontend/src/views/admin/PermissionsView.vue @@ -548,7 +548,7 @@ const getUserTypeText = (type: number) => { const map: Record = { 0: '用户', 2: '店长', - 3: '美甲师', + 3: '店员', 4: '管理员' } return map[type] || '未知' @@ -565,12 +565,12 @@ const filteredUserList = computed(() => { return userList.value.filter(user => user.type !== 0 && !sameId(user.id, currentUserId)) } - // 店长只能看到美甲师(除了自己) + // 店长只能看到店员(除了自己) if (currentLoginUser.value.type === 2) { return userList.value.filter(user => user.type === 3 && !sameId(user.id, currentUserId)) } - // 其他用户类型(如美甲师)不能管理权限 + // 其他用户类型(如店员)不能管理权限 return [] }) diff --git a/JC-Salon-Frontend/src/views/admin/ShopsView.vue b/JC-Salon-Frontend/src/views/admin/ShopsView.vue index d82f45d7..a00154f3 100644 --- a/JC-Salon-Frontend/src/views/admin/ShopsView.vue +++ b/JC-Salon-Frontend/src/views/admin/ShopsView.vue @@ -103,7 +103,7 @@ @change="(checked: any) => handleStatusChange(record, checked === true)" /> -