提交开发分支未提交代码并修正配置

This commit is contained in:
2026-06-23 15:33:06 +08:00
parent a53b27ef20
commit 0fd96d150e
141 changed files with 3624 additions and 6048 deletions
@@ -5,14 +5,16 @@ description: "Use when the user needs to run GitNexus CLI commands like analyze/
# GitNexus CLI Commands # GitNexus CLI Commands
All commands work via `npx` — no global install required. Commands below use `node .gitnexus/run.cjs <command>` — 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 ## Commands
### analyze — Build or refresh the index ### analyze — Build or refresh the index
```bash ```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. 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 ### status — Check index freshness
```bash ```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. 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 ### clean — Delete the index
```bash ```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. 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 ### wiki — Generate documentation from the graph
```bash ```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). 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 ### list — Show all indexed repos
```bash ```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. Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information.
@@ -16,23 +16,23 @@ description: "Use when the user is debugging a bug, tracing an error, or asking
## Workflow ## Workflow
``` ```
1. gitnexus_query({query: "<error or symptom>"}) → Find related execution flows 1. query({query: "<error or symptom>"}) → Find related execution flows
2. gitnexus_context({name: "<suspect>"}) → See callers/callees/processes 2. context({name: "<suspect>"}) → See callers/callees/processes
3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow 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 ## Checklist
``` ```
- [ ] Understand the symptom (error message, unexpected behavior) - [ ] 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 - [ ] 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 - [ ] 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 - [ ] 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 | | 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 | | Wrong return value | `context` on the function → trace callees for data flow |
| Intermittent failure | `context` → look for external calls, async deps | | Intermittent failure | `context` → look for external calls, async deps |
| Performance issue | `context` → find symbols with many callers (hot paths) | | 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 ## 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 → Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError, PaymentException → 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 → Incoming calls: processCheckout, webhookHandler
→ Outgoing calls: verifyCard, fetchRates (external API!) → Outgoing calls: verifyCard, fetchRates (external API!)
→ Processes: CheckoutFlow (step 3/7) → Processes: CheckoutFlow (step 3/7)
``` ```
**gitnexus_cypher** — custom call chain traces: **cypher** — custom call chain traces:
```cypher ```cypher
MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) 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" ## Example: "Payment endpoint returns 500 intermittently"
``` ```
1. gitnexus_query({query: "payment error handling"}) 1. query({query: "payment error handling"})
→ Processes: CheckoutFlow, ErrorHandling → Processes: CheckoutFlow, ErrorHandling
→ Symbols: validatePayment, handlePaymentError → Symbols: validatePayment, handlePaymentError
2. gitnexus_context({name: "validatePayment"}) 2. context({name: "validatePayment"})
→ Outgoing calls: verifyCard, fetchRates (external API!) → Outgoing calls: verifyCard, fetchRates (external API!)
3. READ gitnexus://repo/my-app/process/CheckoutFlow 3. READ gitnexus://repo/my-app/process/CheckoutFlow
@@ -18,20 +18,20 @@ description: "Use when the user asks how code works, wants to understand archite
``` ```
1. READ gitnexus://repos → Discover indexed repos 1. READ gitnexus://repos → Discover indexed repos
2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness 2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness
3. gitnexus_query({query: "<what you want to understand>"}) → Find related execution flows 3. query({query: "<what you want to understand>"}) → Find related execution flows
4. gitnexus_context({name: "<symbol>"}) → Deep dive on specific symbol 4. context({name: "<symbol>"}) → Deep dive on specific symbol
5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow 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 ## Checklist
``` ```
- [ ] READ gitnexus://repo/{name}/context - [ ] 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) - [ ] 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 process resource for full execution traces
- [ ] Read source files for implementation details - [ ] Read source files for implementation details
``` ```
@@ -47,18 +47,18 @@ description: "Use when the user asks how code works, wants to understand archite
## Tools ## 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 → Processes: CheckoutFlow, RefundFlow, WebhookHandler
→ Symbols grouped by flow with file locations → 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 → Incoming calls: loginHandler, apiMiddleware
→ Outgoing calls: checkToken, getUserById → Outgoing calls: checkToken, getUserById
→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3) → 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 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 → CheckoutFlow: processPayment → validateCard → chargeStripe
→ RefundFlow: initiateRefund → calculateRefund → processRefund → RefundFlow: initiateRefund → calculateRefund → processRefund
3. gitnexus_context({name: "processPayment"}) 3. context({name: "processPayment"})
→ Incoming: checkoutHandler, webhookHandler → Incoming: checkoutHandler, webhookHandler
→ Outgoing: validateCard, chargeStripe, saveTransaction → Outgoing: validateCard, chargeStripe, saveTransaction
4. Read src/payments/processor.ts for implementation details 4. Read src/payments/processor.ts for implementation details
@@ -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** 2. **Match your task to a skill below** and **read that skill file**
3. **Follow the skill's workflow and checklist** 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 ## 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 | | `detect_changes` | Git-diff impact — what do your current changes affect |
| `rename` | Multi-file coordinated rename with confidence-tagged edits | | `rename` | Multi-file coordinated rename with confidence-tagged edits |
| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) | | `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 ## Resources Reference
@@ -17,22 +17,22 @@ description: "Use when the user wants to know what will break if they change som
## Workflow ## 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 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 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 ## Checklist
``` ```
- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents - [ ] impact({target, direction: "upstream"}) to find dependents
- [ ] Review d=1 items first (these WILL BREAK) - [ ] Review d=1 items first (these WILL BREAK)
- [ ] Check high-confidence (>0.8) dependencies - [ ] Check high-confidence (>0.8) dependencies
- [ ] READ processes to check affected execution flows - [ ] 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 - [ ] 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 ## Tools
**gitnexus_impact** — the primary tool for symbol blast radius: **impact** — the primary tool for symbol blast radius:
``` ```
gitnexus_impact({ impact({
target: "validateUser", target: "validateUser",
direction: "upstream", direction: "upstream",
minConfidence: 0.8, minConfidence: 0.8,
@@ -73,10 +73,10 @@ gitnexus_impact({
- authRouter (src/routes/auth.ts:22) [CALLS, 95%] - 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 → Changed: 5 symbols in 3 files
→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline → Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline
@@ -86,7 +86,7 @@ gitnexus_detect_changes({scope: "staged"})
## Example: "What breaks if I change validateUser?" ## 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=1: loginHandler, apiMiddleware (WILL BREAK)
→ d=2: authRouter, sessionManager (LIKELY AFFECTED) → d=2: authRouter, sessionManager (LIKELY AFFECTED)
@@ -16,78 +16,78 @@ description: "Use when the user wants to rename, extract, split, move, or restru
## Workflow ## Workflow
``` ```
1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents 1. impact({target: "X", direction: "upstream"}) → Map all dependents
2. gitnexus_query({query: "X"}) → Find execution flows involving X 2. query({query: "X"}) → Find execution flows involving X
3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs 3. context({name: "X"}) → See all incoming/outgoing refs
4. Plan update order: interfaces → implementations → callers → tests 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 ## Checklists
### Rename Symbol ### 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) - [ ] Review graph edits (high confidence) and ast_search edits (review carefully)
- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits - [ ] If satisfied: rename({..., dry_run: false}) — apply edits
- [ ] gitnexus_detect_changes() — verify only expected files changed - [ ] detect_changes() — verify only expected files changed
- [ ] Run tests for affected processes - [ ] Run tests for affected processes
``` ```
### Extract Module ### Extract Module
``` ```
- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs - [ ] context({name: target}) — see all incoming/outgoing refs
- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers - [ ] impact({target, direction: "upstream"}) — find all external callers
- [ ] Define new module interface - [ ] Define new module interface
- [ ] Extract code, update imports - [ ] Extract code, update imports
- [ ] gitnexus_detect_changes() — verify affected scope - [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes - [ ] Run tests for affected processes
``` ```
### Split Function/Service ### Split Function/Service
``` ```
- [ ] gitnexus_context({name: target}) — understand all callees - [ ] context({name: target}) — understand all callees
- [ ] Group callees by responsibility - [ ] 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 - [ ] Create new functions/services
- [ ] Update callers - [ ] Update callers
- [ ] gitnexus_detect_changes() — verify affected scope - [ ] detect_changes() — verify affected scope
- [ ] Run tests for affected processes - [ ] Run tests for affected processes
``` ```
## Tools ## 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 → 12 edits across 8 files
→ 10 graph edits (high confidence), 2 ast_search edits (review) → 10 graph edits (high confidence), 2 ast_search edits (review)
→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}] → 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 → d=1: loginHandler, apiMiddleware, testUtils
→ Affected Processes: LoginFlow, TokenRefresh → 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 → Changed: 8 files, 12 symbols
→ Affected processes: LoginFlow, TokenRefresh → Affected processes: LoginFlow, TokenRefresh
→ Risk: MEDIUM → Risk: MEDIUM
``` ```
**gitnexus_cypher** — custom reference queries: **cypher** — custom reference queries:
```cypher ```cypher
MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) 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 | | 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 | | 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 | | External/public API | Version and deprecate properly |
## Example: Rename `validateUser` to `authenticateUser` ## 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) → 12 edits: 10 graph (safe), 2 ast_search (review)
→ Files: validator.ts, login.ts, middleware.ts, config.json... → Files: validator.ts, login.ts, middleware.ts, config.json...
2. Review ast_search edits (config.json: dynamic reference!) 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 → Applied 12 edits across 8 files
4. gitnexus_detect_changes({scope: "all"}) 4. detect_changes({scope: "all"})
→ Affected: LoginFlow, TokenRefresh → Affected: LoginFlow, TokenRefresh
→ Risk: MEDIUM — run tests for these flows → Risk: MEDIUM — run tests for these flows
``` ```
+31 -13
View File
@@ -1,36 +1,54 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # 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 ## 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 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 `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. - **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. - **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 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 `gitnexus_context({name: "symbolName"})`. - When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
## Never Do ## 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 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 rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope. - NEVER commit changes without running `detect_changes()` to check affected scope.
## Resources ## Resources
| Resource | Use for | | Resource | Use for |
|----------|---------| |----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness | | `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas | | `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows | | `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | | `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` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Project Workflow Rules
- 后端修改如果涉及 SQL,不要修改初始化 SQL;必须新增版本变更 SQL。
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
- 执行 git 提交操作时,提交信息必须使用中文。
## Browser MCP Preference ## 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. - 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.
+24 -13
View File
@@ -1,32 +1,43 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # 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 ## 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 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 `gitnexus_detect_changes()` before committing** to verify your changes only affect expected symbols and execution flows. - **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. - **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 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 `gitnexus_context({name: "symbolName"})`. - When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use `context({name: "symbolName"})`.
## Never Do ## 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 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 rename symbols with find-and-replace — use `rename` which understands the call graph.
- NEVER commit changes without running `gitnexus_detect_changes()` to check affected scope. - NEVER commit changes without running `detect_changes()` to check affected scope.
## Resources ## Resources
| Resource | Use for | | Resource | Use for |
|----------|---------| |----------|---------|
| `gitnexus://repo/xiaowang/context` | Codebase overview, check index freshness | | `gitnexus://repo/FingertipDesigner/context` | Codebase overview, check index freshness |
| `gitnexus://repo/xiaowang/clusters` | All functional areas | | `gitnexus://repo/FingertipDesigner/clusters` | All functional areas |
| `gitnexus://repo/xiaowang/processes` | All execution flows | | `gitnexus://repo/FingertipDesigner/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | | `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` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
+4 -4
View File
@@ -193,11 +193,11 @@
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
</dependency> </dependency>
<!-- MinIO --> <!-- Qiniu Kodo primary object storage -->
<dependency> <dependency>
<groupId>io.minio</groupId> <groupId>com.qiniu</groupId>
<artifactId>minio</artifactId> <artifactId>qiniu-java-sdk</artifactId>
<version>8.5.7</version> <version>[7.19.0, 7.19.99]</version>
</dependency> </dependency>
<!-- Aliyun OSS backup storage --> <!-- Aliyun OSS backup storage -->
@@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.cache") @ConfigurationProperties(prefix = "fingertip-designer.cache")
public class AppCacheProperties { public class AppCacheProperties {
/** /**
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration;
@Data @Data
@Configuration @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. * 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. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
@@ -9,18 +9,18 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt") @ConfigurationProperties(prefix = "fingertip-designer.security.jwt")
public class JwtProperties { public class JwtProperties {
/** /**
* HS512 密钥,生产环境请通过 Nacos 覆盖。 * 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 发行者。 * Token 发行者。
*/ */
private String issuer = "yuminail"; private String issuer = "fingertip-designer";
/** /**
* AccessToken 有效期,单位秒。 * AccessToken 有效期,单位秒。
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration;
@Data @Data
@Configuration @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. * 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. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
@@ -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();
}
}
@@ -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;
}
@@ -1,5 +1,6 @@
package com.xiaowang.yuminailcore.config; package com.xiaowang.yuminailcore.config;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.DirectExchange;
@@ -10,15 +11,14 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
@RequiredArgsConstructor
public class RabbitMQConfig { public class RabbitMQConfig {
public static final String EXAMPLE_QUEUE = "yuminail.example.queue"; public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue";
public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange"; public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange";
public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key"; 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"; private final ObjectStorageProperties objectStorageProperties;
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";
@Bean @Bean
public MessageConverter jsonMessageConverter() { public MessageConverter jsonMessageConverter() {
@@ -41,19 +41,19 @@ public class RabbitMQConfig {
} }
@Bean @Bean
public Queue fileOssBackupQueue() { public Queue objectStorageBackupQueue() {
return new Queue(FILE_OSS_BACKUP_QUEUE, true); return new Queue(objectStorageProperties.getBackupQueueName(), true);
} }
@Bean @Bean
public DirectExchange fileOssBackupExchange() { public DirectExchange objectStorageBackupExchange() {
return new DirectExchange(FILE_OSS_BACKUP_EXCHANGE, true, false); return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false);
} }
@Bean @Bean
public Binding fileOssBackupBinding() { public Binding objectStorageBackupBinding() {
return BindingBuilder.bind(fileOssBackupQueue()) return BindingBuilder.bind(objectStorageBackupQueue())
.to(fileOssBackupExchange()) .to(objectStorageBackupExchange())
.with(FILE_OSS_BACKUP_ROUTING_KEY); .with(objectStorageProperties.getBackupRoutingKey());
} }
} }
@@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.rate-limit") @ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit")
public class RateLimitProperties { public class RateLimitProperties {
private LimitRule login = new LimitRule(10, 60); private LimitRule login = new LimitRule(10, 60);
@@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.signature") @ConfigurationProperties(prefix = "fingertip-designer.security.signature")
public class RequestSignatureProperties { public class RequestSignatureProperties {
/** /**
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration;
@Data @Data
@Configuration @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. * 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. * Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
@@ -9,7 +9,7 @@ import java.util.List;
@Data @Data
@Configuration @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. * 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. * 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 maxSize = 10 * 1024 * 1024;
private long maxTotalSize = 500L * 1024 * 1024;
private List<String> allowedMimeTypes = new ArrayList<>(List.of( private List<String> allowedMimeTypes = new ArrayList<>(List.of(
"image/jpeg", "image/jpeg",
"image/png", "image/png",
@@ -9,7 +9,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.wechat.mini") @ConfigurationProperties(prefix = "fingertip-designer.wechat.mini")
public class WechatMiniProperties { public class WechatMiniProperties {
/** /**
@@ -267,7 +267,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper,
profile.setWorkStartTime(artistInfo.getWorkStartTime()); profile.setWorkStartTime(artistInfo.getWorkStartTime());
profile.setWorkEndTime(artistInfo.getWorkEndTime()); profile.setWorkEndTime(artistInfo.getWorkEndTime());
profile.setStyleTags(parseTextTokens(artistInfo.getSkills())); profile.setStyleTags(parseTextTokens(artistInfo.getSkills()));
profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 6)); profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24));
profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList())); profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList()));
profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList())); profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList()));
return profile; return profile;
@@ -2,48 +2,49 @@ package com.xiaowang.yuminailcore.modules.content.controller.front;
import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.xiaowang.yuminailcore.modules.content.dto.CommentDTO; import com.xiaowang.yuminailcore.modules.content.dto.CommentDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.modules.content.service.CommentService; import com.xiaowang.yuminailcore.modules.content.service.CommentService;
import com.xiaowang.yuminailcore.modules.file.service.MinioService; import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
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.ObjectStorageFileService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.support.security.UploadSecurityValidator; import com.xiaowang.yuminailcore.support.security.UploadSecurityValidator;
import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.util.List; import java.util.List;
/**
* 用户评论信息表 Controller
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController @RestController
@RequestMapping({"/comment", "/api/comment"}) @RequestMapping({"/comment", "/api/comment"})
@RequiredArgsConstructor @RequiredArgsConstructor
public class CommentController { public class CommentController {
/**
* Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentService commentService; private final CommentService commentService;
private final ObjectStorageFileService objectStorageFileService; private final ObjectStorageFileService objectStorageFileService;
private final MinioService minioService; private final PrimaryObjectStorageService primaryObjectStorageService;
private final ChunkUploadService chunkUploadService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final UploadSecurityValidator uploadSecurityValidator; private final UploadSecurityValidator uploadSecurityValidator;
private final ObjectStorageProperties objectStorageProperties;
/**
* 创建评论
*
* @param commentDTO 评论DTO
* @return 评论ID
*/
@PostMapping("/create") @PostMapping("/create")
public Result<Long> createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) { public Result<Long> createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId"); Long userId = (Long) request.getAttribute("userId");
@@ -60,43 +61,76 @@ public class CommentController {
} }
try { try {
uploadSecurityValidator.validate(file); uploadSecurityValidator.validate(file);
String originalFilename = file.getOriginalFilename(); String originalFilename = normalizeOriginalFilename(file.getOriginalFilename());
if (originalFilename == null || originalFilename.isEmpty()) { String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename);
originalFilename = "comment-image"; String fileUrl = primaryObjectStorageService.uploadFile(file, objectName);
} return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize()));
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));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return Result.error("评价图片上传失败: " + e.getMessage()); return Result.error("评价图片上传失败: " + e.getMessage());
} }
} }
/** @PostMapping("/upload-image/init")
* 更新评论 @OperationGuard(action = "comment-image-upload-init", ttlSeconds = 10, message = "图片正在上传中,请勿重复操作")
* public Result<?> initCommentImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
* @param id 评论ID Long userId = (Long) request.getAttribute("userId");
* @param commentDTO 评论DTO if (userId == null) {
* @return 是否更新成功 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<Boolean> 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<ObjectStorageFileVO> 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<Boolean> 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}") @PutMapping("/update/{id}")
public Result<Boolean> updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) { public Result<Boolean> updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId"); Long userId = (Long) request.getAttribute("userId");
@@ -104,12 +138,6 @@ public class CommentController {
return Result.success(success); return Result.success(success);
} }
/**
* 删除评论
*
* @param id 评论ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")
public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) { public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) {
Long userId = (Long) request.getAttribute("userId"); Long userId = (Long) request.getAttribute("userId");
@@ -117,74 +145,71 @@ public class CommentController {
return Result.success(success); return Result.success(success);
} }
/**
* 根据ID查询评论
*
* @param id 评论ID
* @return 评论VO
*/
@GetMapping("/get/{id}") @GetMapping("/get/{id}")
public Result<CommentVO> getCommentById(@PathVariable Long id) { public Result<CommentVO> getCommentById(@PathVariable Long id) {
CommentVO commentVO = commentService.getCommentById(id); CommentVO commentVO = commentService.getCommentById(id);
return Result.success(commentVO); return Result.success(commentVO);
} }
/**
* 查询所有评论
*
* @return 评论VO列表
*/
@GetMapping("/list/all") @GetMapping("/list/all")
public Result<List<CommentVO>> listAllComments() { public Result<List<CommentVO>> listAllComments() {
List<CommentVO> commentVOs = commentService.listAllComments(); List<CommentVO> commentVOs = commentService.listAllComments();
return Result.success(commentVOs); return Result.success(commentVOs);
} }
/**
* 根据用户ID查询评论
*
* @param userId 用户ID
* @return 评论VO列表
*/
@GetMapping("/list/user/{userId}") @GetMapping("/list/user/{userId}")
public Result<List<CommentVO>> listCommentsByUserId(@PathVariable Long userId) { public Result<List<CommentVO>> listCommentsByUserId(@PathVariable Long userId) {
List<CommentVO> commentVOs = commentService.listCommentsByUserId(userId); List<CommentVO> commentVOs = commentService.listCommentsByUserId(userId);
return Result.success(commentVOs); return Result.success(commentVOs);
} }
/**
* 根据店铺ID查询评论
*
* @param shopId 店铺ID
* @return 评论VO列表
*/
@GetMapping("/list/shop/{shopId}") @GetMapping("/list/shop/{shopId}")
public Result<List<CommentVO>> listCommentsByShopId(@PathVariable Long shopId) { public Result<List<CommentVO>> listCommentsByShopId(@PathVariable Long shopId) {
List<CommentVO> commentVOs = commentService.listCommentsByShopId(shopId); List<CommentVO> commentVOs = commentService.listCommentsByShopId(shopId);
return Result.success(commentVOs); return Result.success(commentVOs);
} }
/**
* 根据商品ID查询评论
*
* @param productId 商品ID
* @return 评论VO列表
*/
@GetMapping("/list/product/{productId}") @GetMapping("/list/product/{productId}")
public Result<List<CommentVO>> listCommentsByProductId(@PathVariable Long productId) { public Result<List<CommentVO>> listCommentsByProductId(@PathVariable Long productId) {
List<CommentVO> commentVOs = commentService.listCommentsByProductId(productId); List<CommentVO> commentVOs = commentService.listCommentsByProductId(productId);
return Result.success(commentVOs); return Result.success(commentVOs);
} }
/**
* 根据父级评论ID查询回复
*
* @param parentCommentId 父级评论ID
* @return 评论VO列表
*/
@GetMapping("/list/parent/{parentCommentId}") @GetMapping("/list/parent/{parentCommentId}")
public Result<List<CommentVO>> listCommentsByParentCommentId(@PathVariable Long parentCommentId) { public Result<List<CommentVO>> listCommentsByParentCommentId(@PathVariable Long parentCommentId) {
List<CommentVO> commentVOs = commentService.listCommentsByParentCommentId(parentCommentId); List<CommentVO> commentVOs = commentService.listCommentsByParentCommentId(parentCommentId);
return Result.success(commentVOs); 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("."));
}
} }
@@ -8,19 +8,33 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils; 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 @Data
@Configuration @Configuration
@Validated
@ConfigurationProperties(prefix = "aliyun.oss") @ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssConfig { public class AliyunOssConfig {
private boolean enabled = false; @NotNull
private Boolean enabled;
@NotBlank
private String endpoint; private String endpoint;
@NotBlank
private String region; private String region;
private String bucketName = "fingertipdesigner"; @NotBlank
private String bucketName;
@NotBlank
private String accessKeyId; private String accessKeyId;
@NotBlank
private String accessKeySecret; private String accessKeySecret;
private int signedUrlExpireMinutes = 30; @NotNull
@Min(1)
private Integer signedUrlExpireMinutes;
@Bean(destroyMethod = "shutdown") @Bean(destroyMethod = "shutdown")
@ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true")
@@ -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);
}
}
}
@@ -57,7 +57,7 @@ public class FrontendFileController {
private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) {
return StringUtils.hasText(fileVO.getObjectName()) return StringUtils.hasText(fileVO.getObjectName())
|| StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getMinioUrl())) || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getPrimaryUrl()))
|| StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()));
} }
@@ -1,13 +1,14 @@
package com.xiaowang.yuminailcore.modules.file.controller.front; package com.xiaowang.yuminailcore.modules.file.controller.front;
import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadCompleteRequestDTO; import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadCompleteRequestDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadInitRequestDTO; import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.modules.file.service.ChunkUploadService; 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.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
@@ -45,9 +46,9 @@ public class ObjectStorageFileController {
*/ */
private final ObjectStorageFileService objectStorageFileService; 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. * 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. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/ */
private final UploadSecurityValidator uploadSecurityValidator; private final UploadSecurityValidator uploadSecurityValidator;
private final ObjectStorageProperties objectStorageProperties;
@PostMapping("/upload/init") @PostMapping("/upload/init")
@OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作")
@@ -100,7 +102,7 @@ public class ObjectStorageFileController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
String fileUrl = minioService.uploadStream( String fileUrl = primaryObjectStorageService.uploadStream(
inputStream, inputStream,
preparedUploadFile.getFileSize(), preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(), preparedUploadFile.getContentType(),
@@ -111,12 +113,14 @@ public class ObjectStorageFileController {
dto.setFileName(originalFilename); dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl); dto.setFileUrl(fileUrl);
dto.setObjectName(objectName); dto.setObjectName(objectName);
dto.setMinioUrl(fileUrl); dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider());
dto.setPrimaryUrl(fileUrl);
dto.setBackupProvider(objectStorageProperties.getBackupProvider());
dto.setContentType(preparedUploadFile.getContentType()); dto.setContentType(preparedUploadFile.getContentType());
dto.setFileSize(preparedUploadFile.getFileSize()); dto.setFileSize(preparedUploadFile.getFileSize());
dto.setMinioUploadStatus(1); dto.setPrimaryUploadStatus(1);
dto.setOssUploadStatus(0); dto.setBackupUploadStatus(0);
dto.setOssRetryCount(0); dto.setBackupRetryCount(0);
dto.setStatus(1); dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto); Long fileId = objectStorageFileService.createObjectStorageFile(dto);
@@ -155,18 +159,20 @@ public class ObjectStorageFileController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
String fileUrl = minioService.uploadFile(file, objectName); String fileUrl = primaryObjectStorageService.uploadFile(file, objectName);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename); dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl); dto.setFileUrl(fileUrl);
dto.setObjectName(objectName); dto.setObjectName(objectName);
dto.setMinioUrl(fileUrl); dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider());
dto.setPrimaryUrl(fileUrl);
dto.setBackupProvider(objectStorageProperties.getBackupProvider());
dto.setContentType(file.getContentType()); dto.setContentType(file.getContentType());
dto.setFileSize(file.getSize()); dto.setFileSize(file.getSize());
dto.setMinioUploadStatus(1); dto.setPrimaryUploadStatus(1);
dto.setOssUploadStatus(0); dto.setBackupUploadStatus(0);
dto.setOssRetryCount(0); dto.setBackupRetryCount(0);
dto.setStatus(1); dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto); Long fileId = objectStorageFileService.createObjectStorageFile(dto);
@@ -7,7 +7,7 @@ import lombok.NoArgsConstructor;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class OssBackupUploadMessage { public class ObjectStorageBackupMessage {
private Long fileId; private Long fileId;
} }
@@ -26,25 +26,29 @@ public class ObjectStorageFileDTO {
private String objectName; 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 String contentType;
private Long fileSize; 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-回收站 * 文件状态:1-可用,0-不可用,2-回收站
@@ -35,11 +35,17 @@ public class ObjectStorageFileDO extends BaseEntity {
@TableField("object_name") @TableField("object_name")
private String objectName; private String objectName;
@TableField("minio_url") @TableField("primary_provider")
private String minioUrl; private String primaryProvider;
@TableField("oss_url") @TableField("primary_url")
private String ossUrl; private String primaryUrl;
@TableField("backup_provider")
private String backupProvider;
@TableField("backup_url")
private String backupUrl;
@TableField("content_type") @TableField("content_type")
private String contentType; private String contentType;
@@ -47,23 +53,23 @@ public class ObjectStorageFileDO extends BaseEntity {
@TableField("file_size") @TableField("file_size")
private Long fileSize; private Long fileSize;
@TableField("minio_upload_status") @TableField("primary_upload_status")
private Integer minioUploadStatus; private Integer primaryUploadStatus;
@TableField("oss_upload_status") @TableField("backup_upload_status")
private Integer ossUploadStatus; private Integer backupUploadStatus;
@TableField("oss_retry_count") @TableField("backup_retry_count")
private Integer ossRetryCount; private Integer backupRetryCount;
@TableField("oss_last_error") @TableField("backup_last_error")
private String ossLastError; private String backupLastError;
@TableField("oss_uploaded_at") @TableField("backup_uploaded_at")
private LocalDateTime ossUploadedAt; private LocalDateTime backupUploadedAt;
@TableField("oss_last_retry_time") @TableField("backup_last_retry_time")
private LocalDateTime ossLastRetryTime; private LocalDateTime backupLastRetryTime;
/** /**
* 文件状态:1-可用,0-不可用,2-回收站 * 文件状态:1-可用,0-不可用,2-回收站
@@ -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);
}
}
}
@@ -1,7 +1,7 @@
package com.xiaowang.yuminailcore.modules.file.mq; package com.xiaowang.yuminailcore.modules.file.mq;
import com.xiaowang.yuminailcore.config.RabbitMQConfig; import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.xiaowang.yuminailcore.modules.file.dto.OssBackupUploadMessage; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageBackupMessage;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.core.RabbitTemplate;
@@ -10,9 +10,10 @@ import org.springframework.stereotype.Component;
@Slf4j @Slf4j
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class OssBackupMessagePublisher { public class ObjectStorageBackupMessagePublisher {
private final RabbitTemplate rabbitTemplate; private final RabbitTemplate rabbitTemplate;
private final ObjectStorageProperties objectStorageProperties;
public void publish(Long fileId) { public void publish(Long fileId) {
if (fileId == null || fileId <= 0) { if (fileId == null || fileId <= 0) {
@@ -20,12 +21,12 @@ public class OssBackupMessagePublisher {
} }
try { try {
rabbitTemplate.convertAndSend( rabbitTemplate.convertAndSend(
RabbitMQConfig.FILE_OSS_BACKUP_EXCHANGE, objectStorageProperties.getBackupExchangeName(),
RabbitMQConfig.FILE_OSS_BACKUP_ROUTING_KEY, objectStorageProperties.getBackupRoutingKey(),
new OssBackupUploadMessage(fileId) new ObjectStorageBackupMessage(fileId)
); );
} catch (Exception e) { } catch (Exception e) {
log.warn("Publish OSS backup message failed, fileId={}", fileId, e); log.warn("Publish object storage backup message failed, fileId={}", fileId, e);
} }
} }
} }
@@ -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);
}
}
}
@@ -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<ObjectStorageFileDO> 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);
}
}
}
}
@@ -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<ObjectStorageFileDO> 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);
}
}
}
}
@@ -30,6 +30,10 @@ public interface ChunkUploadService {
*/ */
ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
ChunkUploadSessionVO initUserProfileImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
ChunkUploadSessionVO initCommentImageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
/** /**
* Run business method `uploadAdminObjectStorageChunk`. * 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. * 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 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`. * 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. * 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 prepareUserAvatarFile(Long ownerId, String uploadId);
PreparedUploadFile prepareUserProfileImageFile(Long ownerId, String uploadId);
PreparedUploadFile prepareCommentImageFile(Long ownerId, String uploadId);
/** /**
* Run business method `clearAdminObjectStorageUpload`. * 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. * 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 * @param uploadId parameter `uploadId` supplied by the caller
*/ */
void clearUserAvatarUpload(Long ownerId, String uploadId); 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. * 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. * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
@@ -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;
}
@@ -0,0 +1,6 @@
package com.xiaowang.yuminailcore.modules.file.service;
public interface ObjectStorageBackupService {
void backupFile(Long fileId);
}
@@ -1,6 +0,0 @@
package com.xiaowang.yuminailcore.modules.file.service;
public interface OssBackupService {
void backupFileToOss(Long fileId);
}
@@ -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;
}
@@ -105,6 +105,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService {
return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); 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 @Override
/** /**
* Run business method `uploadAdminObjectStorageChunk`. * Run business method `uploadAdminObjectStorageChunk`.
@@ -155,6 +165,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService {
uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); 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 @Override
/** /**
* Run business method `prepareAdminObjectStorageFile`. * Run business method `prepareAdminObjectStorageFile`.
@@ -195,6 +215,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService {
return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); 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 @Override
/** /**
* Run business method `clearAdminObjectStorageUpload`. * Run business method `clearAdminObjectStorageUpload`.
@@ -233,6 +263,16 @@ public class ChunkUploadServiceImpl implements ChunkUploadService {
clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); 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`. * 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. * 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 { private enum UploadTargetType {
ADMIN_OBJECT_STORAGE, ADMIN_OBJECT_STORAGE,
USER_AVATAR USER_AVATAR,
USER_PROFILE_IMAGE,
COMMENT_IMAGE
} }
@Data @Data
@@ -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);
}
}
}
@@ -1,11 +1,12 @@
package com.xiaowang.yuminailcore.modules.file.service.impl; 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.entity.ObjectStorageFileDO;
import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper;
import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; 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.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -17,7 +18,7 @@ import java.time.LocalDateTime;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @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_PENDING = 0;
public static final int UPLOAD_STATUS_SUCCEEDED = 1; 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 static final int MAX_ERROR_LENGTH = 500;
private final ObjectStorageFileMapper objectStorageFileMapper; private final ObjectStorageFileMapper objectStorageFileMapper;
private final MinioService minioService; private final PrimaryObjectStorageService primaryObjectStorageService;
private final AliyunOssService aliyunOssService; private final AliyunOssService aliyunOssService;
private final ObjectStorageFileService objectStorageFileService; private final ObjectStorageFileService objectStorageFileService;
private final ObjectStorageProperties objectStorageProperties;
@Override @Override
public void backupFileToOss(Long fileId) { public void backupFile(Long fileId) {
if (fileId == null || fileId <= 0) { if (fileId == null || fileId <= 0) {
return; return;
} }
@@ -41,16 +43,16 @@ public class OssBackupServiceImpl implements OssBackupService {
return; return;
} }
try (InputStream inputStream = minioService.downloadFile(file.getObjectName())) { try (InputStream inputStream = primaryObjectStorageService.downloadFile(file.getObjectName())) {
String ossUrl = aliyunOssService.uploadStream( String backupUrl = aliyunOssService.uploadStream(
file.getObjectName(), file.getObjectName(),
inputStream, inputStream,
file.getFileSize() == null ? -1L : file.getFileSize(), file.getFileSize() == null ? -1L : file.getFileSize(),
file.getContentType() file.getContentType()
); );
markSucceeded(file, ossUrl); markSucceeded(file, backupUrl);
} catch (Exception e) { } 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); markFailed(file, e);
} }
} }
@@ -58,25 +60,27 @@ public class OssBackupServiceImpl implements OssBackupService {
private boolean shouldBackup(ObjectStorageFileDO file) { private boolean shouldBackup(ObjectStorageFileDO file) {
return file != null return file != null
&& Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus()) && Integer.valueOf(ACTIVE_STATUS).equals(file.getStatus())
&& Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getMinioUploadStatus()) && objectStorageProperties.getPrimaryProvider().equals(file.getPrimaryProvider())
&& !Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getOssUploadStatus()) && 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()); && StringUtils.hasText(file.getObjectName());
} }
private void markSucceeded(ObjectStorageFileDO file, String ossUrl) { private void markSucceeded(ObjectStorageFileDO file, String backupUrl) {
file.setOssUrl(ossUrl); file.setBackupUrl(backupUrl);
file.setOssUploadStatus(UPLOAD_STATUS_SUCCEEDED); file.setBackupUploadStatus(UPLOAD_STATUS_SUCCEEDED);
file.setOssUploadedAt(LocalDateTime.now()); file.setBackupUploadedAt(LocalDateTime.now());
file.setOssLastError(null); file.setBackupLastError(null);
objectStorageFileMapper.updateById(file); objectStorageFileMapper.updateById(file);
objectStorageFileService.evictObjectStorageFileCache(file.getId()); objectStorageFileService.evictObjectStorageFileCache(file.getId());
} }
private void markFailed(ObjectStorageFileDO file, Exception e) { private void markFailed(ObjectStorageFileDO file, Exception e) {
file.setOssUploadStatus(UPLOAD_STATUS_FAILED); file.setBackupUploadStatus(UPLOAD_STATUS_FAILED);
file.setOssRetryCount((file.getOssRetryCount() == null ? 0 : file.getOssRetryCount()) + 1); file.setBackupRetryCount((file.getBackupRetryCount() == null ? 0 : file.getBackupRetryCount()) + 1);
file.setOssLastError(truncateError(e)); file.setBackupLastError(truncateError(e));
file.setOssLastRetryTime(LocalDateTime.now()); file.setBackupLastRetryTime(LocalDateTime.now());
objectStorageFileMapper.updateById(file); objectStorageFileMapper.updateById(file);
objectStorageFileService.evictObjectStorageFileCache(file.getId()); objectStorageFileService.evictObjectStorageFileCache(file.getId());
} }
@@ -3,11 +3,12 @@ package com.xiaowang.yuminailcore.modules.file.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.config.AppCacheProperties;
import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; 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.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
@@ -55,7 +56,8 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final AppCacheProperties appCacheProperties; private final AppCacheProperties appCacheProperties;
private final OssBackupMessagePublisher ossBackupMessagePublisher; private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
private final ObjectStorageProperties objectStorageProperties;
@Override @Override
/** /**
@@ -69,7 +71,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
applyDTO(objectStorageFileDO, objectStorageFileDTO); applyDTO(objectStorageFileDO, objectStorageFileDTO);
objectStorageFileMapper.insert(objectStorageFileDO); objectStorageFileMapper.insert(objectStorageFileDO);
evictFileCache(objectStorageFileDO.getId()); evictFileCache(objectStorageFileDO.getId());
publishOssBackupIfNeeded(objectStorageFileDO); publishBackupIfNeeded(objectStorageFileDO);
return objectStorageFileDO.getId(); return objectStorageFileDO.getId();
} }
@@ -226,16 +228,18 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
objectStorageFileVO.setFileName(objectStorageFileDO.getFileName()); objectStorageFileVO.setFileName(objectStorageFileDO.getFileName());
objectStorageFileVO.setFileUrl(objectStorageFileDO.getFileUrl()); objectStorageFileVO.setFileUrl(objectStorageFileDO.getFileUrl());
objectStorageFileVO.setObjectName(objectStorageFileDO.getObjectName()); objectStorageFileVO.setObjectName(objectStorageFileDO.getObjectName());
objectStorageFileVO.setMinioUrl(objectStorageFileDO.getMinioUrl()); objectStorageFileVO.setPrimaryProvider(objectStorageFileDO.getPrimaryProvider());
objectStorageFileVO.setOssUrl(objectStorageFileDO.getOssUrl()); objectStorageFileVO.setPrimaryUrl(objectStorageFileDO.getPrimaryUrl());
objectStorageFileVO.setBackupProvider(objectStorageFileDO.getBackupProvider());
objectStorageFileVO.setBackupUrl(objectStorageFileDO.getBackupUrl());
objectStorageFileVO.setContentType(objectStorageFileDO.getContentType()); objectStorageFileVO.setContentType(objectStorageFileDO.getContentType());
objectStorageFileVO.setFileSize(objectStorageFileDO.getFileSize()); objectStorageFileVO.setFileSize(objectStorageFileDO.getFileSize());
objectStorageFileVO.setMinioUploadStatus(objectStorageFileDO.getMinioUploadStatus()); objectStorageFileVO.setPrimaryUploadStatus(objectStorageFileDO.getPrimaryUploadStatus());
objectStorageFileVO.setOssUploadStatus(objectStorageFileDO.getOssUploadStatus()); objectStorageFileVO.setBackupUploadStatus(objectStorageFileDO.getBackupUploadStatus());
objectStorageFileVO.setOssRetryCount(objectStorageFileDO.getOssRetryCount()); objectStorageFileVO.setBackupRetryCount(objectStorageFileDO.getBackupRetryCount());
objectStorageFileVO.setOssLastError(objectStorageFileDO.getOssLastError()); objectStorageFileVO.setBackupLastError(objectStorageFileDO.getBackupLastError());
objectStorageFileVO.setOssUploadedAt(objectStorageFileDO.getOssUploadedAt()); objectStorageFileVO.setBackupUploadedAt(objectStorageFileDO.getBackupUploadedAt());
objectStorageFileVO.setOssLastRetryTime(objectStorageFileDO.getOssLastRetryTime()); objectStorageFileVO.setBackupLastRetryTime(objectStorageFileDO.getBackupLastRetryTime());
objectStorageFileVO.setCreateTime(objectStorageFileDO.getCreateTime()); objectStorageFileVO.setCreateTime(objectStorageFileDO.getCreateTime());
objectStorageFileVO.setStatus(objectStorageFileDO.getStatus()); objectStorageFileVO.setStatus(objectStorageFileDO.getStatus());
objectStorageFileVO.setDeleteTime(objectStorageFileDO.getDeleteTime()); objectStorageFileVO.setDeleteTime(objectStorageFileDO.getDeleteTime());
@@ -247,26 +251,29 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName()); objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName());
objectStorageFileDO.setFileUrl(objectStorageFileDTO.getFileUrl()); objectStorageFileDO.setFileUrl(objectStorageFileDTO.getFileUrl());
objectStorageFileDO.setObjectName(objectStorageFileDTO.getObjectName()); objectStorageFileDO.setObjectName(objectStorageFileDTO.getObjectName());
objectStorageFileDO.setMinioUrl(objectStorageFileDTO.getMinioUrl()); objectStorageFileDO.setPrimaryProvider(objectStorageFileDTO.getPrimaryProvider());
objectStorageFileDO.setOssUrl(objectStorageFileDTO.getOssUrl()); objectStorageFileDO.setPrimaryUrl(objectStorageFileDTO.getPrimaryUrl());
objectStorageFileDO.setBackupProvider(objectStorageFileDTO.getBackupProvider());
objectStorageFileDO.setBackupUrl(objectStorageFileDTO.getBackupUrl());
objectStorageFileDO.setContentType(objectStorageFileDTO.getContentType()); objectStorageFileDO.setContentType(objectStorageFileDTO.getContentType());
objectStorageFileDO.setFileSize(objectStorageFileDTO.getFileSize()); objectStorageFileDO.setFileSize(objectStorageFileDTO.getFileSize());
objectStorageFileDO.setMinioUploadStatus(objectStorageFileDTO.getMinioUploadStatus()); objectStorageFileDO.setPrimaryUploadStatus(objectStorageFileDTO.getPrimaryUploadStatus());
objectStorageFileDO.setOssUploadStatus(objectStorageFileDTO.getOssUploadStatus()); objectStorageFileDO.setBackupUploadStatus(objectStorageFileDTO.getBackupUploadStatus());
objectStorageFileDO.setOssRetryCount(objectStorageFileDTO.getOssRetryCount()); objectStorageFileDO.setBackupRetryCount(objectStorageFileDTO.getBackupRetryCount());
objectStorageFileDO.setOssLastError(objectStorageFileDTO.getOssLastError()); objectStorageFileDO.setBackupLastError(objectStorageFileDTO.getBackupLastError());
objectStorageFileDO.setOssUploadedAt(objectStorageFileDTO.getOssUploadedAt()); objectStorageFileDO.setBackupUploadedAt(objectStorageFileDTO.getBackupUploadedAt());
objectStorageFileDO.setOssLastRetryTime(objectStorageFileDTO.getOssLastRetryTime()); objectStorageFileDO.setBackupLastRetryTime(objectStorageFileDTO.getBackupLastRetryTime());
objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus()); objectStorageFileDO.setStatus(objectStorageFileDTO.getStatus());
objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime()); objectStorageFileDO.setDeleteTime(objectStorageFileDTO.getDeleteTime());
objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime()); objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime());
} }
private void publishOssBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) { private void publishBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) {
if (StringUtils.hasText(objectStorageFileDO.getObjectName()) if (StringUtils.hasText(objectStorageFileDO.getObjectName())
&& Integer.valueOf(1).equals(objectStorageFileDO.getMinioUploadStatus()) && objectStorageProperties.getPrimaryProvider().equals(objectStorageFileDO.getPrimaryProvider())
&& Integer.valueOf(0).equals(objectStorageFileDO.getOssUploadStatus())) { && Integer.valueOf(1).equals(objectStorageFileDO.getPrimaryUploadStatus())
ossBackupMessagePublisher.publish(objectStorageFileDO.getId()); && Integer.valueOf(0).equals(objectStorageFileDO.getBackupUploadStatus())) {
objectStorageBackupMessagePublisher.publish(objectStorageFileDO.getId());
} }
} }
@@ -0,0 +1,122 @@
package com.xiaowang.yuminailcore.modules.file.service.impl;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.xiaowang.yuminailcore.modules.file.config.QiniuKodoConfig;
import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@RequiredArgsConstructor
public class QiniuObjectStorageServiceImpl implements PrimaryObjectStorageService {
private final QiniuKodoConfig qiniuKodoConfig;
private final ObjectStorageProperties objectStorageProperties;
private final Auth qiniuAuth;
private final UploadManager qiniuUploadManager;
private final BucketManager qiniuBucketManager;
@Override
public String uploadFile(MultipartFile file, String objectName) throws Exception {
try (InputStream inputStream = file.getInputStream()) {
return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName);
}
}
@Override
public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception {
byte[] bytes = toBytes(inputStream);
String uploadToken = qiniuAuth.uploadToken(
qiniuKodoConfig.getBucketName(),
objectName,
buildUploadPolicyExpirySeconds(),
new StringMap()
);
Response response = qiniuUploadManager.put(
bytes,
objectName,
uploadToken,
null,
contentType,
false
);
DefaultPutRet putRet = response.jsonToObject(DefaultPutRet.class);
log.info("七牛云文件上传成功, key={}", putRet.key);
return getFileUrl(objectName);
}
@Override
public InputStream downloadFile(String objectName) throws Exception {
URL url = new URL(getPresignedUrl(objectName, objectStorageProperties.getSignedUrlExpireMinutes()));
return url.openStream();
}
@Override
public void deleteFile(String objectName) throws Exception {
qiniuBucketManager.delete(qiniuKodoConfig.getBucketName(), objectName);
log.info("七牛云文件删除成功, key={}", objectName);
}
@Override
public String getFileUrl(String objectName) {
return normalizeDomain(qiniuKodoConfig.getDomain()) + "/" + objectName;
}
@Override
public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) throws Exception {
if (!Boolean.TRUE.equals(qiniuKodoConfig.getPrivateBucket())) {
return getFileUrl(objectName);
}
int expireMinutes = expiryTimeInMinutes == null || expiryTimeInMinutes <= 0
? qiniuKodoConfig.getSignedUrlExpireMinutes()
: expiryTimeInMinutes;
return qiniuAuth.privateDownloadUrl(
getFileUrl(objectName),
TimeUnit.MINUTES.toSeconds(expireMinutes)
);
}
private long buildUploadPolicyExpirySeconds() {
return TimeUnit.MINUTES.toSeconds(qiniuKodoConfig.getSignedUrlExpireMinutes());
}
private byte[] toBytes(InputStream inputStream) throws Exception {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[8192];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return outputStream.toByteArray();
}
}
private String normalizeDomain(String domain) {
String normalized = domain.trim();
while (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
if (!StringUtils.hasText(normalized)) {
throw new IllegalStateException("Qiniu domain is blank");
}
if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) {
return "http://" + normalized;
}
return normalized;
}
}
@@ -1,8 +1,9 @@
package com.xiaowang.yuminailcore.modules.file.support; package com.xiaowang.yuminailcore.modules.file.support;
import com.xiaowang.yuminailcore.config.MinioConfig; import com.xiaowang.yuminailcore.config.ObjectStorageProperties;
import com.xiaowang.yuminailcore.modules.file.config.QiniuKodoConfig;
import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService;
import com.xiaowang.yuminailcore.modules.file.service.MinioService; import com.xiaowang.yuminailcore.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -16,16 +17,12 @@ import java.net.URI;
@RequiredArgsConstructor @RequiredArgsConstructor
public class ObjectStorageUrlSupport { public class ObjectStorageUrlSupport {
private static final int DEFAULT_SIGNED_URL_EXPIRE_MINUTES = 60;
private static final long MINIO_HEALTH_CACHE_MILLIS = 60_000L;
private static final int UPLOAD_STATUS_SUCCEEDED = 1; private static final int UPLOAD_STATUS_SUCCEEDED = 1;
private final MinioService minioService; private final PrimaryObjectStorageService primaryObjectStorageService;
private final MinioConfig minioConfig; private final QiniuKodoConfig qiniuKodoConfig;
private final AliyunOssService aliyunOssService; private final AliyunOssService aliyunOssService;
private final ObjectStorageProperties objectStorageProperties;
private volatile boolean minioHealthy = true;
private volatile long minioHealthCheckedAt = 0L;
public String toAccessibleUrl(String fileUrl) { public String toAccessibleUrl(String fileUrl) {
if (!StringUtils.hasText(fileUrl)) { if (!StringUtils.hasText(fileUrl)) {
@@ -36,15 +33,18 @@ public class ObjectStorageUrlSupport {
return fileUrl; return fileUrl;
} }
try { try {
return signWithMinio(objectName, DEFAULT_SIGNED_URL_EXPIRE_MINUTES); return primaryObjectStorageService.getPresignedUrl(
objectName,
objectStorageProperties.getSignedUrlExpireMinutes()
);
} catch (Exception e) { } catch (Exception e) {
log.warn("Generate MinIO signed URL failed, fallback to safe display URL: {}", fileUrl, e); log.warn("生成主对象存储访问链接失败, fileUrl={}", fileUrl, e);
return null; return null;
} }
} }
public String toAccessibleUrl(ObjectStorageFileVO file) { public String toAccessibleUrl(ObjectStorageFileVO file) {
return toAccessibleUrl(file, DEFAULT_SIGNED_URL_EXPIRE_MINUTES); return toAccessibleUrl(file, objectStorageProperties.getSignedUrlExpireMinutes());
} }
public String toAccessibleUrl(ObjectStorageFileVO file, Integer expiryTimeInMinutes) { public String toAccessibleUrl(ObjectStorageFileVO file, Integer expiryTimeInMinutes) {
@@ -54,8 +54,8 @@ public class ObjectStorageUrlSupport {
try { try {
return getSignedUrlOrThrow(file, expiryTimeInMinutes); return getSignedUrlOrThrow(file, expiryTimeInMinutes);
} catch (Exception e) { } catch (Exception e) {
String fallback = hasObjectStorageReference(file) ? null : firstText(file.getFileUrl(), file.getMinioUrl()); String fallback = hasObjectStorageReference(file) ? null : firstText(file.getFileUrl(), file.getPrimaryUrl());
log.warn("Generate object storage signed URL failed, fallback to safe display URL, fileId={}", file.getId(), e); log.warn("生成对象存储访问链接失败, fileId={}", file.getId(), e);
return fallback; return fallback;
} }
} }
@@ -69,21 +69,15 @@ public class ObjectStorageUrlSupport {
throw new IllegalStateException("No available object storage signed URL: objectName is empty"); throw new IllegalStateException("No available object storage signed URL: objectName is empty");
} }
Exception minioFailure = null; Exception primaryFailure = null;
int minioExpiry = expiryTimeInMinutes == null || expiryTimeInMinutes <= 0 try {
? DEFAULT_SIGNED_URL_EXPIRE_MINUTES return primaryObjectStorageService.getPresignedUrl(objectName, expiryTimeInMinutes);
: expiryTimeInMinutes; } catch (Exception e) {
if (shouldTryMinio()) { primaryFailure = e;
try { log.warn("生成主对象存储访问链接失败, fileId={}, objectName={}", file.getId(), objectName, e);
return signWithMinio(objectName, minioExpiry);
} catch (Exception e) {
minioFailure = e;
markMinioHealth(false);
log.warn("Generate MinIO signed URL failed, fileId={}, objectName={}", file.getId(), objectName, e);
}
} }
if (Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getOssUploadStatus())) { if (Integer.valueOf(UPLOAD_STATUS_SUCCEEDED).equals(file.getBackupUploadStatus())) {
try { try {
return aliyunOssService.getPresignedUrl(objectName); return aliyunOssService.getPresignedUrl(objectName);
} catch (Exception e) { } catch (Exception e) {
@@ -91,9 +85,7 @@ public class ObjectStorageUrlSupport {
"No available object storage signed URL for fileId=" + file.getId(), "No available object storage signed URL for fileId=" + file.getId(),
e e
); );
if (minioFailure != null) { failure.addSuppressed(primaryFailure);
failure.addSuppressed(minioFailure);
}
throw failure; throw failure;
} }
} }
@@ -101,9 +93,7 @@ public class ObjectStorageUrlSupport {
IllegalStateException failure = new IllegalStateException( IllegalStateException failure = new IllegalStateException(
"No available object storage signed URL for fileId=" + file.getId() "No available object storage signed URL for fileId=" + file.getId()
); );
if (minioFailure != null) { failure.addSuppressed(primaryFailure);
failure.addSuppressed(minioFailure);
}
throw failure; throw failure;
} }
@@ -115,7 +105,7 @@ public class ObjectStorageUrlSupport {
if (!StringUtils.hasText(objectName)) { if (!StringUtils.hasText(objectName)) {
return fileUrl; return fileUrl;
} }
return minioService.getFileUrl(objectName); return primaryObjectStorageService.getFileUrl(objectName);
} }
public String extractObjectName(String fileUrl) { public String extractObjectName(String fileUrl) {
@@ -125,18 +115,18 @@ public class ObjectStorageUrlSupport {
String normalizedUrl = fileUrl.trim(); String normalizedUrl = fileUrl.trim();
if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
return trimBucketPrefix(stripQuery(normalizedUrl)); return stripQuery(stripLeadingSlash(normalizedUrl));
} }
try { try {
URI fileUri = URI.create(normalizedUrl); URI fileUri = URI.create(normalizedUrl);
String path = fileUri.getPath(); URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain()));
if (!StringUtils.hasText(path)) { if (!sameAuthority(fileUri, domainUri)) {
return ""; return "";
} }
return extractObjectNameFromUri(fileUri); return stripQuery(stripLeadingSlash(fileUri.getPath()));
} catch (Exception e) { } catch (Exception e) {
log.warn("Parse object storage URL failed: {}", fileUrl, e); log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e);
return ""; return "";
} }
} }
@@ -145,7 +135,7 @@ public class ObjectStorageUrlSupport {
if (StringUtils.hasText(file.getObjectName())) { if (StringUtils.hasText(file.getObjectName())) {
return file.getObjectName(); return file.getObjectName();
} }
String objectName = extractObjectName(file.getMinioUrl()); String objectName = extractObjectName(file.getPrimaryUrl());
if (StringUtils.hasText(objectName)) { if (StringUtils.hasText(objectName)) {
return objectName; return objectName;
} }
@@ -154,28 +144,10 @@ public class ObjectStorageUrlSupport {
private boolean hasObjectStorageReference(ObjectStorageFileVO file) { private boolean hasObjectStorageReference(ObjectStorageFileVO file) {
return StringUtils.hasText(file.getObjectName()) return StringUtils.hasText(file.getObjectName())
|| StringUtils.hasText(extractObjectName(file.getMinioUrl())) || StringUtils.hasText(extractObjectName(file.getPrimaryUrl()))
|| StringUtils.hasText(extractObjectName(file.getFileUrl())); || StringUtils.hasText(extractObjectName(file.getFileUrl()));
} }
private String signWithMinio(String objectName, int expiryTimeInMinutes) throws Exception {
String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes);
markMinioHealth(true);
return signedUrl;
}
private boolean shouldTryMinio() {
if (minioHealthy) {
return true;
}
return System.currentTimeMillis() - minioHealthCheckedAt >= MINIO_HEALTH_CACHE_MILLIS;
}
private void markMinioHealth(boolean healthy) {
minioHealthy = healthy;
minioHealthCheckedAt = System.currentTimeMillis();
}
private String firstText(String... values) { private String firstText(String... values) {
if (values == null) { if (values == null) {
return null; return null;
@@ -188,53 +160,15 @@ public class ObjectStorageUrlSupport {
return null; return null;
} }
private String extractObjectNameFromPath(String path) { private String normalizeDomain(String domain) {
String bucketPrefix = "/" + minioConfig.getBucketName() + "/"; String normalized = domain.trim();
if (path.startsWith(bucketPrefix)) { while (normalized.endsWith("/")) {
return path.substring(bucketPrefix.length()); normalized = normalized.substring(0, normalized.length() - 1);
} }
if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) {
String endpointPath = ""; return "http://" + normalized;
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 "";
} }
return normalized;
} }
private boolean sameAuthority(URI left, URI right) { private boolean sameAuthority(URI left, URI right) {
@@ -252,24 +186,6 @@ public class ObjectStorageUrlSupport {
return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; 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) { private String stripLeadingSlash(String rawValue) {
String normalized = rawValue; String normalized = rawValue;
while (normalized.startsWith("/")) { while (normalized.startsWith("/")) {
@@ -31,25 +31,29 @@ public class ObjectStorageFileVO {
private String objectName; 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 String contentType;
private Long fileSize; 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,5 +1,7 @@
package com.xiaowang.yuminailcore.modules.product.vo; 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 lombok.Data;
import java.math.BigDecimal; import java.math.BigDecimal;
@@ -20,11 +22,13 @@ public class ProductVO {
/** /**
* 商品唯一主键ID(雪花id) * 商品唯一主键ID(雪花id)
*/ */
@JsonSerialize(using = ToStringSerializer.class)
private Long id; private Long id;
/** /**
* 所属店铺ID,关联店铺表主键 * 所属店铺ID,关联店铺表主键
*/ */
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId; private Long shopId;
/** /**
@@ -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.UserVO;
import com.xiaowang.yuminailcore.modules.user.vo.InviteCodeVO; import com.xiaowang.yuminailcore.modules.user.vo.InviteCodeVO;
import com.xiaowang.yuminailcore.modules.integration.vo.WechatMiniLoginResultVO; 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.UserAssetService;
import com.xiaowang.yuminailcore.modules.user.service.UserService; import com.xiaowang.yuminailcore.modules.user.service.UserService;
import com.xiaowang.yuminailcore.modules.security.service.ShopRoleService; import com.xiaowang.yuminailcore.modules.security.service.ShopRoleService;
@@ -95,9 +95,9 @@ public class UserController {
*/ */
private final UserAssetService userAssetService; 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. * 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 fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; 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); userService.updateUserAvatar(userId, avatarUrl);
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
@@ -802,7 +802,7 @@ public class UserController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String avatarUrl = minioService.uploadFile(file, objectName); String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName);
userService.updateUserAvatar(userId, avatarUrl); userService.updateUserAvatar(userId, avatarUrl);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(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<ChunkUploadSessionVO> 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<Boolean> 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<String> 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<Boolean> cancelProfileImageUpload(HttpServletRequest request, @PathVariable String uploadId) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.clearUserProfileImageUpload(userId, uploadId);
return Result.success(true);
}
@PostMapping("/upload-profile-image") @PostMapping("/upload-profile-image")
@OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") @OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
public Result<String> uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { public Result<String> uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
@@ -835,7 +884,7 @@ public class UserController {
fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
} }
String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension; 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)); return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -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. * 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) { 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("上传文件大小不合法"); throw new RuntimeException("上传文件大小不合法");
} }
String extension = resolveExtension(filename); String extension = resolveExtension(filename);
+33 -3
View File
@@ -1,6 +1,6 @@
spring: spring:
datasource: 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: servlet:
multipart: multipart:
max-file-size: 5MB max-file-size: 5MB
@@ -25,10 +25,10 @@ mybatis:
configuration: configuration:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
yuminail: fingertip-designer:
security: security:
jwt: jwt:
issuer: yuminail issuer: fingertip-designer
access-token-expiration-seconds: 7200 access-token-expiration-seconds: 7200
refresh-token-expiration-seconds: 604800 refresh-token-expiration-seconds: 604800
clock-skew-seconds: 30 clock-skew-seconds: 30
@@ -85,3 +85,33 @@ yuminail:
connection-request-timeout-ms: 1000 connection-request-timeout-ms: 1000
max-total-connections: 200 max-total-connections: 200
max-connections-per-route: 50 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}
+34 -40
View File
@@ -1,57 +1,51 @@
spring: spring:
application: application:
name: yumi-nail-core name: fingertip-designer-core
cloud: cloud:
nacos: nacos:
discovery: discovery:
# Nacos集群地址 # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# 命名空间ID # Nacos 命名空间,默认指向开发环境。
namespace: YumiNail-Dev namespace: ${NACOS_NAMESPACE:YumiNail-Dev}
# 分组名称 # 服务注册分组。
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
# 服务名称 # 注册到 Nacos 的服务名。
service: ${spring.application.name} service: ${spring.application.name}
# 是否启用服务发现 # 是否启用服务发现。
enabled: true enabled: true
# 是否启用服务注册 # 是否将当前服务注册到 Nacos。
register-enabled: true register-enabled: true
# Nacos认证用户名 # Nacos 认证用户名。
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码 # Nacos 认证密码。
password: 122503wcy.... password: ${NACOS_PASSWORD:122503wcy....}
config: config:
# Nacos配置中心集群地址 # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# 配置中心命名空间 # Nacos 配置中心命名空间,默认指向开发环境。
namespace: YumiNail-Dev namespace: ${NACOS_NAMESPACE:YumiNail-Dev}
# 配置分组 # 配置分组。
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
# 配置文件名称 # Core 服务独有配置文件。
name: yuminail-core name: core
# 配置文件扩展名 # 所有 Nacos 配置均使用 YAML。
file-extension: yaml file-extension: yaml
# 是否启用配置中心 # 是否启用配置中心。
enabled: true enabled: true
# Nacos认证用户名 # Nacos 认证用户名。
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码 # Nacos 认证密码。
password: 122503wcy.... password: ${NACOS_PASSWORD:122503wcy....}
# 共享配置文件列表 # Core 与 Gateway 共享的公共配置文件。
shared-configs: shared-configs:
- data-id: rabbit-mq.yaml - data-id: infra.yaml
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true refresh: true
- data-id: datasource.yaml - data-id: secret.yaml
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: mybatis-plus.yaml
group: DEFAULT_GROUP
refresh: true refresh: true
- data-id: logging.yaml - data-id: logging.yaml
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: redis.yaml
group: DEFAULT_GROUP
refresh: true refresh: true
File diff suppressed because it is too large Load Diff
+12
View File
@@ -367,8 +367,20 @@ export const adminLegalAgreementApi = {
export interface ObjectStorageFileVO { export interface ObjectStorageFileVO {
id: IdType id: IdType
fileName: string fileName: string
fileUrl?: string
objectName?: string
primaryProvider?: string
primaryUrl?: string
backupProvider?: string
backupUrl?: string
fileSize: number fileSize: number
contentType: string contentType: string
primaryUploadStatus?: number
backupUploadStatus?: number
backupRetryCount?: number
backupLastError?: string
backupUploadedAt?: string
backupLastRetryTime?: string
createTime: string createTime: string
} }
+28
View File
@@ -3,6 +3,8 @@
* Call guide: import the named API object, then call the matching method from a Vue page or composable. * Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/ */
import api from './index' import api from './index'
import type { AxiosProgressEvent } from 'axios'
import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
/** /**
@@ -75,6 +77,32 @@ export const commentApi = {
} }
}) as unknown as Promise<CommentImageFileVO> }) as unknown as Promise<CommentImageFileVO>
}, },
initImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/comment/upload-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
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<boolean>('/comment/upload-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeImageChunkUpload: (uploadId: string) => {
return api.post<CommentImageFileVO>('/comment/upload-image/complete', { uploadId }) as unknown as Promise<CommentImageFileVO>
},
cancelImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/comment/upload-image/${uploadId}`)
},
/** /**
* `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * `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. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
+49
View File
@@ -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
})
})
})
+90
View File
@@ -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
}
}
+26
View File
@@ -114,6 +114,32 @@ export const fileApi = {
cancelAvatarChunkUpload: (uploadId: string) => { cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`) return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
}, },
initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-profile-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
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<boolean>('/user/upload-profile-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeProfileImageChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise<string>
},
cancelProfileImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-profile-image/${uploadId}`)
},
/** /**
* `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
+88 -39
View File
@@ -6,12 +6,23 @@ import axios, { AxiosError } from 'axios'
import { authApi } from './auth' import { authApi } from './auth'
import { adminAuthApi } from './admin' import { adminAuthApi } from './admin'
import { wishlistApi } from './wishlist' 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 { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
import { clearAdminSessionStorage } from '@/utils/admin-session' import { clearAdminSessionStorage } from '@/utils/admin-session'
import { attachRequestSignature } from '@/utils/request-signature' import { attachRequestSignature } from '@/utils/request-signature'
import { isApiAuthFreePath } from './auth-free-paths' import { isApiAuthFreePath } from './auth-free-paths'
import {
getApiResponseMessage,
isPermissionErrorMessage,
isSystemFailureResponse,
isTokenExpiredResponse,
normalizeApiErrorMessage,
shouldShowDedupedError,
updateSystemFailureWindow,
updateErrorPromptState,
type ErrorPromptState
} from './error'
// 防重复提示标志 // 防重复提示标志
let lastErrorTime = 0 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. * 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 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. * 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)) 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. * 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. * 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 => { failedQueue.forEach(prom => {
if (error) { if (error) {
prom.reject(error) prom.reject(error)
@@ -139,11 +131,65 @@ const processQueue = (error: any, token: string | null = null) => {
// 防抖处理错误提示 // 防抖处理错误提示
const showError = (msg: string) => { const showError = (msg: string) => {
const now = Date.now() const now = Date.now()
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { const state: ErrorPromptState = { lastErrorTime, lastErrorMessage }
lastErrorTime = now if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) {
lastErrorMessage = msg return
message.error(msg)
} }
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( api.interceptors.response.use(
response => { response => {
resetSystemFailureWindow()
const res = response.data const res = response.data
if (res.code !== 200) { if (res.code !== 200) {
const errorMsg = res.message || '请求失败' const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) { if (!isPermissionErrorMessage(errorMsg)) {
showError(errorMsg) showError(errorMsg)
} }
return Promise.reject(new Error(errorMsg)) return Promise.reject(new Error(errorMsg))
@@ -245,7 +292,7 @@ api.interceptors.response.use(
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken) const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
if (!isRealTokenExpired) { if (!isRealTokenExpired) {
showError(getResponseMessage(error)) showError(getApiResponseMessage(error, '请求失败'))
return Promise.reject(error) return Promise.reject(error)
} }
@@ -319,8 +366,10 @@ api.interceptors.response.use(
return Promise.reject(error) return Promise.reject(error)
} }
} else if (error.response?.status !== 403) { // 403权限不足不提示 } else if (error.response?.status !== 403) { // 403权限不足不提示
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败' const errorMsg = getApiResponseMessage(error, '请求失败')
showError(errorMsg) if (!recordSystemFailure(error)) {
showError(errorMsg)
}
} }
return Promise.reject(error) return Promise.reject(error)
} }
@@ -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')
})
})
@@ -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)
+2 -19
View File
@@ -5,6 +5,7 @@ import {
isBootstrapAdminUser, isBootstrapAdminUser,
loadCachedAdminUserInfo, loadCachedAdminUserInfo,
} from '@/utils/admin-session' } from '@/utils/admin-session'
import { ADMIN_DASHBOARD_PATH, adminPermissionRouteMap } from '@/config/admin-navigation'
import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions' import { isAllowedForShoplessPlatformAdmin } from '@/utils/platform-admin-permissions'
import { import {
clearStoredPermissions, clearStoredPermissions,
@@ -12,7 +13,6 @@ import {
getStoredUserPermissions, getStoredUserPermissions,
} from '@/utils/permission' } 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. * 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<AuthBootstrapState>('pending') const adminBootstrapState = ref<AuthBootstrapState>('pending')
let bootstrapPromise: Promise<AuthBootstrapState> | null = null let bootstrapPromise: Promise<AuthBootstrapState> | 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. * 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 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' return matchedRoute?.path || '/admin'
} }
@@ -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<string | number | null | undefined>, 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' }
])
})
})
+104
View File
@@ -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<string> => getCachedSignedImageUrl(fileId, fallback, 'admin')
export const refreshSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback: string
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'admin')
export const resolveSignedImageUrls = async (
fileIdsValue: string | null | undefined,
fallback: string,
emptyFallback: boolean
): Promise<string[]> => {
const fileIds = parseImageFileIds(fileIdsValue)
if (!fileIds.length) {
return emptyFallback ? [fallback] : []
}
return getCachedSignedImageUrls(fileIds, fallback, 'admin')
}
export const buildSignedImageUrlMap = async <TRecord extends SignedImageRecord>(
records: TRecord[],
fieldName: ImageFieldName,
fallback: string,
emptyFallback: boolean,
isCancelled: () => boolean
): Promise<Record<string, string[]> | null> => {
const nextImageUrls: Record<string, string[]> = {}
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 = <TRecord extends { id?: IdType }>(
record: TRecord,
imageUrlMap: Record<string, string[]>,
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<AdminUploadFileItem[]> => {
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
}
+17
View File
@@ -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)
})
})
+35
View File
@@ -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
})
@@ -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()
})
})
@@ -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 ''
}
@@ -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<string> = {
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<string> = {
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)
)
})
})
+44 -48
View File
@@ -1,9 +1,5 @@
import type { AxiosProgressEvent } from 'axios' 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 { export interface ChunkUploadSession {
uploadId: string uploadId: string
chunkSize: number chunkSize: number
@@ -11,10 +7,6 @@ export interface ChunkUploadSession {
uploadedChunks: number[] 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 { export interface ChunkUploadInitRequest {
fileName: string fileName: string
fileSize: number fileSize: number
@@ -23,10 +15,6 @@ export interface ChunkUploadInitRequest {
scene: string 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<TResponse> { export interface ChunkUploadApi<TResponse> {
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession> initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
uploadChunk: ( uploadChunk: (
@@ -37,42 +25,27 @@ export interface ChunkUploadApi<TResponse> {
cancelUpload?: (uploadId: string) => Promise<unknown> cancelUpload?: (uploadId: string) => Promise<unknown>
} }
/**
* 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<TResponse> { export interface ChunkUploadOptions<TResponse> {
file: File file: File
scene: string scene: string
api: ChunkUploadApi<TResponse> api: ChunkUploadApi<TResponse>
concurrency: number
preprocessFile?: (file: File) => Promise<File> preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void 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<TResponse> { export interface ChunkUploadResult<TResponse> {
response: TResponse response: TResponse
uploadId: string uploadId: string
processedFile: File 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<TResponse> { export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>> promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void cancel: () => void
getUploadId: () => string 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 computeFileFingerprint = async (file: File) => {
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}` const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
if (!window.crypto?.subtle) { if (!window.crypto?.subtle) {
@@ -84,32 +57,37 @@ const computeFileFingerprint = async (file: File) => {
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('') 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 getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
const start = chunkIndex * chunkSize const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileSize) const end = Math.min(start + chunkSize, fileSize)
return Math.max(end - start, 0) return Math.max(end - start, 0)
} }
/** const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) =>
* Purpose: calculateUploadedBytes supports chunk-upload.ts by holding or executing the calculate uploaded bytes page or API role. uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ const normalizeConcurrency = (concurrency: number) => {
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => { if (!Number.isFinite(concurrency) || concurrency < 1) {
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0) return 1
}
return Math.floor(concurrency)
}
const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set<number>) => {
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 = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => { export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
const abortController = new AbortController() const abortController = new AbortController()
let uploadId = '' let uploadId = ''
let cancelled = false let cancelled = false
const cleanupCancelledSession = async () => { const cleanupCancelledSession = async () => {
if (uploadId && options.api.cancelUpload) { if (uploadId && options.api.cancelUpload) {
await options.api.cancelUpload(uploadId).catch(() => undefined) await options.api.cancelUpload(uploadId).catch(() => undefined)
@@ -135,16 +113,29 @@ export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TRe
const uploadedChunkSet = new Set(session.uploadedChunks || []) const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet)) let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
const uploadingChunkBytes = new Map<number, number>()
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)) 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<void> => {
const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor]
nextChunkIndexCursor += 1
if (chunkIndex === undefined) {
return
}
if (cancelled) { if (cancelled) {
await cleanupCancelledSession() await cleanupCancelledSession()
throw new Error('上传已取消') throw new Error('上传已取消')
} }
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * session.chunkSize const start = chunkIndex * session.chunkSize
const end = Math.min(start + session.chunkSize, processedFile.size) const end = Math.min(start + session.chunkSize, processedFile.size)
@@ -162,17 +153,22 @@ export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TRe
signal: abortController.signal, signal: abortController.signal,
onUploadProgress: (event) => { onUploadProgress: (event) => {
const loaded = Math.min(event.loaded || 0, chunkBytes) const loaded = Math.min(event.loaded || 0, chunkBytes)
const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100 uploadingChunkBytes.set(chunkIndex, loaded)
options.onProgress?.(Math.min(percent, 99.9)) emitProgress(99.9)
} }
} }
) )
uploadedChunkSet.add(chunkIndex) uploadedChunkSet.add(chunkIndex)
uploadedBytes += chunkBytes uploadedBytes += chunkBytes
uploadingChunkBytes.delete(chunkIndex)
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9)) 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) { if (cancelled) {
await cleanupCancelledSession() await cleanupCancelledSession()
throw new Error('上传已取消') throw new Error('上传已取消')
@@ -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'])
})
})
@@ -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<string[]> => {
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<string> => {
const urls = await resolvePublicImageUrls(record, fallback)
return urls[0] || fallback
}
export const refreshPublicImageUrl = async (
fileId: IdType | null | undefined,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'public')
@@ -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)
})
})
+61 -12
View File
@@ -1,8 +1,11 @@
import { fileApi } from '@/api/file' import { fileApi } from '@/api/file'
import { adminFileApi } from '@/api/admin'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000 const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
export type SignedImageSource = 'public' | 'admin'
type SignedImageCacheEntry = { type SignedImageCacheEntry = {
url: string url: string
expiresAt: number expiresAt: number
@@ -12,6 +15,22 @@ const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>() const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim() 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<string> => {
if (source === 'admin') {
return adminFileApi.getSignedUrl(fileId)
}
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
}
const getUsableCacheEntry = (key: string) => { const getUsableCacheEntry = (key: string) => {
const cached = signedImageUrlCache.get(key) const cached = signedImageUrlCache.get(key)
@@ -29,17 +48,23 @@ export const parseImageFileIds = (value?: string | null): string[] =>
.map(id => id.trim()) .map(id => id.trim())
.filter(Boolean) .filter(Boolean)
export const getCachedSignedImageUrlSync = (fileId: IdType | null | undefined): string => { export const getCachedSignedImageUrlSync = (
const key = normalizeFileId(fileId) fileId: IdType | null | undefined,
return key ? getUsableCacheEntry(key) || '' : '' source: SignedImageSource = 'public'
): string => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return ''
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
} }
export const getCachedSignedImageUrl = async ( export const getCachedSignedImageUrl = async (
fileId: IdType | null | undefined, fileId: IdType | null | undefined,
fallback = '' fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => { ): Promise<string> => {
const key = normalizeFileId(fileId) const fileIdKey = normalizeFileId(fileId)
if (!key) return fallback if (!fileIdKey) return fallback
const key = buildCacheKey(source, fileIdKey)
const cachedUrl = getUsableCacheEntry(key) const cachedUrl = getUsableCacheEntry(key)
if (cachedUrl) return cachedUrl if (cachedUrl) return cachedUrl
@@ -49,9 +74,9 @@ export const getCachedSignedImageUrl = async (
return pendingRequest.then(url => url || fallback).catch(() => fallback) return pendingRequest.then(url => url || fallback).catch(() => fallback)
} }
const request = fileApi.getSignedUrl(key) const request = requestSignedImageUrl(source, fileIdKey)
.then(response => { .then(response => {
const url = String(response || '').trim() const url = normalizeImageUrl(String(response || ''))
if (url) { if (url) {
signedImageUrlCache.set(key, { signedImageUrlCache.set(key, {
url, url,
@@ -68,17 +93,41 @@ export const getCachedSignedImageUrl = async (
return request.then(url => url || fallback).catch(() => fallback) 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<string> => {
clearCachedSignedImageUrl(fileId, source)
return getCachedSignedImageUrl(fileId, fallback, source)
}
export const getCachedSignedImageUrls = async ( export const getCachedSignedImageUrls = async (
fileIds: Array<IdType | null | undefined>, fileIds: Array<IdType | null | undefined>,
fallback = '' fallback = '',
source: SignedImageSource = 'public'
): Promise<string[]> => { ): Promise<string[]> => {
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) const validUrls = urls.filter(Boolean)
return validUrls.length ? validUrls : (fallback ? [fallback] : []) return validUrls.length ? validUrls : (fallback ? [fallback] : [])
} }
export const getCachedSignedImageUrlsSync = (fileIds: Array<IdType | null | undefined>): string[] => export const getCachedSignedImageUrlsSync = (
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId)).filter(Boolean) fileIds: Array<IdType | null | undefined>,
source: SignedImageSource = 'public'
): string[] =>
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
export const extractLegacyFileId = (value?: string | null): string => { export const extractLegacyFileId = (value?: string | null): string => {
const source = String(value || '').replace(/<[^>]*>/g, '') const source = String(value || '').replace(/<[^>]*>/g, '')
+72 -2
View File
@@ -14,6 +14,12 @@ import {
} from '@ant-design/icons-vue' } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue' import { message } from 'ant-design-vue'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants' import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrl,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
import { import {
nailArtistApi, nailArtistApi,
type NailArtistAvailabilityVO, type NailArtistAvailabilityVO,
@@ -21,11 +27,13 @@ import {
type NailArtistReviewVO, type NailArtistReviewVO,
type NailArtistWorkVO type NailArtistWorkVO
} from '@/api/nail-artist' } from '@/api/nail-artist'
import { productApi, type ProductVO } from '@/api/product'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const profile = shallowRef<NailArtistProfileVO | null>(null) const profile = shallowRef<NailArtistProfileVO | null>(null)
const workImageUrls = ref<Record<string, string>>({})
const reviews = ref<NailArtistReviewVO[]>([]) const reviews = ref<NailArtistReviewVO[]>([])
const availability = ref<NailArtistAvailabilityVO[]>([]) const availability = ref<NailArtistAvailabilityVO[]>([])
const loading = shallowRef(false) 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 goodRateText = computed(() => ratingValue.value > 0 ? `${Math.min(99, Math.round((ratingValue.value / 5) * 100))}%` : '暂无')
const works = computed<NailArtistWorkVO[]>(() => profile.value?.works || []) const works = computed<NailArtistWorkVO[]>(() => profile.value?.works || [])
const styleTags = computed(() => profile.value?.styleTags?.filter(Boolean) || []) 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 workTimeText = computed(() => {
const start = profile.value?.workStartTime?.slice(0, 5) const start = profile.value?.workStartTime?.slice(0, 5)
const end = profile.value?.workEndTime?.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)) return works.value.filter(work => work.tags?.includes(workFilter.value))
}) })
const PROFILE_WORK_LIMIT = 20
const certificationText = computed(() => { const certificationText = computed(() => {
const identity = profile.value?.identity || '认证美甲师' const identity = profile.value?.identity || '认证美甲师'
const experience = Number(profile.value?.experience || 0) const experience = Number(profile.value?.experience || 0)
@@ -135,6 +148,60 @@ const openProduct = (work: NailArtistWorkVO) => {
router.push(`/product/${work.id}`) 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<NailArtistWorkVO[]> => {
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<string, unknown>, '')
const imageUrl = cachedUrls[0] || await resolvePublicImageUrl(work as NailArtistWorkVO & Record<string, unknown>, 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<string, unknown>)[0]
const imageUrl = fileId ? await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
workImageUrls.value = { ...workImageUrls.value, [String(work.id)]: imageUrl }
}
const openShop = () => { const openShop = () => {
if (!profile.value?.shopId) { if (!profile.value?.shopId) {
message.info('门店信息暂未完善') message.info('门店信息暂未完善')
@@ -191,6 +258,9 @@ const loadProfile = async () => {
profile.value = profileData profile.value = profileData
availability.value = availabilityData || profileData.availability || [] availability.value = availabilityData || profileData.availability || []
reviews.value = reviewData || profileData.reviews || [] 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) selectedDate.value = availability.value[0]?.dateText || String(availability.value[0]?.startTime || '').slice(0, 10)
} catch (error) { } catch (error) {
loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败' loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败'
@@ -317,7 +387,7 @@ onMounted(loadProfile)
</div> </div>
<div v-if="filteredWorks.length" class="work-grid"> <div v-if="filteredWorks.length" class="work-grid">
<button v-for="work in filteredWorks" :key="work.id" type="button" class="work-card" @click="openProduct(work)"> <button v-for="work in filteredWorks" :key="work.id" type="button" class="work-card" @click="openProduct(work)">
<img :src="work.coverImageUrl || DEFAULT_PRODUCT_IMAGE" :alt="work.title || '作品'" loading="lazy" decoding="async" /> <img :src="getWorkImage(work)" :alt="work.title || '作品'" loading="lazy" decoding="async" @error="handleWorkImageError(work)" />
<span>{{ work.title || '美甲作品' }}</span> <span>{{ work.title || '美甲作品' }}</span>
</button> </button>
</div> </div>
+71 -184
View File
@@ -10,40 +10,19 @@
<main class="auth-page"> <main class="auth-page">
<section class="brand-stage" aria-label="指尖设计师"> <section class="brand-stage" aria-label="指尖设计师">
<div class="brand-mark" aria-hidden="true">
<span>指</span>
</div>
<p class="brand-name">指尖设计师</p> <p class="brand-name">指尖设计师</p>
<h1 class="brand-title"> <p class="brand-copy">{{ activeTab === 'login' ? '登录后继续预约与收藏' : '填写信息完成账号注册' }}</p>
{{ activeTab === 'login' ? '艺术触手可及' : '开启你的预约账号' }}
</h1>
<p class="brand-copy">
{{ activeTab === 'login' ? '选择门店,继续你的美甲灵感旅程。' : '注册后即可收藏款式、预约服务并同步门店权益。' }}
</p>
</section> </section>
<section class="auth-container" aria-label="账号登录注册"> <section class="auth-container" aria-label="账号登录注册">
<div class="auth-card-header"> <button
<span class="auth-card-kicker">{{ activeTab === 'login' ? 'Welcome back' : 'Create account' }}</span> v-if="activeTab === 'register'"
<h2>{{ activeTab === 'login' ? '登录账号' : '注册账号' }}</h2> class="auth-mode-link auth-mode-link--top"
</div> type="button"
<div class="tab-container">
<div
class="tab-item"
:class="{ active: activeTab === 'login' }"
@click="activeTab = 'login'" @click="activeTab = 'login'"
> >
账号登录 返回登录
</div> </button>
<div
class="tab-item"
:class="{ active: activeTab === 'register' }"
@click="activeTab = 'register'"
>
注册账号
</div>
</div>
<div v-if="activeTab === 'login'" class="login-type-toggle"> <div v-if="activeTab === 'login'" class="login-type-toggle">
<a-radio-group v-model:value="loginType" button-style="solid"> <a-radio-group v-model:value="loginType" button-style="solid">
@@ -345,6 +324,13 @@
<div class="admin-login"> <div class="admin-login">
<span class="admin-login-link" @click="handleAdminLogin">管理后台登录</span> <span class="admin-login-link" @click="handleAdminLogin">管理后台登录</span>
</div> </div>
<div v-if="activeTab === 'login'" class="auth-mode-footer">
<span>还没有账号?</span>
<button class="auth-mode-link" type="button" @click="activeTab = 'register'">
注册账号
</button>
</div>
</a-form> </a-form>
</section> </section>
</main> </main>
@@ -1334,8 +1320,9 @@ onBeforeUnmount(() => {
var(--theme-page-bg) 100% var(--theme-page-bg) 100%
), ),
var(--theme-background-image), var(--theme-background-image),
var(--theme-gradient),
var(--theme-gradient-soft); var(--theme-gradient-soft);
background-size: cover, cover, auto; background-size: cover, cover, auto, auto;
background-position: center top; background-position: center top;
color: var(--text-primary); color: var(--text-primary);
overflow-x: hidden; overflow-x: hidden;
@@ -1389,113 +1376,41 @@ onBeforeUnmount(() => {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
gap: 22px; gap: 14px;
margin: 0 auto; margin: 0 auto;
} }
.brand-stage { .brand-stage {
width: 100%; width: 100%;
text-align: center; text-align: center;
padding: 12px 10px 0; padding: 6px 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;
} }
.brand-name { .brand-name {
margin: 0; 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); color: var(--text-primary);
font-family: "Playfair Display", serif; font-size: 24px;
font-size: 22px; font-weight: 800;
font-weight: 600;
line-height: 1.2; line-height: 1.2;
letter-spacing: 0; letter-spacing: 0;
} }
.brand-copy { .brand-copy {
max-width: 310px; max-width: 310px;
margin: 10px auto 0; margin: 8px auto 0;
color: var(--text-secondary); color: var(--text-secondary);
font-size: 14px; font-size: 13px;
line-height: 1.7; line-height: 1.5;
letter-spacing: 0; letter-spacing: 0;
} }
.auth-container { .auth-container {
width: 100%; width: 100%;
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent); background: var(--theme-card-bg);
border: 1px solid color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-border)); border: 1px solid var(--theme-border);
border-radius: 28px; border-radius: 18px;
padding: 22px 18px 20px; padding: 20px 18px 18px;
box-shadow: 0 22px 46px color-mix(in srgb, var(--theme-primary) 14%, transparent); box-shadow: 0 12px 28px color-mix(in srgb, var(--theme-neutral) 8%, 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;
} }
.logo-section { .logo-section {
@@ -1515,41 +1430,6 @@ onBeforeUnmount(() => {
color: var(--text-secondary); 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 { .login-type-toggle {
margin-bottom: 18px; margin-bottom: 18px;
} }
@@ -1666,16 +1546,11 @@ onBeforeUnmount(() => {
} }
.shop-select-item { .shop-select-item {
margin: 4px 0 18px; margin: 0 0 14px;
padding: 14px; padding: 10px 12px;
border-radius: 22px; border-radius: 16px;
border: 1px solid var(--theme-border); border: 1px solid var(--theme-border);
background: background: color-mix(in srgb, var(--theme-card-bg) 92%, var(--theme-primary-soft));
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))
);
} }
.shop-select-item :deep(.ant-form-item-label > label) { .shop-select-item :deep(.ant-form-item-label > label) {
@@ -1826,6 +1701,38 @@ onBeforeUnmount(() => {
text-decoration: underline; 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 { .phone-login-tip {
margin-top: 8px; margin-top: 8px;
font-size: 12px; font-size: 12px;
@@ -1838,19 +1745,19 @@ onBeforeUnmount(() => {
min-height: 52px; min-height: 52px;
border: none; border: none;
border-radius: 999px; border-radius: 999px;
background: var(--theme-gradient); background: var(--theme-primary-action);
color: var(--theme-card-bg); color: var(--theme-card-bg);
font-size: 15px; font-size: 15px;
font-weight: 800; font-weight: 800;
letter-spacing: 0; 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):hover,
.primary-action:not(:disabled):focus { .primary-action:not(:disabled):focus {
background: var(--theme-gradient); background: var(--theme-primary-action);
color: var(--theme-card-bg); 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 { .primary-action:disabled {
@@ -1953,27 +1860,11 @@ onBeforeUnmount(() => {
.auth-page { .auth-page {
min-height: calc(100svh - 92px); min-height: calc(100svh - 92px);
gap: 18px; gap: 12px;
}
.brand-mark {
width: 68px;
height: 68px;
margin-bottom: 12px;
}
.brand-mark span {
width: 48px;
height: 48px;
font-size: 22px;
} }
.brand-name { .brand-name {
font-size: 28px; font-size: 23px;
}
.brand-title {
font-size: 21px;
} }
.brand-copy { .brand-copy {
@@ -1981,12 +1872,8 @@ onBeforeUnmount(() => {
} }
.auth-container { .auth-container {
border-radius: 24px; border-radius: 18px;
padding: 20px 16px 18px; padding: 20px 16px 18px;
} }
.auth-card-header h2 {
font-size: 21px;
}
} }
</style> </style>
+280 -39
View File
@@ -34,7 +34,7 @@
> >
<a-checkbox class="product-check" v-model:checked="item.selected" @change="handleToggleSelect" /> <a-checkbox class="product-check" v-model:checked="item.selected" @change="handleToggleSelect" />
<button type="button" class="product-thumb" @click="openProduct(item)"> <button type="button" class="product-thumb" @click="openProduct(item)">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" /> <img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" @error="handleCartImageError(item)" />
<span v-else>{{ item.productTitle?.[0] || 'Y' }}</span> <span v-else>{{ item.productTitle?.[0] || 'Y' }}</span>
</button> </button>
@@ -92,10 +92,11 @@
<img <img
v-if="item.productImage" v-if="item.productImage"
:src="item.productImage" :src="item.productImage"
:alt="item.productTitle" :alt="item.productTitle"
loading="lazy" loading="lazy"
decoding="async" decoding="async"
/> @error="handleCartImageError(item)"
/>
<span v-else>{{ item.productTitle?.[0] || 'Y' }}</span> <span v-else>{{ item.productTitle?.[0] || 'Y' }}</span>
</div> </div>
<div class="service-copy"> <div class="service-copy">
@@ -107,11 +108,11 @@
<RightOutlined /> <RightOutlined />
</button> </button>
<div v-if="item.availableArtists?.length" class="service-artist-strip"> <div v-if="getDisplayArtists(item).length" class="service-artist-strip">
<span class="service-label">选择美甲师</span> <span class="service-label">选择美甲师</span>
<div class="service-artist-list"> <div class="service-artist-list">
<button <button
v-for="artist in item.availableArtists" v-for="artist in getDisplayArtists(item)"
:key="artist.id" :key="artist.id"
type="button" type="button"
class="service-artist-option" class="service-artist-option"
@@ -132,7 +133,7 @@
</div> </div>
<div class="service-time-grid"> <div class="service-time-grid">
<button <button
v-for="slot in getQuickAppointmentSlots(item)" v-for="slot in getDisplayQuickAppointmentSlots(item)"
:key="`${item.id}-${slot.value}`" :key="`${item.id}-${slot.value}`"
type="button" type="button"
class="service-time-option" class="service-time-option"
@@ -234,14 +235,14 @@
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal"> <a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
<div class="modal-section"> <div class="modal-section">
<div class="section-title">美甲师</div> <div class="section-title">美甲师</div>
<div v-if="availableArtists.length" class="artist-list"> <div v-if="getDraftDisplayArtists().length" class="artist-list">
<button <button
v-for="artist in availableArtists" v-for="artist in getDraftDisplayArtists()"
:key="artist.id" :key="artist.id"
type="button" type="button"
class="artist-option" class="artist-option"
:class="{ active: sameId(draftArtistId, artist.id) }" :class="{ active: sameId(draftArtistId, artist.id) }"
@click="draftArtistId = artist.id" @click="selectDraftArtist(artist)"
> >
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" loading="lazy" decoding="async" /> <img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" loading="lazy" decoding="async" />
<span>{{ artist.name }}</span> <span>{{ artist.name }}</span>
@@ -273,7 +274,7 @@
type="button" type="button"
class="quick-time" class="quick-time"
:class="{ active: draftAppointmentTime === slot.value }" :class="{ active: draftAppointmentTime === slot.value }"
@click="draftAppointmentTime = slot.value" @click="selectDraftAppointmentTime(slot.value)"
> >
<span>{{ slot.label }}</span> <span>{{ slot.label }}</span>
<strong>{{ slot.time }}</strong> <strong>{{ slot.time }}</strong>
@@ -313,7 +314,9 @@ import { sameId, toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading' import { runWithGlobalLoading } from '@/utils/action-loading'
import { getBuyNowProductIdFromQuery, isBuyNowCartItem } from '@/utils/buy-now' import { getBuyNowProductIdFromQuery, isBuyNowCartItem } from '@/utils/buy-now'
import { buildRecoveryActions, getRecoveryMessage } from '@/utils/recovery' import { buildRecoveryActions, getRecoveryMessage } from '@/utils/recovery'
import { extractLegacyFileId, getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache' import { extractLegacyFileId } from '@/utils/signed-image-cache'
import { normalizeApiErrorMessage } from '@/api/error'
import { refreshPublicImageUrl, resolvePublicImageUrl, resolvePublicImageUrlsSync } from '@/utils/public-image-assets'
/** /**
* Purpose: router supports CartView.vue by holding or executing the router page or API role. * Purpose: router supports CartView.vue by holding or executing the router page or API role.
@@ -397,6 +400,19 @@ interface CheckoutIssue {
productTitle?: string productTitle?: string
} }
interface AppointmentSlotOption {
value: string
label: string
time: string
}
interface BookableOptionState {
loading: boolean
artists: ArtistOption[]
slots: AppointmentSlotOption[]
validKeys: Set<string>
}
/** /**
* Purpose: cartItems supports CartView.vue by holding or executing the cart items page or API role. * Purpose: cartItems supports CartView.vue by holding or executing the cart items 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. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -452,6 +468,7 @@ const currentShopHours = ref('')
const shopHoursById = ref<Record<string, string>>({}) const shopHoursById = ref<Record<string, string>>({})
/** submittingOrder is a reactive state variable used by the template and event handlers. */ /** submittingOrder is a reactive state variable used by the template and event handlers. */
const submittingOrder = ref(false) const submittingOrder = ref(false)
const bookableOptionsByItemId = ref<Record<string, BookableOptionState>>({})
/** buyNowProductId limits checkout selection to the product that opened cart from "立即预约". */ /** buyNowProductId limits checkout selection to the product that opened cart from "立即预约". */
const buyNowProductId = computed(() => getBuyNowProductIdFromQuery(route.query)) const buyNowProductId = computed(() => getBuyNowProductIdFromQuery(route.query))
/** isBuyNowMode switches cart copy into a focused order-confirmation experience. */ /** isBuyNowMode switches cart copy into a focused order-confirmation experience. */
@@ -501,12 +518,80 @@ const bookingHelperText = computed(() => {
/** quickAppointmentSlots is a reactive state variable used by the template and event handlers. */ /** quickAppointmentSlots is a reactive state variable used by the template and event handlers. */
const quickAppointmentSlots = computed(() => { const quickAppointmentSlots = computed(() => {
if (currentItem.value) { if (currentItem.value) {
return getQuickAppointmentSlots(currentItem.value) return getDisplayQuickAppointmentSlotsForArtist(currentItem.value, draftArtistId.value)
} }
return buildQuickAppointmentSlots() return buildQuickAppointmentSlots()
}) })
const getItemKey = (item: CartItem) => toOptionalIdString(item.id) || toOptionalIdString(item.productId) || ''
const getBookableKey = (artistId: IdType, appointmentTime: string) => {
return `${toOptionalIdString(artistId) || ''}|${appointmentTime}`
}
const normalizeArtists = (item: CartItem): ArtistOption[] => {
return Array.isArray(item.availableArtists)
? (item.availableArtists || [])
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
}))
: []
}
const getBookableOptionState = (item: CartItem): BookableOptionState | null => {
const itemKey = getItemKey(item)
return itemKey ? bookableOptionsByItemId.value[itemKey] || null : null
}
const getDisplayArtists = (item: CartItem) => {
const state = getBookableOptionState(item)
return state ? state.artists : normalizeArtists(item)
}
const getDisplayQuickAppointmentSlots = (item: CartItem) => {
const state = getBookableOptionState(item)
return state ? state.slots : getQuickAppointmentSlots(item)
}
const getDisplayQuickAppointmentSlotsForArtist = (item: CartItem, artistId?: IdType) => {
const state = getBookableOptionState(item)
if (!state || !artistId) {
return getDisplayQuickAppointmentSlots(item)
}
return state.slots.filter(slot => state.validKeys.has(getBookableKey(artistId, slot.value)))
}
const getDraftDisplayArtists = () => {
if (!currentItem.value || !draftAppointmentTime.value) {
return availableArtists.value
}
const state = getBookableOptionState(currentItem.value)
if (!state) {
return availableArtists.value
}
return availableArtists.value.filter(artist =>
state.validKeys.has(getBookableKey(artist.id, draftAppointmentTime.value))
)
}
const hasBookableCombination = (item: CartItem, artistId?: IdType, appointmentTime?: string) => {
if (!artistId || !appointmentTime) {
return false
}
const state = getBookableOptionState(item)
if (!state) {
return true
}
return state.validKeys.has(getBookableKey(artistId, appointmentTime))
}
const buildQuickAppointmentSlots = (item?: CartItem) => { const buildQuickAppointmentSlots = (item?: CartItem) => {
const now = getMinAppointmentDate() const now = getMinAppointmentDate()
const today = new Date(now) const today = new Date(now)
@@ -537,6 +622,94 @@ const buildQuickAppointmentSlots = (item?: CartItem) => {
const getQuickAppointmentSlots = (item: CartItem) => buildQuickAppointmentSlots(item) const getQuickAppointmentSlots = (item: CartItem) => buildQuickAppointmentSlots(item)
const isCheckoutPreviewBookable = (preview: CheckoutPreview) => {
return preview.bookingAvailable !== false && !(preview.bookingIssues || []).length
}
const checkBookableCombination = async (item: CartItem, artist: ArtistOption, slot: AppointmentSlotOption) => {
try {
const preview = await orderApi.checkoutPreview({
items: [{
productId: item.productId,
quantity: item.quantity,
artistId: artist.id,
appointmentTime: slot.value
}]
})
return isCheckoutPreviewBookable(preview)
} catch {
return false
}
}
const refreshBookableOptions = async (item: CartItem) => {
const itemKey = getItemKey(item)
if (!itemKey) {
return
}
const artists = normalizeArtists(item)
const slots = getQuickAppointmentSlots(item)
bookableOptionsByItemId.value = {
...bookableOptionsByItemId.value,
[itemKey]: { loading: true, artists: [], slots: [], validKeys: new Set<string>() }
}
const checks = await Promise.all(artists.flatMap(artist =>
slots.map(async slot => ({
artist,
slot,
valid: await checkBookableCombination(item, artist, slot)
}))
))
const validKeys = new Set(
checks
.filter(check => check.valid)
.map(check => getBookableKey(check.artist.id, check.slot.value))
)
const validArtists = artists.filter(artist =>
slots.some(slot => validKeys.has(getBookableKey(artist.id, slot.value)))
)
const validSlots = slots.filter(slot =>
artists.some(artist => validKeys.has(getBookableKey(artist.id, slot.value)))
)
bookableOptionsByItemId.value = {
...bookableOptionsByItemId.value,
[itemKey]: { loading: false, artists: validArtists, slots: validSlots, validKeys }
}
if (item.artistId && !validArtists.some(artist => sameId(artist.id, item.artistId))) {
item.artistId = undefined
item.artist = undefined
}
if (item.appointmentTime && !validSlots.some(slot => slot.value === item.appointmentTime)) {
item.appointmentTime = ''
}
}
const refreshSelectedBookableOptions = async () => {
await Promise.all(selectedItems.value.map(item => refreshBookableOptions(item)))
}
const findFirstSlotForArtist = (item: CartItem, artistId: IdType) => {
const state = getBookableOptionState(item)
return state?.slots.find(slot => state.validKeys.has(getBookableKey(artistId, slot.value)))
}
const findFirstArtistForSlot = (item: CartItem, appointmentTime: string) => {
const state = getBookableOptionState(item)
return state?.artists.find(artist => state.validKeys.has(getBookableKey(artist.id, appointmentTime)))
}
const findInvalidBookableCombination = () => {
return selectedItems.value.find(item =>
item.artistId
&& item.appointmentTime
&& !hasBookableCombination(item, item.artistId, item.appointmentTime)
)
}
/** getMinAppointmentDate is a local helper used by this page script. */ /** getMinAppointmentDate is a local helper used by this page script. */
const getMinAppointmentDate = () => { const getMinAppointmentDate = () => {
const date = new Date() const date = new Date()
@@ -730,7 +903,7 @@ const mapApiCheckoutIssue = (issue: ApiCheckoutIssue): CheckoutIssue | null => {
return { return {
key: `server-${issue.code || issue.message}`, key: `server-${issue.code || issue.message}`,
message: issue.message, message: normalizeApiErrorMessage(issue.message),
itemId: matchedItem?.id || issue.itemId, itemId: matchedItem?.id || issue.itemId,
productId: issue.productId, productId: issue.productId,
productTitle: issue.productTitle || matchedItem?.productTitle productTitle: issue.productTitle || matchedItem?.productTitle
@@ -816,9 +989,10 @@ const isDisplayableImageSource = (value?: string | null) => {
const getInitialCartImage = (rawImage?: string, previousImage?: string) => { const getInitialCartImage = (rawImage?: string, previousImage?: string) => {
const imageId = extractLegacyFileId(rawImage) const imageId = extractLegacyFileId(rawImage)
const cachedUrl = imageId ? getCachedSignedImageUrlSync(imageId) : '' const cachedUrl = imageId ? resolvePublicImageUrlsSync({ imageFileIds: imageId }, '')[0] : ''
if (cachedUrl) return cachedUrl if (cachedUrl) return cachedUrl
if (previousImage) return previousImage if (previousImage) return previousImage
if (imageId) return ''
return isDisplayableImageSource(rawImage) ? String(rawImage) : '' return isDisplayableImageSource(rawImage) ? String(rawImage) : ''
} }
@@ -846,6 +1020,7 @@ const loadCartItems = async () => {
couponSelectionKey.value = NO_COUPON_KEY couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null selectedCoupon.value = null
await Promise.all([loadProductImages(), loadCartItemShopHours()]) await Promise.all([loadProductImages(), loadCartItemShopHours()])
await refreshSelectedBookableOptions()
await loadAvailableCoupons() await loadAvailableCoupons()
} finally { } finally {
cartLoading.value = false cartLoading.value = false
@@ -866,13 +1041,18 @@ const loadProductImages = async () => {
} }
continue continue
} }
const cachedUrl = getCachedSignedImageUrlSync(imageId) const cachedUrl = resolvePublicImageUrlsSync({ imageFileIds: imageId }, '')[0]
if (cachedUrl) item.productImage = cachedUrl if (cachedUrl) item.productImage = cachedUrl
const signedUrl = await getCachedSignedImageUrl(imageId, item.productImage || item.originalProductImage) const signedUrl = await resolvePublicImageUrl({ imageFileIds: imageId }, item.productImage || '')
if (signedUrl) item.productImage = signedUrl if (signedUrl) item.productImage = signedUrl
} }
} }
const handleCartImageError = async (item: CartItem) => {
const imageId = extractLegacyFileId(item.originalProductImage)
item.productImage = imageId ? await refreshPublicImageUrl(imageId, '') : ''
}
const loadCartItemShopHours = async () => { const loadCartItemShopHours = async () => {
const shopIds = Array.from(new Set( const shopIds = Array.from(new Set(
cartItems.value cartItems.value
@@ -963,7 +1143,10 @@ const loadAvailableCoupons = async () => {
/** handleToggleSelect is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleToggleSelect is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleToggleSelect = async () => { const handleToggleSelect = async () => {
await runWithGlobalLoading(() => loadAvailableCoupons()) await runWithGlobalLoading(async () => {
await refreshSelectedBookableOptions()
await loadAvailableCoupons()
})
} }
/** changeQuantity is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** changeQuantity is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -974,6 +1157,7 @@ const changeQuantity = async (item: CartItem, delta: number) => {
try { try {
await runWithGlobalLoading(async () => { await runWithGlobalLoading(async () => {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next }) await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
await refreshBookableOptions(item)
await loadAvailableCoupons() await loadAvailableCoupons()
}) })
await updateCartCount() await updateCartCount()
@@ -1007,12 +1191,20 @@ const openProduct = (item: CartItem) => {
const selectInlineArtist = async (item: CartItem, artist: ArtistOption) => { const selectInlineArtist = async (item: CartItem, artist: ArtistOption) => {
item.artistId = artist.id item.artistId = artist.id
item.artist = artist item.artist = artist
if (!hasBookableCombination(item, artist.id, item.appointmentTime)) {
item.appointmentTime = findFirstSlotForArtist(item, artist.id)?.value || ''
}
await runWithGlobalLoading(() => loadAvailableCoupons()) await runWithGlobalLoading(() => loadAvailableCoupons())
} }
/** selectInlineTime updates a cart item's appointment slot from the page-level service detail controls. */ /** selectInlineTime updates a cart item's appointment slot from the page-level service detail controls. */
const selectInlineTime = async (item: CartItem, appointmentTime: string) => { const selectInlineTime = async (item: CartItem, appointmentTime: string) => {
item.appointmentTime = appointmentTime item.appointmentTime = appointmentTime
if (!hasBookableCombination(item, item.artistId, appointmentTime)) {
const artist = findFirstArtistForSlot(item, appointmentTime)
item.artistId = artist?.id
item.artist = artist
}
await runWithGlobalLoading(() => loadAvailableCoupons()) await runWithGlobalLoading(() => loadAvailableCoupons())
} }
@@ -1022,28 +1214,21 @@ const openBookingModal = async (item: CartItem) => {
draftArtistId.value = item.artistId draftArtistId.value = item.artistId
draftAppointmentTime.value = item.appointmentTime || '' draftAppointmentTime.value = item.appointmentTime || ''
showBookingModal.value = true showBookingModal.value = true
await runWithGlobalLoading(() => Promise.all([loadArtists(item), loadShopHours(item.shopId)])) await runWithGlobalLoading(async () => {
await Promise.all([refreshBookableOptions(item), loadShopHours(item.shopId)])
await loadArtists(item)
})
} }
/** loadArtists is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** loadArtists is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadArtists = async (item: CartItem) => { const loadArtists = async (item: CartItem) => {
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。 availableArtists.value = getDisplayArtists(item)
availableArtists.value = Array.isArray(item.availableArtists)
? item.availableArtists
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
}))
: []
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) { if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
draftArtistId.value = undefined draftArtistId.value = undefined
} }
if (draftAppointmentTime.value && !hasBookableCombination(item, draftArtistId.value, draftAppointmentTime.value)) {
draftAppointmentTime.value = ''
}
} }
/** loadShopHours is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** loadShopHours is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -1097,6 +1282,26 @@ const disablePastAppointmentTime = (current: any) => {
} }
} }
const selectDraftArtist = (artist: ArtistOption) => {
if (!currentItem.value) {
return
}
draftArtistId.value = artist.id
if (!hasBookableCombination(currentItem.value, artist.id, draftAppointmentTime.value)) {
draftAppointmentTime.value = findFirstSlotForArtist(currentItem.value, artist.id)?.value || ''
}
}
const selectDraftAppointmentTime = (appointmentTime: string) => {
if (!currentItem.value) {
return
}
draftAppointmentTime.value = appointmentTime
if (!hasBookableCombination(currentItem.value, draftArtistId.value, appointmentTime)) {
draftArtistId.value = findFirstArtistForSlot(currentItem.value, appointmentTime)?.id
}
}
/** closeBookingModal is a local helper used by this page script. */ /** closeBookingModal is a local helper used by this page script. */
const closeBookingModal = () => { const closeBookingModal = () => {
showBookingModal.value = false showBookingModal.value = false
@@ -1113,6 +1318,9 @@ const confirmBooking = async () => {
if (!draftArtistId.value) return message.warning('请先选择美甲师') if (!draftArtistId.value) return message.warning('请先选择美甲师')
if (!draftAppointmentTime.value) return message.warning('请选择预约时间') if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟') if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
if (!hasBookableCombination(currentItem.value, draftArtistId.value, draftAppointmentTime.value)) {
return message.warning('请选择可预约的美甲师和时间')
}
currentItem.value.artistId = draftArtistId.value currentItem.value.artistId = draftArtistId.value
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value)) currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
currentItem.value.appointmentTime = draftAppointmentTime.value currentItem.value.appointmentTime = draftAppointmentTime.value
@@ -1138,20 +1346,36 @@ const applyCouponSelection = async () => {
await runWithGlobalLoading(() => loadAvailableCoupons()) await runWithGlobalLoading(() => loadAvailableCoupons())
} }
let checkoutRecoveryModal: { destroy: () => void } | null = null
const openCheckoutRecovery = (error: unknown) => { const openCheckoutRecovery = (error: unknown) => {
checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
const recoveryMessage = error instanceof Error
? normalizeApiErrorMessage(error.message)
: normalizeApiErrorMessage(getRecoveryMessage(error, '询价预约发起失败'))
const actions = buildRecoveryActions([ const actions = buildRecoveryActions([
{ key: 'retry', text: '重试发起询价' }, { key: 'retry', text: '重试发起询价' },
{ key: 'orders', text: '查看订单' } { key: 'orders', text: '查看订单' }
]) ])
const retryAction = actions[0] const retryAction = actions[0]
const ordersAction = actions[1] const ordersAction = actions[1]
Modal.confirm({ checkoutRecoveryModal = Modal.confirm({
title: '发起询价预约失败', title: '发起询价预约失败',
content: `${getRecoveryMessage(error, '询价预约发起失败')}。如果担心重复提交,请先查看订单;仍失败时请联系客服。`, content: `${recoveryMessage}。如担心重复提交,请先查看订单;仍失败时请联系管理员。`,
closable: true,
okText: retryAction?.text || '重试发起询价', okText: retryAction?.text || '重试发起询价',
cancelText: ordersAction?.text || '查看订单', cancelText: ordersAction?.text || '查看订单',
onOk: () => checkout(), onOk: () => {
onCancel: () => router.push(ordersAction?.route || '/orders') checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
void checkout()
},
onCancel: () => {
checkoutRecoveryModal?.destroy()
checkoutRecoveryModal = null
void router.push(ordersAction?.route || '/orders')
}
}) })
} }
@@ -1172,6 +1396,18 @@ const checkout = async () => {
return message.warning('请先选择要结算的作品') return message.warning('请先选择要结算的作品')
} }
await runWithGlobalLoading(async () => {
await refreshSelectedBookableOptions()
await loadAvailableCoupons()
})
const invalidCombination = findInvalidBookableCombination()
if (invalidCombination) {
message.warning(`"${invalidCombination.productTitle}" 当前美甲师和预约时间不可预约,请重新选择`)
scrollToIssue({ key: 'bookable-combination', message: '请选择可预约的美甲师和时间', itemId: invalidCombination.id })
return
}
const firstIssue = checkoutIssues.value[0] const firstIssue = checkoutIssues.value[0]
if (firstIssue) { if (firstIssue) {
message.warning(firstIssue.message) message.warning(firstIssue.message)
@@ -1214,7 +1450,12 @@ const checkout = async () => {
} }
} }
} catch (error: any) { } catch (error: any) {
console.error('创建订单失败:', error) const checkoutErrorMessage = normalizeApiErrorMessage(error instanceof Error ? error.message : getRecoveryMessage(error, '询价预约发起失败'))
if (checkoutErrorMessage.includes('不可预约')) {
console.warn('询价预约被业务规则拦截:', checkoutErrorMessage)
} else {
console.error('创建订单失败:', error)
}
openCheckoutRecovery(error) openCheckoutRecovery(error)
} finally { } finally {
submittingOrder.value = false submittingOrder.value = false
+48 -31
View File
@@ -73,6 +73,7 @@
class="feature-banner__image" class="feature-banner__image"
:loading="index === 0 ? 'eager' : 'lazy'" :loading="index === 0 ? 'eager' : 'lazy'"
decoding="async" decoding="async"
@error="handleProductCardImageError(item)"
/> />
<div class="feature-banner__shade"></div> <div class="feature-banner__shade"></div>
<div class="feature-banner__copy"> <div class="feature-banner__copy">
@@ -131,7 +132,7 @@
@click="handleProductClick(item)" @click="handleProductClick(item)"
> >
<div class="product-img"> <div class="product-img">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" /> <img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" @error="handleProductCardImageError(item)" />
<span v-else>{{ item.name[0] }}</span> <span v-else>{{ item.name[0] }}</span>
</div> </div>
<div class="product-info"> <div class="product-info">
@@ -164,7 +165,7 @@
@click="handleProductClick(item)" @click="handleProductClick(item)"
> >
<div class="product-img"> <div class="product-img">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" /> <img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" loading="lazy" decoding="async" @error="handleProductCardImageError(item)" />
<span v-else>{{ item.name[0] }}</span> <span v-else>{{ item.name[0] }}</span>
</div> </div>
<div class="product-info"> <div class="product-info">
@@ -208,7 +209,7 @@
type="button" type="button"
@click="openShopById(shop.shopId)" @click="openShopById(shop.shopId)"
> >
<img :src="shop.url" :alt="shop.shopName" loading="lazy" decoding="async" /> <img :src="shop.url" :alt="shop.shopName" loading="lazy" decoding="async" @error="handleBannerImageError(shop)" />
<span>{{ shop.shopName }}</span> <span>{{ shop.shopName }}</span>
</button> </button>
</div> </div>
@@ -250,7 +251,12 @@ import { shopApi, type ShopVO } from '../api/shop'
import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants' import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
import { extractRichText, renderRichContent } from '@/utils/rich-content' 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. * Purpose: BannerImage supports HomeView.vue by holding or executing the banner image page or API role.
@@ -262,6 +268,7 @@ interface BannerImage {
shopName: string shopName: string
businessHours?: string businessHours?: string
url: string url: string
imageFileId?: string
} }
/** /**
@@ -275,6 +282,7 @@ interface ProductCardItem {
meta: string meta: string
shopName?: string shopName?: string
coverUrl: string coverUrl: string
imageFileId?: string
bgColor: 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. */ /** getProductCoverUrl is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const getProductCoverUrl = async (product: ProductVO): Promise<string> => { const getProductCoverUrl = async (product: ProductVO): Promise<string> => {
const firstImageId = product.imageFileIds?.split(',').map(id => id.trim()).find(Boolean) const cachedUrls = resolvePublicImageUrlsSync(product, '')
if (firstImageId) { if (cachedUrls.length) return cachedUrls[0] || DEFAULT_PRODUCT_IMAGE
return getCachedSignedImageUrlSync(firstImageId) || await getCachedSignedImageUrl(firstImageId, DEFAULT_PRODUCT_IMAGE) return resolvePublicImageUrl(product, 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
} }
/** formatProductCards is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** formatProductCards is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const formatProductCards = async (products: ProductVO[]): Promise<ProductCardItem[]> => const formatProductCards = async (products: ProductVO[]): Promise<ProductCardItem[]> =>
@@ -439,6 +442,7 @@ const formatProductCards = async (products: ProductVO[]): Promise<ProductCardIte
meta: item.approximateDuration || item.shopName || '支持预约', meta: item.approximateDuration || item.shopName || '支持预约',
shopName: item.shopName, shopName: item.shopName,
coverUrl: await getProductCoverUrl(item), coverUrl: await getProductCoverUrl(item),
imageFileId: getPublicImageFileIds(item)[0],
bgColor: getRandomColor() bgColor: getRandomColor()
}))) })))
@@ -484,30 +488,43 @@ const loadPublicShops = async () => {
const loadBannerImages = async () => { const loadBannerImages = async () => {
const banners: BannerImage[] = [] const banners: BannerImage[] = []
for (const shop of publicShops.value) { for (const shop of publicShops.value) {
const coverIds = (shop.coverImageFileId || shop.imageFileIds || '') const imageRecord = {
.split(',') coverImageFileId: shop.coverImageFileId,
.map(id => id.trim()) imageFileIds: shop.imageFileIds,
.filter(Boolean) imageUrls: shop.imageUrls
for (const id of coverIds) { }
try { const fileId = getPublicImageFileIds(imageRecord)[0]
const url = getCachedSignedImageUrlSync(id) || await getCachedSignedImageUrl(id) const url = await resolvePublicImageUrl(imageRecord, '')
if (url) { if (url) {
banners.push({ banners.push({
id: `${shop.id}-${id}`, id: `${shop.id}-${fileId || url}`,
shopId: shop.id, shopId: shop.id,
shopName: shop.shopName, shopName: shop.shopName,
businessHours: shop.businessHours, businessHours: shop.businessHours,
url url,
}) imageFileId: fileId
} })
} catch (error) {
console.error('获取门店轮播图失败:', error)
}
} }
} }
bannerImages.value = banners.slice(0, 8) 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. */ /** loadNewArrivalProducts fills the top carousel with products tagged as new arrivals. */
const loadNewArrivalProducts = async () => { const loadNewArrivalProducts = async () => {
try { try {
+54 -17
View File
@@ -36,6 +36,7 @@
:alt="`${productTitle} 图片 ${index + 1}`" :alt="`${productTitle} 图片 ${index + 1}`"
:loading="index === 0 ? 'eager' : 'lazy'" :loading="index === 0 ? 'eager' : 'lazy'"
decoding="async" decoding="async"
@error="handleProductImageError(index)"
/> />
</button> </button>
</div> </div>
@@ -54,6 +55,7 @@
:alt="`${productTitle} 图片 ${index + 1}`" :alt="`${productTitle} 图片 ${index + 1}`"
:loading="index === 0 ? 'eager' : 'lazy'" :loading="index === 0 ? 'eager' : 'lazy'"
decoding="async" decoding="async"
@error="handleProductImageError(index)"
/> />
</button> </button>
</div> </div>
@@ -218,9 +220,9 @@
</span> </span>
</div> </div>
<p>{{ comment.commentContent }}</p> <p>{{ comment.commentContent }}</p>
<div v-if="comment.imageUrls?.length" class="review-images"> <div v-if="getCommentImages(comment).length" class="review-images">
<a-image <a-image
v-for="(image, index) in comment.imageUrls" v-for="(image, index) in getCommentImages(comment)"
:key="`${comment.id}-${index}`" :key="`${comment.id}-${index}`"
class="review-image" class="review-image"
:src="image" :src="image"
@@ -323,7 +325,13 @@ import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
import { toOptionalIdString } from '@/utils/id' import { toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading' import { runWithGlobalLoading } from '@/utils/action-loading'
import { getCachedSignedImageUrls, getCachedSignedImageUrlsSync, parseImageFileIds } from '@/utils/signed-image-cache' import { createChunkUploadTask } from '@/utils/chunk-upload'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrls,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
import { buildRatingStars, normalizeCommentRating } from '@/utils/comment-review' import { buildRatingStars, normalizeCommentRating } from '@/utils/comment-review'
/** /**
@@ -366,6 +374,7 @@ const productImagePreviewIndex = ref(0)
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const comments = ref<CommentVO[]>([]) const comments = ref<CommentVO[]>([])
const commentImageUrls = ref<Record<string, string[]>>({})
/** commentText is a reactive state variable used by the template and event handlers. */ /** commentText is a reactive state variable used by the template and event handlers. */
const commentText = ref('') const commentText = ref('')
/** /**
@@ -484,25 +493,24 @@ const requireLogin = (actionText: string) => {
const loadProductImages = async () => { const loadProductImages = async () => {
productImagesReady.value = false productImagesReady.value = false
productImagePreviewIndex.value = 0 productImagePreviewIndex.value = 0
const fileIds = parseImageFileIds(product.value.imageFileIds) const cachedImages = resolvePublicImageUrlsSync(product.value, '')
if (!fileIds.length) {
const fallbackImages = [DEFAULT_PRODUCT_IMAGE]
productImages.value = fallbackImages
productImagesReady.value = true
return
}
const cachedImages = getCachedSignedImageUrlsSync(fileIds)
if (cachedImages.length) { if (cachedImages.length) {
productImages.value = cachedImages productImages.value = cachedImages
productImagesReady.value = true productImagesReady.value = true
} }
const nextImages = await getCachedSignedImageUrls(fileIds, DEFAULT_PRODUCT_IMAGE) const nextImages = await resolvePublicImageUrls(product.value, DEFAULT_PRODUCT_IMAGE)
productImages.value = nextImages productImages.value = nextImages
productImagesReady.value = true 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. */ /** loadShopInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadShopInfo = async (shopId?: IdType | null) => { const loadShopInfo = async (shopId?: IdType | null) => {
shopInfo.value = shopId ? await shopApi.getShopById(shopId).catch(() => null) : 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. */ /** loadComments is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadComments = async () => { const loadComments = async () => {
if (!product.value.id) return 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. */ /** checkInteractionStatus is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkInteractionStatus = async () => { const checkInteractionStatus = async () => {
if (!isLoggedIn.value || !product.value.id) { 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 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 { try {
const uploaded = await commentApi.uploadImage(file) const { response: uploaded } = await task.promise
const stillListed = commentImageFileList.value.some(item => String(item.uid) === uid) const stillListed = commentImageFileList.value.some(item => String(item.uid) === uid)
if (!stillListed) { if (!stillListed) {
URL.revokeObjectURL(previewUrl) URL.revokeObjectURL(previewUrl)
@@ -669,8 +703,11 @@ const handleUploadCommentImage: UploadProps['customRequest'] = async options =>
commentImageFileList.value = commentImageFileList.value.map(item => { commentImageFileList.value = commentImageFileList.value.map(item => {
return String(item.uid) === uid ? { ...item, status: 'error' } : item return String(item.uid) === uid ? { ...item, status: 'error' } : item
}) })
options.onError?.(error) const errorMessage = error?.message || '评价图片上传失败'
message.error(error?.message || '评价图片上传失败') if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
options.onError?.(error)
message.error(errorMessage)
}
} finally { } finally {
uploadingCommentImages.value = Math.max(0, uploadingCommentImages.value - 1) uploadingCommentImages.value = Math.max(0, uploadingCommentImages.value - 1)
} }
+21 -11
View File
@@ -75,6 +75,7 @@
class="product-image" class="product-image"
loading="lazy" loading="lazy"
decoding="async" decoding="async"
@error="handleProductImageError(item)"
/> />
<div v-else class="product-img-placeholder"> <div v-else class="product-img-placeholder">
<span>{{ (item.title || item.name)?.[0] || '作' }}</span> <span>{{ (item.title || item.name)?.[0] || '作' }}</span>
@@ -189,7 +190,12 @@ import { tagApi, type TagFilterGroupVO, type TagVO } from '@/api/tag'
import { cartApi } from '@/api/cart' import { cartApi } from '@/api/cart'
import { runWithGlobalLoading } from '@/utils/action-loading' import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state' 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. * 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. */ /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (productList: ProductVO[]) => { const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) { for (const product of productList) {
if (!product.imageFileIds) { const productKey = String(product.id)
imageUrls.value[String(product.id)] = [DEFAULT_PRODUCT_IMAGE] const cachedUrls = resolvePublicImageUrlsSync(product, '')
continue
}
const ids = parseImageFileIds(product.imageFileIds)
const cachedUrls = getCachedSignedImageUrlsSync(ids)
if (cachedUrls.length) { if (cachedUrls.length) {
imageUrls.value[String(product.id)] = cachedUrls imageUrls.value[productKey] = cachedUrls
} }
const urls = await getCachedSignedImageUrls(ids, DEFAULT_PRODUCT_IMAGE) const urls = await resolvePublicImageUrls(product, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[String(product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE] imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
} }
} }
/** getProductImages is a local helper used by this page script. */ /** getProductImages is a local helper used by this page script. */
const getProductImages = (product: ProductVO): string[] => imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE] 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 displayProductDuration = (product: ProductVO) => {
const duration = product.approximateDuration?.trim() const duration = product.approximateDuration?.trim()
if (duration) return duration if (duration) return duration
+27 -12
View File
@@ -604,15 +604,10 @@ const handleEditProfile = () => {
const beforeUploadAvatar: UploadProps['beforeUpload'] = file => { const beforeUploadAvatar: UploadProps['beforeUpload'] = file => {
const isImage = file.type.startsWith('image/') const isImage = file.type.startsWith('image/')
const isLt20M = file.size / 1024 / 1024 < 20
if (!isImage) { if (!isImage) {
message.error('只能上传图片文件') message.error('只能上传图片文件')
} }
if (!isLt20M) { return isImage
message.error('图片大小不能超过 20MB')
}
return isImage && isLt20M
} }
/** handleAvatarUpload is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** 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({ const task = createChunkUploadTask({
file: file as File, file: file as File,
scene: 'profile-avatar', scene: 'profile-avatar',
concurrency: 3,
api: { api: {
initUpload: fileApi.initAvatarChunkUpload, initUpload: fileApi.initAvatarChunkUpload,
uploadChunk: fileApi.uploadAvatarChunk, uploadChunk: fileApi.uploadAvatarChunk,
@@ -684,18 +680,37 @@ const handleDeleteAvatar = () => {
} }
/** handleWechatQrUpload uploads a user profile QR image without changing the avatar. */ /** handleWechatQrUpload uploads a user profile QR image without changing the avatar. */
const handleWechatQrUpload = async (options: any) => { const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError } = options const { file, onSuccess, onError, onProgress } = options
qrUploadPending.value = true 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 { try {
const response = await fileApi.uploadProfileImage(file as File) const { response } = await task.promise
editForm.wechatQrCode = response as unknown as string editForm.wechatQrCode = response as unknown as string
onSuccess?.({ url: response }) onSuccess?.({ url: response })
message.success('微信二维码上传成功') message.success('微信二维码上传成功')
} catch (error) { } catch (error) {
console.error('微信二维码上传失败:', error) const errorMessage = (error as Error)?.message || '微信二维码上传失败'
message.error((error as Error)?.message || '微信二维码上传失败') if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
onError?.(error) console.error('微信二维码上传失败:', error)
message.error(errorMessage)
onError?.(error as Error)
}
} finally { } finally {
qrUploadPending.value = false qrUploadPending.value = false
} }
+22 -21
View File
@@ -308,11 +308,12 @@ import { nailArtistApi } from '@/api/nail-artist'
import { userApi, type ContactInfoVO } from '@/api/user' import { userApi, type ContactInfoVO } from '@/api/user'
import { toOptionalIdString } from '@/utils/id' import { toOptionalIdString } from '@/utils/id'
import { import {
getCachedSignedImageUrl, getPublicImageFileIds,
getCachedSignedImageUrls, refreshPublicImageUrl,
getCachedSignedImageUrlSync, resolvePublicImageUrl,
parseImageFileIds resolvePublicImageUrls
} from '@/utils/signed-image-cache' } 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. * 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 featuredProducts = computed(() => trustProfile.value?.featuredProducts || [])
const featuredProductCards = computed(() => featuredProducts.value.map(product => { const featuredProductCards = computed(() => featuredProducts.value.map(product => {
const productId = String(product.id) const productId = String(product.id)
const fileIds = parseFileIdList(product.imageFileIds)
const cachedUrl = fileIds[0] ? getCachedSignedImageUrlSync(fileIds[0]) : ''
const directUrl = normalizeImageUrl(product.imageUrl) const directUrl = normalizeImageUrl(product.imageUrl)
return { return {
...product, ...product,
displayImageUrl: failedFeaturedProductImages.value[productId] 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) => { const handleFeaturedImageError = (productId: string | number) => {
failedFeaturedProductImages.value = { const product = featuredProducts.value.find(item => String(item.id) === String(productId))
...failedFeaturedProductImages.value, const fileId = product ? getPublicImageFileIds({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl })[0] : ''
[String(productId)]: true 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 loadFeaturedProductImages = async () => {
const entries = await Promise.all(featuredProducts.value.map(async product => { const entries = await Promise.all(featuredProducts.value.map(async product => {
const productId = String(product.id) const productId = String(product.id)
const firstFileId = parseFileIdList(product.imageFileIds)[0] const signedUrl = await resolvePublicImageUrl({ imageFileIds: product.imageFileIds, imageUrl: product.imageUrl }, '')
if (!firstFileId) {
return [productId, normalizeImageUrl(product.imageUrl)] as const
}
const cachedUrl = getCachedSignedImageUrlSync(firstFileId)
const signedUrl = cachedUrl || await getCachedSignedImageUrl(firstFileId)
return [productId, signedUrl] as const return [productId, signedUrl] as const
})) }))
@@ -674,8 +675,8 @@ const loadShopImages = async () => {
]) ])
const environmentFileIds = parseFileIdList(shop.imageFileIds) const environmentFileIds = parseFileIdList(shop.imageFileIds)
const [bannerSignedUrls, environmentSignedUrls] = await Promise.all([ const [bannerSignedUrls, environmentSignedUrls] = await Promise.all([
getCachedSignedImageUrls(bannerFileIds), resolvePublicImageUrls({ imageFileIds: bannerFileIds.join(',') }, ''),
getCachedSignedImageUrls(environmentFileIds) resolvePublicImageUrls({ imageFileIds: environmentFileIds.join(',') }, '')
]) ])
const bannerUrls = bannerFileIds.length > 0 const bannerUrls = bannerFileIds.length > 0
+10 -13
View File
@@ -92,7 +92,8 @@ import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id' import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading' import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state' 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. * 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. */ /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (items: WishlistItem[]) => { const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) { for (const item of items) {
if (item.product.imageFileIds) { const productKey = String(item.product.id)
const ids = parseImageFileIds(item.product.imageFileIds) const cachedUrls = resolvePublicImageUrlsSync(item.product as PublicImageRecord, '')
const cachedUrls = getCachedSignedImageUrlsSync(ids) if (cachedUrls.length) {
if (cachedUrls.length) { imageUrls.value[productKey] = cachedUrls
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 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. */ /** 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] return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
} }
+24 -35
View File
@@ -219,6 +219,7 @@ import {
UserOutlined UserOutlined
} from '@ant-design/icons-vue' } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-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. * 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. * 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 { runWithGlobalLoading } from '@/utils/action-loading'
import { notifyShopThemeChanged } from '@/utils/shop-theme' import { notifyShopThemeChanged } from '@/utils/shop-theme'
import { useAdminViewport } from '@/composables/useAdminViewport' import { useAdminViewport } from '@/composables/useAdminViewport'
import { adminNavigationItems, findAdminNavigationItemByPath, type AdminNavIconKey } from '@/config/admin-navigation'
import { import {
getAdminCurrentShopName, getAdminCurrentShopName,
getAdminRoleLabel, getAdminRoleLabel,
@@ -237,17 +239,6 @@ import {
isBootstrapAdminUser isBootstrapAdminUser
} from './admin-helpers' } 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. * 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. * 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<string>()
const shopSwitchLoading = ref(false) const shopSwitchLoading = ref(false)
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission() const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
const menuItems: AdminMenuItem[] = [ const adminMenuIconMap: Record<AdminNavIconKey, Component> = {
{ key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' }, home: HomeOutlined,
{ key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' }, dashboard: DashboardOutlined,
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' }, user: UserOutlined,
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' }, shop: ShopOutlined,
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' }, gift: GiftOutlined,
{ key: '/admin/comments', icon: MessageOutlined, label: '评论管理', permissionCode: 'comment:view' }, message: MessageOutlined,
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' }, security: SafetyCertificateOutlined,
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' }, tag: TagOutlined,
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' }, shopping: ShoppingOutlined,
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' }, calendar: CalendarOutlined,
{ key: '/admin/schedules', icon: CalendarOutlined, label: '排班管理', permissionCode: 'schedule:view' }, tool: ToolOutlined,
{ key: '/admin/after-sales', icon: MessageOutlined, label: '售后处理', permissionCode: 'after_sale:view' }, team: TeamOutlined
{ 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' } const menuItems = adminNavigationItems.map(item => ({
, key: item.path,
{ key: '/admin/messages', icon: MessageOutlined, label: '消息发布', permissionCode: 'message:view' }, icon: adminMenuIconMap[item.iconKey],
{ key: '/admin/announcements', icon: MessageOutlined, label: '公告管理', permissionCode: 'announcement:view' }, label: item.label,
{ key: '/admin/vip-recharge-plans', icon: GiftOutlined, label: 'VIP充值配置', permissionCode: 'user:vip:manage' }, permissionCode: item.permissionCode
{ key: '/admin/messagehub-push-configs', icon: MessageOutlined, label: '参数管理', permissionCode: 'messagehub:config:manage' }, }))
{ key: '/admin/legal-agreements', icon: SafetyCertificateOutlined, label: '协议管理', permissionCode: 'legal_agreement:manage' }
]
/** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */ /** isBootstrapAdmin is a reactive state variable used by the template and event handlers. */
const isBootstrapAdmin = computed(() => isBootstrapAdminUser(userInfo.value)) 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. */ /** currentMobileTitle is a reactive state variable used by the template and event handlers. */
const currentMobileTitle = computed(() => { const currentMobileTitle = computed(() => {
const currentMenu = menuItems.find(item => item.key === route.path) const currentMenu = findAdminNavigationItemByPath(route.path)
if (currentMenu) { if (currentMenu) {
return currentMenu.label return currentMenu.label
} }
+62 -173
View File
@@ -69,6 +69,7 @@
:src="url" :src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;" style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false" :preview="false"
@error="handleProductImageError(record, index)"
/> />
<a-image <a-image
v-if="getProductImages(record).length === 0" v-if="getProductImages(record).length === 0"
@@ -128,6 +129,7 @@
class="admin-mobile-card__cover admin-mobile-card__cover--wide" class="admin-mobile-card__cover admin-mobile-card__cover--wide"
:src="getProductImages(item)[0] || DEFAULT_PRODUCT_IMAGE" :src="getProductImages(item)[0] || DEFAULT_PRODUCT_IMAGE"
:preview="false" :preview="false"
@error="handleProductImageError(item, 0)"
/> />
<div class="admin-mobile-card__head" style="margin-top: 14px"> <div class="admin-mobile-card__head" style="margin-top: 14px">
<div class="admin-mobile-card__body"> <div class="admin-mobile-card__body">
@@ -244,7 +246,7 @@
<div style="margin-top: 8px">上传图片</div> <div style="margin-top: 8px">上传图片</div>
</div> </div>
</a-upload> </a-upload>
<div class="upload-tip">支持多选上传,不限制上传张数,单张图片超过 5MB 会自动压缩后再上传。</div> <div class="upload-tip">支持多选上传,不限制上传张数,大图将自动使用分片并发上传。</div>
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div> <div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="previewVisible" :footer="null" :mask-closable="false" @cancel="previewVisible = false"> <a-modal v-model:open="previewVisible" :footer="null" :mask-closable="false" @cancel="previewVisible = false">
<img alt="预览" style="width: 100%" :src="previewImage" /> <img alt="预览" style="width: 100%" :src="previewImage" />
@@ -536,6 +538,7 @@
*/ */
import { computed, ref, reactive, onMounted, watch } from 'vue' import { computed, ref, reactive, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue' import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue' import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue' import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.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 { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft' import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission' 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 type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id' import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading' 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 { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue' import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue' import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
@@ -671,11 +684,6 @@ const imageUrls = ref<Record<string, string[]>>({})
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const viewImageUrls = ref<string[]>([]) const viewImageUrls = ref<string[]>([])
/**
* 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<Record<string, string>>({})
/** isAdmin is a reactive state variable used by the template and event handlers. */ /** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false) 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. * 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. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const pagination = reactive({ const pagination = reactive(createAdminPagination())
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/** /**
* Purpose: formState supports ProductsView.vue by holding or executing the form state page or API role. * 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. */ /** 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 loadImageUrls = async (products: Product[], requestToken?: number) => {
const nextImageUrls: Record<string, string[]> = {} return buildSignedImageUrlMap(
for (const product of products) { products,
if (requestToken && !isLatestRequestToken('products', requestToken)) { 'imageFileIds',
return null DEFAULT_PRODUCT_IMAGE,
} true,
if (product.imageFileIds) { () => Boolean(requestToken && !isLatestRequestToken('products', requestToken))
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
} }
/** getProductImages is a local helper used by this page script. */ /** getProductImages is a local helper used by this page script. */
const getProductImages = (product: Product | Record<string, any>): string[] => { const getProductImages = (product: { id?: IdType }): string[] =>
const productId = 'id' in product ? product.id : (product as any).id getRecordImageUrls(product, imageUrls.value, [DEFAULT_PRODUCT_IMAGE])
if (productId !== undefined) {
return imageUrls.value[String(productId)] || [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. */ /** 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. */ /** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => { const handleTableChange = async (pag: AdminTablePaginationChange) => {
pagination.current = pag.current const nextPagination = applyAdminTablePaginationChange(pagination, pag)
pagination.pageSize = pag.pageSize pagination.current = nextPagination.current
pagination.pageSize = nextPagination.pageSize
await runWithGlobalLoading(() => fetchProductList()) await runWithGlobalLoading(() => fetchProductList())
} }
@@ -1252,27 +1236,7 @@ const showViewModal = async (record: Product | Record<string, any>) => {
}) })
// 加载图片URL // 加载图片URL
if (recordImageFileIds) { viewImageUrls.value = await resolveSignedImageUrls(recordImageFileIds, DEFAULT_PRODUCT_IMAGE, true)
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]
}
// 获取该店铺的美甲师列表 // 获取该店铺的美甲师列表
if (recordShopId) { 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. */ /** buildImageFileListByIds is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const buildImageFileListByIds = async (ids: string[]) => { const buildImageFileListByIds = async (ids: string[]) => {
const fileList = [] return buildAdminUploadFileList(ids, '图片', DEFAULT_PRODUCT_IMAGE)
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
} }
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** 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(',') 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. */ /** 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 : '' const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) { if (fileUrl && !/^\d+$/.test(fileUrl)) {
return 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. */ /** 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 const { file, onSuccess, onError, onProgress } = options
let successMessage = '图片上传成功' const uploadFile = file as AdminUploadTaskFile
const task = createChunkUploadTask({ const task = createChunkUploadTask({
file: file as File, file: uploadFile,
scene: 'admin-product-image', scene: 'admin-product-image',
concurrency: 3,
api: { api: {
initUpload: adminFileApi.initChunkUpload, initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk, uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload, completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload 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) => {
onProgress?.({ percent }) onProgress?.({ percent })
} }
}) })
uploadTaskMap.set(String(file.uid), task) uploadTaskMap.set(String(uploadFile.uid), task)
activeUploadCount.value += 1 activeUploadCount.value += 1
try { try {
@@ -1487,42 +1381,37 @@ const handleUploadImage = async (options: any) => {
const fileId = String((response as any).id) const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId]) syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId }) onSuccess?.({ id: fileId, fileId })
message.success(successMessage) message.success('图片上传成功')
} catch (error) { } catch (error) {
const errorMessage = (error as Error)?.message || '图片上传失败' const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error) console.error('图片上传失败:', error)
message.error(errorMessage) message.error(errorMessage)
onError?.(error) onError?.(error as never)
} }
} finally { } finally {
uploadTaskMap.delete(String(file.uid)) uploadTaskMap.delete(String(uploadFile.uid))
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1) activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
} }
} }
// Ant Upload 的文件对象来源很多,预览时优先复用已有 URL,缺失时再回源签名地址。 // Ant Upload 的文件对象来源很多,预览时优先复用已有 URL,缺失时再回源签名地址。
/** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** 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 { try {
const cachedPreviewUrl = getPreviewUrlFromFile(file) const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) { if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl previewImage.value = cachedPreviewUrl
previewVisible.value = true previewVisible.value = true
return return
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) { if (!fileId) {
throw new Error('未找到图片文件标识') throw new Error('未找到图片文件标识')
} }
if (!imageIdCache.value[fileId]) { previewImage.value = await resolveSignedImageUrl(fileId, '')
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
previewVisible.value = true previewVisible.value = true
} catch (error) { } catch (error) {
console.error('获取预览链接失败:', error) console.error('获取预览链接失败:', error)
@@ -1531,14 +1420,14 @@ const handlePreview = async (file: any) => {
} }
/** handleRemove is a local helper used by this page script. */ /** 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)) const uploadTask = uploadTaskMap.get(String(file.uid))
if (uploadTask) { if (uploadTask) {
uploadTask.cancel() uploadTask.cancel()
return true return true
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) { if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId)) syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
} }
+269 -258
View File
@@ -47,15 +47,22 @@
<template #bodyCell="{ column, record }"> <template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'"> <template v-if="column.key === 'image'">
<div class="shop-images"> <div class="shop-images">
<a-image <div
v-for="(url, index) in getShopImages(record)" v-for="(url, index) in getShopImages(record)"
:key="index" :key="index"
:width="50" class="shop-image-frame"
:height="50" >
:src="url" <a-spin v-if="isShopImageLoading(record, 'imageFileIds', index)" size="small" />
style="object-fit: cover; border-radius: 4px; margin-right: 4px;" <img
:preview="false" :width="50"
/> :height="50"
:src="url"
class="shop-table-image"
alt="店铺图片"
@load="handleShopImageLoad(record, 'imageFileIds', index)"
@error="handleShopImageError(record, index)"
>
</div>
<a-image <a-image
v-if="getShopImages(record).length === 0" v-if="getShopImages(record).length === 0"
:width="50" :width="50"
@@ -68,15 +75,22 @@
</template> </template>
<template v-else-if="column.key === 'banner'"> <template v-else-if="column.key === 'banner'">
<div class="shop-banner"> <div class="shop-banner">
<a-image <div
v-for="(url, index) in getShopBannerImages(record)" v-for="(url, index) in getShopBannerImages(record)"
:key="index" :key="index"
:width="80" class="shop-image-frame shop-image-frame--banner"
:height="40" >
:src="url" <a-spin v-if="isShopImageLoading(record, 'coverImageFileId', index)" size="small" />
style="object-fit: cover; border-radius: 4px; margin-right: 4px;" <img
:preview="false" :width="80"
/> :height="40"
:src="url"
class="shop-table-image"
alt="店铺Banner"
@load="handleShopImageLoad(record, 'coverImageFileId', index)"
@error="handleShopBannerImageError(record, index)"
>
</div>
<span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span> <span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span>
</div> </div>
</template> </template>
@@ -133,11 +147,16 @@
<AdminMobileCardList v-else :items="shopList" empty-description="暂无店铺数据"> <AdminMobileCardList v-else :items="shopList" empty-description="暂无店铺数据">
<template #item="{ item }"> <template #item="{ item }">
<article class="admin-mobile-card"> <article class="admin-mobile-card">
<a-image <div class="shop-mobile-cover-frame">
class="admin-mobile-card__cover admin-mobile-card__cover--wide" <a-spin v-if="isShopCoverImageLoading(item)" size="small" />
:src="getShopBannerImages(item)[0] || getShopImages(item)[0] || DEFAULT_SHOP_IMAGE" <img
:preview="false" class="admin-mobile-card__cover admin-mobile-card__cover--wide"
/> :src="getShopBannerImages(item)[0] || getShopImages(item)[0] || DEFAULT_SHOP_IMAGE"
alt="店铺封面"
@load="handleShopCoverImageLoad(item)"
@error="handleShopCoverImageError(item)"
>
</div>
<div class="admin-mobile-card__head" style="margin-top: 14px"> <div class="admin-mobile-card__head" style="margin-top: 14px">
<div class="admin-mobile-card__body"> <div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.shopName }}</div> <div class="admin-mobile-card__title">{{ item.shopName }}</div>
@@ -584,7 +603,7 @@
*/ */
import { computed, ref, reactive, onMounted } from 'vue' import { computed, ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue' import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue' import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue' import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue' import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue' import TableEllipsisText from '@/components/TableEllipsisText.vue'
@@ -602,6 +621,18 @@ import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-uploa
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft' import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission' import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading' 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 type { IdType } from '@/utils/id'
import {
buildAdminUploadFileList,
buildSignedImageUrlMap,
getRecordImageUrls,
refreshSignedImageUrl,
resolveSignedImageUrl,
resolveSignedImageUrls
} from '@/utils/admin-image-assets'
import { parseImageFileIds } from '@/utils/signed-image-cache'
import { notifyShopThemeChanged, resolveShopTheme } from '@/utils/shop-theme' import { notifyShopThemeChanged, resolveShopTheme } from '@/utils/shop-theme'
import { useAdminViewport } from '@/composables/useAdminViewport' import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue' import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
@@ -842,11 +873,6 @@ const themeBackgroundFileList = ref<any[]>([])
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const uploadedThemeBackgroundId = ref('') const uploadedThemeBackgroundId = ref('')
/**
* Purpose: imageIdCache supports ShopsView.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<Record<string, string>>({})
/** /**
* Purpose: shopImageUrls supports ShopsView.vue by holding or executing the shop image urls page or API role. * Purpose: shopImageUrls supports ShopsView.vue by holding or executing the shop image urls 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. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -857,6 +883,7 @@ const shopImageUrls = ref<Record<string, string[]>>({})
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const shopBannerUrls = ref<Record<string, string[]>>({}) const shopBannerUrls = ref<Record<string, string[]>>({})
const shopImageLoadingKeys = ref<Record<string, boolean>>({})
/** /**
* Purpose: viewImageUrls supports ShopsView.vue by holding or executing the view image urls page or API role. * Purpose: viewImageUrls supports ShopsView.vue by holding or executing the view image urls 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. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -933,14 +960,7 @@ const viewFormState = reactive({
* Purpose: pagination supports ShopsView.vue by holding or executing the pagination page or API role. * Purpose: pagination supports ShopsView.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. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
const pagination = reactive({ const pagination = reactive(createAdminPagination())
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
/** /**
* Purpose: formState supports ShopsView.vue by holding or executing the form state page or API role. * Purpose: formState supports ShopsView.vue by holding or executing the form state page or API role.
@@ -1253,85 +1273,142 @@ const getThemeTemplateStorageKey = () => {
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (shops: Shop[]) => { const loadImageUrls = async (shops: Shop[]) => {
for (const shop of shops) { const [nextShopImageUrls, nextShopBannerUrls] = await Promise.all([
// 加载店铺图片 buildSignedImageUrlMap(shops, 'imageFileIds', DEFAULT_SHOP_IMAGE, false, () => false),
if (shop.imageFileIds) { buildSignedImageUrlMap(shops, 'coverImageFileId', DEFAULT_SHOP_IMAGE, false, () => false)
const ids = shop.imageFileIds.split(',') ])
const urls: string[] = []
shopImageUrls.value = nextShopImageUrls || {}
for (const id of ids) { shopBannerUrls.value = nextShopBannerUrls || {}
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_SHOP_IMAGE)
}
}
}
if (shop.id !== undefined) {
shopImageUrls.value[String(shop.id)] = urls
}
} else {
if (shop.id !== undefined) {
shopImageUrls.value[String(shop.id)] = []
}
}
// 加载Banner图片
if (shop.coverImageFileId) {
const ids = shop.coverImageFileId.split(',')
const urls: string[] = []
for (const id of ids) {
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_SHOP_IMAGE)
}
}
}
if (shop.id !== undefined) {
shopBannerUrls.value[String(shop.id)] = urls
}
} else {
if (shop.id !== undefined) {
shopBannerUrls.value[String(shop.id)] = []
}
}
}
} }
/** getShopImages is a local helper used by this page script. */ /** getShopImages is a local helper used by this page script. */
const getShopImages = (shop: Shop | Record<string, any>): string[] => { const getShopImages = (shop: { id?: IdType }): string[] =>
const shopId = 'id' in shop ? shop.id : (shop as any).id getRecordImageUrls(shop, shopImageUrls.value, [])
if (shopId !== undefined) {
return shopImageUrls.value[String(shopId)] || []
}
return []
}
/** getShopBannerImages is a local helper used by this page script. */ /** getShopBannerImages is a local helper used by this page script. */
const getShopBannerImages = (shop: Shop | Record<string, any>): string[] => { const getShopBannerImages = (shop: { id?: IdType }): string[] =>
const shopId = 'id' in shop ? shop.id : (shop as any).id getRecordImageUrls(shop, shopBannerUrls.value, [])
if (shopId !== undefined) {
return shopBannerUrls.value[String(shopId)] || [] const getShopImageLoadingKey = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): string => `${String(shop.id ?? '')}:${fieldName}:${imageIndex}`
const setShopImageLoading = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number,
loadingValue: boolean
): void => {
const key = getShopImageLoadingKey(shop, fieldName, imageIndex)
if (!key.startsWith(':')) {
shopImageLoadingKeys.value = {
...shopImageLoadingKeys.value,
[key]: loadingValue
}
} }
return [] }
const isShopImageLoading = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): boolean => {
const key = getShopImageLoadingKey(shop, fieldName, imageIndex)
return shopImageLoadingKeys.value[key] !== false
}
const handleShopImageLoad = (
shop: { id?: IdType },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number
): void => {
setShopImageLoading(shop, fieldName, imageIndex, false)
}
const isShopCoverImageLoading = (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
): boolean => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
return isShopImageLoading(shop, 'coverImageFileId', 0)
}
const imageFileIds = parseImageFileIds(shop.imageFileIds)
if (imageFileIds.length) {
return isShopImageLoading(shop, 'imageFileIds', 0)
}
return false
}
const handleShopCoverImageLoad = (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
): void => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
handleShopImageLoad(shop, 'coverImageFileId', 0)
return
}
handleShopImageLoad(shop, 'imageFileIds', 0)
}
const refreshShopImageUrl = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
fieldName: 'imageFileIds' | 'coverImageFileId',
imageIndex: number,
imageUrlMap: Record<string, string[]>
) => {
if (shop.id === undefined || shop.id === null) return null
const fileId = parseImageFileIds(shop[fieldName])[imageIndex]
if (!fileId) return null
const refreshedUrl = await refreshSignedImageUrl(fileId, DEFAULT_SHOP_IMAGE)
if (!refreshedUrl || refreshedUrl === DEFAULT_SHOP_IMAGE) return null
const shopKey = String(shop.id)
const currentUrls = imageUrlMap[shopKey] || []
const nextUrls = [...currentUrls]
nextUrls[imageIndex] = refreshedUrl
return {
...imageUrlMap,
[shopKey]: nextUrls
}
}
const handleShopImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
imageIndex: number
) => {
setShopImageLoading(shop, 'imageFileIds', imageIndex, false)
const nextImageUrls = await refreshShopImageUrl(shop, 'imageFileIds', imageIndex, shopImageUrls.value)
if (nextImageUrls) {
setShopImageLoading(shop, 'imageFileIds', imageIndex, true)
shopImageUrls.value = nextImageUrls
}
}
const handleShopBannerImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string },
imageIndex: number
) => {
setShopImageLoading(shop, 'coverImageFileId', imageIndex, false)
const nextBannerUrls = await refreshShopImageUrl(shop, 'coverImageFileId', imageIndex, shopBannerUrls.value)
if (nextBannerUrls) {
setShopImageLoading(shop, 'coverImageFileId', imageIndex, true)
shopBannerUrls.value = nextBannerUrls
}
}
const handleShopCoverImageError = async (
shop: { id?: IdType; imageFileIds?: string; coverImageFileId?: string }
) => {
const bannerFileIds = parseImageFileIds(shop.coverImageFileId)
if (bannerFileIds.length) {
await handleShopBannerImageError(shop, 0)
return
}
await handleShopImageError(shop, 0)
} }
/** formatAuthorizationExpireTime is a local helper used by this page script. */ /** formatAuthorizationExpireTime is a local helper used by this page script. */
@@ -1600,9 +1677,10 @@ const handleSearch = async () => {
} }
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: any) => { const handleTableChange = async (pag: AdminTablePaginationChange) => {
pagination.current = pag.current const nextPagination = applyAdminTablePaginationChange(pagination, pag)
pagination.pageSize = pag.pageSize pagination.current = nextPagination.current
pagination.pageSize = nextPagination.pageSize
await runWithGlobalLoading(() => fetchShopList()) await runWithGlobalLoading(() => fetchShopList())
} }
@@ -1610,23 +1688,21 @@ const handleTableChange = async (pag: any) => {
const beforeUpload = (file: File) => { const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/') const isImage = file.type.startsWith('image/')
if (!isImage) { if (!isImage) {
message.error('只能上传图片文件!') message.error('只能上传图片文件')
} }
const isLt2M = file.size / 1024 / 1024 < 2 return isImage
if (!isLt2M) {
message.error('图片大小不能超过 2MB!')
}
return isImage && isLt2M
} }
// Banner 与门店环境图分开维护上传任务,便于表单回显和删除时分别同步 fileId 列表。 // Banner 与门店环境图分开维护上传任务,便于表单回显和删除时分别同步 fileId 列表。
/** handleUploadBanner is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleUploadBanner is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadBanner = async (options: any) => { const handleUploadBanner: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options const { file, onSuccess, onError, onProgress } = options
const taskKey = `banner:${String(file.uid)}` const uploadFile = file as AdminUploadTaskFile
const taskKey = `banner:${String(uploadFile.uid)}`
const task = createChunkUploadTask({ const task = createChunkUploadTask({
file: file as File, file: uploadFile,
scene: 'admin-shop-banner', scene: 'admin-shop-banner',
concurrency: 3,
api: { api: {
initUpload: adminFileApi.initChunkUpload, initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk, uploadChunk: adminFileApi.uploadChunk,
@@ -1652,7 +1728,7 @@ const handleUploadBanner = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('Banner上传失败:', error) console.error('Banner上传失败:', error)
message.error(errorMessage) message.error(errorMessage)
onError?.(error) onError?.(error as never)
} }
} finally { } finally {
uploadTaskMap.delete(taskKey) uploadTaskMap.delete(taskKey)
@@ -1661,25 +1737,21 @@ const handleUploadBanner = async (options: any) => {
} }
/** handleBannerPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleBannerPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBannerPreview = async (file: any) => { const handleBannerPreview: UploadProps['onPreview'] = async (file) => {
try { try {
const cachedPreviewUrl = getPreviewUrlFromFile(file) const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) { if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true bannerPreviewVisible.value = true
return return
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) { if (!fileId) {
throw new Error('未找到图片文件标识') throw new Error('未找到图片文件标识')
} }
if (!imageIdCache.value[fileId]) { bannerPreviewImage.value = await resolveSignedImageUrl(fileId, '')
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewVisible.value = true bannerPreviewVisible.value = true
} catch (error) { } catch (error) {
console.error('获取预览链接失败:', error) console.error('获取预览链接失败:', error)
@@ -1688,14 +1760,14 @@ const handleBannerPreview = async (file: any) => {
} }
/** handleBannerRemove is a local helper used by this page script. */ /** handleBannerRemove is a local helper used by this page script. */
const handleBannerRemove = (file: any) => { const handleBannerRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`banner:${String(file.uid)}`) const task = uploadTaskMap.get(`banner:${String(file.uid)}`)
if (task) { if (task) {
task.cancel() task.cancel()
return true return true
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) { if (fileId) {
syncUploadedBannerIds(uploadedBannerIds.value.filter(id => id !== fileId)) syncUploadedBannerIds(uploadedBannerIds.value.filter(id => id !== fileId))
} }
@@ -1704,12 +1776,14 @@ const handleBannerRemove = (file: any) => {
// 店铺环境图与 Banner 走同一套分片上传协议,但写入不同业务字段。 // 店铺环境图与 Banner 走同一套分片上传协议,但写入不同业务字段。
/** handleUploadImage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** 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 const { file, onSuccess, onError, onProgress } = options
const taskKey = `image:${String(file.uid)}` const uploadFile = file as AdminUploadTaskFile
const taskKey = `image:${String(uploadFile.uid)}`
const task = createChunkUploadTask({ const task = createChunkUploadTask({
file: file as File, file: uploadFile,
scene: 'admin-shop-image', scene: 'admin-shop-image',
concurrency: 3,
api: { api: {
initUpload: adminFileApi.initChunkUpload, initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk, uploadChunk: adminFileApi.uploadChunk,
@@ -1735,7 +1809,7 @@ const handleUploadImage = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error) console.error('图片上传失败:', error)
message.error(errorMessage) message.error(errorMessage)
onError?.(error) onError?.(error as never)
} }
} finally { } finally {
uploadTaskMap.delete(taskKey) uploadTaskMap.delete(taskKey)
@@ -1745,25 +1819,21 @@ const handleUploadImage = async (options: any) => {
// 编辑态下 Upload 里的文件可能只剩 fileId,所以预览时需要兼容本地 URL 与远端签名地址两种来源。 // 编辑态下 Upload 里的文件可能只剩 fileId,所以预览时需要兼容本地 URL 与远端签名地址两种来源。
/** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** 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 { try {
const cachedPreviewUrl = getPreviewUrlFromFile(file) const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) { if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl previewImage.value = cachedPreviewUrl
previewVisible.value = true previewVisible.value = true
return return
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) { if (!fileId) {
throw new Error('未找到图片文件标识') throw new Error('未找到图片文件标识')
} }
if (!imageIdCache.value[fileId]) { previewImage.value = await resolveSignedImageUrl(fileId, '')
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
previewVisible.value = true previewVisible.value = true
} catch (error) { } catch (error) {
console.error('获取预览链接失败:', error) console.error('获取预览链接失败:', error)
@@ -1772,14 +1842,14 @@ const handlePreview = async (file: any) => {
} }
/** handleRemove is a local helper used by this page script. */ /** handleRemove is a local helper used by this page script. */
const handleRemove = (file: any) => { const handleRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`image:${String(file.uid)}`) const task = uploadTaskMap.get(`image:${String(file.uid)}`)
if (task) { if (task) {
task.cancel() task.cancel()
return true return true
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) { if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId)) syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
} }
@@ -1787,12 +1857,14 @@ const handleRemove = (file: any) => {
} }
/** handleUploadThemeBackground is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleUploadThemeBackground is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadThemeBackground = async (options: any) => { const handleUploadThemeBackground: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options const { file, onSuccess, onError, onProgress } = options
const taskKey = `theme-bg:${String(file.uid)}` const uploadFile = file as AdminUploadTaskFile
const taskKey = `theme-bg:${String(uploadFile.uid)}`
const task = createChunkUploadTask({ const task = createChunkUploadTask({
file: file as File, file: uploadFile,
scene: 'admin-shop-theme-background', scene: 'admin-shop-theme-background',
concurrency: 3,
api: { api: {
initUpload: adminFileApi.initChunkUpload, initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk, uploadChunk: adminFileApi.uploadChunk,
@@ -1818,7 +1890,7 @@ const handleUploadThemeBackground = async (options: any) => {
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') { if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('背景图上传失败:', error) console.error('背景图上传失败:', error)
message.error(errorMessage) message.error(errorMessage)
onError?.(error) onError?.(error as never)
} }
} finally { } finally {
uploadTaskMap.delete(taskKey) uploadTaskMap.delete(taskKey)
@@ -1827,25 +1899,21 @@ const handleUploadThemeBackground = async (options: any) => {
} }
/** handleThemeBackgroundPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** handleThemeBackgroundPreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleThemeBackgroundPreview = async (file: any) => { const handleThemeBackgroundPreview: UploadProps['onPreview'] = async (file) => {
try { try {
const cachedPreviewUrl = getPreviewUrlFromFile(file) const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) { if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true bannerPreviewVisible.value = true
return return
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) { if (!fileId) {
throw new Error('未找到背景图文件标识') throw new Error('未找到背景图文件标识')
} }
if (!imageIdCache.value[fileId]) { bannerPreviewImage.value = await resolveSignedImageUrl(fileId, '')
const response = await adminFileApi.getSignedUrl(fileId) as any
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewVisible.value = true bannerPreviewVisible.value = true
} catch (error) { } catch (error) {
console.error('获取背景图预览链接失败:', error) console.error('获取背景图预览链接失败:', error)
@@ -1854,14 +1922,14 @@ const handleThemeBackgroundPreview = async (file: any) => {
} }
/** handleThemeBackgroundRemove is a local helper used by this page script. */ /** handleThemeBackgroundRemove is a local helper used by this page script. */
const handleThemeBackgroundRemove = (file: any) => { const handleThemeBackgroundRemove: UploadProps['onRemove'] = (file) => {
const task = uploadTaskMap.get(`theme-bg:${String(file.uid)}`) const task = uploadTaskMap.get(`theme-bg:${String(file.uid)}`)
if (task) { if (task) {
task.cancel() task.cancel()
return true return true
} }
const fileId = resolveUploadedFileId(file) const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) { if (fileId) {
syncUploadedThemeBackgroundId('') syncUploadedThemeBackgroundId('')
} }
@@ -2015,53 +2083,11 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
themeBackgroundImageFileId: 'themeBackgroundImageFileId' in record ? record.themeBackgroundImageFileId : (record as any).themeBackgroundImageFileId themeBackgroundImageFileId: 'themeBackgroundImageFileId' in record ? record.themeBackgroundImageFileId : (record as any).themeBackgroundImageFileId
}) })
// 加载Banner图片URL // 加载图片URL
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
const ids = coverImageFileId.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
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_SHOP_IMAGE)
}
}
viewBannerUrls.value = urls
} else {
viewBannerUrls.value = []
}
// 加载店铺图片URL
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) { viewBannerUrls.value = await resolveSignedImageUrls(coverImageFileId, DEFAULT_SHOP_IMAGE, false)
const ids = imageFileIds.split(',').filter((id: string) => id) viewImageUrls.value = await resolveSignedImageUrls(imageFileIds, DEFAULT_SHOP_IMAGE, false)
const urls: string[] = []
for (const id of ids) {
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_SHOP_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = []
}
viewModalVisible.value = true viewModalVisible.value = true
} }
@@ -2113,32 +2139,7 @@ const buildDraftPayload = () => ({
/** buildShopUploadFileList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** buildShopUploadFileList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const buildShopUploadFileList = async (ids: string[], fileNamePrefix: string) => { const buildShopUploadFileList = async (ids: string[], fileNamePrefix: string) => {
const fileList = [] return buildAdminUploadFileList(ids, fileNamePrefix, DEFAULT_SHOP_IMAGE)
for (const [index, id] of ids.entries()) {
try {
if (!imageIdCache.value[id]) {
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
})
} catch (error) {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: ''
})
}
}
return fileList
} }
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ /** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -2298,37 +2299,8 @@ const handleDeleteCustomThemeTemplate = (id: string) => {
message.success('已删除配色模板') message.success('已删除配色模板')
} }
/** 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. */ /** 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 : '' const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) { if (fileUrl && !/^\d+$/.test(fileUrl)) {
return fileUrl return fileUrl
@@ -2427,6 +2399,45 @@ onMounted(async () => {
gap: 4px; gap: 4px;
} }
.shop-image-frame {
position: relative;
display: inline-grid;
width: 50px;
height: 50px;
place-items: center;
overflow: hidden;
border-radius: 4px;
background: var(--theme-primary-soft);
}
.shop-image-frame--banner {
width: 80px;
height: 40px;
}
.shop-image-frame :deep(.ant-spin) {
position: absolute;
z-index: 1;
}
.shop-table-image {
display: block;
object-fit: cover;
border-radius: 4px;
}
.shop-mobile-cover-frame {
position: relative;
}
.shop-mobile-cover-frame :deep(.ant-spin) {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.map-picker-card { .map-picker-card {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -169,6 +169,7 @@ import SystemMessageCard from '@/components/SystemMessageCard.vue'
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/ */
import { adminFileApi, adminSystemMessageApi, type SystemMessageCreateRequest, type SystemMessageVO } from '@/api/admin' import { adminFileApi, adminSystemMessageApi, type SystemMessageCreateRequest, type SystemMessageVO } from '@/api/admin'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import type { IdType } from '@/utils/id' import type { IdType } from '@/utils/id'
/** /**
@@ -395,20 +396,34 @@ const handleImageUpload = async (options: any) => {
options.onError?.(new Error('invalid image')) options.onError?.(new Error('invalid image'))
return return
} }
if (file.size > 5 * 1024 * 1024) {
message.warning('图片不能超过 5MB')
options.onError?.(new Error('image too large'))
return
}
imageUploading.value = true imageUploading.value = true
const task = createChunkUploadTask({
file,
scene: 'admin-system-message-image',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
options.onProgress?.({ percent })
}
})
try { try {
const uploaded = await adminFileApi.uploadFile(file) const { response: uploaded } = await task.promise
form.imageFileId = uploaded.id form.imageFileId = uploaded.id
imagePreviewUrl.value = await adminFileApi.getSignedUrl(uploaded.id) imagePreviewUrl.value = await adminFileApi.getSignedUrl(uploaded.id)
options.onSuccess?.(uploaded) options.onSuccess?.(uploaded)
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '图片上传失败') const errorMessage = error?.message || '图片上传失败'
options.onError?.(error) if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
message.error(errorMessage)
options.onError?.(error)
}
} finally { } finally {
imageUploading.value = false imageUploading.value = false
} }
+27 -12
View File
@@ -550,7 +550,7 @@
*/ */
import { computed, h, onMounted, reactive, ref } from 'vue' import { computed, h, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue' import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue' import type { FormInstance, UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue' import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue' import DraftActions from '@/components/DraftActions.vue'
import { DEFAULT_AVATAR } from '@/constants' import { DEFAULT_AVATAR } from '@/constants'
@@ -578,6 +578,7 @@ import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id' import { sameId } from '@/utils/id'
import { usePermission } from '@/utils/permission' import { usePermission } from '@/utils/permission'
import { runWithGlobalLoading } from '@/utils/action-loading' import { runWithGlobalLoading } from '@/utils/action-loading'
import { createChunkUploadTask } from '@/utils/chunk-upload'
import { useAdminViewport } from '@/composables/useAdminViewport' import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue' import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue' import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
@@ -888,30 +889,44 @@ const handlePhoneInput = () => {
/** beforeUploadWechatQr validates QR image files before upload. */ /** beforeUploadWechatQr validates QR image files before upload. */
const beforeUploadWechatQr = (file: File) => { const beforeUploadWechatQr = (file: File) => {
const isImage = file.type.startsWith('image/') const isImage = file.type.startsWith('image/')
const isLt10M = file.size / 1024 / 1024 < 10
if (!isImage) { if (!isImage) {
message.error('只能上传图片文件') message.error('只能上传图片文件')
} }
if (!isLt10M) { return isImage
message.error('图片大小不能超过 10MB')
}
return isImage && isLt10M
} }
/** handleWechatQrUpload uploads a QR image through admin object storage and stores the signed URL. */ /** handleWechatQrUpload uploads a QR image through admin object storage and stores the signed URL. */
const handleWechatQrUpload = async (options: any) => { const handleWechatQrUpload: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError } = options const { file, onSuccess, onError, onProgress } = options
wechatQrUploading.value = true wechatQrUploading.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-user-wechat-qr',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
try { try {
const uploaded = await adminFileApi.uploadFile(file as File) const { response: uploaded } = await task.promise
const signedUrl = await adminFileApi.getSignedUrl(uploaded.id) const signedUrl = await adminFileApi.getSignedUrl(uploaded.id)
formState.wechatQrCode = signedUrl as unknown as string formState.wechatQrCode = signedUrl as unknown as string
onSuccess?.(uploaded) onSuccess?.(uploaded)
message.success('微信二维码上传成功') message.success('微信二维码上传成功')
} catch (error) { } catch (error) {
console.error('微信二维码上传失败:', error) const errorMessage = (error as Error)?.message || '微信二维码上传失败'
message.error((error as Error)?.message || '微信二维码上传失败') if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
onError?.(error) console.error('微信二维码上传失败:', error)
message.error(errorMessage)
onError?.(error as Error)
}
} finally { } finally {
wechatQrUploading.value = false wechatQrUploading.value = false
} }
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'
import { join } from 'node:path' import { join } from 'node:path'
const sourceRoot = join(process.cwd(), 'src') const sourceRoot = join(process.cwd(), 'src')
const coreRoot = join(process.cwd(), '..', 'YumiNail-Core', 'src', 'main', 'java') const coreRoot = join(process.cwd(), '..', 'FD-Core', 'src', 'main', 'java')
function readSource(relativePath: string) { function readSource(relativePath: string) {
return readFileSync(join(sourceRoot, relativePath), 'utf-8') return readFileSync(join(sourceRoot, relativePath), 'utf-8')
@@ -68,7 +68,7 @@ describe('web theme governance', () => {
it('keeps frontend and backend platform overview permission allowlists aligned', () => { it('keeps frontend and backend platform overview permission allowlists aligned', () => {
const frontend = readSource('utils/platform-admin-permissions.ts') const frontend = readSource('utils/platform-admin-permissions.ts')
const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'support', 'PermissionCatalog.java'), 'utf-8') const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'modules', 'security', 'support', 'PermissionCatalog.java'), 'utf-8')
expect(backend).toContain('"security:audit:view"') expect(backend).toContain('"security:audit:view"')
expect(frontend).toContain("'security:audit:view'") expect(frontend).toContain("'security:audit:view'")
@@ -4,10 +4,14 @@ import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRe
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const messageError = vi.hoisted(() => vi.fn()) const messageError = vi.hoisted(() => vi.fn())
const modalError = vi.hoisted(() => vi.fn())
vi.mock('ant-design-vue', () => ({ vi.mock('ant-design-vue', () => ({
message: { message: {
error: messageError error: messageError
},
Modal: {
error: modalError
} }
})) }))
@@ -41,6 +45,7 @@ describe('api stale token handling', () => {
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers() vi.useFakeTimers()
messageError.mockClear() messageError.mockClear()
modalError.mockClear()
window.history.replaceState(null, '', '/profile') window.history.replaceState(null, '', '/profile')
localStorage.clear() localStorage.clear()
sessionStorage.clear() sessionStorage.clear()
@@ -114,5 +119,6 @@ describe('api stale token handling', () => {
expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh') expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh')
expect(window.location.href).toBe(hrefBefore401) expect(window.location.href).toBe(hrefBefore401)
expect(messageError).not.toHaveBeenCalled() expect(messageError).not.toHaveBeenCalled()
expect(modalError).not.toHaveBeenCalled()
}) })
}) })
@@ -0,0 +1,146 @@
// @vitest-environment jsdom
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const messageError = vi.hoisted(() => vi.fn())
const modalError = vi.hoisted(() => vi.fn())
vi.mock('ant-design-vue', () => ({
message: {
error: messageError
},
Modal: {
error: modalError
}
}))
import api from '../../src/api'
const createResponseError = (config: InternalAxiosRequestConfig, status: number): AxiosError => {
const response = {
data: {
code: status,
message: `HTTP ${status}`
},
status,
statusText: 'Error',
headers: {},
config,
request: {}
} as AxiosResponse
return new AxiosError(
`Request failed with status code ${status}`,
AxiosError.ERR_BAD_RESPONSE,
config,
{},
response
)
}
const createNetworkError = (config: InternalAxiosRequestConfig): AxiosError =>
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, {})
type MockRequestResult = AxiosError | null
const mockRequestResults = (results: MockRequestResult[]) => {
let currentResultIndex = 0
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
const result = results[currentResultIndex]
currentResultIndex += 1
if (!result) {
return Promise.resolve({
data: { code: 200, data: { ok: true } },
status: 200,
statusText: 'OK',
headers: {},
config,
request: {}
} as AxiosResponse)
}
result.config = config
return Promise.reject(result)
}) as AxiosAdapter
}
describe('api system unavailable handling', () => {
const originalAdapter = api.defaults.adapter
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(1_000)
messageError.mockClear()
modalError.mockClear()
localStorage.clear()
sessionStorage.clear()
})
afterEach(() => {
api.defaults.adapter = originalAdapter
localStorage.clear()
sessionStorage.clear()
vi.useRealTimers()
})
it('shows one system unavailable modal after three server failures in the window', async () => {
const config = {} as InternalAxiosRequestConfig
mockRequestResults([
createResponseError(config, 500),
createResponseError(config, 502),
createResponseError(config, 503),
createResponseError(config, 500)
])
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 502 } })
expect(modalError).not.toHaveBeenCalled()
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 503 } })
expect(modalError).toHaveBeenCalledTimes(1)
expect(modalError).toHaveBeenCalledWith(expect.objectContaining({
title: '系统暂不可用',
content: '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。',
okText: '我知道了'
}))
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
expect(modalError).toHaveBeenCalledTimes(1)
modalError.mock.calls[0]?.[0]?.afterClose?.()
})
it('counts network failures as system failures', async () => {
const config = {} as InternalAxiosRequestConfig
vi.setSystemTime(70_000)
mockRequestResults([
createNetworkError(config),
createNetworkError(config),
createNetworkError(config)
])
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
expect(modalError).toHaveBeenCalledTimes(1)
expect(messageError).toHaveBeenCalledTimes(1)
})
it('resets failure count after a successful response', async () => {
const config = {} as InternalAxiosRequestConfig
vi.setSystemTime(140_000)
mockRequestResults([
createResponseError(config, 500),
createResponseError(config, 500),
null,
createResponseError(config, 500)
])
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
await expect(api.get('/health')).resolves.toEqual({ ok: true })
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
expect(modalError).not.toHaveBeenCalled()
})
})
@@ -7,18 +7,18 @@ import org.springframework.context.annotation.Configuration;
import java.util.List; import java.util.List;
/** /**
* 网关白名单配置 * 网关白名单配置。
* *
* @author xiaowang * @author xiaowang
* @date 2026-02-12 * @date 2026-02-12
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.gateway") @ConfigurationProperties(prefix = "fingertip-designer.gateway")
public class GatewayConfig { public class GatewayConfig {
/** /**
* 白名单路径列表 * 白名单路径列表。
*/ */
private List<String> whitelist; private List<String> whitelist;
@@ -9,12 +9,12 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt") @ConfigurationProperties(prefix = "fingertip-designer.security.jwt")
public class JwtProperties { public class JwtProperties {
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";
private String issuer = "yuminail"; private String issuer = "fingertip-designer";
private long clockSkewSeconds = 30; private long clockSkewSeconds = 30;
} }
@@ -40,11 +40,11 @@ public class HealthController {
private Map<String, Object> diagnosticsPayload() { private Map<String, Object> diagnosticsPayload() {
Map<String, Object> diagnostics = new LinkedHashMap<>(); Map<String, Object> diagnostics = new LinkedHashMap<>();
String serviceName = environment.getProperty("spring.application.name", "yuminail-gateway"); String serviceName = environment.getProperty("spring.application.name", "fingertip-designer-gateway");
diagnostics.put("service", serviceName); diagnostics.put("service", serviceName);
diagnostics.put("port", environment.getProperty("server.port", "")); diagnostics.put("port", environment.getProperty("server.port", ""));
diagnostics.put("gatewayService", discoverySummary(serviceName)); diagnostics.put("gatewayService", discoverySummary(serviceName));
diagnostics.put("coreService", discoverySummary("yumi-nail-core")); diagnostics.put("coreService", discoverySummary("fingertip-designer-core"));
return diagnostics; return diagnostics;
} }
+33 -25
View File
@@ -1,37 +1,45 @@
spring: spring:
application: application:
name: yuminail-gateway name: fingertip-designer-gateway
cloud: cloud:
nacos: nacos:
discovery: discovery:
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 # Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。
namespace: YumiNail-Dev server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
group: DEFAULT_GROUP # Nacos 命名空间,默认指向开发环境。
namespace: ${NACOS_NAMESPACE:YumiNail-Dev}
# 服务注册分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# 注册到 Nacos 的服务名。
service: ${spring.application.name} service: ${spring.application.name}
username: xiaowang # Nacos 认证用户名。
password: 122503wcy.... username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
config: config:
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 # Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。
namespace: YumiNail-Dev server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
group: DEFAULT_GROUP # Nacos 配置中心命名空间,默认指向开发环境。
name: yuminail-gateway namespace: ${NACOS_NAMESPACE:YumiNail-Dev}
# 配置分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# Gateway 服务独有配置文件。
name: gateway
# 所有 Nacos 配置均使用 YAML。
file-extension: yaml file-extension: yaml
username: xiaowang # Nacos 认证用户名。
password: 122503wcy.... username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
# Core 与 Gateway 共享的公共配置文件。
shared-configs: shared-configs:
- data-id: infra.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: secret.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: logging.yaml - data-id: logging.yaml
group: DEFAULT_GROUP group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: rabbitmq.yaml
group: DEFAULT_GROUP
refresh: true
- data-id: datasource.yaml
group: DEFAULT_GROUP
refresh: true
- data-id: mybatis-plus.yaml
group: DEFAULT_GROUP
refresh: true
- data-id: redis.yaml
group: DEFAULT_GROUP
refresh: true refresh: true
@@ -0,0 +1 @@
{}
-1
View File
@@ -99,7 +99,6 @@
"skyline": { "skyline": {
"defaultDisplayBlock": true, "defaultDisplayBlock": true,
"defaultContentBox": true, "defaultContentBox": true,
"tagNameStyleIsolation": "legacy",
"disableABTest": true, "disableABTest": true,
"sdkVersionBegin": "3.0.0", "sdkVersionBegin": "3.0.0",
"sdkVersionEnd": "15.255.255" "sdkVersionEnd": "15.255.255"
@@ -5,17 +5,17 @@
<view class="page-hero"> <view class="page-hero">
<text class="hero-kicker">Account</text> <text class="hero-kicker">Account</text>
<text class="hero-title">账号资料</text> <text class="hero-title">账号资料</text>
<text class="hero-desc">维护昵称、个性签名和基础资料�?/text> <text class="hero-desc">维护昵称、个性签名和基础资料</text>
</view> </view>
<view class="page-card form-card"> <view class="page-card form-card">
<view class="field-block"> <view class="field-block">
<text class="field-label">昵称</text> <text class="field-label">昵称</text>
<input class="field-input" value="{{form.nickname}}" data-field="nickname" bindinput="handleInput" placeholder="请输入昵�? placeholder-class="field-placeholder" /> <input class="field-input" value="{{form.nickname}}" data-field="nickname" bindinput="handleInput" placeholder="请输入昵称" placeholder-class="field-placeholder" />
</view> </view>
<view class="field-block"> <view class="field-block">
<text class="field-label">个��签�?/text> <text class="field-label">个性签名</text>
<textarea class="field-textarea" maxlength="120" value="{{form.signature}}" data-field="signature" bindinput="handleInput" placeholder="写一句介绍自�? placeholder-class="field-placeholder"></textarea> <textarea class="field-textarea" maxlength="120" value="{{form.signature}}" data-field="signature" bindinput="handleInput" placeholder="写一句介绍自己" placeholder-class="field-placeholder"></textarea>
</view> </view>
<button class="primary-btn" loading="{{saving}}" bindtap="saveProfile">保存资料</button> <button class="primary-btn" loading="{{saving}}" bindtap="saveProfile">保存资料</button>
</view> </view>
@@ -5,12 +5,12 @@
<view class="page-hero"> <view class="page-hero">
<text class="hero-kicker">售后申请</text> <text class="hero-kicker">售后申请</text>
<text class="hero-title">{{order && order.orderNo || '选择订单'}}</text> <text class="hero-title">{{order && order.orderNo || '选择订单'}}</text>
<text class="hero-desc">{{order ? '可申请金�?' + amountText : '从订单详情进入可自动带入订单信息'}}</text> <text class="hero-desc">{{order ? '可申请金额' + amountText : '从订单详情进入可自动带入订单信息'}}</text>
</view> </view>
<view wx:if="{{!orderId}}" class="page-card empty-card"> <view wx:if="{{!orderId}}" class="page-card empty-card">
<text class="empty-title">缺少订单信息</text> <text class="empty-title">缺少订单信息</text>
<text class="empty-desc">请从订单详情或订单中心发起售后��?/text> <text class="empty-desc">请从订单详情或订单中心发起售后</text>
<view class="ghost-btn" bindtap="handleBack">返回订单</view> <view class="ghost-btn" bindtap="handleBack">返回订单</view>
</view> </view>
@@ -18,7 +18,7 @@
<view class="field-block"> <view class="field-block">
<text class="field-label">订单项目</text> <text class="field-label">订单项目</text>
<picker mode="selector" range="{{items}}" range-key="productTitle" bindchange="handleItemChange"> <picker mode="selector" range="{{items}}" range-key="productTitle" bindchange="handleItemChange">
<view class="field-picker">{{form.orderItemId ? '已��择项目' : '默认整单'}}</view> <view class="field-picker">{{form.orderItemId ? '已选择项目' : '默认整单'}}</view>
</picker> </picker>
</view> </view>
<view class="field-block"> <view class="field-block">
@@ -28,12 +28,12 @@
</picker> </picker>
</view> </view>
<view class="field-block"> <view class="field-block">
<text class="field-label">逢�款金�?/text> <text class="field-label">退款金额</text>
<input class="field-input" type="digit" value="{{form.refundAmount}}" data-field="refundAmount" bindinput="handleInput" placeholder="可��? placeholder-class="field-placeholder" /> <input class="field-input" type="digit" value="{{form.refundAmount}}" data-field="refundAmount" bindinput="handleInput" placeholder="可选" placeholder-class="field-placeholder" />
</view> </view>
<view class="field-block"> <view class="field-block">
<text class="field-label">原因说明</text> <text class="field-label">原因说明</text>
<textarea class="field-textarea" maxlength="300" value="{{form.reason}}" data-field="reason" bindinput="handleInput" placeholder="请说明���款或售后原因" placeholder-class="field-placeholder"></textarea> <textarea class="field-textarea" maxlength="300" value="{{form.reason}}" data-field="reason" bindinput="handleInput" placeholder="请说明退款或售后原因" placeholder-class="field-placeholder"></textarea>
</view> </view>
<button class="primary-btn" loading="{{submitting}}" bindtap="submit">提交申请</button> <button class="primary-btn" loading="{{submitting}}" bindtap="submit">提交申请</button>
</view> </view>
@@ -4,8 +4,8 @@
<view class="page-content"> <view class="page-content">
<view class="page-hero"> <view class="page-hero">
<text class="hero-kicker">售后服务</text> <text class="hero-kicker">售后服务</text>
<text class="hero-title">{{records.length}} 条记�?/text> <text class="hero-title">{{records.length}} 条记录</text>
<text class="hero-desc">{{orderId ? '当前订单的售后进�? : '逢�款��售后和审核记录集中查看'}}</text> <text class="hero-desc">{{orderId ? '当前订单的售后进度' : '退款、售后和审核记录集中查看'}}</text>
</view> </view>
<view wx:if="{{loading}}" class="page-card empty-card"> <view wx:if="{{loading}}" class="page-card empty-card">
@@ -43,7 +43,7 @@
<view wx:else class="page-card empty-card"> <view wx:else class="page-card empty-card">
<text class="empty-title">暂无售后记录</text> <text class="empty-title">暂无售后记录</text>
<text class="empty-desc">订单完成或支付后可以发起售后申请�?/text> <text class="empty-desc">订单完成或支付后可以发起售后申请</text>
</view> </view>
</view> </view>
</view> </view>

Some files were not shown because too many files have changed in this diff Show More