From 0fd96d150ecf21a74a4500c679fcf9408fed5011 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Tue, 23 Jun 2026 15:33:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E5=BC=80=E5=8F=91=E5=88=86?= =?UTF-8?q?=E6=94=AF=E6=9C=AA=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81=E5=B9=B6?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/skills/gitnexus/gitnexus-cli/SKILL.md | 14 +- .../gitnexus/gitnexus-debugging/SKILL.md | 30 +- .../gitnexus/gitnexus-exploring/SKILL.md | 22 +- .../skills/gitnexus/gitnexus-guide/SKILL.md | 35 +- .../gitnexus-impact-analysis/SKILL.md | 20 +- .../gitnexus/gitnexus-refactoring/SKILL.md | 50 +- AGENTS.md | 44 +- CLAUDE.md | 37 +- FD-Core/pom.xml | 8 +- .../config/AppCacheProperties.java | 2 +- .../config/HttpClientProperties.java | 2 +- .../yuminailcore/config/JwtProperties.java | 6 +- .../config/LoginLockProperties.java | 2 +- .../yuminailcore/config/MinioConfig.java | 50 - .../config/ObjectStorageProperties.java | 43 + .../yuminailcore/config/RabbitMQConfig.java | 28 +- .../config/RateLimitProperties.java | 2 +- .../config/RequestSignatureProperties.java | 2 +- .../config/SlowRequestLogProperties.java | 2 +- .../config/UploadSecurityProperties.java | 4 +- .../config/WechatMiniProperties.java | 2 +- .../impl/NailArtistInfoServiceImpl.java | 2 +- .../controller/front/CommentController.java | 213 +- .../modules/file/config/AliyunOssConfig.java | 20 +- .../modules/file/config/QiniuKodoConfig.java | 82 + .../front/FrontendFileController.java | 2 +- .../front/ObjectStorageFileController.java | 32 +- ...e.java => ObjectStorageBackupMessage.java} | 2 +- .../file/dto/ObjectStorageFileDTO.java | 20 +- .../file/entity/ObjectStorageFileDO.java | 38 +- .../ObjectStorageBackupMessageListener.java | 28 + ... ObjectStorageBackupMessagePublisher.java} | 15 +- .../file/mq/OssBackupMessageListener.java | 29 - .../ObjectStorageBackupRetryScheduler.java | 46 + .../scheduler/OssBackupRetryScheduler.java | 44 - .../file/service/ChunkUploadService.java | 16 + .../modules/file/service/MinioService.java | 78 - .../service/ObjectStorageBackupService.java | 6 + .../file/service/OssBackupService.java | 6 - .../service/PrimaryObjectStorageService.java | 20 + .../service/impl/ChunkUploadServiceImpl.java | 44 +- .../file/service/impl/MinioServiceImpl.java | 174 -- ...va => ObjectStorageBackupServiceImpl.java} | 44 +- .../impl/ObjectStorageFileServiceImpl.java | 53 +- .../impl/QiniuObjectStorageServiceImpl.java | 122 + .../file/support/ObjectStorageUrlSupport.java | 160 +- .../modules/file/vo/ObjectStorageFileVO.java | 20 +- .../modules/product/vo/ProductVO.java | 4 + .../user/controller/front/UserController.java | 61 +- .../security/UploadSecurityValidator.java | 2 +- FD-Core/src/main/resources/application.yaml | 36 +- FD-Core/src/main/resources/bootstrap.yaml | 74 +- FD-Core/src/main/resources/files/YumiNail.sql | 2503 ----------------- FD-Frontend/src/api/admin.ts | 12 + FD-Frontend/src/api/comment.ts | 28 + FD-Frontend/src/api/error.test.ts | 49 + FD-Frontend/src/api/error.ts | 90 + FD-Frontend/src/api/file.ts | 26 + FD-Frontend/src/api/index.ts | 127 +- .../src/config/admin-navigation.test.ts | 11 + FD-Frontend/src/config/admin-navigation.ts | 56 + FD-Frontend/src/utils/admin-auth-bootstrap.ts | 21 +- .../src/utils/admin-image-assets.test.ts | 59 + FD-Frontend/src/utils/admin-image-assets.ts | 104 + FD-Frontend/src/utils/admin-table.test.ts | 17 + FD-Frontend/src/utils/admin-table.ts | 35 + .../src/utils/admin-upload-file.test.ts | 11 + FD-Frontend/src/utils/admin-upload-file.ts | 49 + FD-Frontend/src/utils/chunk-upload.test.ts | 84 + FD-Frontend/src/utils/chunk-upload.ts | 92 +- .../src/utils/public-image-assets.test.ts | 69 + FD-Frontend/src/utils/public-image-assets.ts | 97 + .../src/utils/signed-image-cache.test.ts | 70 + FD-Frontend/src/utils/signed-image-cache.ts | 73 +- FD-Frontend/src/views/ArtistProfileView.vue | 74 +- FD-Frontend/src/views/AuthView.vue | 255 +- FD-Frontend/src/views/CartView.vue | 319 ++- FD-Frontend/src/views/HomeView.vue | 79 +- FD-Frontend/src/views/ProductDetailView.vue | 71 +- FD-Frontend/src/views/ProductListView.vue | 32 +- FD-Frontend/src/views/ProfileView.vue | 39 +- FD-Frontend/src/views/ShopDetailView.vue | 43 +- FD-Frontend/src/views/WishlistView.vue | 23 +- FD-Frontend/src/views/admin/AdminLayout.vue | 59 +- FD-Frontend/src/views/admin/ProductsView.vue | 235 +- FD-Frontend/src/views/admin/ShopsView.vue | 527 ++-- .../src/views/admin/SystemMessagesView.vue | 31 +- FD-Frontend/src/views/admin/UsersView.vue | 39 +- .../src/views/web-theme-governance.test.ts | 4 +- .../tests/api/index.stale-token.test.ts | 6 + .../tests/api/system-unavailable.test.ts | 146 + .../yumitailgateway/config/GatewayConfig.java | 6 +- .../yumitailgateway/config/JwtProperties.java | 6 +- .../controller/HealthController.java | 4 +- FD-Gateway/src/main/resources/bootstrap.yaml | 58 +- .../admin/pages/comments/index.json | 1 + FD-WeChat-Fronted/app.json | 1 - .../pages/account-settings/index.wxml | 8 +- .../pages/after-sale-apply/index.wxml | 12 +- .../pages/after-sales/index.wxml | 6 +- .../pages/after-sales/index.wxss | 2 +- .../pages/artist-calendar/index.wxml | 8 +- .../pages/artist-calendar/index.wxss | 2 +- .../pages/artist-orders/index.wxml | 8 +- .../pages/artist-orders/index.wxss | 2 +- .../pages/artist-profile/index.wxss | 2 +- FD-WeChat-Fronted/pages/coupons/index.wxss | 2 +- FD-WeChat-Fronted/pages/help/index.wxml | 14 +- FD-WeChat-Fronted/pages/help/index.wxss | 2 +- FD-WeChat-Fronted/pages/index/index.wxss | 2 +- .../pages/notifications/index.wxss | 2 +- .../pages/order-detail/index.wxml | 12 +- .../pages/order-detail/index.wxss | 2 +- .../pages/password-settings/index.wxml | 10 +- .../pages/product-detail/index.wxss | 2 +- .../pages/service-progress/index.wxml | 10 +- .../pages/service-progress/index.wxss | 2 +- FD-WeChat-Fronted/pages/settings/index.wxss | 2 +- .../pages/shop-detail/index.wxss | 2 +- FD-WeChat-Fronted/project.private.config.json | 5 + FM-Wechat-Fronted/project.private.config.json | 2 +- docx/YumiNail页面重构功能清单.xlsx | Bin 26336 -> 0 bytes docx/design/backend-design.md | 2 +- docx/handoff/HANDOFF-BOOT.md | 2 +- .../yuminail-edge-mcp-e2e-test-cases.xlsx | Bin 0 -> 25627 bytes .../yuminail-full-regression-test-cases.md | 231 -- ...指尖管理师全流程测试用例矩阵_20260620.xlsx | Bin 0 -> 32594 bytes .../指尖设计师三端真实测试报告_20260618.md | 188 ++ .../指尖设计师三端详细测试计划_20260618.xlsx | Bin 0 -> 21632 bytes docx/指尖设计师三端功能清单_20260618.xlsx | Bin 0 -> 27210 bytes .../FingertipDesigner配置整理说明20260617.md | 40 + scripts/check-doc-encoding.mjs | 135 - scripts/comment-coverage.mjs | 444 --- scripts/promote-yuminail-uploaded-jar.py | 283 -- .../20260523_product_detail_guidance.sql | 3 - .../migrations/20260523_tag_scene_filters.sql | 10 - .../migrations/20260523_wishlist_groups.sql | 111 - .../migrations/20260524_vnext_operations.sql | 397 --- .../20260531_comment_ratings_images.sql | 28 - .../开发环境Nacos默认地址配置说明_20260623.md | 19 + ...名为FingertipDesigner配置说明_20260617.md | 19 + 141 files changed, 3624 insertions(+), 6048 deletions(-) delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/config/MinioConfig.java create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/config/ObjectStorageProperties.java create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/QiniuKodoConfig.java rename FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/{OssBackupUploadMessage.java => ObjectStorageBackupMessage.java} (83%) create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessageListener.java rename FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/{OssBackupMessagePublisher.java => ObjectStorageBackupMessagePublisher.java} (50%) delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/MinioService.java create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageBackupService.java delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/PrimaryObjectStorageService.java delete mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/MinioServiceImpl.java rename FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/{OssBackupServiceImpl.java => ObjectStorageBackupServiceImpl.java} (63%) create mode 100644 FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/QiniuObjectStorageServiceImpl.java delete mode 100644 FD-Core/src/main/resources/files/YumiNail.sql create mode 100644 FD-Frontend/src/api/error.test.ts create mode 100644 FD-Frontend/src/api/error.ts create mode 100644 FD-Frontend/src/config/admin-navigation.test.ts create mode 100644 FD-Frontend/src/config/admin-navigation.ts create mode 100644 FD-Frontend/src/utils/admin-image-assets.test.ts create mode 100644 FD-Frontend/src/utils/admin-image-assets.ts create mode 100644 FD-Frontend/src/utils/admin-table.test.ts create mode 100644 FD-Frontend/src/utils/admin-table.ts create mode 100644 FD-Frontend/src/utils/admin-upload-file.test.ts create mode 100644 FD-Frontend/src/utils/admin-upload-file.ts create mode 100644 FD-Frontend/src/utils/chunk-upload.test.ts create mode 100644 FD-Frontend/src/utils/public-image-assets.test.ts create mode 100644 FD-Frontend/src/utils/public-image-assets.ts create mode 100644 FD-Frontend/src/utils/signed-image-cache.test.ts create mode 100644 FD-Frontend/tests/api/system-unavailable.test.ts create mode 100644 FD-WeChat-Fronted/admin/pages/comments/index.json create mode 100644 FD-WeChat-Fronted/project.private.config.json delete mode 100644 docx/YumiNail页面重构功能清单.xlsx create mode 100644 docx/testing/yuminail-edge-mcp-e2e-test-cases.xlsx delete mode 100644 docx/testing/yuminail-full-regression-test-cases.md create mode 100644 docx/testing/指尖管理师全流程测试用例矩阵_20260620.xlsx create mode 100644 docx/testing/指尖设计师三端真实测试报告_20260618.md create mode 100644 docx/testing/指尖设计师三端详细测试计划_20260618.xlsx create mode 100644 docx/指尖设计师三端功能清单_20260618.xlsx create mode 100644 scripts/FingertipDesigner配置整理说明20260617.md delete mode 100644 scripts/check-doc-encoding.mjs delete mode 100644 scripts/comment-coverage.mjs delete mode 100644 scripts/promote-yuminail-uploaded-jar.py delete mode 100644 scripts/sql/migrations/20260523_product_detail_guidance.sql delete mode 100644 scripts/sql/migrations/20260523_tag_scene_filters.sql delete mode 100644 scripts/sql/migrations/20260523_wishlist_groups.sql delete mode 100644 scripts/sql/migrations/20260524_vnext_operations.sql delete mode 100644 scripts/sql/migrations/20260531_comment_ratings_images.sql create mode 100644 scripts/开发环境Nacos默认地址配置说明_20260623.md create mode 100644 scripts/统一数据库名为FingertipDesigner配置说明_20260617.md diff --git a/.claude/skills/gitnexus/gitnexus-cli/SKILL.md b/.claude/skills/gitnexus/gitnexus-cli/SKILL.md index cd9a83be..989c0827 100644 --- a/.claude/skills/gitnexus/gitnexus-cli/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-cli/SKILL.md @@ -5,14 +5,16 @@ description: "Use when the user needs to run GitNexus CLI commands like analyze/ # GitNexus CLI Commands -All commands work via `npx` — no global install required. +Commands below use `node .gitnexus/run.cjs ` — the project-local runner `gitnexus analyze` drops next to the index. It auto-selects an available runner at call time (global `gitnexus`, else `pnpm dlx`, else `npx`), so no package-manager assumption and no global install is required. + +> **Not analyzed yet, or `node .gitnexus/run.cjs` reports `Cannot find module`** (the gitignored runner is absent — e.g. a fresh clone or `git clean`)? (Re)generate it with `npx gitnexus analyze` from the project root. On **npm 11.x**, if `npx` crashes during install (`node.target is null`), install once with `npm i -g gitnexus` (then `gitnexus analyze`) or use `pnpm --allow-build=@ladybugdb/core --allow-build=gitnexus --allow-build=tree-sitter dlx gitnexus@latest analyze`. See [#1939](https://github.com/abhigyanpatwari/GitNexus/issues/1939). ## Commands ### analyze — Build or refresh the index ```bash -npx gitnexus analyze +node .gitnexus/run.cjs analyze ``` Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates CLAUDE.md / AGENTS.md context files. @@ -28,7 +30,7 @@ Run from the project root. This parses all source files, builds the knowledge gr ### status — Check index freshness ```bash -npx gitnexus status +node .gitnexus/run.cjs status ``` Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed. @@ -36,7 +38,7 @@ Shows whether the current repo has a GitNexus index, when it was last updated, a ### clean — Delete the index ```bash -npx gitnexus clean +node .gitnexus/run.cjs clean ``` Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project. @@ -49,7 +51,7 @@ Deletes the `.gitnexus/` directory and unregisters the repo from the global regi ### wiki — Generate documentation from the graph ```bash -npx gitnexus wiki +node .gitnexus/run.cjs wiki ``` Generates repository documentation from the knowledge graph using an LLM. Requires an API key (saved to `~/.gitnexus/config.json` on first use). @@ -66,7 +68,7 @@ Generates repository documentation from the knowledge graph using an LLM. Requir ### list — Show all indexed repos ```bash -npx gitnexus list +node .gitnexus/run.cjs list ``` Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information. diff --git a/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md b/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md index 9510b97a..9834f94b 100644 --- a/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-debugging/SKILL.md @@ -16,23 +16,23 @@ description: "Use when the user is debugging a bug, tracing an error, or asking ## Workflow ``` -1. gitnexus_query({query: ""}) → Find related execution flows -2. gitnexus_context({name: ""}) → See callers/callees/processes +1. query({query: ""}) → Find related execution flows +2. context({name: ""}) → See callers/callees/processes 3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow -4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed +4. cypher({query: "MATCH path..."}) → Custom traces if needed ``` -> If "Index is stale" → run `npx gitnexus analyze` in terminal. +> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal. ## Checklist ``` - [ ] Understand the symptom (error message, unexpected behavior) -- [ ] gitnexus_query for error text or related code +- [ ] query for error text or related code - [ ] Identify the suspect function from returned processes -- [ ] gitnexus_context to see callers and callees +- [ ] context to see callers and callees - [ ] Trace execution flow via process resource if applicable -- [ ] gitnexus_cypher for custom call chain traces if needed +- [ ] cypher for custom call chain traces if needed - [ ] Read source files to confirm root cause ``` @@ -40,7 +40,7 @@ description: "Use when the user is debugging a bug, tracing an error, or asking | Symptom | GitNexus Approach | | -------------------- | ---------------------------------------------------------- | -| Error message | `gitnexus_query` for error text → `context` on throw sites | +| Error message | `query` for error text → `context` on throw sites | | Wrong return value | `context` on the function → trace callees for data flow | | Intermittent failure | `context` → look for external calls, async deps | | Performance issue | `context` → find symbols with many callers (hot paths) | @@ -48,24 +48,24 @@ description: "Use when the user is debugging a bug, tracing an error, or asking ## Tools -**gitnexus_query** — find code related to error: +**query** — find code related to error: ``` -gitnexus_query({query: "payment validation error"}) +query({query: "payment validation error"}) → Processes: CheckoutFlow, ErrorHandling → Symbols: validatePayment, handlePaymentError, PaymentException ``` -**gitnexus_context** — full context for a suspect: +**context** — full context for a suspect: ``` -gitnexus_context({name: "validatePayment"}) +context({name: "validatePayment"}) → Incoming calls: processCheckout, webhookHandler → Outgoing calls: verifyCard, fetchRates (external API!) → Processes: CheckoutFlow (step 3/7) ``` -**gitnexus_cypher** — custom call chain traces: +**cypher** — custom call chain traces: ```cypher MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) @@ -75,11 +75,11 @@ RETURN [n IN nodes(path) | n.name] AS chain ## Example: "Payment endpoint returns 500 intermittently" ``` -1. gitnexus_query({query: "payment error handling"}) +1. query({query: "payment error handling"}) → Processes: CheckoutFlow, ErrorHandling → Symbols: validatePayment, handlePaymentError -2. gitnexus_context({name: "validatePayment"}) +2. context({name: "validatePayment"}) → Outgoing calls: verifyCard, fetchRates (external API!) 3. READ gitnexus://repo/my-app/process/CheckoutFlow diff --git a/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md b/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md index 927a4e4b..ccf684c2 100644 --- a/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-exploring/SKILL.md @@ -18,20 +18,20 @@ description: "Use when the user asks how code works, wants to understand archite ``` 1. READ gitnexus://repos → Discover indexed repos 2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness -3. gitnexus_query({query: ""}) → Find related execution flows -4. gitnexus_context({name: ""}) → Deep dive on specific symbol +3. query({query: ""}) → Find related execution flows +4. context({name: ""}) → Deep dive on specific symbol 5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow ``` -> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal. +> If step 2 says "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal. ## Checklist ``` - [ ] READ gitnexus://repo/{name}/context -- [ ] gitnexus_query for the concept you want to understand +- [ ] query for the concept you want to understand - [ ] Review returned processes (execution flows) -- [ ] gitnexus_context on key symbols for callers/callees +- [ ] context on key symbols for callers/callees - [ ] READ process resource for full execution traces - [ ] Read source files for implementation details ``` @@ -47,18 +47,18 @@ description: "Use when the user asks how code works, wants to understand archite ## Tools -**gitnexus_query** — find execution flows related to a concept: +**query** — find execution flows related to a concept: ``` -gitnexus_query({query: "payment processing"}) +query({query: "payment processing"}) → Processes: CheckoutFlow, RefundFlow, WebhookHandler → Symbols grouped by flow with file locations ``` -**gitnexus_context** — 360-degree view of a symbol: +**context** — 360-degree view of a symbol: ``` -gitnexus_context({name: "validateUser"}) +context({name: "validateUser"}) → Incoming calls: loginHandler, apiMiddleware → Outgoing calls: checkToken, getUserById → Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3) @@ -68,10 +68,10 @@ gitnexus_context({name: "validateUser"}) ``` 1. READ gitnexus://repo/my-app/context → 918 symbols, 45 processes -2. gitnexus_query({query: "payment processing"}) +2. query({query: "payment processing"}) → CheckoutFlow: processPayment → validateCard → chargeStripe → RefundFlow: initiateRefund → calculateRefund → processRefund -3. gitnexus_context({name: "processPayment"}) +3. context({name: "processPayment"}) → Incoming: checkoutHandler, webhookHandler → Outgoing: validateCard, chargeStripe, saveTransaction 4. Read src/payments/processor.ts for implementation details diff --git a/.claude/skills/gitnexus/gitnexus-guide/SKILL.md b/.claude/skills/gitnexus/gitnexus-guide/SKILL.md index 937ac73d..a5433787 100644 --- a/.claude/skills/gitnexus/gitnexus-guide/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-guide/SKILL.md @@ -15,7 +15,7 @@ For any task involving code understanding, debugging, impact analysis, or refact 2. **Match your task to a skill below** and **read that skill file** 3. **Follow the skill's workflow and checklist** -> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first. +> If step 1 warns the index is stale, run `node .gitnexus/run.cjs analyze` in the terminal first. ## Skills @@ -38,7 +38,38 @@ For any task involving code understanding, debugging, impact analysis, or refact | `detect_changes` | Git-diff impact — what do your current changes affect | | `rename` | Multi-file coordinated rename with confidence-tagged edits | | `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) | -| `list_repos` | Discover indexed repos | +| `list_repos` | Discover indexed repos (paginated — `limit`/`offset`) | + +### Paginating `list_repos` + +`list_repos` is paginated so a large registry is not truncated by MCP/LLM token limits. It takes optional `limit` (default **50**, max **200**) and `offset`, and returns: + +```jsonc +{ + "repositories": [ + { "name": "...", "path": "...", "indexedAt": "...", "lastCommit": "...", "stats": { } } + ], + "pagination": { + "total": 437, + "limit": 50, + "offset": 0, + "returned": 50, + "hasMore": true, + "nextOffset": 50 + } +} +``` + +To enumerate **every** repository, keep calling with `offset` set to `pagination.nextOffset` until `hasMore` is `false`: + +```text +list_repos {} → repos 1–50, nextOffset 50, hasMore true +list_repos { offset: 50 } → repos 51–100, nextOffset 100, hasMore true +… +list_repos { offset: 400 } → repos 401–437, hasMore false (done) +``` + +Notes: `offset` ≥ `total` returns an empty page (with `total` still reported). Out-of-range or malformed `limit`/`offset` (non-integer, `limit` outside `[1, 200]`, `offset < 0`) are rejected with a clear error — `limit` above the max is rejected, not silently capped. The order is deterministic (lower-cased name, then path), so paging never skips or duplicates an entry while the registry is unchanged. ## Resources Reference diff --git a/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md b/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md index e19af280..45eb7ce8 100644 --- a/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md @@ -17,22 +17,22 @@ description: "Use when the user wants to know what will break if they change som ## Workflow ``` -1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this +1. impact({target: "X", direction: "upstream"}) → What depends on this 2. READ gitnexus://repo/{name}/processes → Check affected execution flows -3. gitnexus_detect_changes() → Map current git changes to affected flows +3. detect_changes() → Map current git changes to affected flows 4. Assess risk and report to user ``` -> If "Index is stale" → run `npx gitnexus analyze` in terminal. +> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal. ## Checklist ``` -- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents +- [ ] impact({target, direction: "upstream"}) to find dependents - [ ] Review d=1 items first (these WILL BREAK) - [ ] Check high-confidence (>0.8) dependencies - [ ] READ processes to check affected execution flows -- [ ] gitnexus_detect_changes() for pre-commit check +- [ ] detect_changes() for pre-commit check - [ ] Assess risk level and report to user ``` @@ -55,10 +55,10 @@ description: "Use when the user wants to know what will break if they change som ## Tools -**gitnexus_impact** — the primary tool for symbol blast radius: +**impact** — the primary tool for symbol blast radius: ``` -gitnexus_impact({ +impact({ target: "validateUser", direction: "upstream", minConfidence: 0.8, @@ -73,10 +73,10 @@ gitnexus_impact({ - authRouter (src/routes/auth.ts:22) [CALLS, 95%] ``` -**gitnexus_detect_changes** — git-diff based impact analysis: +**detect_changes** — git-diff based impact analysis: ``` -gitnexus_detect_changes({scope: "staged"}) +detect_changes({scope: "staged"}) → Changed: 5 symbols in 3 files → Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline @@ -86,7 +86,7 @@ gitnexus_detect_changes({scope: "staged"}) ## Example: "What breaks if I change validateUser?" ``` -1. gitnexus_impact({target: "validateUser", direction: "upstream"}) +1. impact({target: "validateUser", direction: "upstream"}) → d=1: loginHandler, apiMiddleware (WILL BREAK) → d=2: authRouter, sessionManager (LIKELY AFFECTED) diff --git a/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md b/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md index f48cc01b..e13c04e1 100644 --- a/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md +++ b/.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md @@ -16,78 +16,78 @@ description: "Use when the user wants to rename, extract, split, move, or restru ## Workflow ``` -1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents -2. gitnexus_query({query: "X"}) → Find execution flows involving X -3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs +1. impact({target: "X", direction: "upstream"}) → Map all dependents +2. query({query: "X"}) → Find execution flows involving X +3. context({name: "X"}) → See all incoming/outgoing refs 4. Plan update order: interfaces → implementations → callers → tests ``` -> If "Index is stale" → run `npx gitnexus analyze` in terminal. +> If "Index is stale" → run `node .gitnexus/run.cjs analyze` in terminal. ## Checklists ### Rename Symbol ``` -- [ ] gitnexus_rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits +- [ ] rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits - [ ] Review graph edits (high confidence) and ast_search edits (review carefully) -- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits -- [ ] gitnexus_detect_changes() — verify only expected files changed +- [ ] If satisfied: rename({..., dry_run: false}) — apply edits +- [ ] detect_changes() — verify only expected files changed - [ ] Run tests for affected processes ``` ### Extract Module ``` -- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs -- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers +- [ ] context({name: target}) — see all incoming/outgoing refs +- [ ] impact({target, direction: "upstream"}) — find all external callers - [ ] Define new module interface - [ ] Extract code, update imports -- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] detect_changes() — verify affected scope - [ ] Run tests for affected processes ``` ### Split Function/Service ``` -- [ ] gitnexus_context({name: target}) — understand all callees +- [ ] context({name: target}) — understand all callees - [ ] Group callees by responsibility -- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update +- [ ] impact({target, direction: "upstream"}) — map callers to update - [ ] Create new functions/services - [ ] Update callers -- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] detect_changes() — verify affected scope - [ ] Run tests for affected processes ``` ## Tools -**gitnexus_rename** — automated multi-file rename: +**rename** — automated multi-file rename: ``` -gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) +rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) → 12 edits across 8 files → 10 graph edits (high confidence), 2 ast_search edits (review) → Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}] ``` -**gitnexus_impact** — map all dependents first: +**impact** — map all dependents first: ``` -gitnexus_impact({target: "validateUser", direction: "upstream"}) +impact({target: "validateUser", direction: "upstream"}) → d=1: loginHandler, apiMiddleware, testUtils → Affected Processes: LoginFlow, TokenRefresh ``` -**gitnexus_detect_changes** — verify your changes after refactoring: +**detect_changes** — verify your changes after refactoring: ``` -gitnexus_detect_changes({scope: "all"}) +detect_changes({scope: "all"}) → Changed: 8 files, 12 symbols → Affected processes: LoginFlow, TokenRefresh → Risk: MEDIUM ``` -**gitnexus_cypher** — custom reference queries: +**cypher** — custom reference queries: ```cypher MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) @@ -98,24 +98,24 @@ RETURN caller.name, caller.filePath ORDER BY caller.filePath | Risk Factor | Mitigation | | ------------------- | ----------------------------------------- | -| Many callers (>5) | Use gitnexus_rename for automated updates | +| Many callers (>5) | Use rename for automated updates | | Cross-area refs | Use detect_changes after to verify scope | -| String/dynamic refs | gitnexus_query to find them | +| String/dynamic refs | query to find them | | External/public API | Version and deprecate properly | ## Example: Rename `validateUser` to `authenticateUser` ``` -1. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) +1. rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) → 12 edits: 10 graph (safe), 2 ast_search (review) → Files: validator.ts, login.ts, middleware.ts, config.json... 2. Review ast_search edits (config.json: dynamic reference!) -3. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false}) +3. rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false}) → Applied 12 edits across 8 files -4. gitnexus_detect_changes({scope: "all"}) +4. detect_changes({scope: "all"}) → Affected: LoginFlow, TokenRefresh → Risk: MEDIUM — run tests for these flows ``` diff --git a/AGENTS.md b/AGENTS.md index 5ddf5e08..db5db45d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,36 +1,54 @@ # GitNexus — Code Intelligence -This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **FingertipDesigner** (14061 symbols, 29907 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. -> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. +> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). ## Always Do -- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. -- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. +- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. +- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`. - **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. -- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. -- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`. +- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. +- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. ## Never Do -- NEVER edit a function, class, or method without first running `gitnexus_impact` on it. +- NEVER edit a function, class, or method without first running `impact` on it. - NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. -- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph. -- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope. +- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph. +- NEVER commit changes without running `detect_changes()` to check affected scope. ## Resources | Resource | Use for | |----------|---------| -| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness | -| `gitnexus://repo/xiaowang/clusters` | All functional areas | -| `gitnexus://repo/xiaowang/processes` | All execution flows | -| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | +| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness | +| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas | +| `gitnexus://repo/FingertipDesigner/processes` | All execution flows | +| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace | + +## CLI + +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | +## Project Workflow Rules + +- 后端修改如果涉及 SQL,不要修改初始化 SQL;必须新增版本变更 SQL。 +- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。 +- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。 +- 执行 git 提交操作时,提交信息必须使用中文。 + ## Browser MCP Preference - For any browser-related operation, including opening, navigating, clicking, typing, inspecting pages/devtools, taking screenshots, testing pages, or automating local/remote web targets, use the `edgedev` MCP server first. diff --git a/CLAUDE.md b/CLAUDE.md index f98cfaf5..2f81f16e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,32 +1,43 @@ # GitNexus — Code Intelligence -This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **FingertipDesigner** (14061 symbols, 29907 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. -> If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. +> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). ## Always Do -- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `gitnexus_impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. -- **MUST run `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. +- **MUST run impact analysis before editing any symbol.** Before modifying a function, class, or method, run `impact({target: "symbolName", direction: "upstream"})` and report the blast radius (direct callers, affected processes, risk level) to the user. +- **MUST run `detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. For regression review, compare against the default branch: `detect_changes({scope: "compare", base_ref: "master"})`. - **MUST warn the user** if impact analysis returns HIGH or CRITICAL risk before proceeding with edits. -- When exploring unfamiliar code, use `gitnexus_query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. -- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `gitnexus_context({name: "symbolName"})`. +- When exploring unfamiliar code, use `query({query: "concept"})` to find execution flows instead of grepping. It returns process-grouped results ranked by relevance. +- When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`. ## Never Do -- NEVER edit a function, class, or method without first running `gitnexus_impact` on it. +- NEVER edit a function, class, or method without first running `impact` on it. - NEVER ignore HIGH or CRITICAL risk warnings from impact analysis. -- NEVER rename symbols with find-and-replace — use `gitnexus_rename` which understands the call graph. -- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope. +- NEVER rename symbols with find-and-replace — use `rename` which understands the call graph. +- NEVER commit changes without running `detect_changes()` to check affected scope. ## Resources | Resource | Use for | |----------|---------| -| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness | -| `gitnexus://repo/xiaowang/clusters` | All functional areas | -| `gitnexus://repo/xiaowang/processes` | All execution flows | -| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | +| `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness | +| `gitnexus://repo/FingertipDesigner/clusters` | All functional areas | +| `gitnexus://repo/FingertipDesigner/processes` | All execution flows | +| `gitnexus://repo/FingertipDesigner/process/{name}` | Step-by-step execution trace | + +## CLI + +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | diff --git a/FD-Core/pom.xml b/FD-Core/pom.xml index c8761b1c..1756a5c7 100644 --- a/FD-Core/pom.xml +++ b/FD-Core/pom.xml @@ -193,11 +193,11 @@ httpclient - + - io.minio - minio - 8.5.7 + com.qiniu + qiniu-java-sdk + [7.19.0, 7.19.99] diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java index ff50eb5e..90644d83 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration; */ @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.cache") +@ConfigurationProperties(prefix = "fingertip-designer.cache") public class AppCacheProperties { /** diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientProperties.java index 4f22d618..e1c61973 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientProperties.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.http-client") +@ConfigurationProperties(prefix = "fingertip-designer.http-client") /** * Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java index 2ec3281d..9a5ad3ce 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java @@ -9,18 +9,18 @@ import org.springframework.context.annotation.Configuration; */ @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.security.jwt") +@ConfigurationProperties(prefix = "fingertip-designer.security.jwt") public class JwtProperties { /** * HS512 密钥,生产环境请通过 Nacos 覆盖。 */ - private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; /** * Token 发行者。 */ - private String issuer = "yuminail"; + private String issuer = "fingertip-designer"; /** * AccessToken 有效期,单位秒。 diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java index 9f2c4ed9..67697df7 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.security.login-lock") +@ConfigurationProperties(prefix = "fingertip-designer.security.login-lock") /** * Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/MinioConfig.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/MinioConfig.java deleted file mode 100644 index d57f6a2f..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/MinioConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.xiaowang.yuminailcore.config; - -import io.minio.MinioClient; -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Data -@Configuration -@ConfigurationProperties(prefix = "minio") -/** - * Purpose: MinioConfig supports MinioConfig.java by holding or executing the minio config business role. - * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. - */ -public class MinioConfig { - - /** - * Purpose: endpoint supports MinioConfig.java by holding or executing the endpoint business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String endpoint; - /** - * Purpose: accessKey supports MinioConfig.java by holding or executing the access key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String accessKey; - /** - * Purpose: secretKey supports MinioConfig.java by holding or executing the secret key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String secretKey; - /** - * Purpose: bucketName supports MinioConfig.java by holding or executing the bucket name business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - private String bucketName; - - @Bean - /** - * Purpose: minioClient supports MinioConfig.java by holding or executing the minio client business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ - public MinioClient minioClient() { - return MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build(); - } -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/ObjectStorageProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/ObjectStorageProperties.java new file mode 100644 index 00000000..430c78f3 --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/ObjectStorageProperties.java @@ -0,0 +1,43 @@ +package com.xiaowang.yuminailcore.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Component +@Validated +@ConfigurationProperties(prefix = "object-storage") +public class ObjectStorageProperties { + + @NotBlank + private String primaryProvider; + + @NotBlank + private String backupProvider; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @NotBlank + private String backupQueueName; + + @NotBlank + private String backupExchangeName; + + @NotBlank + private String backupRoutingKey; + + @NotNull + @Min(1) + private Integer backupRetryBatchLimit; + + @NotBlank + private String backupRetryCron; +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java index b392f914..12f983c5 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java @@ -1,5 +1,6 @@ package com.xiaowang.yuminailcore.config; +import lombok.RequiredArgsConstructor; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; @@ -10,15 +11,14 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration +@RequiredArgsConstructor public class RabbitMQConfig { - public static final String EXAMPLE_QUEUE = "yuminail.example.queue"; - public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange"; - public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key"; + public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue"; + public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange"; + public static final String EXAMPLE_ROUTING_KEY = "fingertip-designer.example.routing.key"; - public static final String FILE_OSS_BACKUP_EXCHANGE = "yuminail.file.oss.backup.exchange"; - public static final String FILE_OSS_BACKUP_QUEUE = "yuminail.file.oss.backup.queue"; - public static final String FILE_OSS_BACKUP_ROUTING_KEY = "yuminail.file.oss.backup"; + private final ObjectStorageProperties objectStorageProperties; @Bean public MessageConverter jsonMessageConverter() { @@ -41,19 +41,19 @@ public class RabbitMQConfig { } @Bean - public Queue fileOssBackupQueue() { - return new Queue(FILE_OSS_BACKUP_QUEUE, true); + public Queue objectStorageBackupQueue() { + return new Queue(objectStorageProperties.getBackupQueueName(), true); } @Bean - public DirectExchange fileOssBackupExchange() { - return new DirectExchange(FILE_OSS_BACKUP_EXCHANGE, true, false); + public DirectExchange objectStorageBackupExchange() { + return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false); } @Bean - public Binding fileOssBackupBinding() { - return BindingBuilder.bind(fileOssBackupQueue()) - .to(fileOssBackupExchange()) - .with(FILE_OSS_BACKUP_ROUTING_KEY); + public Binding objectStorageBackupBinding() { + return BindingBuilder.bind(objectStorageBackupQueue()) + .to(objectStorageBackupExchange()) + .with(objectStorageProperties.getBackupRoutingKey()); } } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java index e466a761..63c8eafa 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration; */ @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.security.rate-limit") +@ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit") public class RateLimitProperties { private LimitRule login = new LimitRule(10, 60); diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java index 1022f003..39afa6f1 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration; */ @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.security.signature") +@ConfigurationProperties(prefix = "fingertip-designer.security.signature") public class RequestSignatureProperties { /** diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/SlowRequestLogProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/SlowRequestLogProperties.java index b1bf1ec4..b7cd2638 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/SlowRequestLogProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/SlowRequestLogProperties.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.slow-request") +@ConfigurationProperties(prefix = "fingertip-designer.slow-request") /** * Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java index 568e3aba..10223878 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java @@ -9,7 +9,7 @@ import java.util.List; @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.security.upload") +@ConfigurationProperties(prefix = "fingertip-designer.security.upload") /** * Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state. @@ -22,6 +22,8 @@ public class UploadSecurityProperties { */ private long maxSize = 10 * 1024 * 1024; + private long maxTotalSize = 500L * 1024 * 1024; + private List allowedMimeTypes = new ArrayList<>(List.of( "image/jpeg", "image/png", diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java index 3f5a4df5..5c3e2dfa 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration; */ @Data @Configuration -@ConfigurationProperties(prefix = "yuminail.wechat.mini") +@ConfigurationProperties(prefix = "fingertip-designer.wechat.mini") public class WechatMiniProperties { /** diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java index c23cdac8..a74bd5cd 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -267,7 +267,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) { Long userId = (Long) request.getAttribute("userId"); @@ -60,43 +61,76 @@ public class CommentController { } try { uploadSecurityValidator.validate(file); - String originalFilename = file.getOriginalFilename(); - if (originalFilename == null || originalFilename.isEmpty()) { - originalFilename = "comment-image"; - } - String fileExtension = originalFilename == null || !originalFilename.contains(".") - ? "" - : originalFilename.substring(originalFilename.lastIndexOf(".")); - String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - String fileUrl = minioService.uploadFile(file, objectName); - - ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); - dto.setFileName(originalFilename); - dto.setFileUrl(fileUrl); - dto.setObjectName(objectName); - dto.setMinioUrl(fileUrl); - dto.setContentType(file.getContentType()); - dto.setFileSize(file.getSize()); - dto.setMinioUploadStatus(1); - dto.setOssUploadStatus(0); - dto.setOssRetryCount(0); - dto.setStatus(1); - - Long fileId = objectStorageFileService.createObjectStorageFile(dto); - return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); + String originalFilename = normalizeOriginalFilename(file.getOriginalFilename()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadFile(file, objectName); + return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize())); } catch (Exception e) { e.printStackTrace(); return Result.error("评价图片上传失败: " + e.getMessage()); } } - /** - * 更新评论 - * - * @param id 评论ID - * @param commentDTO 评论DTO - * @return 是否更新成功 - */ + @PostMapping("/upload-image/init") + @OperationGuard(action = "comment-image-upload-init", ttlSeconds = 10, message = "图片正在上传中,请勿重复操作") + public Result initCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); + return Result.success(chunkUploadService.initCommentImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-image/chunk") + @OperationGuard(action = "comment-image-upload-chunk", ttlSeconds = 20) + public Result uploadCommentImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + uploadSecurityValidator.validateChunk(chunkFile); + chunkUploadService.uploadCommentImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-image/complete") + @OperationGuard(action = "comment-image-upload-complete", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result completeCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再上传评价图片"); + } + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareCommentImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = normalizeOriginalFilename(preparedUploadFile.getFileName()); + String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename); + String fileUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + ObjectStorageFileVO fileVO = createCommentImageRecord(originalFilename, fileUrl, objectName, preparedUploadFile.getContentType(), preparedUploadFile.getFileSize()); + chunkUploadService.clearCommentImageUpload(userId, requestDTO.getUploadId()); + return Result.success(fileVO); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("评价图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-image/{uploadId}") + @OperationGuard(action = "comment-image-upload-cancel", ttlSeconds = 30, message = "图片正在上传中,请勿重复操作") + public Result cancelCommentImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + return Result.error("请先登录后再取消上传"); + } + chunkUploadService.clearCommentImageUpload(userId, uploadId); + return Result.success(true); + } + @PutMapping("/update/{id}") public Result updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) { Long userId = (Long) request.getAttribute("userId"); @@ -104,12 +138,6 @@ public class CommentController { return Result.success(success); } - /** - * 删除评论 - * - * @param id 评论ID - * @return 是否删除成功 - */ @DeleteMapping("/delete/{id}") public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { Long userId = (Long) request.getAttribute("userId"); @@ -117,74 +145,71 @@ public class CommentController { return Result.success(success); } - /** - * 根据ID查询评论 - * - * @param id 评论ID - * @return 评论VO - */ @GetMapping("/get/{id}") public Result getCommentById(@PathVariable Long id) { CommentVO commentVO = commentService.getCommentById(id); return Result.success(commentVO); } - /** - * 查询所有评论 - * - * @return 评论VO列表 - */ @GetMapping("/list/all") public Result> listAllComments() { List commentVOs = commentService.listAllComments(); return Result.success(commentVOs); } - /** - * 根据用户ID查询评论 - * - * @param userId 用户ID - * @return 评论VO列表 - */ @GetMapping("/list/user/{userId}") public Result> listCommentsByUserId(@PathVariable Long userId) { List commentVOs = commentService.listCommentsByUserId(userId); return Result.success(commentVOs); } - /** - * 根据店铺ID查询评论 - * - * @param shopId 店铺ID - * @return 评论VO列表 - */ @GetMapping("/list/shop/{shopId}") public Result> listCommentsByShopId(@PathVariable Long shopId) { List commentVOs = commentService.listCommentsByShopId(shopId); return Result.success(commentVOs); } - /** - * 根据商品ID查询评论 - * - * @param productId 商品ID - * @return 评论VO列表 - */ @GetMapping("/list/product/{productId}") public Result> listCommentsByProductId(@PathVariable Long productId) { List commentVOs = commentService.listCommentsByProductId(productId); return Result.success(commentVOs); } - /** - * 根据父级评论ID查询回复 - * - * @param parentCommentId 父级评论ID - * @return 评论VO列表 - */ @GetMapping("/list/parent/{parentCommentId}") public Result> listCommentsByParentCommentId(@PathVariable Long parentCommentId) { List commentVOs = commentService.listCommentsByParentCommentId(parentCommentId); return Result.success(commentVOs); } + + private ObjectStorageFileVO createCommentImageRecord(String originalFilename, String fileUrl, String objectName, String contentType, Long fileSize) { + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName(originalFilename); + dto.setFileUrl(fileUrl); + dto.setObjectName(objectName); + dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); + dto.setPrimaryUrl(fileUrl); + dto.setBackupProvider(objectStorageProperties.getBackupProvider()); + dto.setContentType(contentType); + dto.setFileSize(fileSize); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); + dto.setStatus(1); + Long fileId = objectStorageFileService.createObjectStorageFile(dto); + return objectStorageFileService.getObjectStorageFileById(fileId); + } + + private String normalizeOriginalFilename(String originalFilename) { + if (originalFilename == null || originalFilename.isBlank()) { + return "comment-image"; + } + return originalFilename; + } + + private String resolveFileExtension(String originalFilename) { + if (originalFilename == null || !originalFilename.contains(".")) { + return ""; + } + return originalFilename.substring(originalFilename.lastIndexOf(".")); + } } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java index d7bedb5a..f991a6d5 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java @@ -8,19 +8,33 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; @Data @Configuration +@Validated @ConfigurationProperties(prefix = "aliyun.oss") public class AliyunOssConfig { - private boolean enabled = false; + @NotNull + private Boolean enabled; + @NotBlank private String endpoint; + @NotBlank private String region; - private String bucketName = "fingertipdesigner"; + @NotBlank + private String bucketName; + @NotBlank private String accessKeyId; + @NotBlank private String accessKeySecret; - private int signedUrlExpireMinutes = 30; + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; @Bean(destroyMethod = "shutdown") @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/QiniuKodoConfig.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/QiniuKodoConfig.java new file mode 100644 index 00000000..b37e35d2 --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/QiniuKodoConfig.java @@ -0,0 +1,82 @@ +package com.xiaowang.yuminailcore.modules.file.config; + +import com.qiniu.common.Zone; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.UploadManager; +import com.qiniu.util.Auth; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; + +@Data +@Configuration +@Validated +@ConfigurationProperties(prefix = "qiniu.kodo") +public class QiniuKodoConfig { + + @NotBlank + private String accessKey; + + @NotBlank + private String secretKey; + + @NotBlank + private String bucketName; + + @NotBlank + private String domain; + + @NotBlank + private String zone; + + @NotNull + private Boolean privateBucket; + + @NotNull + @Min(1) + private Integer signedUrlExpireMinutes; + + @Bean + public Auth qiniuAuth() { + return Auth.create(accessKey, secretKey); + } + + @Bean + public com.qiniu.storage.Configuration qiniuConfiguration() { + return new com.qiniu.storage.Configuration(resolveZone()); + } + + @Bean + public UploadManager qiniuUploadManager(com.qiniu.storage.Configuration qiniuConfiguration) { + return new UploadManager(qiniuConfiguration); + } + + @Bean + public BucketManager qiniuBucketManager(com.qiniu.storage.Configuration qiniuConfiguration, Auth qiniuAuth) { + return new BucketManager(qiniuAuth, qiniuConfiguration); + } + + private Zone resolveZone() { + String normalizedZone = zone.trim().toLowerCase(); + switch (normalizedZone) { + case "z0": + return Zone.zone0(); + case "z1": + return Zone.zone1(); + case "z2": + return Zone.zone2(); + case "na0": + return Zone.zoneNa0(); + case "as0": + return Zone.zoneAs0(); + default: + throw new IllegalStateException("Unsupported Qiniu zone: " + zone); + } + } +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java index 0c4519d0..557009a2 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java @@ -57,7 +57,7 @@ public class FrontendFileController { private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { return StringUtils.hasText(fileVO.getObjectName()) - || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getMinioUrl())) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getPrimaryUrl())) || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java index 3f3dac2e..30741246 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java @@ -1,13 +1,14 @@ package com.xiaowang.yuminailcore.modules.file.controller.front; import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.config.ObjectStorageProperties; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadCompleteRequestDTO; import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadInitRequestDTO; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.modules.file.service.ChunkUploadService; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService; import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; @@ -45,9 +46,9 @@ public class ObjectStorageFileController { */ private final ObjectStorageFileService objectStorageFileService; /** - * Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ - private final MinioService minioService; + private final PrimaryObjectStorageService primaryObjectStorageService; /** * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -65,6 +66,7 @@ public class ObjectStorageFileController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final UploadSecurityValidator uploadSecurityValidator; + private final ObjectStorageProperties objectStorageProperties; @PostMapping("/upload/init") @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") @@ -100,7 +102,7 @@ public class ObjectStorageFileController { String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - String fileUrl = minioService.uploadStream( + String fileUrl = primaryObjectStorageService.uploadStream( inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), @@ -111,12 +113,14 @@ public class ObjectStorageFileController { dto.setFileName(originalFilename); dto.setFileUrl(fileUrl); dto.setObjectName(objectName); - dto.setMinioUrl(fileUrl); + dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); + dto.setPrimaryUrl(fileUrl); + dto.setBackupProvider(objectStorageProperties.getBackupProvider()); dto.setContentType(preparedUploadFile.getContentType()); dto.setFileSize(preparedUploadFile.getFileSize()); - dto.setMinioUploadStatus(1); - dto.setOssUploadStatus(0); - dto.setOssRetryCount(0); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); dto.setStatus(1); Long fileId = objectStorageFileService.createObjectStorageFile(dto); @@ -155,18 +159,20 @@ public class ObjectStorageFileController { String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - String fileUrl = minioService.uploadFile(file, objectName); + String fileUrl = primaryObjectStorageService.uploadFile(file, objectName); ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); dto.setFileName(originalFilename); dto.setFileUrl(fileUrl); dto.setObjectName(objectName); - dto.setMinioUrl(fileUrl); + dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider()); + dto.setPrimaryUrl(fileUrl); + dto.setBackupProvider(objectStorageProperties.getBackupProvider()); dto.setContentType(file.getContentType()); dto.setFileSize(file.getSize()); - dto.setMinioUploadStatus(1); - dto.setOssUploadStatus(0); - dto.setOssRetryCount(0); + dto.setPrimaryUploadStatus(1); + dto.setBackupUploadStatus(0); + dto.setBackupRetryCount(0); dto.setStatus(1); Long fileId = objectStorageFileService.createObjectStorageFile(dto); diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageBackupMessage.java similarity index 83% rename from FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java rename to FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageBackupMessage.java index ac2ef12e..eeb24dba 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageBackupMessage.java @@ -7,7 +7,7 @@ import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor -public class OssBackupUploadMessage { +public class ObjectStorageBackupMessage { private Long fileId; } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java index 9c075c83..f039c76d 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java @@ -26,25 +26,29 @@ public class ObjectStorageFileDTO { private String objectName; - private String minioUrl; + private String primaryProvider; - private String ossUrl; + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; private String contentType; private Long fileSize; - private Integer minioUploadStatus; + private Integer primaryUploadStatus; - private Integer ossUploadStatus; + private Integer backupUploadStatus; - private Integer ossRetryCount; + private Integer backupRetryCount; - private String ossLastError; + private String backupLastError; - private LocalDateTime ossUploadedAt; + private LocalDateTime backupUploadedAt; - private LocalDateTime ossLastRetryTime; + private LocalDateTime backupLastRetryTime; /** * 文件状态:1-可用,0-不可用,2-回收站 diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java index 59424f05..b99dcbca 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java @@ -35,11 +35,17 @@ public class ObjectStorageFileDO extends BaseEntity { @TableField("object_name") private String objectName; - @TableField("minio_url") - private String minioUrl; + @TableField("primary_provider") + private String primaryProvider; - @TableField("oss_url") - private String ossUrl; + @TableField("primary_url") + private String primaryUrl; + + @TableField("backup_provider") + private String backupProvider; + + @TableField("backup_url") + private String backupUrl; @TableField("content_type") private String contentType; @@ -47,23 +53,23 @@ public class ObjectStorageFileDO extends BaseEntity { @TableField("file_size") private Long fileSize; - @TableField("minio_upload_status") - private Integer minioUploadStatus; + @TableField("primary_upload_status") + private Integer primaryUploadStatus; - @TableField("oss_upload_status") - private Integer ossUploadStatus; + @TableField("backup_upload_status") + private Integer backupUploadStatus; - @TableField("oss_retry_count") - private Integer ossRetryCount; + @TableField("backup_retry_count") + private Integer backupRetryCount; - @TableField("oss_last_error") - private String ossLastError; + @TableField("backup_last_error") + private String backupLastError; - @TableField("oss_uploaded_at") - private LocalDateTime ossUploadedAt; + @TableField("backup_uploaded_at") + private LocalDateTime backupUploadedAt; - @TableField("oss_last_retry_time") - private LocalDateTime ossLastRetryTime; + @TableField("backup_last_retry_time") + private LocalDateTime backupLastRetryTime; /** * 文件状态:1-可用,0-不可用,2-回收站 diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessageListener.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessageListener.java new file mode 100644 index 00000000..beba410d --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessageListener.java @@ -0,0 +1,28 @@ +package com.xiaowang.yuminailcore.modules.file.mq; + +import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageBackupMessage; +import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageBackupService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupMessageListener { + + private final ObjectStorageBackupService objectStorageBackupService; + + @RabbitListener(queues = "#{objectStorageProperties.backupQueueName}") + public void handle(ObjectStorageBackupMessage message) { + if (message == null || message.getFileId() == null) { + return; + } + try { + objectStorageBackupService.backupFile(message.getFileId()); + } catch (Exception e) { + log.warn("Handle object storage backup message failed, fileId={}", message.getFileId(), e); + } + } +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessagePublisher.java similarity index 50% rename from FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java rename to FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessagePublisher.java index 8870dcaf..47a88965 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/ObjectStorageBackupMessagePublisher.java @@ -1,7 +1,7 @@ package com.xiaowang.yuminailcore.modules.file.mq; -import com.xiaowang.yuminailcore.config.RabbitMQConfig; -import com.xiaowang.yuminailcore.modules.file.dto.OssBackupUploadMessage; +import com.xiaowang.yuminailcore.config.ObjectStorageProperties; +import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageBackupMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; @@ -10,9 +10,10 @@ import org.springframework.stereotype.Component; @Slf4j @Component @RequiredArgsConstructor -public class OssBackupMessagePublisher { +public class ObjectStorageBackupMessagePublisher { private final RabbitTemplate rabbitTemplate; + private final ObjectStorageProperties objectStorageProperties; public void publish(Long fileId) { if (fileId == null || fileId <= 0) { @@ -20,12 +21,12 @@ public class OssBackupMessagePublisher { } try { rabbitTemplate.convertAndSend( - RabbitMQConfig.FILE_OSS_BACKUP_EXCHANGE, - RabbitMQConfig.FILE_OSS_BACKUP_ROUTING_KEY, - new OssBackupUploadMessage(fileId) + objectStorageProperties.getBackupExchangeName(), + objectStorageProperties.getBackupRoutingKey(), + new ObjectStorageBackupMessage(fileId) ); } catch (Exception e) { - log.warn("Publish OSS backup message failed, fileId={}", fileId, e); + log.warn("Publish object storage backup message failed, fileId={}", fileId, e); } } } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java deleted file mode 100644 index 52f3ceae..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.xiaowang.yuminailcore.modules.file.mq; - -import com.xiaowang.yuminailcore.config.RabbitMQConfig; -import com.xiaowang.yuminailcore.modules.file.dto.OssBackupUploadMessage; -import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.amqp.rabbit.annotation.RabbitListener; -import org.springframework.stereotype.Component; - -@Slf4j -@Component -@RequiredArgsConstructor -public class OssBackupMessageListener { - - private final OssBackupService ossBackupService; - - @RabbitListener(queues = RabbitMQConfig.FILE_OSS_BACKUP_QUEUE) - public void handle(OssBackupUploadMessage message) { - if (message == null || message.getFileId() == null) { - return; - } - try { - ossBackupService.backupFileToOss(message.getFileId()); - } catch (Exception e) { - log.warn("Handle OSS backup message failed, fileId={}", message.getFileId(), e); - } - } -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java new file mode 100644 index 00000000..afc5a7be --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/ObjectStorageBackupRetryScheduler.java @@ -0,0 +1,46 @@ +package com.xiaowang.yuminailcore.modules.file.scheduler; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.yuminailcore.config.ObjectStorageProperties; +import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageBackupService; +import com.xiaowang.yuminailcore.modules.file.service.impl.ObjectStorageBackupServiceImpl; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageBackupRetryScheduler { + + private final ObjectStorageFileMapper objectStorageFileMapper; + private final ObjectStorageBackupService objectStorageBackupService; + private final ObjectStorageProperties objectStorageProperties; + + @Scheduled(cron = "${object-storage.backup-retry-cron}", zone = "Asia/Shanghai") + public void retryPendingOrFailedBackups() { + List files = objectStorageFileMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageFileDO.class) + .eq(ObjectStorageFileDO::getStatus, 1) + .eq(ObjectStorageFileDO::getPrimaryProvider, objectStorageProperties.getPrimaryProvider()) + .eq(ObjectStorageFileDO::getBackupProvider, objectStorageProperties.getBackupProvider()) + .eq(ObjectStorageFileDO::getPrimaryUploadStatus, ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED) + .in(ObjectStorageFileDO::getBackupUploadStatus, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_PENDING, + ObjectStorageBackupServiceImpl.UPLOAD_STATUS_FAILED) + .last("LIMIT " + objectStorageProperties.getBackupRetryBatchLimit()) + ); + for (ObjectStorageFileDO file : files) { + try { + objectStorageBackupService.backupFile(file.getId()); + } catch (Exception e) { + log.warn("Retry object storage backup failed, fileId={}", file.getId(), e); + } + } + } +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java deleted file mode 100644 index 3f00b372..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.xiaowang.yuminailcore.modules.file.scheduler; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; -import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; -import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; -import com.xiaowang.yuminailcore.modules.file.service.impl.OssBackupServiceImpl; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import java.util.List; - -@Slf4j -@Component -@RequiredArgsConstructor -public class OssBackupRetryScheduler { - - private static final int BATCH_LIMIT = 500; - - private final ObjectStorageFileMapper objectStorageFileMapper; - private final OssBackupService ossBackupService; - - @Scheduled(cron = "0 0 2 * * ?", zone = "Asia/Shanghai") - public void retryPendingOrFailedBackups() { - List files = objectStorageFileMapper.selectList( - Wrappers.lambdaQuery(ObjectStorageFileDO.class) - .eq(ObjectStorageFileDO::getStatus, 1) - .eq(ObjectStorageFileDO::getMinioUploadStatus, OssBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED) - .in(ObjectStorageFileDO::getOssUploadStatus, - OssBackupServiceImpl.UPLOAD_STATUS_PENDING, - OssBackupServiceImpl.UPLOAD_STATUS_FAILED) - .last("LIMIT " + BATCH_LIMIT) - ); - for (ObjectStorageFileDO file : files) { - try { - ossBackupService.backupFileToOss(file.getId()); - } catch (Exception e) { - log.warn("Retry OSS backup failed, fileId={}", file.getId(), e); - } - } - } -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ChunkUploadService.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ChunkUploadService.java index a9d9be9e..45018b8e 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ChunkUploadService.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ChunkUploadService.java @@ -30,6 +30,10 @@ public interface ChunkUploadService { */ ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + + ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + /** * Run business method `uploadAdminObjectStorageChunk`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -52,6 +56,10 @@ public interface ChunkUploadService { */ void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + + void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + /** * Run business method `prepareAdminObjectStorageFile`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -70,6 +78,10 @@ public interface ChunkUploadService { */ PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId); + PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId); + + PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId); + /** * Run business method `clearAdminObjectStorageUpload`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -85,6 +97,10 @@ public interface ChunkUploadService { * @param uploadId parameter `uploadId` supplied by the caller */ void clearUserAvatarUpload(Long ownerId, String uploadId); + + void clearUserProfileImageUpload(Long ownerId, String uploadId); + + void clearCommentImageUpload(Long ownerId, String uploadId); /** * PreparedUploadFile declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/MinioService.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/MinioService.java deleted file mode 100644 index 92c1c5e1..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/MinioService.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiaowang.yuminailcore.modules.file.service; - -import org.springframework.web.multipart.MultipartFile; -import java.io.InputStream; -import com.xiaowang.yuminailcore.common.Result; -/** - * MinioService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public interface MinioService { - - /** - * Run business method `uploadFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param file parameter `file` supplied by the caller - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - String uploadFile(MultipartFile file, String objectName) throws Exception; - - /** - * Run business method `uploadStream`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param inputStream parameter `inputStream` supplied by the caller - * @param fileSize parameter `fileSize` supplied by the caller - * @param contentType parameter `contentType` supplied by the caller - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; - - /** - * Run business method `downloadFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @return InputStream result consumed by the caller or returned to the frontend - */ - InputStream downloadFile(String objectName) throws Exception; - - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - */ - void deleteFile(String objectName) throws Exception; - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - String getFileUrl(String objectName); - - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @param expiryTimeInMinutes parameter `expiryTimeInMinutes` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - String getPresignedUrl(String objectName, int expiryTimeInMinutes) throws Exception; - - /** - * Run business method `bucketExists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bucketName parameter `bucketName` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - boolean bucketExists(String bucketName) throws Exception; - - /** - * Run business method `makeBucket`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bucketName parameter `bucketName` supplied by the caller - */ - void makeBucket(String bucketName) throws Exception; -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageBackupService.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageBackupService.java new file mode 100644 index 00000000..aa070831 --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageBackupService.java @@ -0,0 +1,6 @@ +package com.xiaowang.yuminailcore.modules.file.service; + +public interface ObjectStorageBackupService { + + void backupFile(Long fileId); +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java deleted file mode 100644 index 00236015..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.xiaowang.yuminailcore.modules.file.service; - -public interface OssBackupService { - - void backupFileToOss(Long fileId); -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/PrimaryObjectStorageService.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/PrimaryObjectStorageService.java new file mode 100644 index 00000000..ebfdd694 --- /dev/null +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/PrimaryObjectStorageService.java @@ -0,0 +1,20 @@ +package com.xiaowang.yuminailcore.modules.file.service; + +import org.springframework.web.multipart.MultipartFile; + +import java.io.InputStream; + +public interface PrimaryObjectStorageService { + + String uploadFile(MultipartFile file, String objectName) throws Exception; + + String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + + InputStream downloadFile(String objectName) throws Exception; + + void deleteFile(String objectName) throws Exception; + + String getFileUrl(String objectName); + + String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception; +} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ChunkUploadServiceImpl.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ChunkUploadServiceImpl.java index a13cb303..cb726fdf 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ChunkUploadServiceImpl.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ChunkUploadServiceImpl.java @@ -105,6 +105,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); } + @Override + public ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, requestDTO); + } + + @Override + public ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + return initUpload(UploadTargetType.COMMENT_IMAGE, ownerId, requestDTO); + } + @Override /** * Run business method `uploadAdminObjectStorageChunk`. @@ -155,6 +165,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); } + @Override + public void uploadUserProfileImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + + @Override + public void uploadCommentImageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + uploadChunk(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); + } + @Override /** * Run business method `prepareAdminObjectStorageFile`. @@ -195,6 +215,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); } + @Override + public PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId) { + return prepareMergedFile(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + @Override /** * Run business method `clearAdminObjectStorageUpload`. @@ -233,6 +263,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); } + @Override + public void clearUserProfileImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.USER_PROFILE_IMAGE, ownerId, uploadId); + } + + @Override + public void clearCommentImageUpload(Long ownerId, String uploadId) { + clearUpload(UploadTargetType.COMMENT_IMAGE, ownerId, uploadId); + } + /** * Run business method `initUpload`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -791,7 +831,9 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { */ private enum UploadTargetType { ADMIN_OBJECT_STORAGE, - USER_AVATAR + USER_AVATAR, + USER_PROFILE_IMAGE, + COMMENT_IMAGE } @Data diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/MinioServiceImpl.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/MinioServiceImpl.java deleted file mode 100644 index c12c4447..00000000 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/MinioServiceImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.xiaowang.yuminailcore.modules.file.service.impl; - -import com.xiaowang.yuminailcore.config.MinioConfig; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; -import io.minio.*; -import io.minio.http.Method; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; -import java.util.concurrent.TimeUnit; - -import com.xiaowang.yuminailcore.common.Result; -@Slf4j -@Service -@RequiredArgsConstructor -/** - * MinioServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. - * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. - */ -public class MinioServiceImpl implements MinioService { - /** - * Variable `minioClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MinioClient minioClient; - /** - * Variable `minioConfig`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ - private final MinioConfig minioConfig; - - @Override - /** - * Run business method `uploadFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param file parameter `file` supplied by the caller - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - public String uploadFile(MultipartFile file, String objectName) throws Exception { - try { - try (InputStream inputStream = file.getInputStream()) { - return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName); - } - } catch (Exception e) { - log.error("文件上传失败: {}", objectName, e); - throw e; - } - } - - @Override - /** - * Run business method `uploadStream`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param inputStream parameter `inputStream` supplied by the caller - * @param fileSize parameter `fileSize` supplied by the caller - * @param contentType parameter `contentType` supplied by the caller - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { - try { - minioClient.putObject( - PutObjectArgs.builder() - .bucket(minioConfig.getBucketName()) - .object(objectName) - .stream(inputStream, fileSize, -1) - .contentType(contentType) - .build() - ); - - log.info("文件上传成功: {}", objectName); - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return getFileUrl(objectName); - } catch (Exception e) { - log.error("文件上传失败: {}", objectName, e); - throw e; - } - } - - @Override - /** - * Run business method `downloadFile`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @return InputStream result consumed by the caller or returned to the frontend - */ - public InputStream downloadFile(String objectName) throws Exception { - return minioClient.getObject( - GetObjectArgs.builder() - .bucket(minioConfig.getBucketName()) - .object(objectName) - .build() - ); - } - - @Override - /** - * Delete, revoke, or logically remove a record. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - */ - public void deleteFile(String objectName) throws Exception { - minioClient.removeObject( - RemoveObjectArgs.builder() - .bucket(minioConfig.getBucketName()) - .object(objectName) - .build() - ); - log.info("文件删除成功: {}", objectName); - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - public String getFileUrl(String objectName) { - return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + objectName; - } - - @Override - /** - * Load data by the supplied parameter. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param objectName parameter `objectName` supplied by the caller - * @param expiryTimeInMinutes parameter `expiryTimeInMinutes` supplied by the caller - * @return String result consumed by the caller or returned to the frontend - */ - public String getPresignedUrl(String objectName, int expiryTimeInMinutes) throws Exception { - String url = minioClient.getPresignedObjectUrl( - GetPresignedObjectUrlArgs.builder() - .method(Method.GET) - .bucket(minioConfig.getBucketName()) - .object(objectName) - .expiry(expiryTimeInMinutes, TimeUnit.MINUTES) - .build() - ); - log.info("生成带签名的临时访问链接: {}, 有效期: {}分钟", objectName, expiryTimeInMinutes); - return url; - } - - @Override - /** - * Run business method `bucketExists`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bucketName parameter `bucketName` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ - public boolean bucketExists(String bucketName) throws Exception { - return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); - } - - @Override - /** - * Run business method `makeBucket`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param bucketName parameter `bucketName` supplied by the caller - */ - public void makeBucket(String bucketName) throws Exception { - if (!bucketExists(bucketName)) { - minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); - log.info("Bucket 创建成功: {}", bucketName); - } - } -} diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImpl.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageBackupServiceImpl.java similarity index 63% rename from FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImpl.java rename to FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageBackupServiceImpl.java index 7bbd231f..7d919b2a 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImpl.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageBackupServiceImpl.java @@ -1,11 +1,12 @@ package com.xiaowang.yuminailcore.modules.file.service.impl; +import com.xiaowang.yuminailcore.config.ObjectStorageProperties; import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; +import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageBackupService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; -import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; +import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -17,7 +18,7 @@ import java.time.LocalDateTime; @Slf4j @Service @RequiredArgsConstructor -public class OssBackupServiceImpl implements OssBackupService { +public class ObjectStorageBackupServiceImpl implements ObjectStorageBackupService { public static final int UPLOAD_STATUS_PENDING = 0; public static final int UPLOAD_STATUS_SUCCEEDED = 1; @@ -27,12 +28,13 @@ public class OssBackupServiceImpl implements OssBackupService { private static final int MAX_ERROR_LENGTH = 500; private final ObjectStorageFileMapper objectStorageFileMapper; - private final MinioService minioService; + private final PrimaryObjectStorageService primaryObjectStorageService; private final AliyunOssService aliyunOssService; private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageProperties objectStorageProperties; @Override - public void backupFileToOss(Long fileId) { + public void backupFile(Long fileId) { if (fileId == null || fileId <= 0) { return; } @@ -41,16 +43,16 @@ public class OssBackupServiceImpl implements OssBackupService { return; } - try (InputStream inputStream = minioService.downloadFile(file.getObjectName())) { - String ossUrl = aliyunOssService.uploadStream( + try (InputStream inputStream = primaryObjectStorageService.downloadFile(file.getObjectName())) { + String backupUrl = aliyunOssService.uploadStream( file.getObjectName(), inputStream, file.getFileSize() == null ? -1L : file.getFileSize(), file.getContentType() ); - markSucceeded(file, ossUrl); + markSucceeded(file, backupUrl); } catch (Exception e) { - log.warn("Backup file to Aliyun OSS failed, fileId={}", fileId, e); + log.warn("Backup file to object storage failed, fileId={}", fileId, e); markFailed(file, e); } } @@ -58,25 +60,27 @@ public class OssBackupServiceImpl implements OssBackupService { private boolean shouldBackup(ObjectStorageFileDO file) { return file != null && Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus()) - && Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getMinioUploadStatus()) - && !Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getOssUploadStatus()) + && objectStorageProperties.getPrimaryProvider().equals(file.getPrimaryProvider()) + && objectStorageProperties.getBackupProvider().equals(file.getBackupProvider()) + && Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getPrimaryUploadStatus()) + && !Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getBackupUploadStatus()) && StringUtils.hasText(file.getObjectName()); } - private void markSucceeded(ObjectStorageFileDO file, String ossUrl) { - file.setOssUrl(ossUrl); - file.setOssUploadStatus(UPLOAD_STATUS_SUCCEEDED); - file.setOssUploadedAt(LocalDateTime.now()); - file.setOssLastError(null); + private void markSucceeded(ObjectStorageFileDO file, String backupUrl) { + file.setBackupUrl(backupUrl); + file.setBackupUploadStatus(UPLOAD_STATUS_SUCCEEDED); + file.setBackupUploadedAt(LocalDateTime.now()); + file.setBackupLastError(null); objectStorageFileMapper.updateById(file); objectStorageFileService.evictObjectStorageFileCache(file.getId()); } private void markFailed(ObjectStorageFileDO file, Exception e) { - file.setOssUploadStatus(UPLOAD_STATUS_FAILED); - file.setOssRetryCount((file.getOssRetryCount() == null ? 0 : file.getOssRetryCount()) + 1); - file.setOssLastError(truncateError(e)); - file.setOssLastRetryTime(LocalDateTime.now()); + file.setBackupUploadStatus(UPLOAD_STATUS_FAILED); + file.setBackupRetryCount((file.getBackupRetryCount() == null ? 0 : file.getBackupRetryCount()) + 1); + file.setBackupLastError(truncateError(e)); + file.setBackupLastRetryTime(LocalDateTime.now()); objectStorageFileMapper.updateById(file); objectStorageFileService.evictObjectStorageFileCache(file.getId()); } diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java index fb7a9801..8541d45b 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -3,11 +3,12 @@ package com.xiaowang.yuminailcore.modules.file.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.fasterxml.jackson.core.type.TypeReference; import com.xiaowang.yuminailcore.config.AppCacheProperties; +import com.xiaowang.yuminailcore.config.ObjectStorageProperties; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; -import com.xiaowang.yuminailcore.modules.file.mq.OssBackupMessagePublisher; +import com.xiaowang.yuminailcore.modules.file.mq.ObjectStorageBackupMessagePublisher; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; @@ -55,7 +56,8 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl= MINIO_HEALTH_CACHE_MILLIS; - } - - private void markMinioHealth(boolean healthy) { - minioHealthy = healthy; - minioHealthCheckedAt = System.currentTimeMillis(); - } - private String firstText(String... values) { if (values == null) { return null; @@ -188,53 +160,15 @@ public class ObjectStorageUrlSupport { return null; } - private String extractObjectNameFromPath(String path) { - String bucketPrefix = "/" + minioConfig.getBucketName() + "/"; - if (path.startsWith(bucketPrefix)) { - return path.substring(bucketPrefix.length()); + private String normalizeDomain(String domain) { + String normalized = domain.trim(); + while (normalized.endsWith("/")) { + normalized = normalized.substring(0, normalized.length() - 1); } - - String endpointPath = ""; - try { - endpointPath = URI.create(minioConfig.getEndpoint()).getPath(); - } catch (Exception e) { - log.warn("Parse MinIO endpoint failed: {}", minioConfig.getEndpoint(), e); - } - - if (StringUtils.hasText(endpointPath) && !"/".equals(endpointPath)) { - String normalizedEndpointPath = endpointPath.endsWith("/") - ? endpointPath.substring(0, endpointPath.length() - 1) - : endpointPath; - String prefixedBucketPath = normalizedEndpointPath + bucketPrefix; - if (path.startsWith(prefixedBucketPath)) { - return path.substring(prefixedBucketPath.length()); - } - } - - int bucketIndex = path.indexOf(bucketPrefix); - if (bucketIndex >= 0) { - return path.substring(bucketIndex + bucketPrefix.length()); - } - - return ""; - } - - private String extractObjectNameFromUri(URI fileUri) { - String objectName = extractObjectNameFromPath(fileUri.getPath()); - if (StringUtils.hasText(objectName)) { - return objectName; - } - - try { - URI endpointUri = URI.create(minioConfig.getEndpoint()); - if (!sameAuthority(fileUri, endpointUri)) { - return ""; - } - return stripFirstPathSegment(fileUri.getPath()); - } catch (Exception e) { - log.warn("Parse MinIO endpoint failed: {}", minioConfig.getEndpoint(), e); - return ""; + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + return "http://" + normalized; } + return normalized; } private boolean sameAuthority(URI left, URI right) { @@ -252,24 +186,6 @@ public class ObjectStorageUrlSupport { return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; } - private String stripFirstPathSegment(String path) { - String normalizedPath = stripLeadingSlash(path); - int slashIndex = normalizedPath.indexOf('/'); - if (slashIndex < 0 || slashIndex == normalizedPath.length() - 1) { - return ""; - } - return normalizedPath.substring(slashIndex + 1); - } - - private String trimBucketPrefix(String rawValue) { - String normalized = stripLeadingSlash(rawValue); - String bucketPrefix = minioConfig.getBucketName() + "/"; - if (normalized.startsWith(bucketPrefix)) { - return normalized.substring(bucketPrefix.length()); - } - return normalized; - } - private String stripLeadingSlash(String rawValue) { String normalized = rawValue; while (normalized.startsWith("/")) { diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java index a159e6b4..9f6c868b 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java @@ -31,25 +31,29 @@ public class ObjectStorageFileVO { private String objectName; - private String minioUrl; + private String primaryProvider; - private String ossUrl; + private String primaryUrl; + + private String backupProvider; + + private String backupUrl; private String contentType; private Long fileSize; - private Integer minioUploadStatus; + private Integer primaryUploadStatus; - private Integer ossUploadStatus; + private Integer backupUploadStatus; - private Integer ossRetryCount; + private Integer backupRetryCount; - private String ossLastError; + private String backupLastError; - private LocalDateTime ossUploadedAt; + private LocalDateTime backupUploadedAt; - private LocalDateTime ossLastRetryTime; + private LocalDateTime backupLastRetryTime; /** * 文件上传时间 diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/product/vo/ProductVO.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/product/vo/ProductVO.java index 8f3608b4..1f35f1d9 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/product/vo/ProductVO.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/product/vo/ProductVO.java @@ -1,5 +1,7 @@ package com.xiaowang.yuminailcore.modules.product.vo; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import java.math.BigDecimal; @@ -20,11 +22,13 @@ public class ProductVO { /** * 商品唯一主键ID(雪花id) */ + @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 所属店铺ID,关联店铺表主键 */ + @JsonSerialize(using = ToStringSerializer.class) private Long shopId; /** diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/user/controller/front/UserController.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/user/controller/front/UserController.java index 9a382303..c4f32e2c 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/user/controller/front/UserController.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/modules/user/controller/front/UserController.java @@ -33,7 +33,7 @@ import com.xiaowang.yuminailcore.modules.user.vo.UserRelationVO; import com.xiaowang.yuminailcore.modules.user.vo.UserVO; import com.xiaowang.yuminailcore.modules.user.vo.InviteCodeVO; import com.xiaowang.yuminailcore.modules.integration.vo.WechatMiniLoginResultVO; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; +import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService; import com.xiaowang.yuminailcore.modules.user.service.UserAssetService; import com.xiaowang.yuminailcore.modules.user.service.UserService; import com.xiaowang.yuminailcore.modules.security.service.ShopRoleService; @@ -95,9 +95,9 @@ public class UserController { */ private final UserAssetService userAssetService; /** - * Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + * Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ - private final MinioService minioService; + private final PrimaryObjectStorageService primaryObjectStorageService; /** * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -764,7 +764,7 @@ public class UserController { String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); userService.updateUserAvatar(userId, avatarUrl); chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); @@ -802,7 +802,7 @@ public class UserController { String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String avatarUrl = minioService.uploadFile(file, objectName); + String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName); userService.updateUserAvatar(userId, avatarUrl); return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); @@ -821,6 +821,55 @@ public class UserController { /** * 上传个人资料图片,不直接修改头像或资料字段。 */ + @PostMapping("/upload-profile-image/init") + @OperationGuard(action = "user-profile-image-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(chunkUploadService.initUserProfileImageUpload(userId, requestDTO)); + } + + @PostMapping("/upload-profile-image/chunk") + @OperationGuard(action = "user-profile-image-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) + public Result uploadProfileImageChunk(HttpServletRequest request, + @RequestParam("uploadId") String uploadId, + @RequestParam("chunkIndex") Integer chunkIndex, + @RequestParam("totalChunks") Integer totalChunks, + @RequestParam("chunk") MultipartFile chunkFile) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.uploadUserProfileImageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); + return Result.success(true); + } + + @PostMapping("/upload-profile-image/complete") + @OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + Long userId = (Long) request.getAttribute("userId"); + try (ChunkUploadService.PreparedUploadFile preparedUploadFile = + chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId()); + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + String originalFilename = preparedUploadFile.getFileName(); + String fileExtension = ""; + if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) { + fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); + } + String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; + String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId()); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); + } catch (Exception e) { + e.printStackTrace(); + return Result.error("资料图片上传失败: " + e.getMessage()); + } + } + + @DeleteMapping("/upload-profile-image/{uploadId}") + @OperationGuard(action = "user-profile-image-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result cancelProfileImageUpload(HttpServletRequest request, @PathVariable String uploadId) { + Long userId = (Long) request.getAttribute("userId"); + chunkUploadService.clearUserProfileImageUpload(userId, uploadId); + return Result.success(true); + } + @PostMapping("/upload-profile-image") @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { @@ -835,7 +884,7 @@ public class UserController { fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); } String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; - String imageUrl = minioService.uploadFile(file, objectName); + String imageUrl = primaryObjectStorageService.uploadFile(file, objectName); return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl)); } catch (Exception e) { e.printStackTrace(); diff --git a/FD-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java b/FD-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java index 0d520806..926d8002 100644 --- a/FD-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java +++ b/FD-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java @@ -68,7 +68,7 @@ public class UploadSecurityValidator { * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ public void validateMetadata(String filename, String contentType, Long fileSize) { - if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxSize()) { + if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxTotalSize()) { throw new RuntimeException("上传文件大小不合法"); } String extension = resolveExtension(filename); diff --git a/FD-Core/src/main/resources/application.yaml b/FD-Core/src/main/resources/application.yaml index b94453fa..de19748d 100644 --- a/FD-Core/src/main/resources/application.yaml +++ b/FD-Core/src/main/resources/application.yaml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:mysql://localhost:3306/nailart?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + url: jdbc:mysql://localhost:3306/FingertipDesigner?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai servlet: multipart: max-file-size: 5MB @@ -25,10 +25,10 @@ mybatis: configuration: map-underscore-to-camel-case: true -yuminail: +fingertip-designer: security: jwt: - issuer: yuminail + issuer: fingertip-designer access-token-expiration-seconds: 7200 refresh-token-expiration-seconds: 604800 clock-skew-seconds: 30 @@ -85,3 +85,33 @@ yuminail: connection-request-timeout-ms: 1000 max-total-connections: 200 max-connections-per-route: 50 + +object-storage: + primary-provider: QINIU_KODO + backup-provider: 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} + +aliyun: + oss: + enabled: ${ALIYUN_OSS_ENABLED:false} + endpoint: ${ALIYUN_OSS_ENDPOINT:} + region: ${ALIYUN_OSS_REGION:} + bucket-name: ${ALIYUN_OSS_BUCKET_NAME:} + access-key-id: ${ALIYUN_OSS_ACCESS_KEY_ID:} + access-key-secret: ${ALIYUN_OSS_ACCESS_KEY_SECRET:} + signed-url-expire-minutes: ${ALIYUN_OSS_SIGNED_URL_EXPIRE_MINUTES:60} diff --git a/FD-Core/src/main/resources/bootstrap.yaml b/FD-Core/src/main/resources/bootstrap.yaml index b188cb7c..9331d0a3 100644 --- a/FD-Core/src/main/resources/bootstrap.yaml +++ b/FD-Core/src/main/resources/bootstrap.yaml @@ -1,57 +1,51 @@ spring: application: - name: yumi-nail-core + name: fingertip-designer-core cloud: nacos: discovery: - # Nacos集群地址 - server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 - # 命名空间ID - namespace: YumiNail-Dev - # 分组名称 - group: DEFAULT_GROUP - # 服务名称 + # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + # Nacos 命名空间,默认指向开发环境。 + namespace: ${NACOS_NAMESPACE:YumiNail-Dev} + # 服务注册分组。 + group: ${NACOS_GROUP:DEFAULT_GROUP} + # 注册到 Nacos 的服务名。 service: ${spring.application.name} - # 是否启用服务发现 + # 是否启用服务发现。 enabled: true - # 是否启用服务注册 + # 是否将当前服务注册到 Nacos。 register-enabled: true - # Nacos认证用户名 - username: xiaowang - # Nacos认证密码 - password: 122503wcy.... + # Nacos 认证用户名。 + username: ${NACOS_USERNAME:xiaowang} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD:122503wcy....} config: - # Nacos配置中心集群地址 - server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 - # 配置中心命名空间 - namespace: YumiNail-Dev - # 配置分组 - group: DEFAULT_GROUP - # 配置文件名称 - name: yuminail-core - # 配置文件扩展名 + # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。 + server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848} + # Nacos 配置中心命名空间,默认指向开发环境。 + namespace: ${NACOS_NAMESPACE:YumiNail-Dev} + # 配置分组。 + group: ${NACOS_GROUP:DEFAULT_GROUP} + # Core 服务独有配置文件。 + name: core + # 所有 Nacos 配置均使用 YAML。 file-extension: yaml - # 是否启用配置中心 + # 是否启用配置中心。 enabled: true - # Nacos认证用户名 - username: xiaowang - # Nacos认证密码 - password: 122503wcy.... - # 共享配置文件列表 + # Nacos 认证用户名。 + username: ${NACOS_USERNAME:xiaowang} + # Nacos 认证密码。 + password: ${NACOS_PASSWORD:122503wcy....} + # Core 与 Gateway 共享的公共配置文件。 shared-configs: - - data-id: rabbit-mq.yaml - group: DEFAULT_GROUP + - data-id: infra.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} refresh: true - - data-id: datasource.yaml - group: DEFAULT_GROUP - refresh: true - - data-id: mybatis-plus.yaml - group: DEFAULT_GROUP + - data-id: secret.yaml + group: ${NACOS_GROUP:DEFAULT_GROUP} refresh: true - data-id: logging.yaml - group: DEFAULT_GROUP - refresh: true - - data-id: redis.yaml - group: DEFAULT_GROUP + group: ${NACOS_GROUP:DEFAULT_GROUP} refresh: true diff --git a/FD-Core/src/main/resources/files/YumiNail.sql b/FD-Core/src/main/resources/files/YumiNail.sql deleted file mode 100644 index 6a971b50..00000000 --- a/FD-Core/src/main/resources/files/YumiNail.sql +++ /dev/null @@ -1,2503 +0,0 @@ --- Fingertip Designer 最小运行初始化 SQL --- 说明: --- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、基础参数、协议、MessageHub、VIP 规则与管理员初始化。 --- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、 --- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。 --- 3. 当前 Nacos datasource.yaml 指向 nailart,本文件默认按该库名初始化;如果你的实际数据库名不同,请先统一 datasource 与下方库名。 --- 4. 本文件只初始化一个平台管理员 xiaowang(默认密码 888888),不写入开发/验收用户、门店、作品、标签、订单、消息公告等业务数据。 -CREATE DATABASE IF NOT EXISTS nailart DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -use nailart; - --- auto-generated definition -create table t_balance -( - id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' - primary key comment '余额表主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - amount decimal(10, 2) default 0.00 not null comment '当前余额', - total_recharge_amount decimal(10, 2) default 0.00 not null comment '累计充值金额', - last_recharge_time datetime null comment '最近一次充值时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', - last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - constraint uk_user_id - unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' -) - comment '用户余额信息表'; - - --- auto-generated definition -create table t_balance_change_detail -( - id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' - primary key comment '余额变动明细主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', - type varchar(20) not null comment '变动类型(如充值、消费、退款)', - current_balance decimal(10, 2) not null comment '变动后的当前余额', - before_balance decimal(10, 2) null comment '变动前余额', - after_balance decimal(10, 2) null comment '变动后余额', - change_scene varchar(32) null comment '余额变动场景', - related_order_id bigint unsigned null comment '关联系统订单ID', - related_order_no varchar(64) null comment '关联系统订单号', - external_order_no varchar(64) null comment '手工录入的外部订单号', - operator_id bigint unsigned null comment '操作人ID', - remark varchar(255) null comment '备注', - change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' -) - comment '用户余额变动明细表'; - -create index idx_change_time - on t_balance_change_detail (change_time) - comment '按时间查询余额变动的索引'; - -create index idx_user_id - on t_balance_change_detail (user_id) - comment '按用户查询余额变动的索引'; - --- auto-generated definition -create table t_cart -( - id bigint unsigned auto_increment comment '购物车主键索引' - primary key, - user_id bigint unsigned not null comment '关联用户表主键', - product_id bigint unsigned not null comment '关联商品表主键', - quantity int unsigned default 1 not null comment '商品数量', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_product - unique (user_id, product_id) comment '用户-商品唯一索引' -) - comment '购物车表'; - -create index idx_user_id - on t_cart (user_id) - comment '按用户查询购物车的索引'; - --- auto-generated definition -create table t_comment -( - id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' - primary key comment '评论主键索引', - user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', - shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', - product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', - comment_content text not null comment '评论内容', - parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', - rating_score tinyint unsigned default 5 null comment '评论评分:1-5星', - image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔', - like_count int unsigned default 0 null comment '评论点赞数', - create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' -) - comment '用户评论信息表'; - -create index idx_parent_comment_id - on t_comment (parent_comment_id) - comment '按父级评论查询回复的索引'; - -create index idx_product_id - on t_comment (product_id) - comment '按商品查询评论的索引'; - -create index idx_shop_id - on t_comment (shop_id) - comment '按店铺查询评论的索引'; - -create index idx_user_id - on t_comment (user_id) - comment '按用户查询评论的索引'; - --- auto-generated definition -create table t_coupon -( - id bigint unsigned auto_increment comment '优惠券主键索引' - primary key, - coupon_code varchar(50) not null comment '优惠券编码', - coupon_name varchar(100) not null comment '优惠券名称', - coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', - discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', - min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', - reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', - total_count int unsigned default 100 not null comment '优惠券总数量', - used_count int unsigned default 0 not null comment '已使用数量', - start_time datetime not null comment '开始时间', - end_time datetime not null comment '结束时间', - status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - shop_id bigint null comment '所属店铺ID', - coupon_scene varchar(32) default 'NORMAL' not null comment '优惠券场景', - required_vip_level varchar(20) null comment '要求的VIP等级', - auto_match tinyint unsigned default 0 not null comment '是否自动匹配', - constraint uk_coupon_code - unique (coupon_code) comment '优惠券编码唯一索引' -) - comment '优惠券信息表'; - -create index idx_status - on t_coupon (status) - comment '按状态查询优惠券的索引'; - --- auto-generated definition -create table t_coupon_tag -( - id bigint unsigned auto_increment comment '优惠券标签关联主键索引' - primary key, - coupon_id bigint unsigned not null comment '关联优惠券表主键', - tag_id bigint unsigned not null comment '关联标签表主键', - is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_coupon_tag - unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' -) - comment '优惠券标签关联表'; - -create index idx_coupon_id - on t_coupon_tag (coupon_id) - comment '按优惠券查询标签的索引'; - -create index idx_tag_id - on t_coupon_tag (tag_id) - comment '按标签查询优惠券的索引'; - --- auto-generated definition -create table t_effect_diagram -( - id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' - primary key comment '效果图主键索引', - product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', - category varchar(50) default '' null comment '效果图类别', - image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', - description text null comment '效果图描述', - price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', - duration varchar(50) default '' null comment '效果图对应服务耗时', - tag varchar(50) default '' null comment '效果图标签', - like_count int unsigned default 0 null comment '效果图点赞数', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '商品效果图信息表'; - -create index idx_product_id - on t_effect_diagram (product_id) - comment '按商品查询效果图的索引'; - --- auto-generated definition -create table t_login_identity -( - id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' - primary key comment '登录标识主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', - input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', - input_time datetime not null comment '输入时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' -) - comment '用户登录标识信息表'; - -create index idx_login_method - on t_login_identity (login_method) - comment '按登录方式查询的索引'; - -create index idx_user_id - on t_login_identity (user_id) - comment '按用户查询登录标识的索引'; - --- auto-generated definition -create table t_wechat_mini_binding -( - id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)' - primary key, - user_id bigint unsigned not null comment '关联用户ID', - app_id varchar(64) not null comment '微信小程序appId', - openid varchar(100) not null comment '微信小程序openid', - unionid varchar(100) null comment '微信开放平台unionid', - status tinyint unsigned default 1 null comment '状态:1-有效,0-失效', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - constraint uk_wechat_mini_app_openid - unique (app_id, openid), - constraint uk_wechat_mini_app_user - unique (app_id, user_id) -) - comment '微信小程序账号绑定表'; - -create index idx_wechat_mini_unionid - on t_wechat_mini_binding (unionid) - comment '按unionid查询的索引'; - --- auto-generated definition -create table t_nail_artist_info -( - id bigint unsigned auto_increment comment '美甲师信息主键索引' - primary key, - user_id bigint unsigned not null comment '关联用户表主键(美甲师用户)', - identity varchar(50) default '' null comment '身份', - experience int unsigned default 0 null comment '从业年限', - skills text null comment '技能标签ID集合,多个ID以逗号分隔', - rating decimal(3, 1) default 4.5 null comment '评分', - status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', - participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', - work_start_time time null comment '工作开始时间', - work_end_time time null comment '工作结束时间', - portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_id - unique (user_id) comment '用户ID唯一索引(一个美甲师对应一条信息记录)' -) - comment '美甲师信息表'; - -create index idx_status - on t_nail_artist_info (status) - comment '按状态查询美甲师的索引'; - -create index idx_user_id - on t_nail_artist_info (user_id) - comment '按用户查询美甲师信息的索引'; - -create index idx_t_nail_artist_info_participate - on t_nail_artist_info (participate_production, status); - --- auto-generated definition -create table t_object_storage_file -( - id bigint unsigned auto_increment comment '文件记录唯一主键ID(雪花ID)' - primary key comment '对象存储文件主键索引', - file_name varchar(100) not null comment '文件名称', - file_url text not null comment '文件访问链接', - object_name varchar(512) null comment '对象存储Key', - minio_url text null comment 'MinIO访问链接', - oss_url text null comment '阿里云OSS内部备份链接', - content_type varchar(128) null comment '文件Content-Type', - file_size bigint unsigned null comment '文件大小,单位字节', - minio_upload_status tinyint unsigned default 0 not null comment 'MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', - oss_upload_status tinyint unsigned default 0 not null comment 'OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', - oss_retry_count int unsigned default 0 not null comment 'OSS备份重试次数', - oss_last_error varchar(500) null comment '最近一次OSS备份失败原因', - oss_uploaded_at datetime null comment 'OSS备份成功时间', - oss_last_retry_time datetime null comment '最近一次OSS备份重试时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '文件上传时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '文件更新时间', - status tinyint unsigned default 1 null comment '文件状态:1-可用,0-不可用,2-回收站', - delete_time datetime null comment '文件删除时间(NULL表示未删除)', - recycle_time datetime null comment '文件移入回收站时间(NULL表示未移入)' -) - comment '对象存储文件信息表'; - -create index idx_status - on t_object_storage_file (status) - comment '按文件状态查询的索引'; - -create index idx_object_storage_file_oss_retry - on t_object_storage_file (oss_upload_status, minio_upload_status, status) - comment 'OSS备份失败重试扫描索引'; - --- auto-generated definition -create table t_order -( - id bigint unsigned auto_increment comment '订单主键索引' - primary key, - order_no varchar(50) not null comment '订单编号', - user_id bigint unsigned not null comment '关联用户表主键', - shop_id bigint unsigned null comment '所属店铺ID', - total_amount decimal(10, 2) not null comment '订单总金额', - actual_amount decimal(10, 2) not null comment '实际支付金额', - coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', - user_coupon_id bigint unsigned null comment '用户券ID', - coupon_source_type varchar(32) null comment '优惠来源类型', - status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_order_no - unique (order_no) comment '订单编号唯一索引' -) - comment '订单表'; - -create index idx_status - on t_order (status) - comment '按状态查询订单的索引'; - -create index idx_user_id - on t_order (user_id) - comment '按用户查询订单的索引'; - --- auto-generated definition -create table t_order_item -( - id bigint unsigned auto_increment comment '订单商品主键索引' - primary key, - order_id bigint unsigned not null comment '关联订单表主键', - product_id bigint unsigned not null comment '关联商品表主键', - quantity int unsigned not null comment '商品数量', - price decimal(10, 2) not null comment '商品单价', - artist_id bigint unsigned null comment '关联美甲师ID', - appointment_time datetime null comment '预约开始时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单商品表'; - -create index idx_order_id - on t_order_item (order_id) - comment '按订单查询商品的索引'; - -CREATE TABLE IF NOT EXISTS t_order_artist_review -( - id bigint unsigned auto_increment comment '评价任务ID' - primary key, - order_id bigint unsigned not null comment '订单ID', - order_item_id bigint unsigned not null comment '订单项ID', - customer_id bigint unsigned not null comment '下单客户ID', - shop_id bigint unsigned null comment '店铺ID', - artist_id bigint unsigned not null comment '被评价美甲师ID', - product_id bigint unsigned null comment '商品ID', - rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', - content varchar(1000) null comment '评价文字', - image_file_ids text null comment '评价图片文件ID集合', - status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', - reminder_message_id bigint unsigned null comment '提醒消息ID', - submitted_at datetime null comment '提交时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单美甲师评价任务表'; - -create unique index uk_order_artist_review_item - on t_order_artist_review (order_item_id, is_delete); - -create index idx_order_artist_review_customer - on t_order_artist_review (customer_id, status, create_time); - -create index idx_order_artist_review_artist - on t_order_artist_review (artist_id, status); - -CREATE TABLE IF NOT EXISTS t_order_artist_change_request -( - id bigint unsigned auto_increment comment '改派申请ID' - primary key, - order_id bigint unsigned not null comment '订单ID', - order_item_id bigint unsigned not null comment '订单项ID', - customer_id bigint unsigned not null comment '下单客户ID', - shop_id bigint unsigned null comment '店铺ID', - product_id bigint unsigned null comment '商品ID', - from_artist_id bigint unsigned not null comment '原美甲师ID', - to_artist_id bigint unsigned not null comment '新美甲师ID', - requester_id bigint unsigned not null comment '申请人ID', - status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', - reason varchar(500) null comment '申请原因', - reject_reason varchar(500) null comment '拒绝原因', - message_id bigint unsigned null comment '提醒消息ID', - pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', - approved_time datetime null comment '同意时间', - rejected_time datetime null comment '拒绝时间', - expire_time datetime null comment '过期时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单美甲师改派申请表'; - -create index idx_order_artist_change_customer - on t_order_artist_change_request (customer_id, status, create_time); - -create index idx_order_artist_change_artist - on t_order_artist_change_request (from_artist_id, to_artist_id, status); - -create index idx_order_artist_change_shop - on t_order_artist_change_request (shop_id, status, create_time); - -create unique index uk_order_artist_change_pending_key - on t_order_artist_change_request (pending_key); - --- auto-generated definition -create table t_permission -( - id bigint unsigned auto_increment comment '权限唯一主键ID' - primary key, - permission_code varchar(100) not null comment '权限编码(唯一标识)', - permission_name varchar(100) not null comment '权限名称', - permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', - description varchar(255) null comment '权限描述', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_permission_code - unique (permission_code) comment '权限编码唯一索引' -) - comment '系统权限表'; - --- auto-generated definition -create table t_product -( - id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' - primary key comment '商品主键索引', - shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', - title varchar(100) not null comment '商品标题', - description text null comment '商品描述', - target_audience text null comment '适合人群说明', - precautions text null comment '注意事项说明', - image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', - price decimal(10, 2) not null comment '商品价格,保留2位小数', - tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', - like_count int unsigned default 0 null comment '商品点赞数', - collect_count int unsigned default 0 null comment '商品收藏数', - approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', - bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', - available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', - create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' -) - comment '商品信息表'; - -create index idx_price - on t_product (price) - comment '按价格筛选商品的索引'; - -create index idx_shop_id - on t_product (shop_id) - comment '按所属店铺查询商品的索引'; - -create index idx_tags - on t_product (tags) - comment '按标签筛选商品的索引'; - -create index idx_title - on t_product (title) - comment '商品标题搜索的索引'; - --- auto-generated definition -create table t_product_like -( - id bigint unsigned auto_increment comment '商品点赞主键索引' - primary key, - user_id bigint unsigned not null comment '关联用户表主键', - product_id bigint unsigned not null comment '关联商品表主键', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', - constraint uk_user_product_like - unique (user_id, product_id) comment '用户-商品唯一索引' -) - comment '商品点赞记录表'; - -create index idx_product_id_like - on t_product_like (product_id) - comment '按商品查询点赞的索引'; - -create index idx_user_id_like - on t_product_like (user_id) - comment '按用户查询点赞的索引'; - --- auto-generated definition -create table t_shop -( - id bigint unsigned auto_increment comment '店铺唯一主键ID' - primary key comment '店铺主键索引', - shop_name varchar(100) not null comment '店铺名称', - description text null comment '店铺描述', - address varchar(200) not null comment '店铺地址', - map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', - longitude decimal(12, 8) null comment '店铺经度', - latitude decimal(12, 8) null comment '店铺纬度', - business_hours varchar(100) default '' null comment '店铺营业时间', - cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', - theme_primary_color varchar(20) null comment '前台主题主色', - theme_secondary_color varchar(20) null comment '前台主题辅色', - theme_accent_color varchar(20) null comment '前台主题强调色', - theme_page_bg_color varchar(20) null comment '前台主题页面背景色', - theme_card_bg_color varchar(20) null comment '前台主题卡片背景色', - theme_background_image_file_id varchar(50) null comment '前台主题背景图文件ID', - status tinyint unsigned default 1 not null comment '店铺状态:1-启用,0-停用', - authorization_start_date date null comment '店铺授权起始日', - authorization_days int null comment '店铺授权有效天数', - authorization_expire_time datetime null comment '店铺授权到期时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' -) - comment '店铺信息表'; - -create index idx_shop_name - on t_shop (shop_name) - comment '按店铺名称查询的索引'; - --- auto-generated definition -create table t_tag -( - id bigint unsigned auto_increment comment '标签唯一主键ID' - primary key comment '标签主键索引', - tag_name varchar(50) not null comment '标签名称', - text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', - bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', - border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', - scene_group varchar(50) null comment '前台场景筛选分组', - display_name varchar(80) null comment '前台展示名称', - sort_order int default 100 null comment '前台筛选排序', - front_visible tinyint unsigned default 1 null comment '前台筛选是否可见:1-可见,0-隐藏', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - shop_id bigint null comment '店铺ID', - constraint uk_tag_shop_name - unique (shop_id, tag_name) comment '店铺内标签名称唯一索引' -) - comment '系统标签信息表'; - --- auto-generated definition -create table t_user -( - id bigint unsigned auto_increment comment '用户唯一主键ID(雪花ID)' - primary key comment '用户主键索引', - shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', - nickname varchar(50) not null comment '用户昵称', - account varchar(50) not null comment '用户账号(登录用)', - phone varchar(50) null comment '手机号', - contact_phone varchar(50) null comment '联系电话', - birthday date null comment '生日', - wechat_id varchar(100) null comment '微信号', - wechat_qr_code varchar(512) null comment '微信二维码', - email varchar(100) null comment '邮箱', - phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', - email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', - password varchar(100) not null comment '用户密码(加密存储)', - signature varchar(200) default '' null comment '用户签名', - level varchar(20) default '普通' null comment '用户等级', - type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', - vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', - avatar varchar(512) null comment '头像链接', - constraint uk_account - unique (account) comment '用户账号唯一索引' -) - comment '系统用户信息表'; - -create index idx_email - on t_user (email) - comment '按邮箱查询的索引'; - -create index idx_phone - on t_user (phone) - comment '按手机号查询的索引'; - -create index idx_shop_id - on t_user (shop_id) - comment '按店铺查询用户的索引'; - -create index idx_type - on t_user (type) - comment '按用户类型查询的索引'; - --- auto-generated definition -create table t_user_coupon -( - id bigint unsigned auto_increment comment '用户优惠券关联主键索引' - primary key, - user_id bigint unsigned not null comment '关联用户表主键', - coupon_id bigint unsigned not null comment '关联优惠券表主键', - status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', - obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', - use_time datetime null comment '使用时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_coupon - unique (user_id, coupon_id) comment '用户-优惠券唯一索引' -) - comment '用户优惠券关联表'; - -create index idx_status - on t_user_coupon (status) - comment '按状态查询用户优惠券的索引'; - -create index idx_user_id - on t_user_coupon (user_id) - comment '按用户查询优惠券的索引'; - --- auto-generated definition -create table t_user_permission -( - id bigint unsigned auto_increment comment '关联ID' - primary key, - user_id bigint unsigned not null comment '用户ID', - permission_id bigint unsigned not null comment '权限ID', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - create_by bigint unsigned null comment '创建人ID', - update_by bigint unsigned null comment '更新人ID', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_permission - unique (user_id, permission_id) comment '用户-权限唯一索引' -) - comment '用户权限关联表'; - -create index idx_permission_id - on t_user_permission (permission_id) - comment '权限ID索引'; - -create index idx_user_id - on t_user_permission (user_id) - comment '用户ID索引'; - -create table if not exists t_system_message -( - id bigint unsigned auto_increment comment '站内消息主键' - primary key, - title varchar(100) not null comment '消息标题', - content text not null comment '消息内容', - image_file_id bigint unsigned null comment '消息图片文件ID', - publisher_id bigint unsigned not null comment '发布人ID', - publisher_name varchar(100) default '' null comment '发布人名称', - publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', - target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', - target_ids text null comment '目标ID集合,多个ID以逗号分隔', - business_type varchar(64) null comment '业务类型', - business_id bigint unsigned null comment '业务ID', - action_path varchar(255) null comment '业务跳转路径', - idempotency_key varchar(160) null comment '业务消息幂等键', - popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', - status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', - publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '站内消息表'; - -create index idx_t_system_message_publish_time - on t_system_message (publish_time); - -create index idx_t_system_message_target - on t_system_message (target_type, status); - -create unique index uk_t_system_message_idempotency - on t_system_message (idempotency_key); - -create table if not exists t_system_message_user_state -( - id bigint unsigned auto_increment comment '用户消息状态主键' - primary key, - message_id bigint unsigned not null comment '消息ID', - user_id bigint unsigned not null comment '用户ID', - popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', - read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', - popup_time datetime null comment '首次弹窗时间', - read_time datetime null comment '阅读时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_t_system_message_user - unique (message_id, user_id) -) - comment '用户站内消息状态表'; - -create index idx_t_system_message_user_state_user - on t_system_message_user_state (user_id, read_status, popup_shown); - -create table if not exists t_announcement -( - id bigint unsigned auto_increment comment '公告主键' - primary key, - title varchar(100) not null comment '公告标题', - content text not null comment '公告内容', - publisher_id bigint unsigned not null comment '发布人ID', - publisher_name varchar(100) default '' null comment '发布人名称', - publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', - target_type varchar(30) not null comment '目标范围', - target_ids text null comment '目标ID集合,多个ID以逗号分隔', - status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', - sort_order int default 0 not null comment '排序值', - publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '首页滚动公告表'; - -create index idx_t_announcement_target - on t_announcement (target_type, status); - -create index idx_t_announcement_sort_time - on t_announcement (sort_order, publish_time); - -create table if not exists t_vip_recharge_plan -( - id bigint unsigned auto_increment comment 'VIP充值档位主键' - primary key, - shop_id bigint unsigned not null comment '所属店铺ID', - title varchar(100) not null comment '档位标题', - recharge_amount decimal(10, 2) not null comment '充值金额', - gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', - vip_level varchar(20) not null comment '对应VIP等级', - description varchar(255) null comment '展示说明', - sort_order int default 0 not null comment '排序值', - status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment 'VIP充值展示档位表'; - -create index idx_t_vip_recharge_plan_shop_status - on t_vip_recharge_plan (shop_id, status, sort_order); - --- auto-generated definition -create table t_vip_benefit -( - id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' - primary key comment 'VIP权益主键索引', - benefit_info text not null comment '权益详情(如折扣、专属服务)', - required_vip_level varchar(20) not null comment '所需VIP等级', - level_rank int default 0 not null comment '等级序号', - recharge_threshold decimal(10, 2) default 0.00 not null comment '累计充值门槛', - status tinyint unsigned default 1 not null comment '状态', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' -) - comment 'VIP权益信息表'; - -create index idx_required_vip_level - on t_vip_benefit (required_vip_level) - comment '按VIP等级查询权益的索引'; - --- auto-generated definition -create table t_vip_info -( - id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' - primary key comment 'VIP信息主键索引', - user_id bigint unsigned null comment '所属用户ID', - vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', - start_time datetime not null comment 'VIP开通时间', - expire_time datetime null comment 'VIP到期时间', - activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', - benefit_id bigint unsigned null comment '关联VIP权益信息表主键', - manual_override tinyint unsigned default 0 not null comment '是否手工覆盖VIP等级', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' -) - comment '用户VIP信息表'; - -create index idx_vip_level - on t_vip_info (vip_level) - comment '按VIP等级查询的索引'; - --- auto-generated definition -create table t_wishlist_group -( - id bigint unsigned auto_increment comment '收藏分组主键' - primary key, - user_id bigint unsigned not null comment '关联用户表主键', - name varchar(50) not null comment '分组名称,默认预设:最近想做、婚礼款、夏天款', - sort_order int default 100 not null comment '分组排序', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除' -) - comment '商品收藏分组表'; - -create index idx_t_wishlist_group_sort - on t_wishlist_group (user_id, sort_order, create_time) - comment '按用户和排序查询收藏分组的索引'; - -create index idx_t_wishlist_group_user - on t_wishlist_group (user_id) - comment '按用户查询收藏分组的索引'; - --- auto-generated definition -create table t_wishlist -( - id bigint unsigned auto_increment comment '商品收藏主键索引' - primary key, - user_id bigint unsigned not null comment '关联用户表主键', - product_id bigint unsigned not null comment '关联商品表主键', - group_id bigint unsigned null comment '收藏分组ID', - note varchar(500) null comment '收藏灵感备注', - sort_order int default 100 not null comment '分组内排序', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', - constraint uk_user_product - unique (user_id, product_id) comment '用户-商品唯一索引' -) - comment '商品收藏表'; - -create index idx_product_id - on t_wishlist (product_id) - comment '按商品查询收藏的索引'; - -create index idx_user_id - on t_wishlist (user_id) - comment '按用户查询收藏的索引'; - -create index idx_t_wishlist_user_group_sort - on t_wishlist (user_id, group_id, sort_order, create_time) - comment '按用户分组查询收藏灵感的索引'; - --- ======================================== --- 首次部署整合区:用户资产 / VIP / 优惠券补丁 --- 来源:2026-03-20_user_asset_vip_coupon_permission_patch.sql --- ======================================== - -SET NAMES utf8mb4; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_add_column_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN p_definition TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = p_column_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', - p_definition - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_unique_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); -CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); -CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); - -CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''对象存储Key'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_url', 'text NULL COMMENT ''MinIO访问链接'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_url', 'text NULL COMMENT ''阿里云OSS内部备份链接'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''文件Content-Type'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''文件大小,单位字节'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''OSS备份重试次数'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_error', 'varchar(500) NULL COMMENT ''最近一次OSS备份失败原因'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_uploaded_at', 'datetime NULL COMMENT ''OSS备份成功时间'''); -CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_retry_time', 'datetime NULL COMMENT ''最近一次OSS备份重试时间'''); -UPDATE t_object_storage_file -SET minio_url = COALESCE(minio_url, file_url), - minio_upload_status = CASE WHEN minio_upload_status IS NULL OR minio_upload_status = 0 THEN 1 ELSE minio_upload_status END, - oss_upload_status = COALESCE(oss_upload_status, 0), - oss_retry_count = COALESCE(oss_retry_count, 0) -WHERE status = 1; -CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_oss_retry', '(`oss_upload_status`, `minio_upload_status`, `status`)'); - -UPDATE t_balance -SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) -WHERE total_recharge_amount IS NULL; - -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); -CALL sp_add_column_if_not_exists('t_login_identity', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); - -CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL COMMENT ''联系电话'''); -CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日'''); -CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号'''); -CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码'''); - -UPDATE t_balance_change_detail -SET before_balance = COALESCE(before_balance, current_balance - amount), - after_balance = COALESCE(after_balance, current_balance), - change_scene = COALESCE(NULLIF(change_scene, ''), type) -WHERE before_balance IS NULL - OR after_balance IS NULL - OR change_scene IS NULL - OR change_scene = ''; - -CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); -CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); - -CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); -CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); -CALL sp_add_column_if_not_exists('t_order', 'coupon_source_type', 'varchar(32) NULL COMMENT ''优惠来源类型'''); - -UPDATE t_order -SET coupon_id = NULL -WHERE coupon_id = 0; - -UPDATE t_order o -INNER JOIN ( - SELECT oi.order_id, MIN(p.shop_id) AS resolved_shop_id - FROM t_order_item oi - INNER JOIN t_product p ON p.id = oi.product_id - GROUP BY oi.order_id -) detail_shop ON detail_shop.order_id = o.id -SET o.shop_id = detail_shop.resolved_shop_id -WHERE o.shop_id IS NULL; - -UPDATE t_order -SET coupon_source_type = 'USER_COUPON' -WHERE coupon_source_type IS NULL - AND coupon_id IS NOT NULL; - -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_shop_id', '(`shop_id`)'); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_coupon_source_type', '(`coupon_source_type`)'); - -CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); -CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); - -SET @drop_old_tag_unique_sql = ( - SELECT IF( - EXISTS( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 't_tag' - AND INDEX_NAME = 'uk_tag_name' - ), - 'ALTER TABLE `t_tag` DROP INDEX `uk_tag_name`', - 'SELECT 1' - ) -); -PREPARE stmt FROM @drop_old_tag_unique_sql; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; - -CALL sp_add_unique_index_if_not_exists('t_tag', 'uk_tag_shop_name', '(`shop_id`, `tag_name`)'); -CALL sp_add_column_if_not_exists('t_tag', 'scene_group', 'varchar(50) NULL COMMENT ''前台场景筛选分组'''); -CALL sp_add_column_if_not_exists('t_tag', 'display_name', 'varchar(80) NULL COMMENT ''前台展示名称'''); -CALL sp_add_column_if_not_exists('t_tag', 'sort_order', 'int NULL DEFAULT 100 COMMENT ''前台筛选排序'''); -CALL sp_add_column_if_not_exists('t_tag', 'front_visible', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''前台筛选是否可见:1-可见,0-隐藏'''); -UPDATE t_tag -SET front_visible = 1 -WHERE front_visible IS NULL; -CALL sp_add_index_if_not_exists('t_tag', 'idx_t_tag_front_filter', '(`shop_id`, `front_visible`, `scene_group`, `sort_order`, `is_delete`)'); - -CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); -CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); -CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); - -UPDATE t_coupon -SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), - auto_match = COALESCE(auto_match, 0) -WHERE coupon_scene IS NULL - OR coupon_scene = '' - OR auto_match IS NULL; - -CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); -CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); - -CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); -CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); -CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); - -UPDATE t_vip_benefit -SET level_rank = CASE required_vip_level - WHEN '普通' THEN 0 - WHEN '青铜' THEN 1 - WHEN '白银' THEN 2 - WHEN '黄金' THEN 3 - ELSE level_rank - END, - recharge_threshold = CASE required_vip_level - WHEN '普通' THEN 0.00 - WHEN '青铜' THEN 500.00 - WHEN '白银' THEN 1000.00 - WHEN '黄金' THEN 2000.00 - ELSE recharge_threshold - END, - status = COALESCE(status, 1) -WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); - -CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); - -CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); -CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); - -ALTER TABLE t_vip_info - MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', - MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; - -UPDATE t_vip_info vi -INNER JOIN t_user u ON u.vip_id = vi.id -SET vi.user_id = u.id -WHERE (vi.user_id IS NULL OR vi.user_id = 0) - AND u.vip_id IS NOT NULL - AND u.vip_id <> 0; - -UPDATE t_vip_info -SET start_time = COALESCE(start_time, create_time, NOW()), - activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), - manual_override = COALESCE(manual_override, 0); - -CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); -CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); - -UPDATE t_user u -LEFT JOIN t_vip_info vi ON vi.id = u.vip_id -SET u.level = CASE - WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level - WHEN u.type = 0 THEN '普通' - ELSE u.level - END, - u.vip_id = CASE - WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 - ELSE u.vip_id - END, - u.update_time = NOW() -WHERE u.is_delete = 0 - AND u.type = 0 - AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); - -UPDATE t_vip_benefit -SET benefit_info = '普通用户,无额外VIP折扣', - level_rank = 0, - recharge_threshold = 0.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '普通'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '普通' -); - -UPDATE t_vip_benefit -SET benefit_info = '青铜VIP,系统自动匹配9.5折券', - level_rank = 1, - recharge_threshold = 500.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '青铜'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '青铜' -); - -UPDATE t_vip_benefit -SET benefit_info = '白银VIP,系统自动匹配9.2折券', - level_rank = 2, - recharge_threshold = 1000.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '白银'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '白银' -); - -UPDATE t_vip_benefit -SET benefit_info = '黄金VIP,系统自动匹配9.0折券', - level_rank = 3, - recharge_threshold = 2000.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '黄金'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '黄金' -); - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - --- ======================================== --- 首次部署整合区:多店铺登录 / 店铺状态 / 用户店铺绑定补丁 --- 来源:2026-03-25_user_shop_binding_and_shop_status_patch.sql --- ======================================== - -SET NAMES utf8mb4; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_add_column_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN p_definition TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = p_column_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', - p_definition - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_unique_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); -CALL sp_add_column_if_not_exists('t_shop', 'authorization_start_date', 'date NULL COMMENT ''店铺授权起始日'''); -CALL sp_add_column_if_not_exists('t_shop', 'authorization_days', 'int NULL COMMENT ''店铺授权有效天数'''); -CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); -CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); -CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); -CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_primary_color', 'varchar(20) NULL COMMENT ''前台主题主色'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_secondary_color', 'varchar(20) NULL COMMENT ''前台主题辅色'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_accent_color', 'varchar(20) NULL COMMENT ''前台主题强调色'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_page_bg_color', 'varchar(20) NULL COMMENT ''前台主题页面背景色'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_card_bg_color', 'varchar(20) NULL COMMENT ''前台主题卡片背景色'''); -CALL sp_add_column_if_not_exists('t_shop', 'theme_background_image_file_id', 'varchar(50) NULL COMMENT ''前台主题背景图文件ID'''); - -UPDATE t_shop -SET status = 1 -WHERE status IS NULL; - -CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); - -CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( - `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', - `user_id` bigint unsigned NOT NULL COMMENT '用户ID', - `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', - `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (`id`) -) COMMENT='用户与店铺绑定关系表'; - -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); - -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); -CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); - -INSERT INTO t_user_shop_binding ( - user_id, - shop_id, - status, - create_time, - update_time, - is_delete -) -SELECT - u.id, - u.shop_id, - CASE - WHEN COALESCE(u.status, 1) = 1 THEN 1 - ELSE 0 - END AS binding_status, - COALESCE(u.create_time, NOW()), - COALESCE(u.update_time, NOW()), - 0 -FROM t_user u -INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 -LEFT JOIN t_user_shop_binding b - ON b.user_id = u.id - AND b.shop_id = u.shop_id - AND COALESCE(b.is_delete, 0) = 0 -WHERE COALESCE(u.is_delete, 0) = 0 - AND u.shop_id IS NOT NULL - AND u.shop_id > 0 - AND b.id IS NULL; - -UPDATE t_user_shop_binding b -INNER JOIN t_user u ON u.id = b.user_id -SET b.status = CASE - WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END - ELSE b.status - END, - b.is_delete = COALESCE(b.is_delete, 0), - b.update_time = COALESCE(b.update_time, NOW()) -WHERE b.status IS NULL - OR b.is_delete IS NULL - OR b.update_time IS NULL; - -CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); -CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); -CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); -CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); -CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); - -CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型'''); -CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID'''); -CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径'''); -CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键'''); - -CREATE TABLE IF NOT EXISTS t_order_artist_review -( - id bigint unsigned auto_increment comment '评价任务ID' - primary key, - order_id bigint unsigned not null comment '订单ID', - order_item_id bigint unsigned not null comment '订单项ID', - customer_id bigint unsigned not null comment '下单客户ID', - shop_id bigint unsigned null comment '店铺ID', - artist_id bigint unsigned not null comment '被评价美甲师ID', - product_id bigint unsigned null comment '商品ID', - rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5', - content varchar(1000) null comment '评价文字', - image_file_ids text null comment '评价图片文件ID集合', - status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价', - reminder_message_id bigint unsigned null comment '提醒消息ID', - submitted_at datetime null comment '提交时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单美甲师评价任务表'; - -CREATE TABLE IF NOT EXISTS t_order_artist_change_request -( - id bigint unsigned auto_increment comment '改派申请ID' - primary key, - order_id bigint unsigned not null comment '订单ID', - order_item_id bigint unsigned not null comment '订单项ID', - customer_id bigint unsigned not null comment '下单客户ID', - shop_id bigint unsigned null comment '店铺ID', - product_id bigint unsigned null comment '商品ID', - from_artist_id bigint unsigned not null comment '原美甲师ID', - to_artist_id bigint unsigned not null comment '新美甲师ID', - requester_id bigint unsigned not null comment '申请人ID', - status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED', - reason varchar(500) null comment '申请原因', - reject_reason varchar(500) null comment '拒绝原因', - message_id bigint unsigned null comment '提醒消息ID', - pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度', - approved_time datetime null comment '同意时间', - rejected_time datetime null comment '拒绝时间', - expire_time datetime null comment '过期时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单美甲师改派申请表'; - -CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)'); -CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)'); -CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)'); -CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度'''); -CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)'); -CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)'); -CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)'); - -CREATE TABLE IF NOT EXISTS t_business_event_outbox -( - id bigint unsigned auto_increment comment '事件ID' - primary key, - event_key varchar(160) not null comment '事件幂等键', - event_type varchar(64) not null comment '事件类型', - business_type varchar(64) not null comment '业务类型', - business_id bigint unsigned not null comment '业务ID', - payload_json text null comment '事件载荷', - status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED', - retry_count int unsigned default 0 not null comment '重试次数', - next_retry_time datetime null comment '下次重试时间', - last_error varchar(500) null comment '最近错误', - claimed_at datetime null comment '认领时间', - processed_at datetime null comment '处理完成时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除' -) - comment '业务事件Outbox表'; - -CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)'); -CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)'); - --- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request. --- EXPIRED - --- ======================================== --- vNext operations schema: schedule / reservation / payment / after sale / inventory / campaign / growth --- ======================================== - -CALL sp_add_column_if_not_exists('t_order', 'payment_status', 'varchar(20) NOT NULL DEFAULT ''UNPAID'' COMMENT ''支付状态:UNPAID/PAYING/PAID/REFUNDED'''); -CALL sp_add_column_if_not_exists('t_order', 'pay_amount', 'decimal(10,2) NULL COMMENT ''应支付金额快照'''); -CALL sp_add_column_if_not_exists('t_order', 'paid_amount', 'decimal(10,2) NULL COMMENT ''实付金额快照'''); -CALL sp_add_column_if_not_exists('t_order', 'pay_time', 'datetime NULL COMMENT ''支付完成时间'''); -CALL sp_add_column_if_not_exists('t_order', 'payment_method', 'varchar(32) NULL COMMENT ''支付方式/渠道'''); -CALL sp_add_column_if_not_exists('t_order', 'payment_order_no', 'varchar(64) NULL COMMENT ''最近一次支付单号'''); -CALL sp_add_column_if_not_exists('t_order', 'refund_status', 'varchar(20) NOT NULL DEFAULT ''NONE'' COMMENT ''退款状态:NONE/REFUNDED'''); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_status', '(`payment_status`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_payment_order_no', '(`payment_order_no`)'); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_refund_status', '(`refund_status`, `is_delete`)'); - -CREATE TABLE IF NOT EXISTS t_artist_schedule -( - id bigint unsigned NOT NULL COMMENT '排班ID', - shop_id bigint unsigned NOT NULL COMMENT '店铺ID', - artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', - work_date date NOT NULL COMMENT '工作日期', - start_time time NOT NULL COMMENT '班次开始时间', - end_time time NOT NULL COMMENT '班次结束时间', - slot_minutes int NOT NULL DEFAULT 30 COMMENT '预约粒度分钟数', - capacity int NOT NULL DEFAULT 1 COMMENT '同一时段可预约容量', - status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-可预约,0-停用', - remark varchar(255) NULL COMMENT '排班备注', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '美甲师排班表'; - -CREATE TABLE IF NOT EXISTS t_appointment_reservation -( - id bigint unsigned NOT NULL COMMENT '预约占用ID', - order_id bigint unsigned NOT NULL COMMENT '订单ID', - order_item_id bigint unsigned NOT NULL COMMENT '订单项ID', - shop_id bigint unsigned NOT NULL COMMENT '店铺ID', - artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID', - product_title varchar(200) NULL COMMENT '预约作品标题快照', - appointment_start_time datetime NOT NULL COMMENT '预约开始时间', - appointment_end_time datetime NOT NULL COMMENT '预约结束时间', - status varchar(20) NOT NULL DEFAULT 'LOCKED' COMMENT '状态:LOCKED/PENDING_QUOTE/CONFIRMED/RELEASED/CANCELLED/EXPIRED', - client_request_id varchar(80) NULL COMMENT '客户端幂等请求ID', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '订单预约时段占用表'; - -CREATE TABLE IF NOT EXISTS t_payment_order -( - id bigint unsigned NOT NULL COMMENT '支付单ID', - pay_no varchar(64) NOT NULL COMMENT '支付单号', - order_id bigint unsigned NOT NULL COMMENT '订单ID', - order_no varchar(64) NOT NULL COMMENT '订单号快照', - user_id bigint unsigned NOT NULL COMMENT '支付用户ID', - shop_id bigint unsigned NULL COMMENT '店铺ID', - channel varchar(32) NOT NULL DEFAULT 'MANUAL' COMMENT '支付渠道', - status varchar(20) NOT NULL DEFAULT 'PAYING' COMMENT '状态:PAYING/PAID/CLOSED', - pay_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '应支付金额', - paid_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '实付金额', - pay_time datetime NULL COMMENT '支付完成时间', - expire_time datetime NULL COMMENT '支付单过期时间', - operator_id bigint unsigned NULL COMMENT '手工确认操作人ID', - remark varchar(255) NULL COMMENT '支付备注', - idempotency_key varchar(160) NULL COMMENT '支付幂等键', - raw_payload text NULL COMMENT '支付渠道原始载荷', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '订单支付单表'; - -CREATE TABLE IF NOT EXISTS t_refund_order -( - id bigint unsigned NOT NULL COMMENT '退款单ID', - refund_no varchar(64) NOT NULL COMMENT '退款单号', - after_sale_id bigint unsigned NULL COMMENT '售后单ID', - payment_order_id bigint unsigned NOT NULL COMMENT '支付单ID', - order_id bigint unsigned NOT NULL COMMENT '订单ID', - status varchar(20) NOT NULL DEFAULT 'REFUNDED' COMMENT '状态:PROCESSING/REFUNDED/FAILED', - refund_amount decimal(10, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', - refund_time datetime NULL COMMENT '退款完成时间', - channel varchar(32) NULL COMMENT '退款渠道', - external_refund_no varchar(64) NULL COMMENT '外部退款单号', - fail_reason varchar(255) NULL COMMENT '失败原因或备注', - idempotency_key varchar(160) NULL COMMENT '退款幂等键', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '订单退款单表'; - -CREATE TABLE IF NOT EXISTS t_after_sale -( - id bigint unsigned NOT NULL COMMENT '售后单ID', - after_sale_no varchar(64) NOT NULL COMMENT '售后单号', - order_id bigint unsigned NOT NULL COMMENT '订单ID', - order_item_id bigint unsigned NULL COMMENT '订单项ID', - user_id bigint unsigned NOT NULL COMMENT '申请用户ID', - shop_id bigint unsigned NULL COMMENT '店铺ID', - type varchar(32) NOT NULL COMMENT '售后类型', - reason varchar(1000) NULL COMMENT '申请原因', - refund_amount decimal(10, 2) NULL COMMENT '申请退款金额', - status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '状态:PENDING/APPROVED/REJECTED', - audit_user_id bigint unsigned NULL COMMENT '审核人ID', - audit_reason varchar(500) NULL COMMENT '审核说明', - audit_time datetime NULL COMMENT '审核时间', - refund_order_id bigint unsigned NULL COMMENT '关联退款单ID', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '订单售后申请表'; - -CREATE TABLE IF NOT EXISTS t_after_sale_log -( - id bigint unsigned NOT NULL COMMENT '售后日志ID', - after_sale_id bigint unsigned NOT NULL COMMENT '售后单ID', - action varchar(32) NOT NULL COMMENT '动作:CREATE/APPROVE/REJECT', - from_status varchar(20) NULL COMMENT '变更前状态', - to_status varchar(20) NULL COMMENT '变更后状态', - operator_id bigint unsigned NULL COMMENT '操作人ID', - operator_type varchar(20) NULL COMMENT '操作人类型:USER/ADMIN', - remark varchar(500) NULL COMMENT '备注', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id) -) - COMMENT '订单售后流转日志表'; - -CREATE TABLE IF NOT EXISTS t_inventory_item -( - id bigint unsigned NOT NULL COMMENT '库存物料ID', - shop_id bigint unsigned NOT NULL COMMENT '店铺ID', - category varchar(50) NULL COMMENT '物料分类', - item_name varchar(100) NOT NULL COMMENT '物料名称', - unit varchar(20) NOT NULL DEFAULT '件' COMMENT '计量单位', - stock_quantity decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '当前库存数量', - warning_threshold decimal(12, 3) NOT NULL DEFAULT 0.000 COMMENT '库存预警阈值', - status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1-启用,0-停用', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '门店库存物料表'; - -CREATE TABLE IF NOT EXISTS t_inventory_record -( - id bigint unsigned NOT NULL COMMENT '库存流水ID', - inventory_item_id bigint unsigned NOT NULL COMMENT '库存物料ID', - shop_id bigint unsigned NOT NULL COMMENT '店铺ID', - change_type varchar(32) NOT NULL COMMENT '变动类型:IN/OUT/ADJUST', - change_quantity decimal(12, 3) NOT NULL COMMENT '变动数量', - before_quantity decimal(12, 3) NOT NULL COMMENT '变动前数量', - after_quantity decimal(12, 3) NOT NULL COMMENT '变动后数量', - operator_id bigint unsigned NULL COMMENT '操作人ID', - remark varchar(255) NULL COMMENT '备注', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id) -) - COMMENT '门店库存变动流水表'; - -CREATE TABLE IF NOT EXISTS t_campaign -( - id bigint unsigned NOT NULL COMMENT '营销活动ID', - shop_id bigint unsigned NULL COMMENT '店铺ID,空表示平台活动', - title varchar(120) NOT NULL COMMENT '活动标题', - description varchar(1000) NULL COMMENT '活动说明', - scene varchar(32) NOT NULL DEFAULT 'HOME' COMMENT '活动场景', - product_ids text NULL COMMENT '关联作品ID集合', - coupon_ids text NULL COMMENT '关联优惠券ID集合', - status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0-草稿,1-启用,2-停用', - start_time datetime NULL COMMENT '开始时间', - end_time datetime NULL COMMENT '结束时间', - sort_order int NOT NULL DEFAULT 100 COMMENT '排序', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint unsigned DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (id) -) - COMMENT '营销活动配置表'; - -CREATE TABLE IF NOT EXISTS t_user_growth_record -( - id bigint unsigned NOT NULL COMMENT '成长值记录ID', - user_id bigint unsigned NOT NULL COMMENT '用户ID', - source_type varchar(32) NOT NULL COMMENT '成长来源:REVIEW/REBOOK/ORDER', - source_id bigint unsigned NULL COMMENT '来源业务ID', - growth_value int NOT NULL DEFAULT 0 COMMENT '成长值变化', - remark varchar(255) NULL COMMENT '备注', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id) -) - COMMENT '用户成长值流水表'; - -CALL sp_add_unique_index_if_not_exists('t_artist_schedule', 'uk_t_artist_schedule_slot', '(`shop_id`, `artist_id`, `work_date`, `start_time`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_artist_date', '(`artist_id`, `work_date`, `status`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_artist_schedule', 'idx_t_artist_schedule_shop_date', '(`shop_id`, `work_date`, `status`, `is_delete`)'); -CALL sp_add_column_if_not_exists('t_appointment_reservation', 'client_request_id', 'varchar(80) NULL COMMENT ''客户端幂等请求ID'''); -CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_item', '(`order_item_id`, `is_delete`)'); -CALL sp_add_unique_index_if_not_exists('t_appointment_reservation', 'uk_t_appointment_reservation_client_request', '(`shop_id`, `artist_id`, `client_request_id`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_artist_time', '(`artist_id`, `status`, `appointment_start_time`, `appointment_end_time`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_order', '(`order_id`, `status`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_appointment_reservation', 'idx_t_appointment_reservation_shop_time', '(`shop_id`, `appointment_start_time`, `status`, `is_delete`)'); -CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_pay_no', '(`pay_no`)'); -CALL sp_add_unique_index_if_not_exists('t_payment_order', 'uk_t_payment_order_idempotency', '(`idempotency_key`)'); -CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_order_latest', '(`order_id`, `is_delete`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_user_status', '(`user_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_shop_status', '(`shop_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_payment_order', 'idx_t_payment_order_expire', '(`status`, `expire_time`, `is_delete`)'); -CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_refund_no', '(`refund_no`)'); -CALL sp_add_unique_index_if_not_exists('t_refund_order', 'uk_t_refund_order_idempotency', '(`idempotency_key`)'); -CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_after_sale', '(`after_sale_id`)'); -CALL sp_add_index_if_not_exists('t_refund_order', 'idx_t_refund_order_order_status', '(`order_id`, `status`, `create_time`)'); -CALL sp_add_unique_index_if_not_exists('t_after_sale', 'uk_t_after_sale_no', '(`after_sale_no`)'); -CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_user_status', '(`user_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_shop_status', '(`shop_id`, `status`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_after_sale', 'idx_t_after_sale_order', '(`order_id`, `order_item_id`)'); -CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_after_sale', '(`after_sale_id`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_after_sale_log', 'idx_t_after_sale_log_operator', '(`operator_id`, `create_time`)'); -CALL sp_add_unique_index_if_not_exists('t_inventory_item', 'uk_t_inventory_item_shop_name', '(`shop_id`, `item_name`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_shop_status', '(`shop_id`, `status`, `is_delete`)'); -CALL sp_add_index_if_not_exists('t_inventory_item', 'idx_t_inventory_item_warning', '(`shop_id`, `stock_quantity`, `warning_threshold`)'); -CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_item_time', '(`inventory_item_id`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_inventory_record', 'idx_t_inventory_record_shop_time', '(`shop_id`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_shop_status', '(`shop_id`, `status`, `is_delete`, `sort_order`)'); -CALL sp_add_index_if_not_exists('t_campaign', 'idx_t_campaign_scene_time', '(`scene`, `status`, `start_time`, `end_time`)'); -CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_user_time', '(`user_id`, `create_time`)'); -CALL sp_add_index_if_not_exists('t_user_growth_record', 'idx_t_user_growth_source', '(`source_type`, `source_id`)'); -CALL sp_add_unique_index_if_not_exists('t_user_growth_record', 'uk_t_user_growth_source_once', '(`user_id`, `source_type`, `source_id`)'); - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (313931273555136610, 'schedule:view', '查看排班', '排班管理', '查看美甲师排班和可约时段', NOW(), NOW(), 0), - (313931273555136611, 'schedule:edit', '编辑排班', '排班管理', '维护美甲师班次、休息日和预约容量', NOW(), NOW(), 0), - (313931273555136612, 'payment:view', '查看支付', '支付退款', '查看订单支付状态和支付单', NOW(), NOW(), 0), - (313931273555136613, 'payment:manage', '确认支付', '支付退款', '手工确认支付或处理支付异常', NOW(), NOW(), 0), - (313931273555136614, 'refund:view', '查看退款', '支付退款', '查看退款申请和退款单', NOW(), NOW(), 0), - (313931273555136615, 'refund:manage', '处理退款', '支付退款', '手工确认退款或处理退款异常', NOW(), NOW(), 0), - (313931273555136616, 'after_sale:view', '查看售后', '售后管理', '查看订单售后和客户反馈', NOW(), NOW(), 0), - (313931273555136617, 'after_sale:audit', '处理售后', '售后管理', '审批或驳回售后申请', NOW(), NOW(), 0), - (313931273555136618, 'inventory:view', '查看库存', '库存管理', '查看门店耗材库存和预警', NOW(), NOW(), 0), - (313931273555136619, 'inventory:manage', '调整库存', '库存管理', '维护耗材、入库和库存调整', NOW(), NOW(), 0), - (313931273555136620, 'campaign:view', '查看活动', '活动管理', '查看营销活动和推荐位', NOW(), NOW(), 0), - (313931273555136621, 'campaign:manage', '管理活动', '活动管理', '创建、编辑和发布营销活动', NOW(), NOW(), 0), - (313931273555136622, 'growth:view', '查看成长', '用户成长', '查看用户成长值和会员权益进度', NOW(), NOW(), 0), - (313931273555136623, 'analytics:view', '查看经营分析', '经营分析', '查看订单漏斗和经营指标', NOW(), NOW(), 0), - (313931273555136624, 'performance:view', '查看绩效', '绩效统计', '查看门店和美甲师服务绩效', NOW(), NOW(), 0), - (313931273555136625, 'workbench:view', '查看工作台', '门店工作台', '查看今日订单、售后待办、排班和绩效摘要', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - is_delete = 0, - update_time = NOW(); - -CALL sp_add_column_if_not_exists('t_order', 'customer_remark', 'varchar(500) NULL COMMENT ''用户询价预约备注'''); -CALL sp_add_column_if_not_exists('t_order', 'quote_status', 'varchar(32) NULL COMMENT ''报价状态:CONFIRMING/CONFIRMED/EXPIRED'''); -CALL sp_add_column_if_not_exists('t_order', 'quote_user_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''用户是否确认当前报价'''); -CALL sp_add_column_if_not_exists('t_order', 'quote_shop_confirmed', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''店长是否确认当前报价'''); -CALL sp_add_column_if_not_exists('t_order', 'quote_expire_time', 'datetime NULL COMMENT ''询价报价过期时间'''); -CALL sp_add_column_if_not_exists('t_order', 'quote_confirmed_time', 'datetime NULL COMMENT ''双方确认报价时间'''); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_quote_status_expire', '(`quote_status`, `quote_expire_time`)'); - -CALL sp_add_column_if_not_exists('t_order_item', 'reference_price', 'decimal(10,2) NULL COMMENT ''作品参考价快照'''); -CALL sp_add_column_if_not_exists('t_order_item', 'quoted_price', 'decimal(10,2) NULL COMMENT ''当前报价'''); -CALL sp_add_column_if_not_exists('t_order_item', 'confirmed_price', 'decimal(10,2) NULL COMMENT ''最终确认价'''); - -CREATE TABLE IF NOT EXISTS t_order_quote_message -( - id bigint unsigned auto_increment comment '报价交互消息主键' - primary key, - order_id bigint unsigned not null comment '订单ID', - actor_id bigint unsigned null comment '操作人ID', - actor_type varchar(32) not null comment '操作人类型:USER/SHOP/SYSTEM', - action varchar(32) not null comment '动作:CREATE/SHOP_QUOTE/USER_REPLY/USER_CONFIRM/SHOP_CONFIRM/SYSTEM_CONFIRM/SYSTEM_EXPIRE', - remark varchar(500) null comment '备注', - items_snapshot text null comment '订单项报价快照JSON', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '订单询价报价交互消息表'; - -CALL sp_add_index_if_not_exists('t_order_quote_message', 'idx_order_quote_message_order_id', '(`order_id`, `is_delete`, `create_time`)'); - -CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( - `id` bigint unsigned NOT NULL COMMENT '主键ID', - `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', - `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', - `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', - `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', - `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', - `source_system` varchar(80) NOT NULL DEFAULT 'yuminail' COMMENT 'MessageHub 来源系统编码', - `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', - `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', - `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', - `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', - `remark` varchar(255) NULL COMMENT '备注', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), - KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) -) COMMENT='Fingertip Designer按业务场景投递MessageHub的配置'; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - --- ======================================== --- 首次部署整合区:权限种子 / xiaowang 初始化 / 默认权限分配 --- 来源:2026-03-20_init_admin_permission_template.sql --- ======================================== - -SET NAMES utf8mb4; - -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), - ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), - ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), - ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), - ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), - ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), - ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), - ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), - ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), - ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), - ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), - ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), - ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), - ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), - ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), - ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), - ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), - ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), - ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), - ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), - ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), - ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), - ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), - ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), - ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), - ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), - ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), - ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), - ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), - ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), - ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), - ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), - ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), - ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), - ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), - ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), - ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), - ('comment:view', '查看评论', '评论管理', '查看作品评论与回复', NOW(), NOW(), 0), - ('comment:delete', '删除评论', '评论管理', '删除不合规作品评论', NOW(), NOW(), 0), - ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), - ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), - ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), - ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), - ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), - ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), - ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), - ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), - ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) - , - ('announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), - ('announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), - ('announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - update_time = NOW(), - is_delete = 0; - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), - (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), - (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - update_time = NOW(), - is_delete = 0; - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (910000000008011, 'announcement:view', '查看公告', '公告管理', '查看公告列表与详情', NOW(), NOW(), 0), - (910000000008012, 'announcement:create', '发布公告', '公告管理', '发布公告', NOW(), NOW(), 0), - (910000000008013, 'announcement:delete', '撤回公告', '公告管理', '撤回已发布公告', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - update_time = NOW(), - is_delete = 0; - -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - update_time = NOW(), - is_delete = 0; - -INSERT INTO t_user ( - shop_id, - nickname, - account, - phone_verified, - email_verified, - password, - signature, - level, - type, - vip_id, - create_time, - update_time, - is_delete, - status -) -SELECT - 0, - '系统管理员', - 'xiaowang', - 0, - 0, - '$2a$10$I3mV64NhISqMmm7soSki1.Y36ve.TOINGOrVt0U0kxjO7GtxavE16', - '', - '管理员', - 4, - 0, - NOW(), - NOW(), - 0, - 1 -WHERE NOT EXISTS ( - SELECT 1 - FROM t_user - WHERE account = 'xiaowang' -); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'dashboard:view', - 'user:view', - 'user:create', - 'user:edit', - 'user:disable', - 'user:unbind', - 'user:reset_password', - 'user:delete', - 'user:balance:view', - 'user:balance:manage', - 'user:vip:manage', - 'product:view', - 'product:create', - 'product:edit', - 'product:delete', - 'product:category:manage', - 'shop:view', - 'shop:create', - 'shop:edit', - 'shop:delete', - 'shop:staff:manage', - 'permission:view', - 'permission:create', - 'permission:edit', - 'permission:delete', - 'permission:assign', - 'tag:view', - 'tag:create', - 'tag:edit', - 'tag:delete', - 'tag:assign', - 'coupon:view', - 'coupon:create', - 'coupon:edit', - 'coupon:delete', - 'coupon:assign', - 'comment:view', - 'comment:delete', - 'order:view', - 'order:process', - 'order:artist-change', - 'order:edit', - 'order:delete', - 'nail_artist:view', - 'nail_artist:edit', - 'schedule:view', - 'schedule:edit', - 'payment:view', - 'payment:manage', - 'refund:view', - 'refund:manage', - 'after_sale:view', - 'after_sale:audit', - 'inventory:view', - 'inventory:manage', - 'campaign:view', - 'campaign:manage', - 'growth:view', - 'analytics:view', - 'performance:view', - 'message:view', - 'message:create', - 'message:delete', - 'announcement:view', - 'announcement:create', - 'announcement:delete' - ) -WHERE u.is_delete = 0 - AND u.type = 4 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'dashboard:view', - 'user:view', - 'user:create', - 'user:edit', - 'user:unbind', - 'user:reset_password', - 'user:balance:view', - 'user:balance:manage', - 'user:vip:manage', - 'product:view', - 'product:create', - 'product:edit', - 'product:delete', - 'product:category:manage', - 'shop:view', - 'shop:edit', - 'shop:staff:manage', - 'permission:view', - 'permission:assign', - 'tag:view', - 'tag:create', - 'tag:edit', - 'tag:delete', - 'tag:assign', - 'coupon:view', - 'coupon:create', - 'coupon:edit', - 'coupon:delete', - 'coupon:assign', - 'comment:view', - 'comment:delete', - 'order:view', - 'order:process', - 'order:artist-change', - 'order:edit', - 'order:delete', - 'nail_artist:view', - 'nail_artist:edit', - 'schedule:view', - 'schedule:edit', - 'payment:view', - 'refund:view', - 'after_sale:view', - 'after_sale:audit', - 'inventory:view', - 'inventory:manage', - 'campaign:view', - 'campaign:manage', - 'analytics:view', - 'performance:view', - 'message:view', - 'message:create', - 'announcement:view', - 'announcement:create' - ) -WHERE u.is_delete = 0 - AND u.type = 2 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'user:view', - 'user:balance:view', - 'product:view', - 'shop:view', - 'tag:view', - 'coupon:view', - 'comment:view', - 'order:view', - 'order:process', - 'order:artist-change', - 'schedule:view', - 'after_sale:view', - 'performance:view' - ) -WHERE u.is_delete = 0 - AND u.type = 3 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - - -INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT 910000000009000 + ((u.id % 1000000) * 10) + CASE p.permission_code - WHEN 'message:view' THEN 1 - WHEN 'message:create' THEN 2 - WHEN 'message:delete' THEN 3 - WHEN 'announcement:view' THEN 4 - WHEN 'announcement:create' THEN 5 - WHEN 'announcement:delete' THEN 6 - ELSE 0 - END, - u.id, - p.id, - NOW(), - NOW(), - u.id, - u.id, - 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND ( - (u.type = 4 AND p.permission_code IN ('message:view', 'message:create', 'message:delete', 'announcement:view', 'announcement:create', 'announcement:delete')) - OR (u.type = 2 AND p.permission_code IN ('message:view', 'message:create', 'announcement:view', 'announcement:create')) - ) -WHERE u.is_delete = 0 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ) -ON DUPLICATE KEY UPDATE - is_delete = 0, - update_time = NOW(); - - --- ======================================== --- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT --- 说明: --- 1. 前面的建表与基础配置种子继续沿用旧链路,保证空库初始化过程不受影响 --- 2. 本段将运行时已切到应用层雪花 ID 的主键表统一收口 --- 3. 后续基础配置插入均使用显式主键,与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 --- ======================================== - -DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) -BEGIN - DECLARE v_column_type VARCHAR(128) DEFAULT NULL; - DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; - DECLARE v_extra VARCHAR(128) DEFAULT NULL; - - SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA - INTO v_column_type, v_column_comment, v_extra - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = 'id' - LIMIT 1; - - IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN - SET @alter_sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', - v_column_type, - ' NOT NULL' - ); - - IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN - SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); - END IF; - - PREPARE stmt FROM @alter_sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); -CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); -CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); -CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); -CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); -CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); -CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); -CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); -CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding'); -CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); -CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); -CALL sp_drop_auto_increment_on_id_if_exists('t_order'); -CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); -CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); -CALL sp_drop_auto_increment_on_id_if_exists('t_product'); -CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); -CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); -CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); -CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); -CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); -CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist_group'); -CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); -CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); -CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); -CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); -CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); -CALL sp_drop_auto_increment_on_id_if_exists('t_artist_schedule'); -CALL sp_drop_auto_increment_on_id_if_exists('t_appointment_reservation'); -CALL sp_drop_auto_increment_on_id_if_exists('t_payment_order'); -CALL sp_drop_auto_increment_on_id_if_exists('t_refund_order'); -CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale'); -CALL sp_drop_auto_increment_on_id_if_exists('t_after_sale_log'); -CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_item'); -CALL sp_drop_auto_increment_on_id_if_exists('t_inventory_record'); -CALL sp_drop_auto_increment_on_id_if_exists('t_campaign'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_growth_record'); - -DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; - -CREATE TABLE IF NOT EXISTS t_shop_role ( - id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, - shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', - role_name VARCHAR(100) NOT NULL COMMENT '角色名称', - creator_id BIGINT UNSIGNED NULL COMMENT '创建人', - status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', - remark VARCHAR(255) NULL COMMENT '备注', - sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, - is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' -) COMMENT='店铺自定义角色表'; - -CREATE TABLE IF NOT EXISTS t_shop_role_permission ( - id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, - role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', - permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, - is_delete TINYINT UNSIGNED DEFAULT 0 -) COMMENT='店铺角色权限关联表'; - -CREATE TABLE IF NOT EXISTS t_user_shop_role ( - id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, - user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', - shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', - role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', - status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, - is_delete TINYINT UNSIGNED DEFAULT 0 -) COMMENT='用户店铺角色绑定表'; - -CREATE TABLE IF NOT EXISTS t_user_relation ( - id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, - user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', - shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', - parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', - parent_role_type INT NULL COMMENT '上级身份类型', - source_type VARCHAR(32) NULL COMMENT '来源类型', - creator_id BIGINT UNSIGNED NULL COMMENT '创建人', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, - is_delete TINYINT UNSIGNED DEFAULT 0 -) COMMENT='用户归属关系表'; - -CREATE TABLE IF NOT EXISTS t_user_invite_code ( - id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, - invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', - owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', - shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', - status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', - use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', - expire_time DATETIME NULL COMMENT '过期时间', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, - is_delete TINYINT UNSIGNED DEFAULT 0, - UNIQUE KEY uk_invite_code (invite_code) -) COMMENT='邀请码表'; - --- Indexes are created by the corresponding migration path in environments that need them. --- Existing databases already have these indexes, and MySQL 5.7 does not support CREATE INDEX IF NOT EXISTS. - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (313931273555136490, 'messagehub:config:manage', '管理消息参数', '参数管理', '管理地图 Key、短信 MessageHub 等平台参数', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - is_delete = 0, - update_time = NOW(); - -INSERT INTO t_messagehub_push_config ( - id, - scene_code, - scene_name, - platform, - msg_type, - queue_name, - source_system, - template_code, - channel_id, - send_method, - enabled, - remark, - create_time, - update_time, - is_delete -) -VALUES - (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), - (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), - (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), - (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), - (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), - (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - scene_name = VALUES(scene_name), - platform = VALUES(platform), - msg_type = VALUES(msg_type), - queue_name = VALUES(queue_name), - source_system = VALUES(source_system), - template_code = VALUES(template_code), - channel_id = VALUES(channel_id), - send_method = VALUES(send_method), - enabled = VALUES(enabled), - remark = VALUES(remark), - is_delete = 0, - update_time = NOW(); - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), - (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), - (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), - (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), - (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), - (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - id = VALUES(id), - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - is_delete = 0, - update_time = NOW(); - --- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 -CREATE TABLE IF NOT EXISTS t_legal_agreement ( - id bigint NOT NULL COMMENT '协议ID', - agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', - title varchar(100) NOT NULL COMMENT '协议标题', - version varchar(32) NOT NULL COMMENT '协议版本号', - content longtext NOT NULL COMMENT '协议正文', - status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', - effective_time datetime NULL COMMENT '生效时间', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', - PRIMARY KEY (id), - UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), - KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; - -CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( - id bigint NOT NULL COMMENT '同意记录ID', - user_id bigint NOT NULL COMMENT '用户ID', - agreement_type varchar(32) NOT NULL COMMENT '协议类型', - version varchar(32) NOT NULL COMMENT '同意版本号', - entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', - client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', - ip_address varchar(64) NULL COMMENT '同意IP', - device_id varchar(128) NULL COMMENT '设备ID', - consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id), - UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), - KEY idx_user_agreement_user (user_id, agreement_type) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; - -CREATE TABLE IF NOT EXISTS t_security_audit_log ( - id bigint NOT NULL COMMENT '审计日志ID', - user_id bigint NULL COMMENT '操作用户ID', - account varchar(100) NULL COMMENT '操作账号', - action varchar(64) NOT NULL COMMENT '安全动作', - result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', - reason varchar(255) NULL COMMENT '失败或补充原因', - ip_address varchar(64) NULL COMMENT '请求IP', - device_id varchar(128) NULL COMMENT '设备ID', - operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id), - KEY idx_security_audit_action_time (action, operate_time), - KEY idx_security_audit_account_time (account, operate_time) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; - -CREATE TABLE IF NOT EXISTS t_system_parameter_config ( - id bigint NOT NULL COMMENT '配置ID', - config_group varchar(50) NOT NULL COMMENT '配置分组', - config_key varchar(100) NOT NULL COMMENT '配置键', - config_name varchar(100) NOT NULL COMMENT '配置名称', - config_value varchar(1000) NULL COMMENT '配置值', - enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', - remark varchar(255) NULL COMMENT '备注', - create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', - PRIMARY KEY (id), - UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; - -SET @system_parameter_enabled_missing := ( - SELECT COUNT(1) = 0 - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 't_system_parameter_config' - AND COLUMN_NAME = 'enabled' -); -SET @system_parameter_enabled_sql := IF( - @system_parameter_enabled_missing, - 'ALTER TABLE t_system_parameter_config ADD COLUMN enabled tinyint NOT NULL DEFAULT 1 COMMENT ''是否启用:1启用,0停用'' AFTER config_value', - 'SELECT 1' -); -PREPARE stmt_system_parameter_enabled FROM @system_parameter_enabled_sql; -EXECUTE stmt_system_parameter_enabled; -DEALLOCATE PREPARE stmt_system_parameter_enabled; - -INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) -VALUES - (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 Fingertip Designer 指尖设计师。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), - (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'Fingertip Designer 指尖设计师会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 1, NOW(), NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - title = VALUES(title), - content = VALUES(content), - status = VALUES(status), - effective_time = VALUES(effective_time), - is_delete = 0, - update_time = NOW(); - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (313931273555136601, 'legal_agreement:manage', '管理协议', '协议管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - is_delete = 0, - update_time = NOW(); - -INSERT INTO t_system_parameter_config ( - id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete -) -VALUES - (313931273555139000, 'MAP', 'MAP_PROVIDER', '当前地图渠道', 'TENCENT', 1, 'TENCENT 或 AMAP;决定后台店铺选点默认使用哪个地图渠道', NOW(), NOW(), 0), - (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯 Web Key', '', 0, '用于后台腾讯地图选点和 Web 展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0), - (313931273555139002, 'MAP', 'AMAP_WEB_KEY', '高德 Web Key', '', 0, '用于后台高德地图选点和 Web 展示;Web 端 Key 与小程序 Key 分开维护', NOW(), NOW(), 0), - (313931273555139003, 'MAP', 'AMAP_MINI_KEY', '高德小程序 Key', '', 0, '用于后续小程序端高德 SDK/API 调用;不要与 Web Key 混用', NOW(), NOW(), 0), - (313931273555139004, 'USER', 'DEFAULT_PASSWORD', '后台新增用户默认密码', 'Fingertip@123', 1, '后台新增用户不填写密码时使用;需满足 8-32 位且至少包含数字、小写字母、大写字母、特殊符号中的 3 类', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - config_name = VALUES(config_name), - remark = VALUES(remark), - config_value = IF(t_system_parameter_config.config_key = 'MAP_PROVIDER' AND (t_system_parameter_config.config_value IS NULL OR t_system_parameter_config.config_value = ''), VALUES(config_value), t_system_parameter_config.config_value), - is_delete = 0, - update_time = NOW(); - --- 最小运行初始化:确保 xiaowang 拥有当前权限目录中的全部权限。 -INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT - 313931273556000000 + p.id, - u.id, - p.id, - NOW(), - NOW(), - u.id, - u.id, - 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 -WHERE u.account = 'xiaowang' - AND u.is_delete = 0 - AND u.type = 4 -ON DUPLICATE KEY UPDATE - is_delete = 0, - update_by = VALUES(update_by), - update_time = NOW(); - -INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - (313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - is_delete = 0, - update_time = NOW(); diff --git a/FD-Frontend/src/api/admin.ts b/FD-Frontend/src/api/admin.ts index c99ee63a..a331d2d5 100644 --- a/FD-Frontend/src/api/admin.ts +++ b/FD-Frontend/src/api/admin.ts @@ -367,8 +367,20 @@ export const adminLegalAgreementApi = { export interface ObjectStorageFileVO { id: IdType fileName: string + fileUrl?: string + objectName?: string + primaryProvider?: string + primaryUrl?: string + backupProvider?: string + backupUrl?: string fileSize: number contentType: string + primaryUploadStatus?: number + backupUploadStatus?: number + backupRetryCount?: number + backupLastError?: string + backupUploadedAt?: string + backupLastRetryTime?: string createTime: string } diff --git a/FD-Frontend/src/api/comment.ts b/FD-Frontend/src/api/comment.ts index 436e95a8..dc7a08b2 100644 --- a/FD-Frontend/src/api/comment.ts +++ b/FD-Frontend/src/api/comment.ts @@ -3,6 +3,8 @@ * Call guide: import the named API object, then call the matching method from a Vue page or composable. */ import api from './index' +import type { AxiosProgressEvent } from 'axios' +import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file' import type { IdType } from '@/utils/id' /** @@ -75,6 +77,32 @@ export const commentApi = { } }) as unknown as Promise }, + initImageChunkUpload: (data: ChunkUploadInitRequest) => { + return api.post('/comment/upload-image/init', data) as unknown as Promise + }, + uploadImageChunk: ( + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return api.post('/comment/upload-image/chunk', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + }, + signal: config?.signal, + onUploadProgress: config?.onUploadProgress + }) + }, + completeImageChunkUpload: (uploadId: string) => { + return api.post('/comment/upload-image/complete', { uploadId }) as unknown as Promise + }, + cancelImageChunkUpload: (uploadId: string) => { + return api.delete(`/comment/upload-image/${uploadId}`) + }, /** * `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. diff --git a/FD-Frontend/src/api/error.test.ts b/FD-Frontend/src/api/error.test.ts new file mode 100644 index 00000000..2a0ad844 --- /dev/null +++ b/FD-Frontend/src/api/error.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import type { AxiosError } from 'axios' +import { + getApiResponseMessage, + isPermissionErrorMessage, + isSystemFailureResponse, + isTokenExpiredMessage, + normalizeApiErrorMessage, + shouldShowDedupedError, + updateSystemFailureWindow +} from './error' + +describe('api error helpers', () => { + it('extracts messages and classifies error types', () => { + const error = { message: 'fallback', response: { data: { message: '服务异常' } } } as AxiosError + expect(getApiResponseMessage(error, '请求失败')).toBe('服务异常') + expect(isPermissionErrorMessage('权限不足')).toBe(true) + expect(isPermissionErrorMessage('permission denied')).toBe(true) + expect(isTokenExpiredMessage('登录已过期,请重新登录')).toBe(true) + }) + + it('dedupes prompts by message and time', () => { + expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'a', 40, 50)).toBe(false) + expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'b', 100, 50)).toBe(true) + }) + + it('normalizes garbled booking unavailable messages', () => { + expect(normalizeApiErrorMessage('涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试') + expect(normalizeApiErrorMessage('创建订单失败:涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试') + }) + + it('classifies system failure responses', () => { + expect(isSystemFailureResponse({ response: { status: 500 } } as AxiosError)).toBe(true) + expect(isSystemFailureResponse({ response: { status: 503 } } as AxiosError)).toBe(true) + expect(isSystemFailureResponse({ response: { status: 400 } } as AxiosError)).toBe(false) + expect(isSystemFailureResponse({ response: undefined } as AxiosError)).toBe(true) + }) + + it('tracks failure windows with pruning and threshold', () => { + expect(updateSystemFailureWindow([1_000, 12_000], 40_000, 30_000, 3)).toEqual({ + failureTimes: [12_000, 40_000], + triggered: false + }) + expect(updateSystemFailureWindow([1_000, 12_000, 20_000], 30_000, 30_000, 3)).toEqual({ + failureTimes: [1_000, 12_000, 20_000, 30_000], + triggered: true + }) + }) +}) diff --git a/FD-Frontend/src/api/error.ts b/FD-Frontend/src/api/error.ts new file mode 100644 index 00000000..cdf20ad7 --- /dev/null +++ b/FD-Frontend/src/api/error.ts @@ -0,0 +1,90 @@ +import type { AxiosError } from 'axios' + +export interface ApiResponseBody { + message?: string +} + +export interface ErrorPromptState { + lastErrorTime: number + lastErrorMessage: string +} + +export interface SystemFailureWindowState { + failureTimes: number[] + triggered: boolean +} + +const BOOKING_UNAVAILABLE_MESSAGE = '不可预约,请调整美甲师或预约时间后重试' +const GARbled_BOOKING_UNAVAILABLE_MESSAGES = [ + '涓嶅彲棰勭害' +] + +export const normalizeApiErrorMessage = (messageText: string): string => { + const trimmedMessage = String(messageText || '').trim() + if (!trimmedMessage) return trimmedMessage + if (GARbled_BOOKING_UNAVAILABLE_MESSAGES.some(message => trimmedMessage.includes(message))) { + return BOOKING_UNAVAILABLE_MESSAGE + } + return trimmedMessage +} + +export const getApiResponseMessage = (error: AxiosError, fallbackMessage: string): string => { + const responseData = error.response?.data as ApiResponseBody | undefined + return normalizeApiErrorMessage(responseData?.message || error.message || fallbackMessage) +} + +export const isPermissionErrorMessage = (messageText: string): boolean => + messageText.includes('权限') || messageText.includes('permission') + +export const isTokenExpiredMessage = (messageText: string): boolean => ( + messageText.includes('Token') + || messageText.includes('token') + || messageText.includes('登录态') + || messageText.includes('登录已过期') + || messageText.includes('未登录') + || messageText.includes('认证') + || messageText.includes('重新登录') +) + +export const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null): boolean => + Boolean(requestToken && isTokenExpiredMessage(getApiResponseMessage(error, '请求失败'))) + +export const isSystemFailureResponse = (error: AxiosError): boolean => { + const status = error.response?.status + if (typeof status === 'number') { + return status >= 500 + } + + return !error.response +} + +export const shouldShowDedupedError = ( + state: ErrorPromptState, + messageText: string, + now: number, + debounceTime: number +): boolean => now - state.lastErrorTime > debounceTime || messageText !== state.lastErrorMessage + +export const updateErrorPromptState = ( + messageText: string, + now: number +): ErrorPromptState => ({ + lastErrorTime: now, + lastErrorMessage: messageText +}) + +export const updateSystemFailureWindow = ( + failureTimes: number[], + now: number, + windowMs: number, + threshold: number +): SystemFailureWindowState => { + const nextFailureTimes = failureTimes + .filter(failureTime => now - failureTime <= windowMs) + .concat(now) + + return { + failureTimes: nextFailureTimes, + triggered: nextFailureTimes.length >= threshold + } +} diff --git a/FD-Frontend/src/api/file.ts b/FD-Frontend/src/api/file.ts index eb79cde7..7887f29b 100644 --- a/FD-Frontend/src/api/file.ts +++ b/FD-Frontend/src/api/file.ts @@ -114,6 +114,32 @@ export const fileApi = { cancelAvatarChunkUpload: (uploadId: string) => { return api.delete(`/user/upload-avatar/${uploadId}`) }, + initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => { + return api.post('/user/upload-profile-image/init', data) as unknown as Promise + }, + uploadProfileImageChunk: ( + data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob }, + config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void } + ) => { + const formData = new FormData() + formData.append('uploadId', data.uploadId) + formData.append('chunkIndex', String(data.chunkIndex)) + formData.append('totalChunks', String(data.totalChunks)) + formData.append('chunk', data.chunk) + return api.post('/user/upload-profile-image/chunk', formData, { + headers: { + 'Content-Type': 'multipart/form-data' + }, + signal: config?.signal, + onUploadProgress: config?.onUploadProgress + }) + }, + completeProfileImageChunkUpload: (uploadId: string) => { + return api.post('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise + }, + cancelProfileImageChunkUpload: (uploadId: string) => { + return api.delete(`/user/upload-profile-image/${uploadId}`) + }, /** * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. diff --git a/FD-Frontend/src/api/index.ts b/FD-Frontend/src/api/index.ts index 0962a73a..e61943df 100644 --- a/FD-Frontend/src/api/index.ts +++ b/FD-Frontend/src/api/index.ts @@ -6,12 +6,23 @@ import axios, { AxiosError } from 'axios' import { authApi } from './auth' import { adminAuthApi } from './admin' import { wishlistApi } from './wishlist' -import { message } from 'ant-design-vue' +import { message, Modal } from 'ant-design-vue' import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' import { attachRequestSignature } from '@/utils/request-signature' import { isApiAuthFreePath } from './auth-free-paths' +import { + getApiResponseMessage, + isPermissionErrorMessage, + isSystemFailureResponse, + isTokenExpiredResponse, + normalizeApiErrorMessage, + shouldShowDedupedError, + updateSystemFailureWindow, + updateErrorPromptState, + type ErrorPromptState +} from './error' // 防重复提示标志 let lastErrorTime = 0 @@ -25,6 +36,15 @@ let lastErrorMessage = '' * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误 +const SYSTEM_FAILURE_WINDOW_MS = 30 * 1000 +const SYSTEM_FAILURE_THRESHOLD = 3 +const SYSTEM_FAILURE_MODAL_COOLDOWN_MS = 60 * 1000 +const SYSTEM_FAILURE_MODAL_TITLE = '系统暂不可用' +const SYSTEM_FAILURE_MODAL_CONTENT = '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。' +const SYSTEM_FAILURE_MODAL_OK_TEXT = '我知道了' +let systemFailureTimes: number[] = [] +let systemFailureModalVisible = false +let lastSystemFailureModalTime: number | null = null /** * Purpose: api supports index.ts by holding or executing the api page or API role. @@ -93,39 +113,11 @@ const isCurrentStoredToken = (token: string | null, isAdmin = false) => { return Boolean(token && token === getStoredAccessToken(isAdmin)) } -/** - * Purpose: getResponseMessage supports index.ts by holding or executing the get response message page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ -const getResponseMessage = (error: AxiosError) => { - return (error.response?.data as any)?.message || error.message || '请求失败' -} - -/** - * Purpose: isTokenExpiredResponse supports index.ts by holding or executing the is token expired response 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 isTokenExpiredResponse = (error: AxiosError, requestToken: string | null) => { - const messageText = getResponseMessage(error) - return Boolean( - requestToken - && ( - messageText.includes('Token') - || messageText.includes('token') - || messageText.includes('登录态') - || messageText.includes('登录已过期') - || messageText.includes('未登录') - || messageText.includes('认证') - || messageText.includes('重新登录') - ) - ) -} - /** * Purpose: processQueue supports index.ts by holding or executing the process queue page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ -const processQueue = (error: any, token: string | null = null) => { +const processQueue = (error: unknown, token: string | null = null) => { failedQueue.forEach(prom => { if (error) { prom.reject(error) @@ -139,11 +131,65 @@ const processQueue = (error: any, token: string | null = null) => { // 防抖处理错误提示 const showError = (msg: string) => { const now = Date.now() - if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { - lastErrorTime = now - lastErrorMessage = msg - message.error(msg) + const state: ErrorPromptState = { lastErrorTime, lastErrorMessage } + if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) { + return } + + const nextState = updateErrorPromptState(msg, now) + lastErrorTime = nextState.lastErrorTime + lastErrorMessage = nextState.lastErrorMessage + message.error(msg) +} + +const resetSystemFailureWindow = () => { + systemFailureTimes = [] +} + +const showSystemFailureModal = (now: number) => { + if ( + systemFailureModalVisible + || ( + lastSystemFailureModalTime !== null + && now - lastSystemFailureModalTime < SYSTEM_FAILURE_MODAL_COOLDOWN_MS + ) + ) { + return + } + + systemFailureModalVisible = true + lastSystemFailureModalTime = now + Modal.error({ + title: SYSTEM_FAILURE_MODAL_TITLE, + content: SYSTEM_FAILURE_MODAL_CONTENT, + okText: SYSTEM_FAILURE_MODAL_OK_TEXT, + onOk: () => { + systemFailureModalVisible = false + }, + afterClose: () => { + systemFailureModalVisible = false + } + }) +} + +const recordSystemFailure = (error: AxiosError): boolean => { + if (!isSystemFailureResponse(error)) { + return false + } + + const now = Date.now() + const nextState = updateSystemFailureWindow( + systemFailureTimes, + now, + SYSTEM_FAILURE_WINDOW_MS, + SYSTEM_FAILURE_THRESHOLD + ) + systemFailureTimes = nextState.failureTimes + if (nextState.triggered) { + showSystemFailureModal(now) + return true + } + return false } /** @@ -221,10 +267,11 @@ api.interceptors.request.use( api.interceptors.response.use( response => { + resetSystemFailureWindow() const res = response.data if (res.code !== 200) { - const errorMsg = res.message || '请求失败' - if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) { + const errorMsg = normalizeApiErrorMessage(res.message || '请求失败') + if (!isPermissionErrorMessage(errorMsg)) { showError(errorMsg) } return Promise.reject(new Error(errorMsg)) @@ -245,7 +292,7 @@ api.interceptors.response.use( const isRealTokenExpired = isTokenExpiredResponse(error, requestToken) if (!isRealTokenExpired) { - showError(getResponseMessage(error)) + showError(getApiResponseMessage(error, '请求失败')) return Promise.reject(error) } @@ -319,8 +366,10 @@ api.interceptors.response.use( return Promise.reject(error) } } else if (error.response?.status !== 403) { // 403权限不足不提示 - const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败' - showError(errorMsg) + const errorMsg = getApiResponseMessage(error, '请求失败') + if (!recordSystemFailure(error)) { + showError(errorMsg) + } } return Promise.reject(error) } diff --git a/FD-Frontend/src/config/admin-navigation.test.ts b/FD-Frontend/src/config/admin-navigation.test.ts new file mode 100644 index 00000000..15d62791 --- /dev/null +++ b/FD-Frontend/src/config/admin-navigation.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { adminNavigationItems, adminPermissionRouteMap, findAdminNavigationItemByPath, ADMIN_DASHBOARD_PATH } from './admin-navigation' + +describe('admin-navigation', () => { + it('keeps dashboard landing and permission routes aligned', () => { + expect(ADMIN_DASHBOARD_PATH).toBe('/admin/dashboard') + expect(findAdminNavigationItemByPath('/admin/products')?.label).toBe('作品管理') + expect(adminPermissionRouteMap.some(item => item.code === 'shop:view' && item.path === '/admin/shops')).toBe(true) + expect(adminNavigationItems[0]?.path).toBe('/admin') + }) +}) diff --git a/FD-Frontend/src/config/admin-navigation.ts b/FD-Frontend/src/config/admin-navigation.ts new file mode 100644 index 00000000..e29e39d2 --- /dev/null +++ b/FD-Frontend/src/config/admin-navigation.ts @@ -0,0 +1,56 @@ +export type AdminNavIconKey = + | 'home' + | 'dashboard' + | 'user' + | 'shop' + | 'gift' + | 'message' + | 'security' + | 'tag' + | 'shopping' + | 'calendar' + | 'tool' + | 'team' + +export interface AdminNavigationItem { + path: string + iconKey: AdminNavIconKey + label: string + permissionCode: string +} + +export const ADMIN_HOME_PATH = '/admin' +export const ADMIN_DASHBOARD_PATH = '/admin/dashboard' + +export const adminNavigationItems: AdminNavigationItem[] = [ + { path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' }, + { path: ADMIN_DASHBOARD_PATH, iconKey: 'dashboard', label: '仪表盘', permissionCode: 'dashboard:view' }, + { path: '/admin/users', iconKey: 'user', label: '用户管理', permissionCode: 'user:view' }, + { path: '/admin/products', iconKey: 'shop', label: '作品管理', permissionCode: 'product:view' }, + { path: '/admin/coupons', iconKey: 'gift', label: '优惠券管理', permissionCode: 'coupon:view' }, + { path: '/admin/comments', iconKey: 'message', label: '评论管理', permissionCode: 'comment:view' }, + { path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' }, + { path: '/admin/permissions', iconKey: 'security', label: '权限管理', permissionCode: 'permission:view' }, + { path: '/admin/tags', iconKey: 'tag', label: '标签管理', permissionCode: 'tag:view' }, + { path: '/admin/orders', iconKey: 'shopping', label: '订单管理', permissionCode: 'order:view' }, + { path: '/admin/schedules', iconKey: 'calendar', label: '排班管理', permissionCode: 'schedule:view' }, + { path: '/admin/after-sales', iconKey: 'message', label: '售后处理', permissionCode: 'after_sale:view' }, + { path: '/admin/inventory', iconKey: 'tool', label: '库存管理', permissionCode: 'inventory:view' }, + { path: '/admin/campaigns', iconKey: 'gift', label: '活动管理', permissionCode: 'campaign:view' }, + { path: '/admin/nail-artists', iconKey: 'team', label: '美甲师管理', permissionCode: 'nail_artist:view' }, + { path: '/admin/messages', iconKey: 'message', label: '消息发布', permissionCode: 'message:view' }, + { path: '/admin/announcements', iconKey: 'message', label: '公告管理', permissionCode: 'announcement:view' }, + { path: '/admin/vip-recharge-plans', iconKey: 'gift', label: 'VIP充值配置', permissionCode: 'user:vip:manage' }, + { path: '/admin/messagehub-push-configs', iconKey: 'message', label: '参数管理', permissionCode: 'messagehub:config:manage' }, + { path: '/admin/legal-agreements', iconKey: 'security', label: '协议管理', permissionCode: 'legal_agreement:manage' } +] + +export const adminPermissionRouteMap = adminNavigationItems + .filter(item => item.permissionCode) + .map(item => ({ + code: item.permissionCode, + path: item.path + })) + +export const findAdminNavigationItemByPath = (path: string) => + adminNavigationItems.find(item => item.path === path) diff --git a/FD-Frontend/src/utils/admin-auth-bootstrap.ts b/FD-Frontend/src/utils/admin-auth-bootstrap.ts index b201f6ba..524b832d 100644 --- a/FD-Frontend/src/utils/admin-auth-bootstrap.ts +++ b/FD-Frontend/src/utils/admin-auth-bootstrap.ts @@ -5,6 +5,7 @@ import { isBootstrapAdminUser, loadCachedAdminUserInfo, } from '@/utils/admin-session' +import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation' import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' import { clearStoredPermissions, @@ -12,7 +13,6 @@ import { getStoredUserPermissions, } from '@/utils/permission' -const ADMIN_DASHBOARD_PATH = '/admin/dashboard' /** * Purpose: AuthBootstrapState supports admin-auth-bootstrap.ts by holding or executing the auth bootstrap state page or API role. @@ -27,23 +27,6 @@ export type AuthBootstrapState = 'pending' | 'ready' | 'invalid' const adminBootstrapState = ref('pending') let bootstrapPromise: Promise | null = null -const ADMIN_PERMISSION_ROUTE_MAP: Array<{ code: string; path: string }> = [ - { code: 'dashboard:view', path: '/admin/dashboard' }, - { code: 'shop:view', path: '/admin/shops' }, - { code: 'product:view', path: '/admin/products' }, - { code: 'coupon:view', path: '/admin/coupons' }, - { code: 'comment:view', path: '/admin/comments' }, - { code: 'order:view', path: '/admin/orders' }, - { code: 'user:view', path: '/admin/users' }, - { code: 'tag:view', path: '/admin/tags' }, - { code: 'permission:view', path: '/admin/permissions' }, - { code: 'nail_artist:view', path: '/admin/nail-artists' }, - { code: 'message:view', path: '/admin/messages' }, - { code: 'announcement:view', path: '/admin/announcements' }, - { code: 'user:vip:manage', path: '/admin/vip-recharge-plans' }, - { code: 'messagehub:config:manage', path: '/admin/messagehub-push-configs' }, - { code: 'legal_agreement:manage', path: '/admin/legal-agreements' }, -] /** * Purpose: useAdminBootstrapState supports admin-auth-bootstrap.ts by holding or executing the use admin bootstrap state page or API role. @@ -116,7 +99,7 @@ export const resolveAdminLandingPath = () => { return ADMIN_DASHBOARD_PATH } - const matchedRoute = ADMIN_PERMISSION_ROUTE_MAP.find(item => snapshot.permissions.includes(item.code)) + const matchedRoute = adminPermissionRouteMap.find(item => snapshot.permissions.includes(item.code)) return matchedRoute?.path || '/admin' } diff --git a/FD-Frontend/src/utils/admin-image-assets.test.ts b/FD-Frontend/src/utils/admin-image-assets.test.ts new file mode 100644 index 00000000..797c76e4 --- /dev/null +++ b/FD-Frontend/src/utils/admin-image-assets.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from 'vitest' +import { + buildAdminUploadFileList, + buildSignedImageUrlMap, + getRecordImageUrls, + resolveSignedImageUrls +} from './admin-image-assets' + +vi.mock('@/utils/signed-image-cache', () => ({ + parseImageFileIds: (value?: string | null) => String(value || '').split(',').map(id => id.trim()).filter(Boolean), + getCachedSignedImageUrl: async (fileId: string | number | null | undefined, fallback = '') => + fileId ? `signed-${fileId}` : fallback, + getCachedSignedImageUrls: async (fileIds: Array, fallback = '') => { + const urls = fileIds.filter(Boolean).map(fileId => `signed-${fileId}`) + return urls.length ? urls : (fallback ? [fallback] : []) + } +})) + +describe('admin-image-assets', () => { + it('resolves comma separated image ids with fallback policy', async () => { + await expect(resolveSignedImageUrls('1, 2,,3', 'fallback.png', true)).resolves.toEqual([ + 'signed-1', + 'signed-2', + 'signed-3' + ]) + await expect(resolveSignedImageUrls('', 'fallback.png', true)).resolves.toEqual(['fallback.png']) + await expect(resolveSignedImageUrls('', 'fallback.png', false)).resolves.toEqual([]) + }) + + it('builds image url maps and respects cancellation', async () => { + await expect(buildSignedImageUrlMap( + [{ id: 7, imageFileIds: '10,11' }], + 'imageFileIds', + 'fallback.png', + true, + () => false + )).resolves.toEqual({ 7: ['signed-10', 'signed-11'] }) + + await expect(buildSignedImageUrlMap( + [{ id: 7, imageFileIds: '10,11' }], + 'imageFileIds', + 'fallback.png', + true, + () => true + )).resolves.toBeNull() + }) + + it('returns mapped record images or fallback images', () => { + expect(getRecordImageUrls({ id: 1 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['a.png']) + expect(getRecordImageUrls({ id: 2 }, { 1: ['a.png'] }, ['fallback.png'])).toEqual(['fallback.png']) + }) + + it('builds upload file list from ids', async () => { + await expect(buildAdminUploadFileList(['8', ' 9 '], '图片', 'fallback.png')).resolves.toEqual([ + { uid: '8', fileId: '8', name: '图片1', status: 'done', url: 'signed-8' }, + { uid: '9', fileId: '9', name: '图片2', status: 'done', url: 'signed-9' } + ]) + }) +}) diff --git a/FD-Frontend/src/utils/admin-image-assets.ts b/FD-Frontend/src/utils/admin-image-assets.ts new file mode 100644 index 00000000..7d92bf09 --- /dev/null +++ b/FD-Frontend/src/utils/admin-image-assets.ts @@ -0,0 +1,104 @@ +import { + getCachedSignedImageUrl, + getCachedSignedImageUrls, + parseImageFileIds, + refreshCachedSignedImageUrl +} from '@/utils/signed-image-cache' +import type { IdType } from '@/utils/id' + +export interface AdminUploadFileItem { + uid: string + fileId: string + name: string + status: 'done' + url: string +} + +export type SignedImageRecord = { + id?: IdType + imageFileIds?: string + coverImageFileId?: string +} + +export type ImageFieldName = 'imageFileIds' | 'coverImageFileId' + +export const resolveSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback: string +): Promise => getCachedSignedImageUrl(fileId, fallback, 'admin') + +export const refreshSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback: string +): Promise => refreshCachedSignedImageUrl(fileId, fallback, 'admin') + +export const resolveSignedImageUrls = async ( + fileIdsValue: string | null | undefined, + fallback: string, + emptyFallback: boolean +): Promise => { + const fileIds = parseImageFileIds(fileIdsValue) + if (!fileIds.length) { + return emptyFallback ? [fallback] : [] + } + return getCachedSignedImageUrls(fileIds, fallback, 'admin') +} + +export const buildSignedImageUrlMap = async ( + records: TRecord[], + fieldName: ImageFieldName, + fallback: string, + emptyFallback: boolean, + isCancelled: () => boolean +): Promise | null> => { + const nextImageUrls: Record = {} + + for (const record of records) { + if (isCancelled()) { + return null + } + if (record.id === undefined || record.id === null) { + continue + } + + nextImageUrls[String(record.id)] = await resolveSignedImageUrls(record[fieldName], fallback, emptyFallback) + } + + return nextImageUrls +} + +export const getRecordImageUrls = ( + record: TRecord, + imageUrlMap: Record, + fallbackImages: string[] +): string[] => { + if (record.id === undefined || record.id === null) { + return fallbackImages + } + return imageUrlMap[String(record.id)] || fallbackImages +} + +export const buildAdminUploadFileList = async ( + fileIds: string[], + fileNamePrefix: string, + fallback: string +): Promise => { + const fileList: AdminUploadFileItem[] = [] + + for (const [index, fileId] of fileIds.entries()) { + const normalizedFileId = fileId.trim() + if (!normalizedFileId) { + continue + } + const url = await resolveSignedImageUrl(normalizedFileId, fallback) + fileList.push({ + uid: normalizedFileId, + fileId: normalizedFileId, + name: `${fileNamePrefix}${index + 1}`, + status: 'done', + url + }) + } + + return fileList +} diff --git a/FD-Frontend/src/utils/admin-table.test.ts b/FD-Frontend/src/utils/admin-table.test.ts new file mode 100644 index 00000000..380a01eb --- /dev/null +++ b/FD-Frontend/src/utils/admin-table.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { applyAdminTablePaginationChange, createAdminPagination } from './admin-table' + +describe('admin-table', () => { + it('creates default pagination state', () => { + expect(createAdminPagination().current).toBe(1) + expect(createAdminPagination().pageSize).toBe(10) + }) + + it('applies pagination changes', () => { + const pagination = createAdminPagination() + const nextPagination = applyAdminTablePaginationChange(pagination, { current: 3, pageSize: 20 }) + expect(nextPagination.current).toBe(3) + expect(nextPagination.pageSize).toBe(20) + expect(pagination.current).toBe(1) + }) +}) diff --git a/FD-Frontend/src/utils/admin-table.ts b/FD-Frontend/src/utils/admin-table.ts new file mode 100644 index 00000000..1bee7309 --- /dev/null +++ b/FD-Frontend/src/utils/admin-table.ts @@ -0,0 +1,35 @@ +export interface AdminPaginationState { + current: number + pageSize: number + total: number + showSizeChanger: boolean + showQuickJumper: boolean + showTotal: (total: number) => string +} + +export interface AdminTablePaginationChange { + current?: number + pageSize?: number +} + +export interface AdminPaginationPageChange { + current: number + pageSize: number +} + +export const createAdminPagination = (): AdminPaginationState => ({ + current: 1, + pageSize: 10, + total: 0, + showSizeChanger: true, + showQuickJumper: true, + showTotal: (total: number) => `共 ${total} 条` +}) + +export const applyAdminTablePaginationChange = ( + pagination: AdminPaginationState, + change: AdminTablePaginationChange +): AdminPaginationPageChange => ({ + current: change.current || pagination.current, + pageSize: change.pageSize || pagination.pageSize +}) diff --git a/FD-Frontend/src/utils/admin-upload-file.test.ts b/FD-Frontend/src/utils/admin-upload-file.test.ts new file mode 100644 index 00000000..7e0615e3 --- /dev/null +++ b/FD-Frontend/src/utils/admin-upload-file.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest' +import { getUploadResponse, resolveUploadedFileId } from './admin-upload-file' + +describe('admin-upload-file', () => { + it('resolves uploaded file id from response or file shape', () => { + expect(resolveUploadedFileId({ response: { id: 7 } })).toBe('7') + expect(resolveUploadedFileId({ fileId: '8' })).toBe('8') + expect(resolveUploadedFileId({ uid: '9' })).toBe('9') + expect(getUploadResponse(null)).toBeNull() + }) +}) diff --git a/FD-Frontend/src/utils/admin-upload-file.ts b/FD-Frontend/src/utils/admin-upload-file.ts new file mode 100644 index 00000000..8c00fe4f --- /dev/null +++ b/FD-Frontend/src/utils/admin-upload-file.ts @@ -0,0 +1,49 @@ +export interface AdminUploadResponseData { + id?: string | number + fileId?: string | number +} + +export interface AdminUploadResponse { + id?: string | number + fileId?: string | number + data?: AdminUploadResponseData +} + +export interface AdminUploadFileLike { + uid?: string | number + url?: string + thumbUrl?: string + fileId?: string | number + response?: AdminUploadResponse +} + +export interface AdminUploadTaskFile extends File { + uid: string +} + +export const getUploadResponse = (file: AdminUploadFileLike | null | undefined): AdminUploadResponse | null => { + if (!file || typeof file !== 'object') { + return null + } + return file.response || null +} + +export const resolveUploadedFileId = (file: AdminUploadFileLike | null | undefined): string => { + const response = getUploadResponse(file) + const responseId = response?.id ?? response?.data?.id ?? response?.fileId ?? response?.data?.fileId ?? file?.fileId + if (responseId !== undefined && responseId !== null && responseId !== '') { + return String(responseId) + } + + const fileUid = String(file?.uid || '') + if (/^\d+$/.test(fileUid)) { + return fileUid + } + + const fileUrl = String(file?.url || '') + if (/^\d+$/.test(fileUrl)) { + return fileUrl + } + + return '' +} diff --git a/FD-Frontend/src/utils/chunk-upload.test.ts b/FD-Frontend/src/utils/chunk-upload.test.ts new file mode 100644 index 00000000..f91fdffc --- /dev/null +++ b/FD-Frontend/src/utils/chunk-upload.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from 'vitest' +import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload' + +const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', { + type: 'image/png', + lastModified: 1 +}) + +describe('chunk-upload', () => { + it('uploads chunks with the requested concurrency', async () => { + const releaseCallbacks: Array<() => void> = [] + let activeUploads = 0 + let maxActiveUploads = 0 + + const api: ChunkUploadApi = { + initUpload: vi.fn().mockResolvedValue({ + uploadId: 'upload-1', + chunkSize: 2, + totalChunks: 4, + uploadedChunks: [] + }), + uploadChunk: vi.fn((_payload, config) => { + activeUploads += 1 + maxActiveUploads = Math.max(maxActiveUploads, activeUploads) + config?.onUploadProgress?.({ loaded: 2, total: 2 } as never) + return new Promise(resolve => { + releaseCallbacks.push(() => { + activeUploads -= 1 + resolve(true) + }) + }) + }), + completeUpload: vi.fn().mockResolvedValue('done'), + cancelUpload: vi.fn() + } + + const task = createChunkUploadTask({ + file: createFile(8), + scene: 'test-image', + concurrency: 3, + api + }) + + await vi.waitFor(() => expect(maxActiveUploads).toBe(3)) + while (releaseCallbacks.length) { + releaseCallbacks.shift()?.() + await Promise.resolve() + } + + await expect(task.promise).resolves.toMatchObject({ + response: 'done', + uploadId: 'upload-1' + }) + expect(api.uploadChunk).toHaveBeenCalledTimes(4) + expect(api.completeUpload).toHaveBeenCalledWith('upload-1') + }) + + it('skips already uploaded chunks', async () => { + const api: ChunkUploadApi = { + initUpload: vi.fn().mockResolvedValue({ + uploadId: 'upload-2', + chunkSize: 2, + totalChunks: 3, + uploadedChunks: [0, 2] + }), + uploadChunk: vi.fn().mockResolvedValue(true), + completeUpload: vi.fn().mockResolvedValue('done') + } + + const task = createChunkUploadTask({ + file: createFile(6), + scene: 'test-image', + concurrency: 3, + api + }) + + await expect(task.promise).resolves.toMatchObject({ response: 'done' }) + expect(api.uploadChunk).toHaveBeenCalledTimes(1) + expect(api.uploadChunk).toHaveBeenCalledWith( + expect.objectContaining({ chunkIndex: 1 }), + expect.any(Object) + ) + }) +}) diff --git a/FD-Frontend/src/utils/chunk-upload.ts b/FD-Frontend/src/utils/chunk-upload.ts index 88537572..1cfc3bf1 100644 --- a/FD-Frontend/src/utils/chunk-upload.ts +++ b/FD-Frontend/src/utils/chunk-upload.ts @@ -1,9 +1,5 @@ import type { AxiosProgressEvent } from 'axios' -/** - * Purpose: ChunkUploadSession supports chunk-upload.ts by holding or executing the chunk upload session page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadSession { uploadId: string chunkSize: number @@ -11,10 +7,6 @@ export interface ChunkUploadSession { uploadedChunks: number[] } -/** - * Purpose: ChunkUploadInitRequest supports chunk-upload.ts by holding or executing the chunk upload init request page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadInitRequest { fileName: string fileSize: number @@ -23,10 +15,6 @@ export interface ChunkUploadInitRequest { scene: string } -/** - * Purpose: ChunkUploadApi supports chunk-upload.ts by holding or executing the chunk upload api page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadApi { initUpload: (payload: ChunkUploadInitRequest) => Promise uploadChunk: ( @@ -37,42 +25,27 @@ export interface ChunkUploadApi { cancelUpload?: (uploadId: string) => Promise } -/** - * Purpose: ChunkUploadOptions supports chunk-upload.ts by holding or executing the chunk upload options page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadOptions { file: File scene: string api: ChunkUploadApi + concurrency: number preprocessFile?: (file: File) => Promise onProgress?: (percent: number) => void } -/** - * Purpose: ChunkUploadResult supports chunk-upload.ts by holding or executing the chunk upload result page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadResult { response: TResponse uploadId: string processedFile: File } -/** - * Purpose: ChunkUploadTask supports chunk-upload.ts by holding or executing the chunk upload task page or API role. - * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. - */ export interface ChunkUploadTask { promise: Promise> cancel: () => void getUploadId: () => string } -/** - * Purpose: computeFileFingerprint supports chunk-upload.ts by holding or executing the compute file fingerprint 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 computeFileFingerprint = async (file: File) => { const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}` if (!window.crypto?.subtle) { @@ -84,32 +57,37 @@ const computeFileFingerprint = async (file: File) => { return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('') } -/** - * Purpose: getChunkSizeByIndex supports chunk-upload.ts by holding or executing the get chunk size by index 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 getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => { const start = chunkIndex * chunkSize const end = Math.min(start + chunkSize, fileSize) return Math.max(end - start, 0) } -/** - * Purpose: calculateUploadedBytes supports chunk-upload.ts by holding or executing the calculate uploaded bytes 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 calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => { - return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0) +const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => + uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0) + +const normalizeConcurrency = (concurrency: number) => { + if (!Number.isFinite(concurrency) || concurrency < 1) { + return 1 + } + return Math.floor(concurrency) +} + +const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set) => { + const chunkIndexes: number[] = [] + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + if (!uploadedChunkSet.has(chunkIndex)) { + chunkIndexes.push(chunkIndex) + } + } + return chunkIndexes } -/** - * Purpose: createChunkUploadTask supports chunk-upload.ts by holding or executing the create chunk upload task page or API role. - * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. - */ export const createChunkUploadTask = (options: ChunkUploadOptions): ChunkUploadTask => { const abortController = new AbortController() let uploadId = '' let cancelled = false + const cleanupCancelledSession = async () => { if (uploadId && options.api.cancelUpload) { await options.api.cancelUpload(uploadId).catch(() => undefined) @@ -135,16 +113,29 @@ export const createChunkUploadTask = (options: ChunkUploadOptions() + const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet) + const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1)) + + const emitProgress = (limit: number) => { + const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0) + const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100 + options.onProgress?.(Math.min(percent, limit)) + } + options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100)) - for (let chunkIndex = 0; chunkIndex < session.totalChunks; chunkIndex++) { + let nextChunkIndexCursor = 0 + const uploadNextChunk = async (): Promise => { + const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor] + nextChunkIndexCursor += 1 + if (chunkIndex === undefined) { + return + } if (cancelled) { await cleanupCancelledSession() throw new Error('上传已取消') } - if (uploadedChunkSet.has(chunkIndex)) { - continue - } const start = chunkIndex * session.chunkSize const end = Math.min(start + session.chunkSize, processedFile.size) @@ -162,17 +153,22 @@ export const createChunkUploadTask = (options: ChunkUploadOptions { const loaded = Math.min(event.loaded || 0, chunkBytes) - const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100 - options.onProgress?.(Math.min(percent, 99.9)) + uploadingChunkBytes.set(chunkIndex, loaded) + emitProgress(99.9) } } ) uploadedChunkSet.add(chunkIndex) uploadedBytes += chunkBytes + uploadingChunkBytes.delete(chunkIndex) options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9)) + + await uploadNextChunk() } + await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk())) + if (cancelled) { await cleanupCancelledSession() throw new Error('上传已取消') diff --git a/FD-Frontend/src/utils/public-image-assets.test.ts b/FD-Frontend/src/utils/public-image-assets.test.ts new file mode 100644 index 00000000..cbb646f5 --- /dev/null +++ b/FD-Frontend/src/utils/public-image-assets.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const publicGetSignedUrl = vi.fn() + +vi.mock('@/api/file', () => ({ + fileApi: { + getSignedUrl: publicGetSignedUrl + } +})) + +vi.mock('@/api/admin', () => ({ + adminFileApi: { + getSignedUrl: vi.fn() + } +})) + +describe('public-image-assets', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' }) + }) + + it('prefers direct image urls over signing file ids', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({ + imageUrls: ['http://img.yunail.art/direct.jpg'], + imageFileIds: '42' + }, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg']) + expect(publicGetSignedUrl).not.toHaveBeenCalled() + }) + + it('normalizes direct image urls without scheme', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({ + imageUrls: ['img.yunail.art/direct.jpg?token=1'] + }, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1']) + }) + + it('signs public file ids when direct urls are missing', async () => { + const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets') + + expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png']) + await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([ + 'http://img.yunail.art/signed.jpg?token=1' + ]) + expect(publicGetSignedUrl).toHaveBeenCalledWith('42') + }) + + it('extracts legacy file ids from old file urls', async () => { + const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets') + + const record = { + imageUrl: '/api/file/get/325517232303947776', + imageFileIds: '325517232303947776,325517220106911744' + } + + expect(getDirectPublicImageUrls(record)).toEqual([]) + expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744']) + }) + + it('uses fallback when no image source is available', async () => { + const { resolvePublicImageUrls } = await import('./public-image-assets') + + await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png']) + }) +}) diff --git a/FD-Frontend/src/utils/public-image-assets.ts b/FD-Frontend/src/utils/public-image-assets.ts new file mode 100644 index 00000000..d69b0880 --- /dev/null +++ b/FD-Frontend/src/utils/public-image-assets.ts @@ -0,0 +1,97 @@ +import { DEFAULT_PRODUCT_IMAGE } from '@/constants' +import type { IdType } from '@/utils/id' +import { + extractLegacyFileId, + getCachedSignedImageUrl, + getCachedSignedImageUrlSync, + parseImageFileIds, + refreshCachedSignedImageUrl +} from '@/utils/signed-image-cache' + +export interface PublicImageRecord { + imageUrls?: string[] | string | null + imageFileIds?: string[] | string | null + coverImageUrl?: string | null + coverImageUrls?: string[] | string | null + coverImageFileId?: string[] | string | null + imageUrl?: string | null +} + +const normalizePublicUrl = (value: unknown): string => { + const source = String(value || '').replace(/[`]/g, '').trim() + if (!source) return '' + if (/^\/?api\/file\/get\/\d+/i.test(source)) return '' + if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) { + return source.startsWith('//') ? `http:${source}` : source + } + if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) { + return `http://${source}` + } + return '' +} + +const normalizeUrlList = (value: unknown): string[] => { + const rawValues = Array.isArray(value) ? value : String(value || '').split(',') + return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean))) +} + +export const getPublicImageFileIds = (record: PublicImageRecord): string[] => { + const rawFileIds = [ + ...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))), + ...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))), + extractLegacyFileId(record.coverImageUrl), + extractLegacyFileId(record.imageUrl) + ] + return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean))) +} + +export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => { + return Array.from(new Set([ + ...normalizeUrlList(record.coverImageUrls), + ...normalizeUrlList(record.coverImageUrl), + ...normalizeUrlList(record.imageUrls), + ...normalizeUrlList(record.imageUrl) + ])) +} + +export const resolvePublicImageUrlsSync = ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): string[] => { + const directUrls = getDirectPublicImageUrls(record) + if (directUrls.length) return directUrls + + const cachedUrls = getPublicImageFileIds(record) + .map(fileId => getCachedSignedImageUrlSync(fileId, 'public')) + .filter(Boolean) + if (cachedUrls.length) return cachedUrls + + return fallback ? [fallback] : [] +} + +export const resolvePublicImageUrls = async ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => { + const directUrls = getDirectPublicImageUrls(record) + if (directUrls.length) return directUrls + + const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public'))) + const usableUrls = signedUrls.filter(Boolean) + if (usableUrls.length) return usableUrls + + return fallback ? [fallback] : [] +} + +export const resolvePublicImageUrl = async ( + record: PublicImageRecord, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => { + const urls = await resolvePublicImageUrls(record, fallback) + return urls[0] || fallback +} + +export const refreshPublicImageUrl = async ( + fileId: IdType | null | undefined, + fallback = DEFAULT_PRODUCT_IMAGE +): Promise => refreshCachedSignedImageUrl(fileId, fallback, 'public') diff --git a/FD-Frontend/src/utils/signed-image-cache.test.ts b/FD-Frontend/src/utils/signed-image-cache.test.ts new file mode 100644 index 00000000..57fb2a8e --- /dev/null +++ b/FD-Frontend/src/utils/signed-image-cache.test.ts @@ -0,0 +1,70 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const publicGetSignedUrl = vi.fn() +const adminGetSignedUrl = vi.fn() + +vi.mock('@/api/file', () => ({ + fileApi: { + getSignedUrl: publicGetSignedUrl + } +})) + +vi.mock('@/api/admin', () => ({ + adminFileApi: { + getSignedUrl: adminGetSignedUrl + } +})) + +describe('signed-image-cache', () => { + beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + publicGetSignedUrl.mockResolvedValue({ data: 'https://public.test/image.jpg' }) + adminGetSignedUrl.mockResolvedValue('https://admin.test/image.jpg') + }) + + it('keeps public and admin signed url cache entries isolated', async () => { + const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache') + + await expect(getCachedSignedImageUrl('42', '', 'public')).resolves.toBe('https://public.test/image.jpg') + await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/image.jpg') + + expect(publicGetSignedUrl).toHaveBeenCalledTimes(1) + expect(adminGetSignedUrl).toHaveBeenCalledTimes(1) + expect(getCachedSignedImageUrlSync('42', 'public')).toBe('https://public.test/image.jpg') + expect(getCachedSignedImageUrlSync('42', 'admin')).toBe('https://admin.test/image.jpg') + }) + + it('uses fallback when file id is empty or signing fails', async () => { + const { getCachedSignedImageUrl } = await import('./signed-image-cache') + + await expect(getCachedSignedImageUrl('', 'fallback.png', 'public')).resolves.toBe('fallback.png') + publicGetSignedUrl.mockRejectedValueOnce(new Error('sign failed')) + await expect(getCachedSignedImageUrl('99', 'fallback.png', 'public')).resolves.toBe('fallback.png') + }) + + it('normalizes signed image urls without scheme', async () => { + const { getCachedSignedImageUrl, getCachedSignedImageUrlSync } = await import('./signed-image-cache') + + adminGetSignedUrl.mockResolvedValueOnce('img.yunail.art/325517220106911744.jpg?e=1&token=test') + + await expect(getCachedSignedImageUrl('325517232303947776', '', 'admin')).resolves.toBe( + 'http://img.yunail.art/325517220106911744.jpg?e=1&token=test' + ) + expect(getCachedSignedImageUrlSync('325517232303947776', 'admin')).toBe( + 'http://img.yunail.art/325517220106911744.jpg?e=1&token=test' + ) + }) + + it('refreshes a cached signed image url after clearing the old entry', async () => { + const { getCachedSignedImageUrl, refreshCachedSignedImageUrl } = await import('./signed-image-cache') + + adminGetSignedUrl + .mockResolvedValueOnce('https://admin.test/old.jpg') + .mockResolvedValueOnce('https://admin.test/new.jpg') + + await expect(getCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/old.jpg') + await expect(refreshCachedSignedImageUrl('42', '', 'admin')).resolves.toBe('https://admin.test/new.jpg') + expect(adminGetSignedUrl).toHaveBeenCalledTimes(2) + }) +}) diff --git a/FD-Frontend/src/utils/signed-image-cache.ts b/FD-Frontend/src/utils/signed-image-cache.ts index 05df4729..dcfa2490 100644 --- a/FD-Frontend/src/utils/signed-image-cache.ts +++ b/FD-Frontend/src/utils/signed-image-cache.ts @@ -1,8 +1,11 @@ import { fileApi } from '@/api/file' +import { adminFileApi } from '@/api/admin' import type { IdType } from '@/utils/id' const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000 +export type SignedImageSource = 'public' | 'admin' + type SignedImageCacheEntry = { url: string expiresAt: number @@ -12,6 +15,22 @@ const signedImageUrlCache = new Map() const pendingSignedImageUrlRequests = new Map>() const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim() +const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}` +const normalizeImageUrl = (url: string): string => { + const trimmedUrl = url.trim() + if (!trimmedUrl) return '' + if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) { + return trimmedUrl + } + return `http://${trimmedUrl}` +} + +const requestSignedImageUrl = (source: SignedImageSource, fileId: string): Promise => { + if (source === 'admin') { + return adminFileApi.getSignedUrl(fileId) + } + return fileApi.getSignedUrl(fileId).then(response => String(response.data || '')) +} const getUsableCacheEntry = (key: string) => { const cached = signedImageUrlCache.get(key) @@ -29,17 +48,23 @@ export const parseImageFileIds = (value?: string | null): string[] => .map(id => id.trim()) .filter(Boolean) -export const getCachedSignedImageUrlSync = (fileId: IdType | null | undefined): string => { - const key = normalizeFileId(fileId) - return key ? getUsableCacheEntry(key) || '' : '' +export const getCachedSignedImageUrlSync = ( + fileId: IdType | null | undefined, + source: SignedImageSource = 'public' +): string => { + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return '' + return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || '' } export const getCachedSignedImageUrl = async ( fileId: IdType | null | undefined, - fallback = '' + fallback = '', + source: SignedImageSource = 'public' ): Promise => { - const key = normalizeFileId(fileId) - if (!key) return fallback + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return fallback + const key = buildCacheKey(source, fileIdKey) const cachedUrl = getUsableCacheEntry(key) if (cachedUrl) return cachedUrl @@ -49,9 +74,9 @@ export const getCachedSignedImageUrl = async ( return pendingRequest.then(url => url || fallback).catch(() => fallback) } - const request = fileApi.getSignedUrl(key) + const request = requestSignedImageUrl(source, fileIdKey) .then(response => { - const url = String(response || '').trim() + const url = normalizeImageUrl(String(response || '')) if (url) { signedImageUrlCache.set(key, { url, @@ -68,17 +93,41 @@ export const getCachedSignedImageUrl = async ( return request.then(url => url || fallback).catch(() => fallback) } +export const clearCachedSignedImageUrl = ( + fileId: IdType | null | undefined, + source: SignedImageSource = 'public' +): void => { + const fileIdKey = normalizeFileId(fileId) + if (!fileIdKey) return + const cacheKey = buildCacheKey(source, fileIdKey) + signedImageUrlCache.delete(cacheKey) + pendingSignedImageUrlRequests.delete(cacheKey) +} + +export const refreshCachedSignedImageUrl = async ( + fileId: IdType | null | undefined, + fallback = '', + source: SignedImageSource = 'public' +): Promise => { + clearCachedSignedImageUrl(fileId, source) + return getCachedSignedImageUrl(fileId, fallback, source) +} + export const getCachedSignedImageUrls = async ( fileIds: Array, - fallback = '' + fallback = '', + source: SignedImageSource = 'public' ): Promise => { - const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId))) + const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source))) const validUrls = urls.filter(Boolean) return validUrls.length ? validUrls : (fallback ? [fallback] : []) } -export const getCachedSignedImageUrlsSync = (fileIds: Array): string[] => - fileIds.map(fileId => getCachedSignedImageUrlSync(fileId)).filter(Boolean) +export const getCachedSignedImageUrlsSync = ( + fileIds: Array, + source: SignedImageSource = 'public' +): string[] => + fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean) export const extractLegacyFileId = (value?: string | null): string => { const source = String(value || '').replace(/<[^>]*>/g, '') diff --git a/FD-Frontend/src/views/ArtistProfileView.vue b/FD-Frontend/src/views/ArtistProfileView.vue index 10a7a3f2..9dec8136 100644 --- a/FD-Frontend/src/views/ArtistProfileView.vue +++ b/FD-Frontend/src/views/ArtistProfileView.vue @@ -14,6 +14,12 @@ import { } from '@ant-design/icons-vue' import { message } from 'ant-design-vue' import { DEFAULT_PRODUCT_IMAGE } from '@/constants' +import { + getPublicImageFileIds, + refreshPublicImageUrl, + resolvePublicImageUrl, + resolvePublicImageUrlsSync +} from '@/utils/public-image-assets' import { nailArtistApi, type NailArtistAvailabilityVO, @@ -21,11 +27,13 @@ import { type NailArtistReviewVO, type NailArtistWorkVO } from '@/api/nail-artist' +import { productApi, type ProductVO } from '@/api/product' const route = useRoute() const router = useRouter() const profile = shallowRef(null) +const workImageUrls = ref>({}) const reviews = ref([]) const availability = ref([]) const loading = shallowRef(false) @@ -41,7 +49,10 @@ const serviceCountText = computed(() => formatCompactNumber(Number(profile.value const goodRateText = computed(() => ratingValue.value > 0 ? `${Math.min(99, Math.round((ratingValue.value / 5) * 100))}%` : '暂无') const works = computed(() => profile.value?.works || []) const styleTags = computed(() => profile.value?.styleTags?.filter(Boolean) || []) -const firstWorkImage = computed(() => works.value.find(work => work.coverImageUrl)?.coverImageUrl || DEFAULT_PRODUCT_IMAGE) +const firstWorkImage = computed(() => { + const firstWork = works.value.find(work => getWorkImage(work) !== DEFAULT_PRODUCT_IMAGE) + return firstWork ? getWorkImage(firstWork) : DEFAULT_PRODUCT_IMAGE +}) const workTimeText = computed(() => { const start = profile.value?.workStartTime?.slice(0, 5) const end = profile.value?.workEndTime?.slice(0, 5) @@ -85,6 +96,8 @@ const filteredWorks = computed(() => { return works.value.filter(work => work.tags?.includes(workFilter.value)) }) +const PROFILE_WORK_LIMIT = 20 + const certificationText = computed(() => { const identity = profile.value?.identity || '认证美甲师' const experience = Number(profile.value?.experience || 0) @@ -135,6 +148,60 @@ const openProduct = (work: NailArtistWorkVO) => { router.push(`/product/${work.id}`) } +const getWorkImage = (work: NailArtistWorkVO) => workImageUrls.value[String(work.id)] || work.coverImageUrl || DEFAULT_PRODUCT_IMAGE + +const isArtistBookableForProduct = (product: ProductVO) => { + const ids = String(product.bookableArtists || '') + .split(',') + .map(id => id.trim()) + .filter(Boolean) + return ids.includes(artistId.value) +} + +const mapProductToWork = (product: ProductVO): NailArtistWorkVO & { imageFileIds?: string } => ({ + id: product.id, + title: product.title || product.name, + description: product.description, + price: product.price, + imageUrls: product.imageUrls, + imageFileIds: product.imageFileIds, + tags: product.tagList || product.tags?.split(/[;,,、]/).map(tag => tag.trim()).filter(Boolean), + likeCount: product.likeCount, + collectCount: product.collectCount +}) + +const loadSupplementWorks = async (existingWorks: NailArtistWorkVO[]): Promise => { + if (existingWorks.length >= PROFILE_WORK_LIMIT) { + return existingWorks.slice(0, PROFILE_WORK_LIMIT) + } + + const existingIds = new Set(existingWorks.map(work => String(work.id))) + const products = await productApi.getAllProducts().catch(() => []) + const supplementWorks = products + .filter(product => !existingIds.has(String(product.id))) + .filter(product => !profile.value?.shopId || String(product.shopId || '') === String(profile.value.shopId)) + .filter(isArtistBookableForProduct) + .slice(0, PROFILE_WORK_LIMIT - existingWorks.length) + .map(mapProductToWork) + + return [...existingWorks, ...supplementWorks] +} + +const loadWorkImages = async (nextWorks: NailArtistWorkVO[]) => { + const entries = await Promise.all(nextWorks.map(async work => { + const cachedUrls = resolvePublicImageUrlsSync(work as NailArtistWorkVO & Record, '') + const imageUrl = cachedUrls[0] || await resolvePublicImageUrl(work as NailArtistWorkVO & Record, DEFAULT_PRODUCT_IMAGE) + return [String(work.id), imageUrl] as const + })) + workImageUrls.value = Object.fromEntries(entries) +} + +const handleWorkImageError = async (work: NailArtistWorkVO) => { + const fileId = getPublicImageFileIds(work as NailArtistWorkVO & Record)[0] + const imageUrl = fileId ? await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE + workImageUrls.value = { ...workImageUrls.value, [String(work.id)]: imageUrl } +} + const openShop = () => { if (!profile.value?.shopId) { message.info('门店信息暂未完善') @@ -191,6 +258,9 @@ const loadProfile = async () => { profile.value = profileData availability.value = availabilityData || profileData.availability || [] reviews.value = reviewData || profileData.reviews || [] + const nextWorks = await loadSupplementWorks(profileData.works || []) + profile.value = { ...profileData, works: nextWorks } + await loadWorkImages(nextWorks) selectedDate.value = availability.value[0]?.dateText || String(availability.value[0]?.startTime || '').slice(0, 10) } catch (error) { loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败' @@ -317,7 +387,7 @@ onMounted(loadProfile)
diff --git a/FD-Frontend/src/views/AuthView.vue b/FD-Frontend/src/views/AuthView.vue index 400432fc..b732bd98 100644 --- a/FD-Frontend/src/views/AuthView.vue +++ b/FD-Frontend/src/views/AuthView.vue @@ -10,40 +10,19 @@
-

指尖设计师

-

- {{ activeTab === 'login' ? '艺术触手可及' : '开启你的预约账号' }} -

-

- {{ activeTab === 'login' ? '选择门店,继续你的美甲灵感旅程。' : '注册后即可收藏款式、预约服务并同步门店权益。' }} -

+

{{ activeTab === 'login' ? '登录后继续预约与收藏' : '填写信息完成账号注册' }}

-
- {{ activeTab === 'login' ? 'Welcome back' : 'Create account' }} -

{{ activeTab === 'login' ? '登录账号' : '注册账号' }}

-
- -
-
- 账号登录 -
-
- 注册账号 -
-
+ 返回登录 +
@@ -1334,8 +1320,9 @@ onBeforeUnmount(() => { var(--theme-page-bg) 100% ), var(--theme-background-image), + var(--theme-gradient), var(--theme-gradient-soft); - background-size: cover, cover, auto; + background-size: cover, cover, auto, auto; background-position: center top; color: var(--text-primary); overflow-x: hidden; @@ -1389,113 +1376,41 @@ onBeforeUnmount(() => { display: flex; flex-direction: column; justify-content: center; - gap: 22px; + gap: 14px; margin: 0 auto; } .brand-stage { width: 100%; text-align: center; - padding: 12px 10px 0; -} - -.brand-mark { - width: 76px; - height: 76px; - margin: 0 auto 14px; - display: grid; - place-items: center; - border-radius: 999px; - background: - linear-gradient( - 145deg, - color-mix(in srgb, var(--theme-card-bg) 88%, transparent), - color-mix(in srgb, var(--theme-primary-soft) 84%, var(--theme-card-bg)) - ); - border: 1px solid color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-border)); - box-shadow: var(--theme-button-shadow); -} - -.brand-mark span { - width: 52px; - height: 52px; - display: grid; - place-items: center; - border-radius: 999px; - background: var(--theme-gradient); - color: var(--theme-card-bg); - font-family: "Playfair Display", serif; - font-size: 24px; - font-weight: 700; - line-height: 1; - letter-spacing: 0; + padding: 6px 10px 0; } .brand-name { margin: 0; - color: var(--theme-primary-action); - font-family: "Playfair Display", serif; - font-size: 28px; - font-weight: 700; - line-height: 1.05; - letter-spacing: 0; -} - -.brand-title { - margin: 8px 0 0; color: var(--text-primary); - font-family: "Playfair Display", serif; - font-size: 22px; - font-weight: 600; + font-size: 24px; + font-weight: 800; line-height: 1.2; letter-spacing: 0; } .brand-copy { max-width: 310px; - margin: 10px auto 0; + margin: 8px auto 0; color: var(--text-secondary); - font-size: 14px; - line-height: 1.7; + font-size: 13px; + line-height: 1.5; letter-spacing: 0; } .auth-container { width: 100%; - background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent); - border: 1px solid color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-border)); - border-radius: 28px; - padding: 22px 18px 20px; - box-shadow: 0 22px 46px color-mix(in srgb, var(--theme-primary) 14%, transparent); - backdrop-filter: blur(18px); -} - -.auth-card-header { - margin-bottom: 18px; -} - -.auth-card-kicker { - display: inline-flex; - align-items: center; - min-height: 24px; - padding: 4px 10px; - border-radius: 999px; - background: color-mix(in srgb, var(--theme-primary-soft) 82%, var(--theme-card-bg)); - color: var(--theme-primary-action); - font-size: 12px; - font-weight: 700; - line-height: 1; - letter-spacing: 0; -} - -.auth-card-header h2 { - margin: 10px 0 0; - color: var(--text-primary); - font-family: "Playfair Display", serif; - font-size: 22px; - font-weight: 600; - line-height: 1.25; - letter-spacing: 0; + background: var(--theme-card-bg); + border: 1px solid var(--theme-border); + border-radius: 18px; + padding: 20px 18px 18px; + box-shadow: 0 12px 28px color-mix(in srgb, var(--theme-neutral) 8%, transparent); } .logo-section { @@ -1515,41 +1430,6 @@ onBeforeUnmount(() => { color: var(--text-secondary); } -.tab-container { - display: flex; - gap: 8px; - margin-bottom: 18px; - padding: 5px; - border: 1px solid var(--theme-border); - border-radius: 999px; - background: color-mix(in srgb, var(--theme-primary-soft) 52%, var(--theme-card-bg)); -} - -.tab-item { - flex: 1; - text-align: center; - min-height: 42px; - padding: 11px 8px; - border-radius: 999px; - font-size: 14px; - font-weight: 700; - color: var(--text-secondary); - cursor: pointer; - transition: background 0.25s ease, color 0.25s ease, box-shadow 0.25s ease; - position: relative; - user-select: none; -} - -.tab-item.active { - color: var(--theme-card-bg); - background: var(--theme-gradient); - box-shadow: var(--theme-button-shadow); -} - -.tab-item.active::after { - display: none; -} - .login-type-toggle { margin-bottom: 18px; } @@ -1666,16 +1546,11 @@ onBeforeUnmount(() => { } .shop-select-item { - margin: 4px 0 18px; - padding: 14px; - border-radius: 22px; + margin: 0 0 14px; + padding: 10px 12px; + border-radius: 16px; border: 1px solid var(--theme-border); - background: - linear-gradient( - 145deg, - color-mix(in srgb, var(--theme-card-bg) 88%, var(--theme-primary-soft)), - color-mix(in srgb, var(--theme-secondary-soft) 32%, var(--theme-card-bg)) - ); + background: color-mix(in srgb, var(--theme-card-bg) 92%, var(--theme-primary-soft)); } .shop-select-item :deep(.ant-form-item-label > label) { @@ -1826,6 +1701,38 @@ onBeforeUnmount(() => { text-decoration: underline; } +.auth-mode-footer { + display: flex; + justify-content: center; + align-items: center; + gap: 6px; + margin-top: 14px; + color: var(--text-secondary); + font-size: 13px; + line-height: 1.5; +} + +.auth-mode-link { + padding: 0; + border: 0; + background: transparent; + color: var(--theme-primary-action); + font-size: 13px; + font-weight: 700; + line-height: 1.5; + letter-spacing: 0; + cursor: pointer; +} + +.auth-mode-link:hover { + text-decoration: underline; +} + +.auth-mode-link--top { + display: inline-flex; + margin: 0 0 16px; +} + .phone-login-tip { margin-top: 8px; font-size: 12px; @@ -1838,19 +1745,19 @@ onBeforeUnmount(() => { min-height: 52px; border: none; border-radius: 999px; - background: var(--theme-gradient); + background: var(--theme-primary-action); color: var(--theme-card-bg); font-size: 15px; font-weight: 800; letter-spacing: 0; - box-shadow: var(--theme-button-shadow); + box-shadow: 0 10px 22px color-mix(in srgb, var(--theme-primary) 16%, transparent); } .primary-action:not(:disabled):hover, .primary-action:not(:disabled):focus { - background: var(--theme-gradient); + background: var(--theme-primary-action); color: var(--theme-card-bg); - box-shadow: var(--theme-button-shadow); + box-shadow: 0 10px 22px color-mix(in srgb, var(--theme-primary) 16%, transparent); } .primary-action:disabled { @@ -1953,27 +1860,11 @@ onBeforeUnmount(() => { .auth-page { min-height: calc(100svh - 92px); - gap: 18px; - } - - .brand-mark { - width: 68px; - height: 68px; - margin-bottom: 12px; - } - - .brand-mark span { - width: 48px; - height: 48px; - font-size: 22px; + gap: 12px; } .brand-name { - font-size: 28px; - } - - .brand-title { - font-size: 21px; + font-size: 23px; } .brand-copy { @@ -1981,12 +1872,8 @@ onBeforeUnmount(() => { } .auth-container { - border-radius: 24px; + border-radius: 18px; padding: 20px 16px 18px; } - - .auth-card-header h2 { - font-size: 21px; - } } diff --git a/FD-Frontend/src/views/CartView.vue b/FD-Frontend/src/views/CartView.vue index e3cb8a3f..23d47abb 100644 --- a/FD-Frontend/src/views/CartView.vue +++ b/FD-Frontend/src/views/CartView.vue @@ -34,7 +34,7 @@ > @@ -92,10 +92,11 @@ + :alt="item.productTitle" + loading="lazy" + decoding="async" + @error="handleCartImageError(item)" + /> {{ item.productTitle?.[0] || 'Y' }}
@@ -107,11 +108,11 @@ -
+
选择美甲师
@@ -250,7 +251,12 @@ import { shopApi, type ShopVO } from '../api/shop' import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants' import type { IdType } from '@/utils/id' import { extractRichText, renderRichContent } from '@/utils/rich-content' -import { getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache' +import { + getPublicImageFileIds, + refreshPublicImageUrl, + resolvePublicImageUrl, + resolvePublicImageUrlsSync +} from '@/utils/public-image-assets' /** * Purpose: BannerImage supports HomeView.vue by holding or executing the banner image page or API role. @@ -262,6 +268,7 @@ interface BannerImage { shopName: string businessHours?: string url: string + imageFileId?: string } /** @@ -275,6 +282,7 @@ interface ProductCardItem { meta: string shopName?: string coverUrl: string + imageFileId?: string bgColor: string } @@ -421,14 +429,9 @@ const getRandomColor = (): string => { /** getProductCoverUrl is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const getProductCoverUrl = async (product: ProductVO): Promise => { - const firstImageId = product.imageFileIds?.split(',').map(id => id.trim()).find(Boolean) - if (firstImageId) { - return getCachedSignedImageUrlSync(firstImageId) || await getCachedSignedImageUrl(firstImageId, DEFAULT_PRODUCT_IMAGE) - } - - const directImageUrl = product.imageUrls?.map(url => String(url || '').trim()) - .find(url => /^(https?:\/\/|data:image\/|blob:|\/assets\/)/.test(url)) - return directImageUrl || DEFAULT_PRODUCT_IMAGE + const cachedUrls = resolvePublicImageUrlsSync(product, '') + if (cachedUrls.length) return cachedUrls[0] || DEFAULT_PRODUCT_IMAGE + return resolvePublicImageUrl(product, DEFAULT_PRODUCT_IMAGE) } /** formatProductCards is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const formatProductCards = async (products: ProductVO[]): Promise => @@ -439,6 +442,7 @@ const formatProductCards = async (products: ProductVO[]): Promise { const loadBannerImages = async () => { const banners: BannerImage[] = [] for (const shop of publicShops.value) { - const coverIds = (shop.coverImageFileId || shop.imageFileIds || '') - .split(',') - .map(id => id.trim()) - .filter(Boolean) - for (const id of coverIds) { - try { - const url = getCachedSignedImageUrlSync(id) || await getCachedSignedImageUrl(id) - if (url) { - banners.push({ - id: `${shop.id}-${id}`, - shopId: shop.id, - shopName: shop.shopName, - businessHours: shop.businessHours, - url - }) - } - } catch (error) { - console.error('获取门店轮播图失败:', error) - } + const imageRecord = { + coverImageFileId: shop.coverImageFileId, + imageFileIds: shop.imageFileIds, + imageUrls: shop.imageUrls + } + const fileId = getPublicImageFileIds(imageRecord)[0] + const url = await resolvePublicImageUrl(imageRecord, '') + if (url) { + banners.push({ + id: `${shop.id}-${fileId || url}`, + shopId: shop.id, + shopName: shop.shopName, + businessHours: shop.businessHours, + url, + imageFileId: fileId + }) } } bannerImages.value = banners.slice(0, 8) } +const replaceProductCardImage = (items: ProductCardItem[], productId: IdType, imageUrl: string): ProductCardItem[] => + items.map(item => String(item.id) === String(productId) ? { ...item, coverUrl: imageUrl } : item) + +const handleProductCardImageError = async (item: ProductCardItem) => { + const imageUrl = item.imageFileId ? await refreshPublicImageUrl(item.imageFileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE + newArrivalItems.value = replaceProductCardImage(newArrivalItems.value, item.id, imageUrl) + featuredItems.value = replaceProductCardImage(featuredItems.value, item.id, imageUrl) + popularSource.value = replaceProductCardImage(popularSource.value, item.id, imageUrl) + popularItems.value = replaceProductCardImage(popularItems.value, item.id, imageUrl) +} + +const handleBannerImageError = async (shop: BannerImage) => { + const imageUrl = shop.imageFileId ? await refreshPublicImageUrl(shop.imageFileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE + bannerImages.value = bannerImages.value.map(item => item.id === shop.id ? { ...item, url: imageUrl } : item) +} + /** loadNewArrivalProducts fills the top carousel with products tagged as new arrivals. */ const loadNewArrivalProducts = async () => { try { diff --git a/FD-Frontend/src/views/ProductDetailView.vue b/FD-Frontend/src/views/ProductDetailView.vue index 4ea6fe58..83b98984 100644 --- a/FD-Frontend/src/views/ProductDetailView.vue +++ b/FD-Frontend/src/views/ProductDetailView.vue @@ -36,6 +36,7 @@ :alt="`${productTitle} 图片 ${index + 1}`" :loading="index === 0 ? 'eager' : 'lazy'" decoding="async" + @error="handleProductImageError(index)" />
@@ -54,6 +55,7 @@ :alt="`${productTitle} 图片 ${index + 1}`" :loading="index === 0 ? 'eager' : 'lazy'" decoding="async" + @error="handleProductImageError(index)" />
@@ -218,9 +220,9 @@

{{ comment.commentContent }}

-
+
([]) +const commentImageUrls = ref>({}) /** commentText is a reactive state variable used by the template and event handlers. */ const commentText = ref('') /** @@ -484,25 +493,24 @@ const requireLogin = (actionText: string) => { const loadProductImages = async () => { productImagesReady.value = false productImagePreviewIndex.value = 0 - const fileIds = parseImageFileIds(product.value.imageFileIds) - if (!fileIds.length) { - const fallbackImages = [DEFAULT_PRODUCT_IMAGE] - productImages.value = fallbackImages - productImagesReady.value = true - return - } - - const cachedImages = getCachedSignedImageUrlsSync(fileIds) + const cachedImages = resolvePublicImageUrlsSync(product.value, '') if (cachedImages.length) { productImages.value = cachedImages productImagesReady.value = true } - const nextImages = await getCachedSignedImageUrls(fileIds, DEFAULT_PRODUCT_IMAGE) + const nextImages = await resolvePublicImageUrls(product.value, DEFAULT_PRODUCT_IMAGE) productImages.value = nextImages productImagesReady.value = true } +const handleProductImageError = async (imageIndex: number) => { + const fileId = getPublicImageFileIds(product.value)[imageIndex] + productImages.value[imageIndex] = DEFAULT_PRODUCT_IMAGE + if (!fileId) return + productImages.value[imageIndex] = await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) +} + /** loadShopInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const loadShopInfo = async (shopId?: IdType | null) => { shopInfo.value = shopId ? await shopApi.getShopById(shopId).catch(() => null) : null @@ -511,9 +519,20 @@ const loadShopInfo = async (shopId?: IdType | null) => { /** loadComments is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const loadComments = async () => { if (!product.value.id) return - comments.value = await commentApi.listByProduct(product.value.id).catch(() => []) + const nextComments = await commentApi.listByProduct(product.value.id).catch(() => []) + comments.value = nextComments + const entries = await Promise.all(nextComments.map(async comment => { + const urls = await resolvePublicImageUrls({ + imageUrls: comment.imageUrls, + imageFileIds: Array.isArray(comment.imageFileIds) ? comment.imageFileIds.map(id => String(id)).join(',') : comment.imageFileIds + }, '') + return [String(comment.id), urls] as const + })) + commentImageUrls.value = Object.fromEntries(entries) } +const getCommentImages = (comment: CommentVO): string[] => commentImageUrls.value[String(comment.id)] || [] + /** checkInteractionStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const checkInteractionStatus = async () => { if (!isLoggedIn.value || !product.value.id) { @@ -651,8 +670,23 @@ const handleUploadCommentImage: UploadProps['customRequest'] = async options => return String(item.uid) === uid ? { ...item, url: previewUrl, thumbUrl: previewUrl, status: 'uploading' } : item }) + const task = createChunkUploadTask({ + file, + scene: 'comment-image', + concurrency: 3, + api: { + initUpload: commentApi.initImageChunkUpload, + uploadChunk: commentApi.uploadImageChunk, + completeUpload: commentApi.completeImageChunkUpload, + cancelUpload: commentApi.cancelImageChunkUpload + }, + onProgress: (percent) => { + options.onProgress?.({ percent }) + } + }) + try { - const uploaded = await commentApi.uploadImage(file) + const { response: uploaded } = await task.promise const stillListed = commentImageFileList.value.some(item => String(item.uid) === uid) if (!stillListed) { URL.revokeObjectURL(previewUrl) @@ -669,8 +703,11 @@ const handleUploadCommentImage: UploadProps['customRequest'] = async options => commentImageFileList.value = commentImageFileList.value.map(item => { return String(item.uid) === uid ? { ...item, status: 'error' } : item }) - options.onError?.(error) - message.error(error?.message || '评价图片上传失败') + const errorMessage = error?.message || '评价图片上传失败' + if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { + options.onError?.(error) + message.error(errorMessage) + } } finally { uploadingCommentImages.value = Math.max(0, uploadingCommentImages.value - 1) } diff --git a/FD-Frontend/src/views/ProductListView.vue b/FD-Frontend/src/views/ProductListView.vue index 35c45cfc..f8a5a635 100644 --- a/FD-Frontend/src/views/ProductListView.vue +++ b/FD-Frontend/src/views/ProductListView.vue @@ -75,6 +75,7 @@ class="product-image" loading="lazy" decoding="async" + @error="handleProductImageError(item)" />
{{ (item.title || item.name)?.[0] || '作' }} @@ -189,7 +190,12 @@ import { tagApi, type TagFilterGroupVO, type TagVO } from '@/api/tag' import { cartApi } from '@/api/cart' import { runWithGlobalLoading } from '@/utils/action-loading' import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state' -import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache' +import { + getPublicImageFileIds, + refreshPublicImageUrl, + resolvePublicImageUrls, + resolvePublicImageUrlsSync +} from '@/utils/public-image-assets' /** * Purpose: ProductListItem supports ProductListView.vue by holding or executing the product list item page or API role. @@ -323,24 +329,28 @@ const ensureLoginForAction = (actionText: string) => { /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const loadImageUrls = async (productList: ProductVO[]) => { for (const product of productList) { - if (!product.imageFileIds) { - imageUrls.value[String(product.id)] = [DEFAULT_PRODUCT_IMAGE] - continue - } - - const ids = parseImageFileIds(product.imageFileIds) - const cachedUrls = getCachedSignedImageUrlsSync(ids) + const productKey = String(product.id) + const cachedUrls = resolvePublicImageUrlsSync(product, '') if (cachedUrls.length) { - imageUrls.value[String(product.id)] = cachedUrls + imageUrls.value[productKey] = cachedUrls } - const urls = await getCachedSignedImageUrls(ids, DEFAULT_PRODUCT_IMAGE) - imageUrls.value[String(product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE] + const urls = await resolvePublicImageUrls(product, DEFAULT_PRODUCT_IMAGE) + imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE] } } /** getProductImages is a local helper used by this page script. */ const getProductImages = (product: ProductVO): string[] => imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE] +const handleProductImageError = async (product: ProductVO) => { + const productKey = String(product.id) + const firstFileId = getPublicImageFileIds(product)[0] + imageUrls.value[productKey] = [DEFAULT_PRODUCT_IMAGE] + if (!firstFileId) return + const refreshedUrl = await refreshPublicImageUrl(firstFileId, DEFAULT_PRODUCT_IMAGE) + imageUrls.value[productKey] = [refreshedUrl || DEFAULT_PRODUCT_IMAGE] +} + const displayProductDuration = (product: ProductVO) => { const duration = product.approximateDuration?.trim() if (duration) return duration diff --git a/FD-Frontend/src/views/ProfileView.vue b/FD-Frontend/src/views/ProfileView.vue index 57c4e887..e1ad98f0 100644 --- a/FD-Frontend/src/views/ProfileView.vue +++ b/FD-Frontend/src/views/ProfileView.vue @@ -604,15 +604,10 @@ const handleEditProfile = () => { const beforeUploadAvatar: UploadProps['beforeUpload'] = file => { const isImage = file.type.startsWith('image/') - const isLt20M = file.size / 1024 / 1024 < 20 - if (!isImage) { message.error('只能上传图片文件') } - if (!isLt20M) { - message.error('图片大小不能超过 20MB') - } - return isImage && isLt20M + return isImage } /** handleAvatarUpload is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ @@ -626,6 +621,7 @@ const handleAvatarUpload = async (options: any) => { const task = createChunkUploadTask({ file: file as File, scene: 'profile-avatar', + concurrency: 3, api: { initUpload: fileApi.initAvatarChunkUpload, uploadChunk: fileApi.uploadAvatarChunk, @@ -684,18 +680,37 @@ const handleDeleteAvatar = () => { } /** handleWechatQrUpload uploads a user profile QR image without changing the avatar. */ -const handleWechatQrUpload = async (options: any) => { - const { file, onSuccess, onError } = options +const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => { + const { file, onSuccess, onError, onProgress } = options + qrUploadPending.value = true + const task = createChunkUploadTask({ + file: file as File, + scene: 'profile-wechat-qr', + concurrency: 3, + api: { + initUpload: fileApi.initProfileImageChunkUpload, + uploadChunk: fileApi.uploadProfileImageChunk, + completeUpload: fileApi.completeProfileImageChunkUpload, + cancelUpload: fileApi.cancelProfileImageChunkUpload + }, + onProgress: (percent) => { + onProgress?.({ percent }) + } + }) + try { - const response = await fileApi.uploadProfileImage(file as File) + const { response } = await task.promise editForm.wechatQrCode = response as unknown as string onSuccess?.({ url: response }) message.success('微信二维码上传成功') } catch (error) { - console.error('微信二维码上传失败:', error) - message.error((error as Error)?.message || '微信二维码上传失败') - onError?.(error) + const errorMessage = (error as Error)?.message || '微信二维码上传失败' + if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { + console.error('微信二维码上传失败:', error) + message.error(errorMessage) + onError?.(error as Error) + } } finally { qrUploadPending.value = false } diff --git a/FD-Frontend/src/views/ShopDetailView.vue b/FD-Frontend/src/views/ShopDetailView.vue index 96282024..afa5215c 100644 --- a/FD-Frontend/src/views/ShopDetailView.vue +++ b/FD-Frontend/src/views/ShopDetailView.vue @@ -308,11 +308,12 @@ import { nailArtistApi } from '@/api/nail-artist' import { userApi, type ContactInfoVO } from '@/api/user' import { toOptionalIdString } from '@/utils/id' import { - getCachedSignedImageUrl, - getCachedSignedImageUrls, - getCachedSignedImageUrlSync, - parseImageFileIds -} from '@/utils/signed-image-cache' + getPublicImageFileIds, + refreshPublicImageUrl, + resolvePublicImageUrl, + resolvePublicImageUrls +} from '@/utils/public-image-assets' +import { parseImageFileIds } from '@/utils/signed-image-cache' /** * Purpose: router supports ShopDetailView.vue by holding or executing the router page or API role. @@ -412,15 +413,13 @@ const artistCount = computed(() => { const featuredProducts = computed(() => trustProfile.value?.featuredProducts || []) const featuredProductCards = computed(() => featuredProducts.value.map(product => { const productId = String(product.id) - const fileIds = parseFileIdList(product.imageFileIds) - const cachedUrl = fileIds[0] ? getCachedSignedImageUrlSync(fileIds[0]) : '' const directUrl = normalizeImageUrl(product.imageUrl) return { ...product, displayImageUrl: failedFeaturedProductImages.value[productId] ? '' - : (featuredProductImageUrls.value[productId] || cachedUrl || directUrl) + : (featuredProductImageUrls.value[productId] || directUrl) } })) /** @@ -629,23 +628,25 @@ const copyContactInfo = async () => { } const handleFeaturedImageError = (productId: string | number) => { - failedFeaturedProductImages.value = { - ...failedFeaturedProductImages.value, - [String(productId)]: true + const product = featuredProducts.value.find(item => String(item.id) === String(productId)) + const fileId = product ? getPublicImageFileIds({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl })[0] : '' + if (!fileId) { + failedFeaturedProductImages.value = { + ...failedFeaturedProductImages.value, + [String(productId)]: true + } + return } + refreshPublicImageUrl(fileId, '').then(url => { + featuredProductImageUrls.value = { ...featuredProductImageUrls.value, [String(productId)]: url } + failedFeaturedProductImages.value = { ...failedFeaturedProductImages.value, [String(productId)]: false } + }) } const loadFeaturedProductImages = async () => { const entries = await Promise.all(featuredProducts.value.map(async product => { const productId = String(product.id) - const firstFileId = parseFileIdList(product.imageFileIds)[0] - - if (!firstFileId) { - return [productId, normalizeImageUrl(product.imageUrl)] as const - } - - const cachedUrl = getCachedSignedImageUrlSync(firstFileId) - const signedUrl = cachedUrl || await getCachedSignedImageUrl(firstFileId) + const signedUrl = await resolvePublicImageUrl({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl }, '') return [productId, signedUrl] as const })) @@ -674,8 +675,8 @@ const loadShopImages = async () => { ]) const environmentFileIds = parseFileIdList(shop.imageFileIds) const [bannerSignedUrls, environmentSignedUrls] = await Promise.all([ - getCachedSignedImageUrls(bannerFileIds), - getCachedSignedImageUrls(environmentFileIds) + resolvePublicImageUrls({ imageFileIds: bannerFileIds.join(',') }, ''), + resolvePublicImageUrls({ imageFileIds: environmentFileIds.join(',') }, '') ]) const bannerUrls = bannerFileIds.length > 0 diff --git a/FD-Frontend/src/views/WishlistView.vue b/FD-Frontend/src/views/WishlistView.vue index e7212724..8d159eed 100644 --- a/FD-Frontend/src/views/WishlistView.vue +++ b/FD-Frontend/src/views/WishlistView.vue @@ -92,7 +92,8 @@ import type { IdType } from '@/utils/id' import { sameId } from '@/utils/id' import { runWithGlobalLoading } from '@/utils/action-loading' import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state' -import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache' +import { resolvePublicImageUrls, resolvePublicImageUrlsSync } from '@/utils/public-image-assets' +import type { PublicImageRecord } from '@/utils/public-image-assets' /** * Purpose: router supports WishlistView.vue by holding or executing the router page or API role. @@ -158,22 +159,18 @@ const fetchWishlist = async () => { /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const loadImageUrls = async (items: WishlistItem[]) => { for (const item of items) { - if (item.product.imageFileIds) { - const ids = parseImageFileIds(item.product.imageFileIds) - const cachedUrls = getCachedSignedImageUrlsSync(ids) - if (cachedUrls.length) { - imageUrls.value[String(item.product.id)] = cachedUrls - } - - const urls = await getCachedSignedImageUrls(ids, DEFAULT_PRODUCT_IMAGE) - imageUrls.value[String(item.product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE] - } else { - imageUrls.value[String(item.product.id)] = [DEFAULT_PRODUCT_IMAGE] + const productKey = String(item.product.id) + const cachedUrls = resolvePublicImageUrlsSync(item.product as PublicImageRecord, '') + if (cachedUrls.length) { + imageUrls.value[productKey] = cachedUrls } + + const urls = await resolvePublicImageUrls(item.product as PublicImageRecord, DEFAULT_PRODUCT_IMAGE) + imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE] } } /** getProductImages is a local helper used by this page script. */ -const getProductImages = (product: any): string[] => { +const getProductImages = (product: { id: IdType }): string[] => { return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE] } diff --git a/FD-Frontend/src/views/admin/AdminLayout.vue b/FD-Frontend/src/views/admin/AdminLayout.vue index f2ecf82b..8ba20b0d 100644 --- a/FD-Frontend/src/views/admin/AdminLayout.vue +++ b/FD-Frontend/src/views/admin/AdminLayout.vue @@ -219,6 +219,7 @@ import { UserOutlined } from '@ant-design/icons-vue' import { message, Modal } from 'ant-design-vue' +import type { Component } from 'vue' /** * Purpose: UserVO supports AdminLayout.vue by holding or executing the user vo page or API role. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. @@ -230,6 +231,7 @@ import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permis import { runWithGlobalLoading } from '@/utils/action-loading' import { notifyShopThemeChanged } from '@/utils/shop-theme' import { useAdminViewport } from '@/composables/useAdminViewport' +import { adminNavigationItems, findAdminNavigationItemByPath, type AdminNavIconKey } from '@/config/admin-navigation' import { getAdminCurrentShopName, getAdminRoleLabel, @@ -237,17 +239,6 @@ import { isBootstrapAdminUser } from './admin-helpers' -/** - * Purpose: AdminMenuItem supports AdminLayout.vue by holding or executing the admin menu item page or API role. - * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. - */ -type AdminMenuItem = { - key: string - icon: any - label: string - permissionCode: string -} - /** * Purpose: router supports AdminLayout.vue by holding or executing the router page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. @@ -283,29 +274,27 @@ const selectedShopId = ref() const shopSwitchLoading = ref(false) const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission() -const menuItems: AdminMenuItem[] = [ - { key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' }, - { key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' }, - { key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' }, - { key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' }, - { key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' }, - { key: '/admin/comments', icon: MessageOutlined, label: '评论管理', permissionCode: 'comment:view' }, - { key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' }, - { key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' }, - { key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' }, - { key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' }, - { key: '/admin/schedules', icon: CalendarOutlined, label: '排班管理', permissionCode: 'schedule:view' }, - { key: '/admin/after-sales', icon: MessageOutlined, label: '售后处理', permissionCode: 'after_sale:view' }, - { key: '/admin/inventory', icon: ToolOutlined, label: '库存管理', permissionCode: 'inventory:view' }, - { key: '/admin/campaigns', icon: GiftOutlined, label: '活动管理', permissionCode: 'campaign:view' }, - { key: '/admin/nail-artists', icon: TeamOutlined, label: '美甲师管理', permissionCode: 'nail_artist:view' } - , - { key: '/admin/messages', icon: MessageOutlined, label: '消息发布', permissionCode: 'message:view' }, - { key: '/admin/announcements', icon: MessageOutlined, label: '公告管理', permissionCode: 'announcement:view' }, - { key: '/admin/vip-recharge-plans', icon: GiftOutlined, label: 'VIP充值配置', permissionCode: 'user:vip:manage' }, - { key: '/admin/messagehub-push-configs', icon: MessageOutlined, label: '参数管理', permissionCode: 'messagehub:config:manage' }, - { key: '/admin/legal-agreements', icon: SafetyCertificateOutlined, label: '协议管理', permissionCode: 'legal_agreement:manage' } -] +const adminMenuIconMap: Record = { + home: HomeOutlined, + dashboard: DashboardOutlined, + user: UserOutlined, + shop: ShopOutlined, + gift: GiftOutlined, + message: MessageOutlined, + security: SafetyCertificateOutlined, + tag: TagOutlined, + shopping: ShoppingOutlined, + calendar: CalendarOutlined, + tool: ToolOutlined, + team: TeamOutlined +} + +const menuItems = adminNavigationItems.map(item => ({ + key: item.path, + icon: adminMenuIconMap[item.iconKey], + label: item.label, + permissionCode: item.permissionCode +})) /** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */ const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value)) @@ -364,7 +353,7 @@ const currentMobileSectionLabel = computed(() => { /** currentMobileTitle is a reactive state variable used by the template and event handlers. */ const currentMobileTitle = computed(() => { - const currentMenu = menuItems.find(item => item.key === route.path) + const currentMenu = findAdminNavigationItemByPath(route.path) if (currentMenu) { return currentMenu.label } diff --git a/FD-Frontend/src/views/admin/ProductsView.vue b/FD-Frontend/src/views/admin/ProductsView.vue index 3f362772..ff177733 100644 --- a/FD-Frontend/src/views/admin/ProductsView.vue +++ b/FD-Frontend/src/views/admin/ProductsView.vue @@ -69,6 +69,7 @@ :src="url" style="object-fit: cover; border-radius: 4px; margin-right: 4px;" :preview="false" + @error="handleProductImageError(record, index)" />
@@ -244,7 +246,7 @@
上传图片
-
支持多选上传,不限制上传张数,单张图片超过 5MB 会自动压缩后再上传。
+
支持多选上传,不限制上传张数,大图将自动使用分片并发上传。
图片正在上传中,上传完成前不可提交。
预览 @@ -536,6 +538,7 @@ */ import { computed, ref, reactive, onMounted, watch } from 'vue' import { message } from 'ant-design-vue' +import type { UploadProps } from 'ant-design-vue' import { PlusOutlined } from '@ant-design/icons-vue' import DraftActions from '@/components/DraftActions.vue' import TableEllipsisText from '@/components/TableEllipsisText.vue' @@ -552,10 +555,20 @@ import { adminProductApi, type Product, adminShopApi, type Shop, adminFileApi, a import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload' import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft' import { usePermission } from '@/utils/permission' -import { MAX_IMAGE_UPLOAD_SIZE, compressImageIfNeeded, formatFileSize } from '@/utils/image-upload' +import { + buildAdminUploadFileList, + buildSignedImageUrlMap, + getRecordImageUrls, + refreshSignedImageUrl, + resolveSignedImageUrl, + resolveSignedImageUrls +} from '@/utils/admin-image-assets' +import { parseImageFileIds } from '@/utils/signed-image-cache' import type { IdType } from '@/utils/id' import { sameId } from '@/utils/id' import { runWithGlobalLoading } from '@/utils/action-loading' +import { createAdminPagination, applyAdminTablePaginationChange, type AdminTablePaginationChange } from '@/utils/admin-table' +import { resolveUploadedFileId, type AdminUploadFileLike, type AdminUploadTaskFile } from '@/utils/admin-upload-file' import { useAdminViewport } from '@/composables/useAdminViewport' import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue' import AdminMobileFab from '@/components/admin/AdminMobileFab.vue' @@ -671,11 +684,6 @@ const imageUrls = ref>({}) * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const viewImageUrls = ref([]) -/** - * Purpose: imageIdCache supports ProductsView.vue by holding or executing the image id cache 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 imageIdCache = ref>({}) /** isAdmin is a reactive state variable used by the template and event handlers. */ const isAdmin = ref(false) /** @@ -751,14 +759,7 @@ const viewFormState = reactive({ * Purpose: pagination supports ProductsView.vue by holding or executing the pagination 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 pagination = reactive({ - current: 1, - pageSize: 10, - total: 0, - showSizeChanger: true, - showQuickJumper: true, - showTotal: (total: number) => `共 ${total} 条` -}) +const pagination = reactive(createAdminPagination()) /** * Purpose: formState supports ProductsView.vue by holding or executing the form state page or API role. @@ -1053,53 +1054,35 @@ const resetFilters = () => { /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const loadImageUrls = async (products: Product[], requestToken?: number) => { - const nextImageUrls: Record = {} - for (const product of products) { - if (requestToken && !isLatestRequestToken('products', requestToken)) { - return null - } - if (product.imageFileIds) { - const ids = product.imageFileIds.split(',') - const urls: string[] = [] - - for (const id of ids) { - if (requestToken && !isLatestRequestToken('products', requestToken)) { - return null - } - if (id) { - try { - // 检查缓存 - if (!imageIdCache.value[id]) { - const response = await adminFileApi.getSignedUrl(id.trim()) as any - imageIdCache.value[id] = response - } - urls.push(imageIdCache.value[id]!) - } catch (error) { - console.error('获取签名链接失败:', error) - urls.push(DEFAULT_PRODUCT_IMAGE) - } - } - } - - if (product.id) { - nextImageUrls[String(product.id)] = urls - } - } else { - if (product.id) { - nextImageUrls[String(product.id)] = [DEFAULT_PRODUCT_IMAGE] - } - } - } - return nextImageUrls + return buildSignedImageUrlMap( + products, + 'imageFileIds', + DEFAULT_PRODUCT_IMAGE, + true, + () => Boolean(requestToken && !isLatestRequestToken('products', requestToken)) + ) } /** getProductImages is a local helper used by this page script. */ -const getProductImages = (product: Product | Record): string[] => { - const productId = 'id' in product ? product.id : (product as any).id - if (productId !== undefined) { - return imageUrls.value[String(productId)] || [DEFAULT_PRODUCT_IMAGE] +const getProductImages = (product: { id?: IdType }): string[] => + getRecordImageUrls(product, imageUrls.value, [DEFAULT_PRODUCT_IMAGE]) + +const handleProductImageError = async (product: { id?: IdType; imageFileIds?: string }, imageIndex: number) => { + if (product.id === undefined || product.id === null) return + const fileId = parseImageFileIds(product.imageFileIds)[imageIndex] + if (!fileId) return + + const refreshedUrl = await refreshSignedImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) + if (!refreshedUrl || refreshedUrl === DEFAULT_PRODUCT_IMAGE) return + + const productKey = String(product.id) + const currentUrls = imageUrls.value[productKey] || [] + const nextUrls = [...currentUrls] + nextUrls[imageIndex] = refreshedUrl + imageUrls.value = { + ...imageUrls.value, + [productKey]: nextUrls } - return [DEFAULT_PRODUCT_IMAGE] } /** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ @@ -1109,9 +1092,10 @@ const handleSearch = async () => { } /** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const handleTableChange = async (pag: any) => { - pagination.current = pag.current - pagination.pageSize = pag.pageSize +const handleTableChange = async (pag: AdminTablePaginationChange) => { + const nextPagination = applyAdminTablePaginationChange(pagination, pag) + pagination.current = nextPagination.current + pagination.pageSize = nextPagination.pageSize await runWithGlobalLoading(() => fetchProductList()) } @@ -1252,27 +1236,7 @@ const showViewModal = async (record: Product | Record) => { }) // 加载图片URL - if (recordImageFileIds) { - const ids = recordImageFileIds.split(',').filter((id: string) => id) - const urls: string[] = [] - - for (const id of ids) { - try { - // 检查缓存 - if (!imageIdCache.value[id]) { - const response = await adminFileApi.getSignedUrl(id) as unknown as string - imageIdCache.value[id] = response - } - urls.push(imageIdCache.value[id]) - } catch (error) { - console.error('获取签名链接失败:', error) - urls.push(DEFAULT_PRODUCT_IMAGE) - } - } - viewImageUrls.value = urls - } else { - viewImageUrls.value = [DEFAULT_PRODUCT_IMAGE] - } + viewImageUrls.value = await resolveSignedImageUrls(recordImageFileIds, DEFAULT_PRODUCT_IMAGE, true) // 获取该店铺的美甲师列表 if (recordShopId) { @@ -1319,32 +1283,7 @@ const buildDraftPayload = () => ({ /** buildImageFileListByIds is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const buildImageFileListByIds = async (ids: string[]) => { - const fileList = [] - for (const [index, id] of ids.entries()) { - try { - if (!imageIdCache.value[id]) { - const response = await adminFileApi.getSignedUrl(id) as any - imageIdCache.value[id] = response - } - fileList.push({ - uid: id, - fileId: id, - name: `图片${index + 1}`, - status: 'done', - url: imageIdCache.value[id] - }) - } catch (error) { - console.error('获取签名链接失败:', error) - fileList.push({ - uid: id, - fileId: id, - name: `图片${index + 1}`, - status: 'done', - url: '' - }) - } - } - return fileList + return buildAdminUploadFileList(ids, '图片', DEFAULT_PRODUCT_IMAGE) } /** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ @@ -1390,37 +1329,8 @@ const syncUploadedFileIds = (fileIds: string[]) => { formState.imageFileIds = uploadedFileIds.value.join(',') } -/** getUploadResponse is a local helper used by this page script. */ -const getUploadResponse = (file: any) => { - if (!file || typeof file !== 'object') { - return null - } - return file.response || null -} - -/** resolveUploadedFileId is a local helper used by this page script. */ -const resolveUploadedFileId = (file: any) => { - const response = getUploadResponse(file) - const responseId = response?.id ?? response?.data?.id ?? file?.fileId - if (responseId !== undefined && responseId !== null && responseId !== '') { - return String(responseId) - } - - const fileUid = String(file?.uid || '') - if (/^\d+$/.test(fileUid)) { - return fileUid - } - - const fileUrl = String(file?.url || '') - if (/^\d+$/.test(fileUrl)) { - return fileUrl - } - - return '' -} - /** getPreviewUrlFromFile is a local helper used by this page script. */ -const getPreviewUrlFromFile = (file: any) => { +const getPreviewUrlFromFile = (file: AdminUploadFileLike) => { const fileUrl = typeof file?.url === 'string' ? file.url : '' if (fileUrl && !/^\d+$/.test(fileUrl)) { return fileUrl @@ -1445,41 +1355,25 @@ const beforeUpload = (file: File) => { // 作品图片走分片上传,并在上传前做压缩兜底,保证大图也能稳定进入对象存储。 /** handleUploadImage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const handleUploadImage = async (options: any) => { +const handleUploadImage: UploadProps['customRequest'] = async (options) => { const { file, onSuccess, onError, onProgress } = options - let successMessage = '图片上传成功' + const uploadFile = file as AdminUploadTaskFile const task = createChunkUploadTask({ - file: file as File, + file: uploadFile, scene: 'admin-product-image', + concurrency: 3, api: { initUpload: adminFileApi.initChunkUpload, uploadChunk: adminFileApi.uploadChunk, completeUpload: adminFileApi.completeChunkUpload, cancelUpload: adminFileApi.cancelChunkUpload }, - preprocessFile: async (originalFile) => { - const compressedResult = await compressImageIfNeeded(originalFile, MAX_IMAGE_UPLOAD_SIZE) - - if (compressedResult.skippedReason) { - throw new Error(compressedResult.skippedReason) - } - - if (compressedResult.finalSize > MAX_IMAGE_UPLOAD_SIZE) { - throw new Error('图片压缩后仍超过 5MB,请裁剪后重试') - } - - if (compressedResult.compressed && compressedResult.originalSize !== compressedResult.finalSize) { - successMessage = `${originalFile.name} 已压缩并上传成功(${formatFileSize(compressedResult.originalSize)} -> ${formatFileSize(compressedResult.finalSize)})` - } - - return compressedResult.file - }, onProgress: (percent) => { onProgress?.({ percent }) } }) - uploadTaskMap.set(String(file.uid), task) + uploadTaskMap.set(String(uploadFile.uid), task) activeUploadCount.value += 1 try { @@ -1487,42 +1381,37 @@ const handleUploadImage = async (options: any) => { const fileId = String((response as any).id) syncUploadedFileIds([...uploadedFileIds.value, fileId]) onSuccess?.({ id: fileId, fileId }) - message.success(successMessage) + message.success('图片上传成功') } catch (error) { const errorMessage = (error as Error)?.message || '图片上传失败' if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { console.error('图片上传失败:', error) message.error(errorMessage) - onError?.(error) + onError?.(error as never) } } finally { - uploadTaskMap.delete(String(file.uid)) + uploadTaskMap.delete(String(uploadFile.uid)) activeUploadCount.value = Math.max(0, activeUploadCount.value - 1) } } // Ant Upload 的文件对象来源很多,预览时优先复用已有 URL,缺失时再回源签名地址。 /** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ -const handlePreview = async (file: any) => { +const handlePreview: UploadProps['onPreview'] = async (file) => { try { - const cachedPreviewUrl = getPreviewUrlFromFile(file) + const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike) if (cachedPreviewUrl) { previewImage.value = cachedPreviewUrl previewVisible.value = true return } - const fileId = resolveUploadedFileId(file) + const fileId = resolveUploadedFileId(file as AdminUploadFileLike) if (!fileId) { throw new Error('未找到图片文件标识') } - if (!imageIdCache.value[fileId]) { - const response = await adminFileApi.getSignedUrl(fileId) as any - imageIdCache.value[fileId] = response - } - - previewImage.value = imageIdCache.value[fileId] || '' + previewImage.value = await resolveSignedImageUrl(fileId, '') previewVisible.value = true } catch (error) { console.error('获取预览链接失败:', error) @@ -1531,14 +1420,14 @@ const handlePreview = async (file: any) => { } /** handleRemove is a local helper used by this page script. */ -const handleRemove = (file: any) => { +const handleRemove: UploadProps['onRemove'] = (file) => { const uploadTask = uploadTaskMap.get(String(file.uid)) if (uploadTask) { uploadTask.cancel() return true } - const fileId = resolveUploadedFileId(file) + const fileId = resolveUploadedFileId(file as AdminUploadFileLike) if (fileId) { syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId)) } diff --git a/FD-Frontend/src/views/admin/ShopsView.vue b/FD-Frontend/src/views/admin/ShopsView.vue index 0ea528fb..0528d8f2 100644 --- a/FD-Frontend/src/views/admin/ShopsView.vue +++ b/FD-Frontend/src/views/admin/ShopsView.vue @@ -47,15 +47,22 @@